Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eae2711f21 | ||
|
|
fac956b761 | ||
|
|
b286244aab | ||
|
|
c46f824e3f | ||
|
|
dbe55f0804 | ||
|
|
3bcce02b92 | ||
|
|
2a23911a5b | ||
|
|
5aa24c8472 | ||
|
|
8277ce934b | ||
|
|
bb68cd73ef | ||
|
|
445b307972 | ||
|
|
d2d86a4079 | ||
|
|
7601cc2194 | ||
|
|
aa48e72c12 | ||
|
|
bec49ef417 | ||
|
|
c13aa69565 | ||
|
|
1470adb159 | ||
|
|
bf89991eef | ||
|
|
4dfab874e0 | ||
|
|
4303fb8726 | ||
|
|
64f811ed0b | ||
|
|
4d51873140 | ||
|
|
3c0fc2e88b | ||
|
|
c702da0334 | ||
|
|
92169eb0d2 | ||
|
|
3d74357e96 | ||
|
|
6593291d00 | ||
|
|
c48fb44a8d | ||
|
|
e7c908bc80 | ||
|
|
ad35e19f8e | ||
|
|
3fc8c6c84e | ||
|
|
da7aeb4a21 | ||
|
|
6197a2a5c5 | ||
|
|
de186b95c1 | ||
|
|
6b24513073 | ||
|
|
55ea18128a | ||
|
|
d5557fa512 | ||
|
|
9c97b2aa6d | ||
|
|
1e226a40d1 | ||
|
|
bbe46eaa7d | ||
|
|
7799b191ec | ||
|
|
f3269a3ddf | ||
|
|
a4be822636 | ||
|
|
7cd8dbf7d8 | ||
|
|
654a865007 | ||
|
|
409a0277fb | ||
|
|
7adab1f65f | ||
|
|
3b92c86582 | ||
|
|
de195a1c0f | ||
|
|
d7d2487f6d | ||
|
|
3e31945157 | ||
|
|
c11814c342 | ||
|
|
60e3244088 | ||
|
|
a1ac5f36f0 | ||
|
|
6f38d40613 | ||
|
|
6b7d22de3f | ||
|
|
2f763dceda | ||
|
|
96468c4083 | ||
|
|
858d52563f | ||
|
|
7505b3b271 | ||
|
|
758dc88b55 | ||
|
|
9be418dc65 | ||
|
|
2ac310456e | ||
|
|
ff264d6f7a | ||
|
|
8019c414e1 | ||
|
|
a3fbe3731e | ||
|
|
e3742dbc66 | ||
|
|
83bf717d6d | ||
|
|
7fcdaa1c46 | ||
|
|
a8154f9405 | ||
|
|
52a5afeba5 | ||
|
|
43cc40d7fe | ||
|
|
42a98f000e | ||
|
|
f003ef935b | ||
|
|
e2b2a184c8 | ||
|
|
094595c435 | ||
|
|
4118a86c0d | ||
|
|
928d6f3821 | ||
|
|
b2ade568c8 | ||
|
|
27820ce897 | ||
|
|
fea7e66996 | ||
|
|
474d1571ae | ||
|
|
2ef627b87e | ||
|
|
2dfb82b623 | ||
|
|
ccd7fdfd52 | ||
|
|
f92e59ed34 | ||
|
|
d29477349a | ||
|
|
259e480baa | ||
|
|
0055dd1142 | ||
|
|
61c44780f0 | ||
|
|
9710d3b15c | ||
|
|
04cefebd75 | ||
|
|
dbd927c002 | ||
|
|
e6b2116a2b | ||
|
|
855a02091f | ||
|
|
358434429e | ||
|
|
b00061d85e | ||
|
|
022f08c05e |
@@ -144,6 +144,12 @@ GOOGLE_WEBHOOK_TOKEN=
|
||||
# Optional URL to override for tunelling webhooks. Defaults to NEXT_PUBLIC_WEBAPP_URL.
|
||||
GOOGLE_WEBHOOK_URL=
|
||||
|
||||
# Token to verify incoming webhooks from Microsoft Calendar
|
||||
MICROSOFT_WEBHOOK_TOKEN=
|
||||
|
||||
# Optional URL to override for tunelling webhooks. Defaults to NEXT_PUBLIC_WEBAPP_URL.
|
||||
MICROSOFT_WEBHOOK_URL=
|
||||
|
||||
# Inbox to send user feedback
|
||||
SEND_FEEDBACK_EMAIL=
|
||||
|
||||
@@ -261,6 +267,9 @@ NEXT_PUBLIC_CLOUDFLARE_SITEKEY=
|
||||
NEXT_PUBLIC_CLOUDFLARE_USE_TURNSTILE_IN_BOOKER=
|
||||
CLOUDFLARE_TURNSTILE_SECRET=
|
||||
|
||||
# 0 = false, 1=true
|
||||
NEXT_PUBLIC_VERCEL_USE_BOTID_IN_BOOKER=
|
||||
|
||||
# Set the following value to true if you wish to enable Team Impersonation
|
||||
NEXT_PUBLIC_TEAM_IMPERSONATION=false
|
||||
|
||||
@@ -473,3 +482,7 @@ DATABASE_CHUNK_SIZE=
|
||||
# Service Account Encryption Key for encrypting/decrypting service account keys
|
||||
# You can use: `openssl rand -base64 24` to generate one
|
||||
CALCOM_SERVICE_ACCOUNT_ENCRYPTION_KEY=
|
||||
|
||||
SALESFORCE_GRAPHQL_DELAY_MS=500
|
||||
SALESFORCE_GRAPHQL_MAX_DELAY_MS=2000
|
||||
SALESFORCE_GRAPHQL_MAX_RETRIES=3
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
/packages/app-store/office365calendar/**/* @calcom/Foundation
|
||||
/packages/app-store/zohocalendar/**/* @calcom/Foundation
|
||||
/packages/embeds/**/* @calcom/Foundation
|
||||
/packages/features/auth/lib/next-auth-options.ts @calcom/Foundation
|
||||
/packages/features/bookings/lib/**/* @calcom/Foundation
|
||||
/packages/lib/getAggregatedAvailability.ts @calcom/Foundation
|
||||
/packages/lib/getUserAvailability.ts @calcom/Foundation
|
||||
|
||||
@@ -82,7 +82,7 @@ jobs:
|
||||
with:
|
||||
base: https://raw.githubusercontent.com/calcom/cal.com/refs/heads/main/docs/api-reference/v2/openapi.json
|
||||
revision: docs/api-reference/v2/openapi.json
|
||||
fail-on: WARN
|
||||
fail-on: ERR
|
||||
|
||||
- name: Run Tests
|
||||
working-directory: apps/api/v2
|
||||
|
||||
Vendored
Vendored
Vendored
Vendored
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
undecided:
|
||||
- "@calcom/prisma"
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
undecided:
|
||||
- calcom-monorepo
|
||||
Vendored
@@ -1,7 +1,7 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getUserAvailabilityService } from "@calcom/lib/di/containers/GetUserAvailability";
|
||||
import { getUserAvailabilityService } from "@calcom/features/di/containers/GetUserAvailability";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { NextApiRequest } from "next";
|
||||
import {
|
||||
getRecordingsOfCalVideoByRoomName,
|
||||
getDownloadLinkOfCalVideoByRecordingId,
|
||||
} from "@calcom/app-store/videoClient";
|
||||
} from "@calcom/features/conferencing/lib/videoClient";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { NextApiRequest } from "next";
|
||||
import {
|
||||
getTranscriptsAccessLinkFromRecordingId,
|
||||
checkIfRoomNameMatchesInRecording,
|
||||
} from "@calcom/app-store/videoClient";
|
||||
} from "@calcom/features/conferencing/lib/videoClient";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { getAllTranscriptsAccessLinkFromRoomName } from "@calcom/app-store/videoClient";
|
||||
import { getAllTranscriptsAccessLinkFromRoomName } from "@calcom/features/conferencing/lib/videoClient";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { getRegularBookingService } from "@calcom/features/bookings/di/RegularBookingService.container";
|
||||
import getBookingDataSchemaForApi from "@calcom/features/bookings/lib/getBookingDataSchemaForApi";
|
||||
import handleNewBooking from "@calcom/features/bookings/lib/handleNewBooking";
|
||||
import { ErrorCode } from "@calcom/lib/errorCodes";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
@@ -239,15 +239,17 @@ async function handler(req: NextApiRequest) {
|
||||
}
|
||||
|
||||
try {
|
||||
return await handleNewBooking(
|
||||
{
|
||||
bookingData: req.body,
|
||||
const regularBookingService = getRegularBookingService();
|
||||
|
||||
return await regularBookingService.createBookingForApiV1({
|
||||
bookingData: req.body,
|
||||
bookingMeta: {
|
||||
userId,
|
||||
hostname: req.headers.host || "",
|
||||
forcedSlug: req.headers["x-cal-force-slug"] as string | undefined,
|
||||
},
|
||||
getBookingDataSchemaForApi
|
||||
);
|
||||
bookingDataSchemaGetter: getBookingDataSchemaForApi,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
const knownError = error as Error;
|
||||
if (knownError?.message === ErrorCode.NoAvailableUsersFound) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import type { UserWithCalendars } from "@calcom/lib/getConnectedDestinationCalendars";
|
||||
import { getConnectedDestinationCalendarsAndEnsureDefaultsInDb } from "@calcom/lib/getConnectedDestinationCalendars";
|
||||
import type { UserWithCalendars } from "@calcom/features/calendars/lib/getConnectedDestinationCalendars";
|
||||
import { getConnectedDestinationCalendarsAndEnsureDefaultsInDb } from "@calcom/features/calendars/lib/getConnectedDestinationCalendars";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { isSupportedTimeZone } from "@calcom/lib/dayjs";
|
||||
import { getAvailableSlotsService } from "@calcom/lib/di/containers/AvailableSlots";
|
||||
import { getAvailableSlotsService } from "@calcom/features/di/containers/AvailableSlots";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
import { createContext } from "@calcom/trpc/server/createContext";
|
||||
|
||||
@@ -4,6 +4,7 @@ import { purchaseTeamOrOrgSubscription } from "@calcom/features/ee/teams/lib/pay
|
||||
import { IS_TEAM_BILLING_ENABLED } from "@calcom/lib/constants";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
|
||||
@@ -61,24 +62,24 @@ export async function patchHandler(req: NextApiRequest) {
|
||||
const { teamId } = schemaQueryTeamId.parse(req.query);
|
||||
|
||||
/** Only OWNERS and ADMINS can edit teams */
|
||||
const _team = await prisma.team.findFirst({
|
||||
const team = await prisma.team.findFirst({
|
||||
// eslint-disable-next-line @calcom/eslint/no-prisma-include-true
|
||||
include: { members: true },
|
||||
where: { id: teamId, members: { some: { userId, role: { in: ["OWNER", "ADMIN"] } } } },
|
||||
});
|
||||
if (!_team) throw new HttpError({ statusCode: 401, message: "Unauthorized: OWNER or ADMIN required" });
|
||||
if (!team) throw new HttpError({ statusCode: 401, message: "Unauthorized: OWNER or ADMIN required" });
|
||||
|
||||
const slugAlreadyExists = await prisma.team.findFirst({
|
||||
where: {
|
||||
slug: {
|
||||
mode: "insensitive",
|
||||
equals: data.slug,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (slugAlreadyExists && data.slug !== _team.slug)
|
||||
throw new HttpError({ statusCode: 409, message: "Team slug already exists" });
|
||||
if (data.slug) {
|
||||
const teamRepository = new TeamRepository(prisma);
|
||||
const isSlugAvailable = await teamRepository.isSlugAvailableForUpdate({
|
||||
slug: data.slug,
|
||||
teamId: team.id,
|
||||
parentId: team.parentId,
|
||||
});
|
||||
if (!isSlugAvailable) {
|
||||
throw new HttpError({ statusCode: 409, message: "Team slug already exists" });
|
||||
}
|
||||
}
|
||||
|
||||
// Check if parentId is related to this user
|
||||
if (data.parentId && data.parentId === teamId) {
|
||||
@@ -99,16 +100,16 @@ export async function patchHandler(req: NextApiRequest) {
|
||||
}
|
||||
|
||||
let paymentUrl;
|
||||
if (_team.slug === null && data.slug) {
|
||||
if (team.slug === null && data.slug) {
|
||||
data.metadata = {
|
||||
...(_team.metadata as Prisma.JsonObject),
|
||||
...(team.metadata as Prisma.JsonObject),
|
||||
requestedSlug: data.slug,
|
||||
};
|
||||
delete data.slug;
|
||||
if (IS_TEAM_BILLING_ENABLED) {
|
||||
const checkoutSession = await purchaseTeamOrOrgSubscription({
|
||||
teamId: _team.id,
|
||||
seatsUsed: _team.members.length,
|
||||
teamId: team.id,
|
||||
seatsUsed: team.members.length,
|
||||
userId,
|
||||
pricePerSeat: null,
|
||||
});
|
||||
@@ -131,9 +132,9 @@ export async function patchHandler(req: NextApiRequest) {
|
||||
bookingLimits: data.bookingLimits === null ? {} : data.bookingLimits,
|
||||
metadata: data.metadata === null ? {} : data.metadata || undefined,
|
||||
};
|
||||
const team = await prisma.team.update({ where: { id: teamId }, data: cloneData });
|
||||
const updatedTeam = await prisma.team.update({ where: { id: teamId }, data: cloneData });
|
||||
const result = {
|
||||
team: schemaTeamReadPublic.parse(team),
|
||||
team: schemaTeamReadPublic.parse(updatedTeam),
|
||||
paymentUrl,
|
||||
};
|
||||
if (!paymentUrl) {
|
||||
|
||||
@@ -9,7 +9,7 @@ import { buildBooking } from "@calcom/lib/test/builder";
|
||||
import {
|
||||
getRecordingsOfCalVideoByRoomName,
|
||||
getDownloadLinkOfCalVideoByRecordingId,
|
||||
} from "@calcom/app-store/videoClient";
|
||||
} from "@calcom/features/conferencing/lib/videoClient";
|
||||
|
||||
import { getAccessibleUsers } from "~/lib/utils/retrieveScopedAccessibleUsers";
|
||||
|
||||
@@ -22,7 +22,7 @@ type CustomNextApiResponse = NextApiResponse & Response;
|
||||
const adminUserId = 1;
|
||||
const memberUserId = 10;
|
||||
|
||||
vi.mock("@calcom/app-store/videoClient", () => {
|
||||
vi.mock("@calcom/features/conferencing/lib/videoClient", () => {
|
||||
return {
|
||||
getRecordingsOfCalVideoByRoomName: vi.fn(),
|
||||
getDownloadLinkOfCalVideoByRecordingId: vi.fn(),
|
||||
|
||||
@@ -8,7 +8,7 @@ import { describe, expect, test, vi, afterEach } from "vitest";
|
||||
import {
|
||||
getTranscriptsAccessLinkFromRecordingId,
|
||||
checkIfRoomNameMatchesInRecording,
|
||||
} from "@calcom/app-store/videoClient";
|
||||
} from "@calcom/features/conferencing/lib/videoClient";
|
||||
import { buildBooking } from "@calcom/lib/test/builder";
|
||||
|
||||
import { getAccessibleUsers } from "~/lib/utils/retrieveScopedAccessibleUsers";
|
||||
@@ -19,7 +19,7 @@ import handler from "../../../../../../pages/api/bookings/[id]/transcripts/[reco
|
||||
type CustomNextApiRequest = NextApiRequest & Request;
|
||||
type CustomNextApiResponse = NextApiResponse & Response;
|
||||
|
||||
vi.mock("@calcom/app-store/videoClient", () => {
|
||||
vi.mock("@calcom/features/conferencing/lib/videoClient", () => {
|
||||
return {
|
||||
getTranscriptsAccessLinkFromRecordingId: vi.fn(),
|
||||
checkIfRoomNameMatchesInRecording: vi.fn(),
|
||||
|
||||
@@ -6,7 +6,7 @@ import { createMocks } from "node-mocks-http";
|
||||
import { describe, expect, test, vi, afterEach } from "vitest";
|
||||
|
||||
import { buildBooking } from "@calcom/lib/test/builder";
|
||||
import { getAllTranscriptsAccessLinkFromRoomName } from "@calcom/app-store/videoClient";
|
||||
import { getAllTranscriptsAccessLinkFromRoomName } from "@calcom/features/conferencing/lib/videoClient";
|
||||
|
||||
import { getAccessibleUsers } from "~/lib/utils/retrieveScopedAccessibleUsers";
|
||||
|
||||
@@ -16,7 +16,7 @@ import handler from "../../../../../pages/api/bookings/[id]/transcripts/_get";
|
||||
type CustomNextApiRequest = NextApiRequest & Request;
|
||||
type CustomNextApiResponse = NextApiResponse & Response;
|
||||
|
||||
vi.mock("@calcom/app-store/videoClient", () => {
|
||||
vi.mock("@calcom/features/conferencing/lib/videoClient", () => {
|
||||
return {
|
||||
getAllTranscriptsAccessLinkFromRoomName: vi.fn(),
|
||||
};
|
||||
|
||||
@@ -76,7 +76,7 @@ vi.mock("@calcom/features/watchlist/operations/check-if-users-are-blocked.contro
|
||||
checkIfUsersAreBlocked: vi.fn().mockResolvedValue(false),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/di/containers/QualifiedHosts", () => ({
|
||||
vi.mock("@calcom/features/di/containers/QualifiedHosts", () => ({
|
||||
getQualifiedHostsService: vi.fn().mockReturnValue({
|
||||
findQualifiedHostsWithDelegationCredentials: vi.fn().mockResolvedValue({
|
||||
qualifiedRRHosts: [],
|
||||
|
||||
@@ -6,6 +6,7 @@ import { createMocks } from "node-mocks-http";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import type { User } from "@calcom/prisma/client";
|
||||
|
||||
import handler from "../../../pages/api/selected-calendars/_post";
|
||||
|
||||
@@ -72,7 +73,7 @@ describe("POST /api/selected-calendars", () => {
|
||||
|
||||
prismaMock.user.findFirstOrThrow.mockResolvedValue({
|
||||
id: 444444,
|
||||
} as any);
|
||||
} as User);
|
||||
|
||||
prismaMock.selectedCalendar.create.mockResolvedValue({
|
||||
credentialId: 1,
|
||||
@@ -95,6 +96,16 @@ describe("POST /api/selected-calendars", () => {
|
||||
unwatchAttempts: 0,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
channelId: null,
|
||||
channelKind: null,
|
||||
channelResourceId: null,
|
||||
channelResourceUri: null,
|
||||
channelExpiration: null,
|
||||
syncSubscribedAt: null,
|
||||
syncToken: null,
|
||||
syncedAt: null,
|
||||
syncErrorAt: null,
|
||||
syncErrorCount: null,
|
||||
});
|
||||
|
||||
await handler(req, res);
|
||||
@@ -140,6 +151,16 @@ describe("POST /api/selected-calendars", () => {
|
||||
unwatchAttempts: 0,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
channelId: null,
|
||||
channelKind: null,
|
||||
channelResourceId: null,
|
||||
channelResourceUri: null,
|
||||
channelExpiration: null,
|
||||
syncSubscribedAt: null,
|
||||
syncToken: null,
|
||||
syncedAt: null,
|
||||
syncErrorAt: null,
|
||||
syncErrorCount: null,
|
||||
});
|
||||
|
||||
await handler(req, res);
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import prismock from "../../../../../../tests/libs/__mocks__/prisma";
|
||||
|
||||
import type { NextApiRequest } from "next";
|
||||
import { describe, expect, it, beforeEach } from "vitest";
|
||||
|
||||
import { WatchlistSeverity } from "@calcom/prisma/enums";
|
||||
|
||||
import { isLockedOrBlocked } from "../../../lib/utils/isLockedOrBlocked";
|
||||
|
||||
describe("isLockedOrBlocked", () => {
|
||||
@@ -18,7 +17,6 @@ describe("isLockedOrBlocked", () => {
|
||||
{
|
||||
type: "DOMAIN",
|
||||
value: "blocked.com",
|
||||
severity: WatchlistSeverity.CRITICAL,
|
||||
createdById: 1,
|
||||
},
|
||||
],
|
||||
@@ -26,13 +24,13 @@ describe("isLockedOrBlocked", () => {
|
||||
});
|
||||
|
||||
it("should return false if no user in request", async () => {
|
||||
const req = { userId: null, user: null } as any;
|
||||
const req = { userId: null, user: null } as unknown as NextApiRequest;
|
||||
const result = await isLockedOrBlocked(req);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false if user has no email", async () => {
|
||||
const req = { userId: 123, user: { email: null } } as any;
|
||||
const req = { userId: 123, user: { email: null } } as unknown as NextApiRequest;
|
||||
const result = await isLockedOrBlocked(req);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
@@ -44,7 +42,7 @@ describe("isLockedOrBlocked", () => {
|
||||
locked: true,
|
||||
email: "test@example.com",
|
||||
},
|
||||
} as any;
|
||||
} as unknown as NextApiRequest;
|
||||
|
||||
const result = await isLockedOrBlocked(req);
|
||||
expect(result).toBe(true);
|
||||
@@ -57,7 +55,7 @@ describe("isLockedOrBlocked", () => {
|
||||
locked: false,
|
||||
email: "test@blocked.com",
|
||||
},
|
||||
} as any;
|
||||
} as unknown as NextApiRequest;
|
||||
|
||||
const result = await isLockedOrBlocked(req);
|
||||
expect(result).toBe(true);
|
||||
@@ -70,7 +68,7 @@ describe("isLockedOrBlocked", () => {
|
||||
locked: false,
|
||||
email: "test@example.com",
|
||||
},
|
||||
} as any;
|
||||
} as unknown as NextApiRequest;
|
||||
|
||||
const result = await isLockedOrBlocked(req);
|
||||
expect(result).toBe(false);
|
||||
@@ -83,7 +81,7 @@ describe("isLockedOrBlocked", () => {
|
||||
locked: false,
|
||||
email: "test@BLOCKED.COM",
|
||||
},
|
||||
} as any;
|
||||
} as unknown as NextApiRequest;
|
||||
|
||||
const result = await isLockedOrBlocked(req);
|
||||
expect(result).toBe(true);
|
||||
|
||||
@@ -6,6 +6,9 @@ import { CalendarsService } from "@/ee/calendars/services/calendars.service";
|
||||
import { EventTypesModule_2024_04_15 } from "@/ee/event-types/event-types_2024_04_15/event-types.module";
|
||||
import { EventTypesModule_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.module";
|
||||
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
|
||||
import { InstantBookingModule } from "@/lib/modules/instant-booking.module";
|
||||
import { RecurringBookingModule } from "@/lib/modules/recurring-booking.module";
|
||||
import { RegularBookingModule } from "@/lib/modules/regular-booking.module";
|
||||
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
|
||||
import { AppsRepository } from "@/modules/apps/apps.repository";
|
||||
import { BillingModule } from "@/modules/billing/billing.module";
|
||||
@@ -35,6 +38,9 @@ import { Module } from "@nestjs/common";
|
||||
SchedulesModule_2024_04_15,
|
||||
EventTypesModule_2024_06_14,
|
||||
ProfilesModule,
|
||||
RegularBookingModule,
|
||||
RecurringBookingModule,
|
||||
InstantBookingModule,
|
||||
],
|
||||
providers: [
|
||||
TokensRepository,
|
||||
|
||||
@@ -21,7 +21,7 @@ import { randomString } from "test/utils/randomString";
|
||||
import { withApiAuth } from "test/utils/withApiAuth";
|
||||
|
||||
import { SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||
import { handleNewBooking } from "@calcom/platform-libraries";
|
||||
import { type RegularBookingCreateResult } from "@calcom/platform-libraries/bookings";
|
||||
import type { ApiSuccessResponse, ApiErrorResponse } from "@calcom/platform-types";
|
||||
import type { User } from "@calcom/prisma/client";
|
||||
|
||||
@@ -41,7 +41,7 @@ describe("Bookings Endpoints 2024-04-15", () => {
|
||||
|
||||
let eventTypeId: number;
|
||||
|
||||
let createdBooking: Awaited<ReturnType<typeof handleNewBooking>>;
|
||||
let createdBooking: RegularBookingCreateResult;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await withApiAuth(
|
||||
@@ -131,8 +131,7 @@ describe("Bookings Endpoints 2024-04-15", () => {
|
||||
.send(body)
|
||||
.expect(201)
|
||||
.then(async (response) => {
|
||||
const responseBody: ApiSuccessResponse<Awaited<ReturnType<typeof handleNewBooking>>> =
|
||||
response.body;
|
||||
const responseBody: ApiSuccessResponse<RegularBookingCreateResult> = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
expect(responseBody.data.userPrimaryEmail).toBeDefined();
|
||||
@@ -231,8 +230,7 @@ describe("Bookings Endpoints 2024-04-15", () => {
|
||||
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
|
||||
.expect(201)
|
||||
.then(async (response) => {
|
||||
const responseBody: ApiSuccessResponse<Awaited<ReturnType<typeof handleNewBooking>>> =
|
||||
response.body;
|
||||
const responseBody: ApiSuccessResponse<RegularBookingCreateResult> = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
expect(responseBody.data.userPrimaryEmail).toBeDefined();
|
||||
@@ -289,8 +287,7 @@ describe("Bookings Endpoints 2024-04-15", () => {
|
||||
.send(body)
|
||||
.expect(201)
|
||||
.then(async (response) => {
|
||||
const responseBody: ApiSuccessResponse<Awaited<ReturnType<typeof handleNewBooking>>> =
|
||||
response.body;
|
||||
const responseBody: ApiSuccessResponse<RegularBookingCreateResult> = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
expect(responseBody.data.userPrimaryEmail).toBeDefined();
|
||||
@@ -387,8 +384,7 @@ describe("Bookings Endpoints 2024-04-15", () => {
|
||||
.send(body)
|
||||
.expect(201)
|
||||
.then(async (response) => {
|
||||
const responseBody: ApiSuccessResponse<Awaited<ReturnType<typeof handleNewBooking>>> =
|
||||
response.body;
|
||||
const responseBody: ApiSuccessResponse<RegularBookingCreateResult> = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
expect(responseBody.data.userPrimaryEmail).toBeDefined();
|
||||
|
||||
@@ -7,6 +7,9 @@ import { MarkNoShowOutput_2024_04_15 } from "@/ee/bookings/2024-04-15/outputs/ma
|
||||
import { PlatformBookingsService } from "@/ee/bookings/shared/platform-bookings.service";
|
||||
import { sha256Hash, isApiKey, stripApiKey } from "@/lib/api-key";
|
||||
import { VERSION_2024_04_15, VERSION_2024_06_11, VERSION_2024_06_14 } from "@/lib/api-versions";
|
||||
import { InstantBookingCreateService } from "@/lib/services/instant-booking-create.service";
|
||||
import { RecurringBookingService } from "@/lib/services/recurring-booking.service";
|
||||
import { RegularBookingService } from "@/lib/services/regular-booking.service";
|
||||
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
|
||||
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
|
||||
import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";
|
||||
@@ -45,11 +48,8 @@ import { v4 as uuidv4 } from "uuid";
|
||||
import { X_CAL_CLIENT_ID, X_CAL_PLATFORM_EMBED } from "@calcom/platform-constants";
|
||||
import { BOOKING_READ, SUCCESS_STATUS, BOOKING_WRITE } from "@calcom/platform-constants";
|
||||
import {
|
||||
handleNewRecurringBooking,
|
||||
handleNewBooking,
|
||||
BookingResponse,
|
||||
HttpError,
|
||||
handleInstantMeeting,
|
||||
handleMarkNoShow,
|
||||
getAllUserBookings,
|
||||
getBookingInfo,
|
||||
@@ -58,6 +58,7 @@ import {
|
||||
ErrorCode,
|
||||
} from "@calcom/platform-libraries";
|
||||
import { CreationSource } from "@calcom/platform-libraries";
|
||||
import { type InstantBookingCreateResult } from "@calcom/platform-libraries/bookings";
|
||||
import {
|
||||
GetBookingsInput_2024_04_15,
|
||||
CancelBookingInput_2024_04_15,
|
||||
@@ -109,7 +110,10 @@ export class BookingsController_2024_04_15 {
|
||||
private readonly apiKeyRepository: ApiKeysRepository,
|
||||
private readonly platformBookingsService: PlatformBookingsService,
|
||||
private readonly usersRepository: UsersRepository,
|
||||
private readonly usersService: UsersService
|
||||
private readonly usersService: UsersService,
|
||||
private readonly regularBookingService: RegularBookingService,
|
||||
private readonly recurringBookingService: RecurringBookingService,
|
||||
private readonly instantBookingCreateService: InstantBookingCreateService
|
||||
) {}
|
||||
|
||||
@Get("/")
|
||||
@@ -187,17 +191,19 @@ export class BookingsController_2024_04_15 {
|
||||
const { orgSlug, locationUrl } = body;
|
||||
try {
|
||||
const bookingRequest = await this.createNextApiBookingRequest(req, oAuthClientId, locationUrl, isEmbed);
|
||||
const booking = await handleNewBooking({
|
||||
const booking = await this.regularBookingService.createBooking({
|
||||
bookingData: bookingRequest.body,
|
||||
userId: bookingRequest.userId,
|
||||
hostname: bookingRequest.headers?.host || "",
|
||||
forcedSlug: orgSlug,
|
||||
platformClientId: bookingRequest.platformClientId,
|
||||
platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
|
||||
platformCancelUrl: bookingRequest.platformCancelUrl,
|
||||
platformBookingUrl: bookingRequest.platformBookingUrl,
|
||||
platformBookingLocation: bookingRequest.platformBookingLocation,
|
||||
areCalendarEventsEnabled: bookingRequest.areCalendarEventsEnabled,
|
||||
bookingMeta: {
|
||||
userId: bookingRequest.userId,
|
||||
hostname: bookingRequest.headers?.host || "",
|
||||
forcedSlug: orgSlug,
|
||||
platformClientId: bookingRequest.platformClientId,
|
||||
platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
|
||||
platformCancelUrl: bookingRequest.platformCancelUrl,
|
||||
platformBookingUrl: bookingRequest.platformBookingUrl,
|
||||
platformBookingLocation: bookingRequest.platformBookingLocation,
|
||||
areCalendarEventsEnabled: bookingRequest.areCalendarEventsEnabled,
|
||||
},
|
||||
});
|
||||
if (booking.userId && booking.uid && booking.startTime) {
|
||||
void (await this.billingService.increaseUsageByUserId(booking.userId, {
|
||||
@@ -315,15 +321,17 @@ export class BookingsController_2024_04_15 {
|
||||
|
||||
const bookingRequest = await this.createNextApiBookingRequest(req, oAuthClientId, undefined, isEmbed);
|
||||
|
||||
const createdBookings: BookingResponse[] = await handleNewRecurringBooking({
|
||||
const createdBookings: BookingResponse[] = await this.recurringBookingService.createBooking({
|
||||
bookingData: bookingRequest.body,
|
||||
userId: bookingRequest.userId,
|
||||
hostname: bookingRequest.headers?.host || "",
|
||||
platformClientId: bookingRequest.platformClientId,
|
||||
platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
|
||||
platformCancelUrl: bookingRequest.platformCancelUrl,
|
||||
platformBookingUrl: bookingRequest.platformBookingUrl,
|
||||
platformBookingLocation: bookingRequest.platformBookingLocation,
|
||||
bookingMeta: {
|
||||
userId: bookingRequest.userId,
|
||||
hostname: bookingRequest.headers?.host || "",
|
||||
platformClientId: bookingRequest.platformClientId,
|
||||
platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
|
||||
platformCancelUrl: bookingRequest.platformCancelUrl,
|
||||
platformBookingUrl: bookingRequest.platformBookingUrl,
|
||||
platformBookingLocation: bookingRequest.platformBookingLocation,
|
||||
},
|
||||
});
|
||||
|
||||
createdBookings.forEach(async (booking) => {
|
||||
@@ -351,14 +359,15 @@ export class BookingsController_2024_04_15 {
|
||||
@Body() body: CreateBookingInput_2024_04_15,
|
||||
@Headers(X_CAL_CLIENT_ID) clientId?: string,
|
||||
@Headers(X_CAL_PLATFORM_EMBED) isEmbed?: string
|
||||
): Promise<ApiResponse<Awaited<ReturnType<typeof handleInstantMeeting>>>> {
|
||||
): Promise<ApiResponse<InstantBookingCreateResult>> {
|
||||
const oAuthClientId =
|
||||
clientId?.toString() || (await this.getOAuthClientIdFromEventType(body.eventTypeId));
|
||||
req.userId = (await this.getOwnerId(req)) ?? -1;
|
||||
try {
|
||||
const instantMeeting = await handleInstantMeeting(
|
||||
await this.createNextApiBookingRequest(req, oAuthClientId, undefined, isEmbed)
|
||||
);
|
||||
const bookingReq = await this.createNextApiBookingRequest(req, oAuthClientId, undefined, isEmbed);
|
||||
const instantMeeting = await this.instantBookingCreateService.createBooking({
|
||||
bookingData: bookingReq.body,
|
||||
});
|
||||
|
||||
if (instantMeeting.userId && instantMeeting.bookingUid) {
|
||||
const now = new Date();
|
||||
|
||||
@@ -16,6 +16,9 @@ import { EventTypesModule_2024_04_15 } from "@/ee/event-types/event-types_2024_0
|
||||
import { EventTypesModule_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.module";
|
||||
import { EventTypesRepository_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.repository";
|
||||
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
|
||||
import { InstantBookingModule } from "@/lib/modules/instant-booking.module";
|
||||
import { RecurringBookingModule } from "@/lib/modules/recurring-booking.module";
|
||||
import { RegularBookingModule } from "@/lib/modules/regular-booking.module";
|
||||
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
|
||||
import { AppsRepository } from "@/modules/apps/apps.repository";
|
||||
import { BillingModule } from "@/modules/billing/billing.module";
|
||||
@@ -58,6 +61,9 @@ import { Module } from "@nestjs/common";
|
||||
TeamsEventTypesModule,
|
||||
MembershipsModule,
|
||||
ProfilesModule,
|
||||
RegularBookingModule,
|
||||
RecurringBookingModule,
|
||||
InstantBookingModule,
|
||||
],
|
||||
providers: [
|
||||
TokensRepository,
|
||||
|
||||
@@ -87,7 +87,7 @@ import {
|
||||
@DocsTags("Bookings")
|
||||
@ApiHeader({
|
||||
name: "cal-api-version",
|
||||
description: `Must be set to ${VERSION_2024_08_13}`,
|
||||
description: `Must be set to ${VERSION_2024_08_13}. If not set to this value, the endpoint will default to an older version.`,
|
||||
example: VERSION_2024_08_13,
|
||||
required: true,
|
||||
schema: {
|
||||
@@ -133,6 +133,8 @@ export class BookingsController_2024_08_13 {
|
||||
|
||||
If you are creating a seated booking for an event type with 'show attendees' disabled, then to retrieve attendees in the response either set 'show attendees' to true on event type level or
|
||||
you have to provide an authentication method of event type owner, host, team admin or owner or org admin or owner.
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
@ApiBody({
|
||||
@@ -188,6 +190,8 @@ export class BookingsController_2024_08_13 {
|
||||
|
||||
If you are fetching a seated booking for an event type with 'show attendees' disabled, then to retrieve attendees in the response either set 'show attendees' to true on event type level or
|
||||
you have to provide an authentication method of event type owner, host, team admin or owner or org admin or owner.
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
async getBooking(
|
||||
@@ -206,7 +210,10 @@ export class BookingsController_2024_08_13 {
|
||||
@UseGuards(BookingUidGuard)
|
||||
@ApiOperation({
|
||||
summary: "Get all the recordings for the booking",
|
||||
description: `Fetches all the recordings for the booking \`:bookingUid\``,
|
||||
description: `Fetches all the recordings for the booking \`:bookingUid\`
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
async getBookingRecordings(@Param("bookingUid") bookingUid: string): Promise<GetBookingRecordingsOutput> {
|
||||
const recordings = await this.calVideoService.getRecordings(bookingUid);
|
||||
@@ -221,7 +228,10 @@ export class BookingsController_2024_08_13 {
|
||||
@UseGuards(BookingUidGuard)
|
||||
@ApiOperation({
|
||||
summary: "Get all the transcripts download links for the booking",
|
||||
description: `Fetches all the transcripts download links for the booking \`:bookingUid\``,
|
||||
description: `Fetches all the transcripts download links for the booking \`:bookingUid\`
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
async getBookingTranscripts(@Param("bookingUid") bookingUid: string): Promise<GetBookingTranscriptsOutput> {
|
||||
const transcripts = await this.calVideoService.getTranscripts(bookingUid);
|
||||
@@ -236,7 +246,10 @@ export class BookingsController_2024_08_13 {
|
||||
@UseGuards(ApiAuthGuard)
|
||||
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
|
||||
@Permissions([BOOKING_READ])
|
||||
@ApiOperation({ summary: "Get all bookings" })
|
||||
@ApiOperation({
|
||||
summary: "Get all bookings",
|
||||
description: `<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>`,
|
||||
})
|
||||
async getBookings(
|
||||
@Query() queryParams: GetBookingsInput_2024_08_13,
|
||||
@GetUser() user: ApiAuthGuardUser
|
||||
@@ -263,7 +276,10 @@ export class BookingsController_2024_08_13 {
|
||||
@ApiHeader(OPTIONAL_API_KEY_OR_ACCESS_TOKEN_HEADER)
|
||||
@ApiOperation({
|
||||
summary: "Reschedule a booking",
|
||||
description: "Reschedule a booking or seated booking",
|
||||
description: `Reschedule a booking or seated booking
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
@ApiBody({
|
||||
schema: {
|
||||
@@ -315,6 +331,8 @@ export class BookingsController_2024_08_13 {
|
||||
|
||||
If you are cancelling a seated booking for an event type with 'show attendees' disabled, then to retrieve attendees in the response either set 'show attendees' to true on event type level or
|
||||
you have to provide an authentication method of event type owner, host, team admin or owner or org admin or owner.
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
@ApiBody({
|
||||
@@ -350,7 +368,10 @@ export class BookingsController_2024_08_13 {
|
||||
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
|
||||
@ApiOperation({
|
||||
summary: "Mark a booking absence",
|
||||
description: "The provided authorization header refers to the owner of the booking.",
|
||||
description: `The provided authorization header refers to the owner of the booking.
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
async markNoShow(
|
||||
@Param("bookingUid") bookingUid: string,
|
||||
@@ -372,8 +393,10 @@ export class BookingsController_2024_08_13 {
|
||||
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
|
||||
@ApiOperation({
|
||||
summary: "Reassign a booking to auto-selected host",
|
||||
description:
|
||||
"Currently only supports reassigning host for round robin bookings. The provided authorization header refers to the owner of the booking.",
|
||||
description: `Currently only supports reassigning host for round robin bookings. The provided authorization header refers to the owner of the booking.
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
async reassignBooking(
|
||||
@Param("bookingUid") bookingUid: string,
|
||||
@@ -394,8 +417,10 @@ export class BookingsController_2024_08_13 {
|
||||
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
|
||||
@ApiOperation({
|
||||
summary: "Reassign a booking to a specific host",
|
||||
description:
|
||||
"Currently only supports reassigning host for round robin bookings. The provided authorization header refers to the owner of the booking.",
|
||||
description: `Currently only supports reassigning host for round robin bookings. The provided authorization header refers to the owner of the booking.
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
async reassignBookingToUser(
|
||||
@Param("bookingUid") bookingUid: string,
|
||||
@@ -423,7 +448,10 @@ export class BookingsController_2024_08_13 {
|
||||
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
|
||||
@ApiOperation({
|
||||
summary: "Confirm a booking",
|
||||
description: "The provided authorization header refers to the owner of the booking.",
|
||||
description: `The provided authorization header refers to the owner of the booking.
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
async confirmBooking(
|
||||
@Param("bookingUid") bookingUid: string,
|
||||
@@ -444,7 +472,10 @@ export class BookingsController_2024_08_13 {
|
||||
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
|
||||
@ApiOperation({
|
||||
summary: "Decline a booking",
|
||||
description: "The provided authorization header refers to the owner of the booking.",
|
||||
description: `The provided authorization header refers to the owner of the booking.
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
async declineBooking(
|
||||
@Param("bookingUid") bookingUid: string,
|
||||
@@ -465,8 +496,10 @@ export class BookingsController_2024_08_13 {
|
||||
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
|
||||
@ApiOperation({
|
||||
summary: "Get 'Add to Calendar' links for a booking",
|
||||
description:
|
||||
"Retrieve calendar links for a booking that can be used to add the event to various calendar services. Returns links for Google Calendar, Microsoft Office, Microsoft Outlook, and a downloadable ICS file.",
|
||||
description: `Retrieve calendar links for a booking that can be used to add the event to various calendar services. Returns links for Google Calendar, Microsoft Office, Microsoft Outlook, and a downloadable ICS file.
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async getCalendarLinks(@Param("bookingUid") bookingUid: string): Promise<CalendarLinksOutput_2024_08_13> {
|
||||
@@ -485,6 +518,7 @@ export class BookingsController_2024_08_13 {
|
||||
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
|
||||
@ApiOperation({
|
||||
summary: "Get booking references",
|
||||
description: `<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>`,
|
||||
})
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async getBookingReferences(
|
||||
|
||||
@@ -65,6 +65,8 @@ describe("Bookings Endpoints 2024-08-13", () => {
|
||||
let team1EventTypeId: number;
|
||||
let team2EventTypeId: number;
|
||||
let phoneOnlyEventTypeId: number;
|
||||
let collectiveEventWithoutHostsId: number;
|
||||
let roundRobinEventWithoutHostsId: number;
|
||||
|
||||
const team1EventTypeSlug = `team-bookings-event-type-${randomString()}`;
|
||||
const team2EventTypeSlug = `team-bookings-event-type-${randomString()}`;
|
||||
@@ -223,6 +225,28 @@ describe("Bookings Endpoints 2024-08-13", () => {
|
||||
|
||||
team1EventTypeId = team1EventType.id;
|
||||
|
||||
const team1CollectiveEventTypeWithoutHosts = await eventTypesRepositoryFixture.createTeamEventType({
|
||||
schedulingType: "COLLECTIVE",
|
||||
team: {
|
||||
connect: { id: team1.id },
|
||||
},
|
||||
title: `team-bookings-2024-08-13-collective-event-type-without-hosts-${randomString()}`,
|
||||
slug: `team-bookings-2024-08-13-collective-event-type-without-hosts-${randomString()}`,
|
||||
length: 60,
|
||||
});
|
||||
collectiveEventWithoutHostsId = team1CollectiveEventTypeWithoutHosts.id;
|
||||
|
||||
const team1RoundRobinEventTypeWithoutHosts = await eventTypesRepositoryFixture.createTeamEventType({
|
||||
schedulingType: "ROUND_ROBIN",
|
||||
team: {
|
||||
connect: { id: team1.id },
|
||||
},
|
||||
title: `team-bookings-2024-08-13-round-robin-event-type-without-hosts-${randomString()}`,
|
||||
slug: `team-bookings-2024-08-13-round-robin-event-type-without-hosts-${randomString()}`,
|
||||
length: 60,
|
||||
});
|
||||
roundRobinEventWithoutHostsId = team1RoundRobinEventTypeWithoutHosts.id;
|
||||
|
||||
const phoneOnlyEventType = await eventTypesRepositoryFixture.createTeamEventType({
|
||||
schedulingType: "ROUND_ROBIN",
|
||||
team: {
|
||||
@@ -363,6 +387,52 @@ describe("Bookings Endpoints 2024-08-13", () => {
|
||||
await app.init();
|
||||
});
|
||||
|
||||
describe("cant book event types without hosts", () => {
|
||||
it("should fail to book a collective event type without hosts", async () => {
|
||||
const body: CreateBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2030, 0, 8, 13, 0, 0)).toISOString(),
|
||||
eventTypeId: collectiveEventWithoutHostsId,
|
||||
attendee: {
|
||||
name: "alice",
|
||||
timeZone: "Europe/Madrid",
|
||||
email: "alice@gmail.com",
|
||||
},
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(body)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(response.status).toBe(422);
|
||||
expect(response.body.error.message).toBe(
|
||||
`Can't book this team event type because it has no hosts. Please, add at least 1 host to event type with id=${collectiveEventWithoutHostsId} belonging to team with id=${team1.id} and try again.`
|
||||
);
|
||||
});
|
||||
|
||||
it("should fail to book a round robin event type without hosts", async () => {
|
||||
const body: CreateBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2030, 0, 8, 13, 0, 0)).toISOString(),
|
||||
eventTypeId: roundRobinEventWithoutHostsId,
|
||||
attendee: {
|
||||
name: "alice",
|
||||
timeZone: "Europe/Madrid",
|
||||
email: "alice@gmail.com",
|
||||
},
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(body)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(response.status).toBe(422);
|
||||
expect(response.body.error.message).toBe(
|
||||
`Can't book this team event type because it has no hosts. Please, add at least 1 host to event type with id=${roundRobinEventWithoutHostsId} belonging to team with id=${team1.id} and try again.`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("create team bookings", () => {
|
||||
it("should create a team 1 booking", async () => {
|
||||
const body: CreateBookingInput_2024_08_13 = {
|
||||
@@ -765,8 +835,8 @@ describe("Bookings Endpoints 2024-08-13", () => {
|
||||
return client;
|
||||
}
|
||||
|
||||
function responseDataIsBooking(data: any): data is BookingOutput_2024_08_13 {
|
||||
return !Array.isArray(data) && typeof data === "object" && data && "id" in data;
|
||||
function responseDataIsBooking(data: unknown): data is BookingOutput_2024_08_13 {
|
||||
return !Array.isArray(data) && typeof data === "object" && data !== null && data && "id" in data;
|
||||
}
|
||||
|
||||
afterAll(async () => {
|
||||
|
||||
@@ -6,6 +6,9 @@ import { OutputBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/servi
|
||||
import { PlatformBookingsService } from "@/ee/bookings/shared/platform-bookings.service";
|
||||
import { EventTypesRepository_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.repository";
|
||||
import { getPagination } from "@/lib/pagination/pagination";
|
||||
import { InstantBookingCreateService } from "@/lib/services/instant-booking-create.service";
|
||||
import { RecurringBookingService } from "@/lib/services/recurring-booking.service";
|
||||
import { RegularBookingService } from "@/lib/services/regular-booking.service";
|
||||
import { AuthOptionalUser } from "@/modules/auth/decorators/get-optional-user/get-optional-user.decorator";
|
||||
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
|
||||
import { BillingService } from "@/modules/billing/services/billing.service";
|
||||
@@ -29,6 +32,7 @@ import {
|
||||
Logger,
|
||||
NotFoundException,
|
||||
UnauthorizedException,
|
||||
UnprocessableEntityException,
|
||||
} from "@nestjs/common";
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
@@ -36,10 +40,8 @@ import { DateTime } from "luxon";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
handleNewRecurringBooking,
|
||||
getTranslation,
|
||||
getAllUserBookings,
|
||||
handleInstantMeeting,
|
||||
handleCancelBooking,
|
||||
roundRobinReassignment,
|
||||
roundRobinManualReassignment,
|
||||
@@ -47,7 +49,6 @@ import {
|
||||
confirmBookingHandler,
|
||||
getCalendarLinks,
|
||||
} from "@calcom/platform-libraries";
|
||||
import { handleNewBooking } from "@calcom/platform-libraries";
|
||||
import {
|
||||
CreateBookingInput_2024_08_13,
|
||||
CreateBookingInput,
|
||||
@@ -108,7 +109,10 @@ export class BookingsService_2024_08_13 {
|
||||
private readonly teamsEventTypesRepository: TeamsEventTypesRepository,
|
||||
private readonly membershipsRepository: MembershipsRepository,
|
||||
private readonly membershipsService: MembershipsService,
|
||||
private readonly errorsBookingsService: ErrorsBookingsService_2024_08_13
|
||||
private readonly errorsBookingsService: ErrorsBookingsService_2024_08_13,
|
||||
private readonly regularBookingService: RegularBookingService,
|
||||
private readonly recurringBookingService: RecurringBookingService,
|
||||
private readonly instantBookingCreateService: InstantBookingCreateService
|
||||
) {}
|
||||
|
||||
async createBooking(request: Request, body: CreateBookingInput, authUser: AuthOptionalUser) {
|
||||
@@ -132,6 +136,10 @@ export class BookingsService_2024_08_13 {
|
||||
);
|
||||
}
|
||||
|
||||
if (eventType.schedulingType === "COLLECTIVE" || eventType.schedulingType === "ROUND_ROBIN") {
|
||||
await this.checkEventTypeHasHosts(eventType.id);
|
||||
}
|
||||
|
||||
body.eventTypeId = eventType.id;
|
||||
|
||||
if ("instant" in body && body.instant) {
|
||||
@@ -159,6 +167,15 @@ export class BookingsService_2024_08_13 {
|
||||
}
|
||||
}
|
||||
|
||||
async checkEventTypeHasHosts(eventTypeId: number) {
|
||||
const eventType = await this.eventTypesRepository.getEventTypeWithHosts(eventTypeId);
|
||||
if (!eventType?.hosts?.length) {
|
||||
throw new UnprocessableEntityException(
|
||||
`Can't book this team event type because it has no hosts. Please, add at least 1 host to event type with id=${eventTypeId} belonging to team with id=${eventType?.teamId} and try again.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async checkBookingRequiresAuthenticationSetting(
|
||||
eventType: EventTypeWithOwnerAndTeam,
|
||||
authUser: AuthOptionalUser,
|
||||
@@ -450,7 +467,9 @@ export class BookingsService_2024_08_13 {
|
||||
}
|
||||
|
||||
const bookingRequest = await this.inputService.createBookingRequest(request, body, eventType);
|
||||
const booking = await handleInstantMeeting(bookingRequest);
|
||||
const booking = await this.instantBookingCreateService.createBooking({
|
||||
bookingData: bookingRequest.body,
|
||||
});
|
||||
|
||||
const databaseBooking = await this.bookingsRepository.getByIdWithAttendeesAndUserAndEvent(
|
||||
booking.bookingId
|
||||
@@ -468,17 +487,19 @@ export class BookingsService_2024_08_13 {
|
||||
eventType: EventTypeWithOwnerAndTeam
|
||||
) {
|
||||
const bookingRequest = await this.inputService.createRecurringBookingRequest(request, body, eventType);
|
||||
const bookings = await handleNewRecurringBooking({
|
||||
const bookings = await this.recurringBookingService.createBooking({
|
||||
bookingData: bookingRequest.body,
|
||||
userId: bookingRequest.userId,
|
||||
hostname: bookingRequest.headers?.host || "",
|
||||
platformClientId: bookingRequest.platformClientId,
|
||||
platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
|
||||
platformCancelUrl: bookingRequest.platformCancelUrl,
|
||||
platformBookingUrl: bookingRequest.platformBookingUrl,
|
||||
platformBookingLocation: bookingRequest.platformBookingLocation,
|
||||
noEmail: bookingRequest.noEmail,
|
||||
areCalendarEventsEnabled: bookingRequest.areCalendarEventsEnabled,
|
||||
bookingMeta: {
|
||||
userId: bookingRequest.userId,
|
||||
hostname: bookingRequest.headers?.host || "",
|
||||
platformClientId: bookingRequest.platformClientId,
|
||||
platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
|
||||
platformCancelUrl: bookingRequest.platformCancelUrl,
|
||||
platformBookingUrl: bookingRequest.platformBookingUrl,
|
||||
platformBookingLocation: bookingRequest.platformBookingLocation,
|
||||
noEmail: bookingRequest.noEmail,
|
||||
areCalendarEventsEnabled: bookingRequest.areCalendarEventsEnabled,
|
||||
},
|
||||
});
|
||||
const ids = bookings.map((booking) => booking.id || 0);
|
||||
return this.outputService.getOutputRecurringBookings(ids);
|
||||
@@ -491,16 +512,18 @@ export class BookingsService_2024_08_13 {
|
||||
userIsEventTypeAdminOrOwner: boolean
|
||||
) {
|
||||
const bookingRequest = await this.inputService.createRecurringBookingRequest(request, body, eventType);
|
||||
const bookings = await handleNewRecurringBooking({
|
||||
const bookings = await this.recurringBookingService.createBooking({
|
||||
bookingData: bookingRequest.body,
|
||||
userId: bookingRequest.userId,
|
||||
hostname: bookingRequest.headers?.host || "",
|
||||
platformClientId: bookingRequest.platformClientId,
|
||||
platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
|
||||
platformCancelUrl: bookingRequest.platformCancelUrl,
|
||||
platformBookingUrl: bookingRequest.platformBookingUrl,
|
||||
platformBookingLocation: bookingRequest.platformBookingLocation,
|
||||
areCalendarEventsEnabled: bookingRequest.areCalendarEventsEnabled,
|
||||
bookingMeta: {
|
||||
userId: bookingRequest.userId,
|
||||
hostname: bookingRequest.headers?.host || "",
|
||||
platformClientId: bookingRequest.platformClientId,
|
||||
platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
|
||||
platformCancelUrl: bookingRequest.platformCancelUrl,
|
||||
platformBookingUrl: bookingRequest.platformBookingUrl,
|
||||
platformBookingLocation: bookingRequest.platformBookingLocation,
|
||||
areCalendarEventsEnabled: bookingRequest.areCalendarEventsEnabled,
|
||||
},
|
||||
});
|
||||
return this.outputService.getOutputCreateRecurringSeatedBookings(
|
||||
bookings.map((booking) => ({ uid: booking.uid || "", seatUid: booking.seatReferenceUid || "" })),
|
||||
@@ -514,16 +537,18 @@ export class BookingsService_2024_08_13 {
|
||||
eventType: EventTypeWithOwnerAndTeam
|
||||
) {
|
||||
const bookingRequest = await this.inputService.createBookingRequest(request, body, eventType);
|
||||
const booking = await handleNewBooking({
|
||||
const booking = await this.regularBookingService.createBooking({
|
||||
bookingData: bookingRequest.body,
|
||||
userId: bookingRequest.userId,
|
||||
hostname: bookingRequest.headers?.host || "",
|
||||
platformClientId: bookingRequest.platformClientId,
|
||||
platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
|
||||
platformCancelUrl: bookingRequest.platformCancelUrl,
|
||||
platformBookingUrl: bookingRequest.platformBookingUrl,
|
||||
platformBookingLocation: bookingRequest.platformBookingLocation,
|
||||
areCalendarEventsEnabled: bookingRequest.areCalendarEventsEnabled,
|
||||
bookingMeta: {
|
||||
userId: bookingRequest.userId,
|
||||
hostname: bookingRequest.headers?.host || "",
|
||||
platformClientId: bookingRequest.platformClientId,
|
||||
platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
|
||||
platformCancelUrl: bookingRequest.platformCancelUrl,
|
||||
platformBookingUrl: bookingRequest.platformBookingUrl,
|
||||
platformBookingLocation: bookingRequest.platformBookingLocation,
|
||||
areCalendarEventsEnabled: bookingRequest.areCalendarEventsEnabled,
|
||||
},
|
||||
});
|
||||
|
||||
if (!booking.uid) {
|
||||
@@ -546,16 +571,18 @@ export class BookingsService_2024_08_13 {
|
||||
) {
|
||||
const bookingRequest = await this.inputService.createBookingRequest(request, body, eventType);
|
||||
try {
|
||||
const booking = await handleNewBooking({
|
||||
const booking = await this.regularBookingService.createBooking({
|
||||
bookingData: bookingRequest.body,
|
||||
userId: bookingRequest.userId,
|
||||
hostname: bookingRequest.headers?.host || "",
|
||||
platformClientId: bookingRequest.platformClientId,
|
||||
platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
|
||||
platformCancelUrl: bookingRequest.platformCancelUrl,
|
||||
platformBookingUrl: bookingRequest.platformBookingUrl,
|
||||
platformBookingLocation: bookingRequest.platformBookingLocation,
|
||||
areCalendarEventsEnabled: bookingRequest.areCalendarEventsEnabled,
|
||||
bookingMeta: {
|
||||
userId: bookingRequest.userId,
|
||||
hostname: bookingRequest.headers?.host || "",
|
||||
platformClientId: bookingRequest.platformClientId,
|
||||
platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
|
||||
platformCancelUrl: bookingRequest.platformCancelUrl,
|
||||
platformBookingUrl: bookingRequest.platformBookingUrl,
|
||||
platformBookingLocation: bookingRequest.platformBookingLocation,
|
||||
areCalendarEventsEnabled: bookingRequest.areCalendarEventsEnabled,
|
||||
},
|
||||
});
|
||||
|
||||
if (!booking.uid) {
|
||||
@@ -741,16 +768,18 @@ export class BookingsService_2024_08_13 {
|
||||
bookingUid,
|
||||
body
|
||||
);
|
||||
const booking = await handleNewBooking({
|
||||
const booking = await this.regularBookingService.createBooking({
|
||||
bookingData: bookingRequest.body,
|
||||
userId: bookingRequest.userId,
|
||||
hostname: bookingRequest.headers?.host || "",
|
||||
platformClientId: bookingRequest.platformClientId,
|
||||
platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
|
||||
platformCancelUrl: bookingRequest.platformCancelUrl,
|
||||
platformBookingUrl: bookingRequest.platformBookingUrl,
|
||||
platformBookingLocation: bookingRequest.platformBookingLocation,
|
||||
areCalendarEventsEnabled: bookingRequest.areCalendarEventsEnabled,
|
||||
bookingMeta: {
|
||||
userId: bookingRequest.userId,
|
||||
hostname: bookingRequest.headers?.host || "",
|
||||
platformClientId: bookingRequest.platformClientId,
|
||||
platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
|
||||
platformCancelUrl: bookingRequest.platformCancelUrl,
|
||||
platformBookingUrl: bookingRequest.platformBookingUrl,
|
||||
platformBookingLocation: bookingRequest.platformBookingLocation,
|
||||
areCalendarEventsEnabled: bookingRequest.areCalendarEventsEnabled,
|
||||
},
|
||||
});
|
||||
if (!booking.uid) {
|
||||
throw new Error("Booking missing uid");
|
||||
|
||||
+21
-7
@@ -61,7 +61,7 @@ import {
|
||||
@DocsTags("Event Types")
|
||||
@ApiHeader({
|
||||
name: "cal-api-version",
|
||||
description: `Must be set to ${VERSION_2024_06_14}`,
|
||||
description: `Must be set to ${VERSION_2024_06_14}. If not set to this value, the endpoint will default to an older version.`,
|
||||
example: VERSION_2024_06_14,
|
||||
required: true,
|
||||
schema: {
|
||||
@@ -80,7 +80,10 @@ export class EventTypesController_2024_06_14 {
|
||||
@Permissions([EVENT_TYPE_WRITE])
|
||||
@UseGuards(ApiAuthGuard)
|
||||
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
|
||||
@ApiOperation({ summary: "Create an event type" })
|
||||
@ApiOperation({
|
||||
summary: "Create an event type",
|
||||
description: `<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>`,
|
||||
})
|
||||
async createEventType(
|
||||
@Body() body: CreateEventTypeInput_2024_06_14,
|
||||
@GetUser() user: UserWithProfile
|
||||
@@ -102,7 +105,10 @@ export class EventTypesController_2024_06_14 {
|
||||
@Permissions([EVENT_TYPE_READ])
|
||||
@UseGuards(ApiAuthGuard)
|
||||
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
|
||||
@ApiOperation({ summary: "Get an event type" })
|
||||
@ApiOperation({
|
||||
summary: "Get an event type",
|
||||
description: `<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>`,
|
||||
})
|
||||
async getEventTypeById(
|
||||
@Param("eventTypeId") eventTypeId: string,
|
||||
@GetUser() user: UserWithProfile
|
||||
@@ -122,8 +128,10 @@ export class EventTypesController_2024_06_14 {
|
||||
@Get("/")
|
||||
@ApiOperation({
|
||||
summary: "Get all event types",
|
||||
description:
|
||||
"Hidden event types are returned only if authentication is provided and it belongs to the event type owner.",
|
||||
description: `Hidden event types are returned only if authentication is provided and it belongs to the event type owner.
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
@UseGuards(OptionalApiAuthGuard)
|
||||
@ApiHeader(OPTIONAL_X_CAL_CLIENT_ID_HEADER)
|
||||
@@ -149,7 +157,10 @@ export class EventTypesController_2024_06_14 {
|
||||
@UseGuards(ApiAuthGuard)
|
||||
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: "Update an event type" })
|
||||
@ApiOperation({
|
||||
summary: "Update an event type",
|
||||
description: `<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>`,
|
||||
})
|
||||
async updateEventType(
|
||||
@Param("eventTypeId", ParseIntPipe) eventTypeId: number,
|
||||
@Body() body: UpdateEventTypeInput_2024_06_14,
|
||||
@@ -173,7 +184,10 @@ export class EventTypesController_2024_06_14 {
|
||||
@Permissions([EVENT_TYPE_WRITE])
|
||||
@UseGuards(ApiAuthGuard)
|
||||
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
|
||||
@ApiOperation({ summary: "Delete an event type" })
|
||||
@ApiOperation({
|
||||
summary: "Delete an event type",
|
||||
description: `<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>`,
|
||||
})
|
||||
async deleteEventType(
|
||||
@Param("eventTypeId") eventTypeId: number,
|
||||
@GetUser("id") userId: number
|
||||
|
||||
+23
-6
@@ -40,7 +40,7 @@ import {
|
||||
@DocsTags("Schedules")
|
||||
@ApiHeader({
|
||||
name: "cal-api-version",
|
||||
description: `Must be set to ${VERSION_2024_06_11}`,
|
||||
description: `Must be set to ${VERSION_2024_06_11}. If not set to this value, the endpoint will default to an older version.`,
|
||||
example: VERSION_2024_06_11,
|
||||
required: true,
|
||||
schema: {
|
||||
@@ -69,6 +69,8 @@ export class SchedulesController_2024_06_11 {
|
||||
After creating a non-default schedule, you can update an event type to point to that schedule via the PATCH \`event-types/{eventTypeId}\` endpoint.
|
||||
|
||||
When specifying start time and end time for each day use the 24 hour format e.g. 08:00, 15:00 etc.
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
async createSchedule(
|
||||
@@ -91,7 +93,10 @@ export class SchedulesController_2024_06_11 {
|
||||
})
|
||||
@ApiOperation({
|
||||
summary: "Get default schedule",
|
||||
description: "Get the default schedule of the authenticated user.",
|
||||
description: `Get the default schedule of the authenticated user.
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
async getDefaultSchedule(@GetUser() user: UserWithProfile): Promise<GetScheduleOutput_2024_06_11> {
|
||||
const schedule = await this.schedulesService.getUserScheduleDefault(user.id);
|
||||
@@ -104,7 +109,10 @@ export class SchedulesController_2024_06_11 {
|
||||
|
||||
@Get("/:scheduleId")
|
||||
@Permissions([SCHEDULE_READ])
|
||||
@ApiOperation({ summary: "Get a schedule" })
|
||||
@ApiOperation({
|
||||
summary: "Get a schedule",
|
||||
description: `<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>`,
|
||||
})
|
||||
async getSchedule(
|
||||
@GetUser() user: UserWithProfile,
|
||||
@Param("scheduleId") scheduleId: number
|
||||
@@ -121,7 +129,10 @@ export class SchedulesController_2024_06_11 {
|
||||
@Permissions([SCHEDULE_READ])
|
||||
@ApiOperation({
|
||||
summary: "Get all schedules",
|
||||
description: "Get all schedules of the authenticated user.",
|
||||
description: `Get all schedules of the authenticated user.
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
async getSchedules(@GetUser() user: UserWithProfile): Promise<GetSchedulesOutput_2024_06_11> {
|
||||
const schedules = await this.schedulesService.getUserSchedules(user.id);
|
||||
@@ -134,7 +145,10 @@ export class SchedulesController_2024_06_11 {
|
||||
|
||||
@Patch("/:scheduleId")
|
||||
@Permissions([SCHEDULE_WRITE])
|
||||
@ApiOperation({ summary: "Update a schedule" })
|
||||
@ApiOperation({
|
||||
summary: "Update a schedule",
|
||||
description: `<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>`,
|
||||
})
|
||||
async updateSchedule(
|
||||
@GetUser() user: UserWithProfile,
|
||||
@Body() bodySchedule: UpdateScheduleInput_2024_06_11,
|
||||
@@ -155,7 +169,10 @@ export class SchedulesController_2024_06_11 {
|
||||
@Delete("/:scheduleId")
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Permissions([SCHEDULE_WRITE])
|
||||
@ApiOperation({ summary: "Delete a schedule" })
|
||||
@ApiOperation({
|
||||
summary: "Delete a schedule",
|
||||
description: `<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>`,
|
||||
})
|
||||
async deleteSchedule(
|
||||
@GetUser("id") userId: number,
|
||||
@Param("scheduleId") scheduleId: number
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { InstantBookingCreateService } from "@/lib/services/instant-booking-create.service";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
@Module({
|
||||
providers: [InstantBookingCreateService],
|
||||
exports: [InstantBookingCreateService],
|
||||
})
|
||||
export class InstantBookingModule {}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { RegularBookingModule } from "@/lib/modules/regular-booking.module";
|
||||
import { RecurringBookingService } from "@/lib/services/recurring-booking.service";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
@Module({
|
||||
imports: [RegularBookingModule],
|
||||
providers: [RecurringBookingService],
|
||||
exports: [RecurringBookingService],
|
||||
})
|
||||
export class RecurringBookingModule {}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { PrismaAttributeRepository } from "@/lib/repositories/prisma-attribute.repository";
|
||||
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
|
||||
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
|
||||
import { PrismaHostRepository } from "@/lib/repositories/prisma-host.repository";
|
||||
import { PrismaOOORepository } from "@/lib/repositories/prisma-ooo.repository";
|
||||
import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository";
|
||||
import { CacheService } from "@/lib/services/cache.service";
|
||||
import { CheckBookingAndDurationLimitsService } from "@/lib/services/check-booking-and-duration-limits.service";
|
||||
import { CheckBookingLimitsService } from "@/lib/services/check-booking-limits.service";
|
||||
import { LuckyUserService } from "@/lib/services/lucky-user.service";
|
||||
import { RegularBookingService } from "@/lib/services/regular-booking.service";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
providers: [
|
||||
PrismaAttributeRepository,
|
||||
PrismaBookingRepository,
|
||||
PrismaFeaturesRepository,
|
||||
PrismaHostRepository,
|
||||
PrismaOOORepository,
|
||||
PrismaUserRepository,
|
||||
CacheService,
|
||||
CheckBookingAndDurationLimitsService,
|
||||
CheckBookingLimitsService,
|
||||
LuckyUserService,
|
||||
RegularBookingService,
|
||||
],
|
||||
exports: [RegularBookingService],
|
||||
})
|
||||
export class RegularBookingModule {}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { InstantBookingCreateService as BaseInstantBookingCreateService } from "@calcom/platform-libraries/bookings";
|
||||
|
||||
@Injectable()
|
||||
export class InstantBookingCreateService extends BaseInstantBookingCreateService {}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { RegularBookingService } from "@/lib/services/regular-booking.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { RecurringBookingService as BaseRecurringBookingService } from "@calcom/platform-libraries/bookings";
|
||||
|
||||
@Injectable()
|
||||
export class RecurringBookingService extends BaseRecurringBookingService {
|
||||
constructor(regularBookingService: RegularBookingService) {
|
||||
super({
|
||||
regularBookingService,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { PrismaAttributeRepository } from "@/lib/repositories/prisma-attribute.repository";
|
||||
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
|
||||
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
|
||||
import { PrismaHostRepository } from "@/lib/repositories/prisma-host.repository";
|
||||
import { PrismaOOORepository } from "@/lib/repositories/prisma-ooo.repository";
|
||||
import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository";
|
||||
import { CacheService } from "@/lib/services/cache.service";
|
||||
import { CheckBookingAndDurationLimitsService } from "@/lib/services/check-booking-and-duration-limits.service";
|
||||
import { CheckBookingLimitsService } from "@/lib/services/check-booking-limits.service";
|
||||
import { LuckyUserService } from "@/lib/services/lucky-user.service";
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { RegularBookingService as BaseRegularBookingService } from "@calcom/platform-libraries/bookings";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
|
||||
@Injectable()
|
||||
export class RegularBookingService extends BaseRegularBookingService {
|
||||
constructor(
|
||||
cacheService: CacheService,
|
||||
checkBookingAndDurationLimitsService: CheckBookingAndDurationLimitsService,
|
||||
prismaWriteService: PrismaWriteService,
|
||||
bookingRepository: PrismaBookingRepository,
|
||||
featuresRepository: PrismaFeaturesRepository,
|
||||
checkBookingLimitsService: CheckBookingLimitsService,
|
||||
luckyUserService: LuckyUserService,
|
||||
hostRepository: PrismaHostRepository,
|
||||
oooRepository: PrismaOOORepository,
|
||||
userRepository: PrismaUserRepository,
|
||||
attributeRepository: PrismaAttributeRepository
|
||||
) {
|
||||
super({
|
||||
cacheService,
|
||||
checkBookingAndDurationLimitsService,
|
||||
prismaClient: prismaWriteService.prisma as unknown as PrismaClient,
|
||||
bookingRepository,
|
||||
featuresRepository,
|
||||
checkBookingLimitsService,
|
||||
luckyUserService,
|
||||
hostRepository,
|
||||
oooRepository,
|
||||
userRepository,
|
||||
attributeRepository,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
@Injectable()
|
||||
export class AtomsSecondaryEmailsRepository {
|
||||
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
|
||||
|
||||
async getSecondaryEmailsVerified(userId: number) {
|
||||
return await this.dbRead.prisma.secondaryEmail.findMany({
|
||||
where: {
|
||||
userId,
|
||||
emailVerified: {
|
||||
not: null,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async getExistingSecondaryEmailByUserAndEmail(userId: number, email: string) {
|
||||
const existingSecondaryEmailRecord = await this.dbRead.prisma.secondaryEmail.findUnique({
|
||||
where: {
|
||||
userId_email: { userId, email },
|
||||
},
|
||||
});
|
||||
|
||||
return existingSecondaryEmailRecord?.email;
|
||||
}
|
||||
|
||||
async getExistingSecondaryEmail(email: string) {
|
||||
const existingSecondaryEmailRecord = await this.dbRead.prisma.secondaryEmail.findUnique({
|
||||
where: {
|
||||
email,
|
||||
},
|
||||
});
|
||||
|
||||
return existingSecondaryEmailRecord?.email;
|
||||
}
|
||||
|
||||
async addSecondaryEmailVerified(userId: number, email: string) {
|
||||
const existingSecondaryEmailRecord = await this.dbWrite.prisma.secondaryEmail.create({
|
||||
data: {
|
||||
userId,
|
||||
email,
|
||||
emailVerified: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
return existingSecondaryEmailRecord?.email;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { EventTypesModule_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.module";
|
||||
import { AtomsSecondaryEmailsRepository } from "@/modules/atoms/atoms-secondary-emails.repository";
|
||||
import { AtomsRepository } from "@/modules/atoms/atoms.repository";
|
||||
import { AtomsConferencingAppsController } from "@/modules/atoms/controllers/atoms.conferencing-apps.controller";
|
||||
import { AtomsController } from "@/modules/atoms/controllers/atoms.controller";
|
||||
@@ -33,6 +34,7 @@ import { Module } from "@nestjs/common";
|
||||
CredentialsRepository,
|
||||
UsersRepository,
|
||||
AtomsRepository,
|
||||
AtomsSecondaryEmailsRepository,
|
||||
UsersService,
|
||||
SchedulesAtomsService,
|
||||
VerificationAtomsService,
|
||||
|
||||
@@ -64,47 +64,4 @@ export class AtomsRepository {
|
||||
|
||||
return userTeams;
|
||||
}
|
||||
|
||||
async getSecondaryEmails(userId: number) {
|
||||
return await this.dbRead.prisma.secondaryEmail.findMany({
|
||||
where: {
|
||||
userId,
|
||||
emailVerified: {
|
||||
not: null,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async getExistingSecondaryEmailByUserAndEmail(userId: number, email: string) {
|
||||
const existingSecondaryEmailRecord = await this.dbRead.prisma.secondaryEmail.findUnique({
|
||||
where: {
|
||||
userId_email: { userId, email },
|
||||
},
|
||||
});
|
||||
|
||||
return existingSecondaryEmailRecord?.email;
|
||||
}
|
||||
|
||||
async getExistingSecondaryEmail(email: string) {
|
||||
const existingSecondaryEmailRecord = await this.dbRead.prisma.secondaryEmail.findUnique({
|
||||
where: {
|
||||
email,
|
||||
},
|
||||
});
|
||||
|
||||
return existingSecondaryEmailRecord?.email;
|
||||
}
|
||||
|
||||
async addSecondaryEmail(userId: number, email: string) {
|
||||
const existingSecondaryEmailRecord = await this.dbWrite.prisma.secondaryEmail.create({
|
||||
data: {
|
||||
userId,
|
||||
email,
|
||||
emailVerified: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
return existingSecondaryEmailRecord?.email;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { AtomsRepository } from "@/modules/atoms/atoms.repository";
|
||||
import { AtomsSecondaryEmailsRepository } from "@/modules/atoms/atoms-secondary-emails.repository";
|
||||
import { CheckEmailVerificationRequiredParams } from "@/modules/atoms/inputs/check-email-verification-required-params";
|
||||
import { GetVerifiedEmailsInput } from "@/modules/atoms/inputs/get-verified-emails-params";
|
||||
import { SendVerificationEmailInput } from "@/modules/atoms/inputs/send-verification-email.input";
|
||||
import { VerifyEmailCodeInput } from "@/modules/atoms/inputs/verify-email-code.input";
|
||||
import { TeamsRepository } from "@/modules/teams/teams/teams.repository";
|
||||
import { UserWithProfile } from "@/modules/users/users.repository";
|
||||
import { UsersRepository } from "@/modules/users/users.repository";
|
||||
import { Injectable, BadRequestException, UnauthorizedException } from "@nestjs/common";
|
||||
|
||||
import {
|
||||
@@ -17,8 +17,8 @@ import {
|
||||
@Injectable()
|
||||
export class VerificationAtomsService {
|
||||
constructor(
|
||||
private readonly atomsRepository: AtomsRepository,
|
||||
private readonly teamsRepository: TeamsRepository
|
||||
private readonly atomsSecondaryEmailsRepository: AtomsSecondaryEmailsRepository,
|
||||
private readonly usersRepository: UsersRepository
|
||||
) {}
|
||||
|
||||
async checkEmailVerificationRequired(input: CheckEmailVerificationRequiredParams) {
|
||||
@@ -76,7 +76,8 @@ export class VerificationAtomsService {
|
||||
|
||||
if (teamId) {
|
||||
const verifiedEmails: string[] = [];
|
||||
const teamMembers = await this.teamsRepository.getTeamMemberEmails(teamId);
|
||||
|
||||
const teamMembers = await this.usersRepository.getUserEmailsVerifiedForTeam(teamId);
|
||||
|
||||
if (teamMembers.length === 0) {
|
||||
return verifiedEmails;
|
||||
@@ -96,7 +97,7 @@ export class VerificationAtomsService {
|
||||
|
||||
let verifiedEmails = [userEmailWithoutOauthClientId];
|
||||
|
||||
const secondaryEmails = await this.atomsRepository.getSecondaryEmails(userId);
|
||||
const secondaryEmails = await this.atomsSecondaryEmailsRepository.getSecondaryEmailsVerified(userId);
|
||||
verifiedEmails = verifiedEmails.concat(
|
||||
secondaryEmails.map((secondaryEmail) => this.removeClientIdFromEmail(secondaryEmail.email))
|
||||
);
|
||||
@@ -113,11 +114,9 @@ export class VerificationAtomsService {
|
||||
existingPrimaryEmail: string;
|
||||
email: string;
|
||||
}): Promise<boolean> {
|
||||
const existingSecondaryEmail = await this.atomsRepository.getExistingSecondaryEmailByUserAndEmail(
|
||||
userId,
|
||||
email
|
||||
);
|
||||
const alreadyExistingEmail = await this.atomsRepository.getExistingSecondaryEmail(email);
|
||||
const existingSecondaryEmail =
|
||||
await this.atomsSecondaryEmailsRepository.getExistingSecondaryEmailByUserAndEmail(userId, email);
|
||||
const alreadyExistingEmail = await this.atomsSecondaryEmailsRepository.getExistingSecondaryEmail(email);
|
||||
|
||||
if (alreadyExistingEmail) {
|
||||
throw new BadRequestException("Email already exists");
|
||||
@@ -127,7 +126,7 @@ export class VerificationAtomsService {
|
||||
return true;
|
||||
}
|
||||
|
||||
await this.atomsRepository.addSecondaryEmail(userId, email);
|
||||
await this.atomsSecondaryEmailsRepository.addSecondaryEmailVerified(userId, email);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { PlatformPlan } from "@/modules/billing/types";
|
||||
import { hasMinimumPlan } from "@/modules/auth/guards/billing/platform-plan.guard";
|
||||
import { orderedPlans, PlatformPlan } from "@/modules/billing/types";
|
||||
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
|
||||
|
||||
@Injectable()
|
||||
export class ManagedOrganizationsBillingService {
|
||||
@@ -14,8 +15,18 @@ export class ManagedOrganizationsBillingService {
|
||||
if (!managerOrgBilling) {
|
||||
throw new NotFoundException("Manager organization billing not found.");
|
||||
}
|
||||
if (managerOrgBilling.plan !== PlatformPlan.SCALE) {
|
||||
throw new NotFoundException("Manager organization billing plan is not SCALE.");
|
||||
if (
|
||||
!hasMinimumPlan({
|
||||
currentPlan: managerOrgBilling.plan as PlatformPlan,
|
||||
minimumPlan: PlatformPlan.SCALE,
|
||||
plans: orderedPlans,
|
||||
})
|
||||
) {
|
||||
throw new ForbiddenException(
|
||||
`organization with id=${managerOrgId} does not have required plan for this operation. Minimum plan is ${
|
||||
PlatformPlan.SCALE
|
||||
} while the organization has ${managerOrgBilling.plan || "undefined"}.`
|
||||
);
|
||||
}
|
||||
|
||||
return this.dbWrite.prisma.platformBilling.create({
|
||||
|
||||
+109
-4
@@ -705,6 +705,111 @@ describe("OAuth Client Users Endpoints", () => {
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
describe("managed user time zone", () => {
|
||||
describe("negative tests", () => {
|
||||
it("should not allow '' time zone", async () => {
|
||||
const requestBody = {
|
||||
email: "whatever2@gmail.com",
|
||||
timeZone: "",
|
||||
name: "Bob Smithson",
|
||||
};
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post(`/api/v2/oauth-clients/${oAuthClient.id}/users`)
|
||||
.set("x-cal-secret-key", oAuthClient.secret)
|
||||
.send(requestBody)
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it("should not allow 'invalid-timezone' time zone", async () => {
|
||||
const requestBody = {
|
||||
email: "whatever2@gmail.com",
|
||||
timeZone: "invalid-timezone",
|
||||
name: "Bob Smithson",
|
||||
};
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post(`/api/v2/oauth-clients/${oAuthClient.id}/users`)
|
||||
.set("x-cal-secret-key", oAuthClient.secret)
|
||||
.send(requestBody)
|
||||
.expect(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("positive tests", () => {
|
||||
it("should allow null timezone", async () => {
|
||||
const requestBody = {
|
||||
email: "whatever1@gmail.com",
|
||||
timeZone: null,
|
||||
name: "Bob Smithson",
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/api/v2/oauth-clients/${oAuthClient.id}/users`)
|
||||
.set("x-cal-secret-key", oAuthClient.secret)
|
||||
.send(requestBody)
|
||||
.expect(201);
|
||||
|
||||
const responseBody: CreateManagedUserOutput = response.body;
|
||||
expect(responseBody.data.user.timeZone).toEqual("Europe/London");
|
||||
await userRepositoryFixture.delete(responseBody.data.user.id);
|
||||
});
|
||||
|
||||
it("should allow undefined time zone", async () => {
|
||||
const requestBody = {
|
||||
email: "whatever3@gmail.com",
|
||||
timeZone: undefined,
|
||||
name: "Bob Smithson",
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/api/v2/oauth-clients/${oAuthClient.id}/users`)
|
||||
.set("x-cal-secret-key", oAuthClient.secret)
|
||||
.send(requestBody)
|
||||
.expect(201);
|
||||
|
||||
const responseBody: CreateManagedUserOutput = response.body;
|
||||
expect(responseBody.data.user.timeZone).toEqual("Europe/London");
|
||||
await userRepositoryFixture.delete(responseBody.data.user.id);
|
||||
});
|
||||
|
||||
it("should allow valid time zone", async () => {
|
||||
const requestBody = {
|
||||
email: "whatever4@gmail.com",
|
||||
timeZone: "Europe/Rome",
|
||||
name: "Bob Smithson",
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/api/v2/oauth-clients/${oAuthClient.id}/users`)
|
||||
.set("x-cal-secret-key", oAuthClient.secret)
|
||||
.send(requestBody)
|
||||
.expect(201);
|
||||
|
||||
const responseBody: CreateManagedUserOutput = response.body;
|
||||
expect(responseBody.data.user.timeZone).toBe("Europe/Rome");
|
||||
await userRepositoryFixture.delete(responseBody.data.user.id);
|
||||
});
|
||||
|
||||
it("should allow without any time zone", async () => {
|
||||
const requestBody = {
|
||||
email: "whatever5@gmail.com",
|
||||
name: "Bob Smithson",
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/api/v2/oauth-clients/${oAuthClient.id}/users`)
|
||||
.set("x-cal-secret-key", oAuthClient.secret)
|
||||
.send(requestBody)
|
||||
.expect(201);
|
||||
|
||||
const responseBody: CreateManagedUserOutput = response.body;
|
||||
expect(responseBody.data.user.timeZone).toEqual("Europe/London");
|
||||
await userRepositoryFixture.delete(responseBody.data.user.id);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await oauthClientRepositoryFixture.delete(oAuthClient.id);
|
||||
await oauthClientRepositoryFixture.delete(oAuthClientEventTypesDisabled.id);
|
||||
@@ -712,17 +817,17 @@ describe("OAuth Client Users Endpoints", () => {
|
||||
try {
|
||||
await userRepositoryFixture.delete(postResponseData.user.id);
|
||||
} catch (e) {
|
||||
// User might have been deleted by the test
|
||||
console.log(e);
|
||||
}
|
||||
try {
|
||||
await userRepositoryFixture.delete(postResponseData2.user.id);
|
||||
} catch (e) {
|
||||
// User might have been deleted by the test
|
||||
console.log(e);
|
||||
}
|
||||
try {
|
||||
await userRepositoryFixture.delete(platformAdmin.id);
|
||||
} catch (e) {
|
||||
// User might have been deleted by the test
|
||||
console.log(e);
|
||||
}
|
||||
await app.close();
|
||||
});
|
||||
@@ -931,7 +1036,7 @@ describe("OAuth Client Users Endpoints", () => {
|
||||
try {
|
||||
await userRepositoryFixture.delete(postResponseData.user.id);
|
||||
} catch (e) {
|
||||
// User might have been deleted by the test
|
||||
console.log(e);
|
||||
}
|
||||
await app.close();
|
||||
});
|
||||
|
||||
+132
-45
@@ -61,11 +61,24 @@ describe("Organizations Organizations Endpoints", () => {
|
||||
let profilesRepositoryFixture: ProfileRepositoryFixture;
|
||||
|
||||
let managerOrg: Team;
|
||||
let payPerUserPlanManagerOrg: Team;
|
||||
let essentialsPlanManagerOrg: Team;
|
||||
|
||||
let managedOrg: ManagedOrganizationWithApiKeyOutput;
|
||||
let managedOrg2: ManagedOrganizationWithApiKeyOutput;
|
||||
|
||||
const managerOrgAdminEmail = `organizations-organizations-admin-${randomString()}@api.com`;
|
||||
const payPerUserPlanManagerOrgAdminEmail = `organizations-organizations-admin-${randomString()}@api.com`;
|
||||
const essentialsPlanManagerOrgAdminEmail = `organizations-organizations-admin-${randomString()}@api.com`;
|
||||
|
||||
let managerOrgAdmin: User;
|
||||
let payPerUserPlanManagerOrgAdmin: User;
|
||||
let essentialsPlanManagerOrgAdmin: User;
|
||||
|
||||
let managerOrgAdminApiKey: string;
|
||||
let payPerUserPlanManagerOrgAdminApiKey: string;
|
||||
let essentialsPlanManagerOrgAdminApiKey: string;
|
||||
|
||||
let managerOrgBilling: PlatformBilling;
|
||||
|
||||
let managedOrgApiKey: string;
|
||||
@@ -93,40 +106,36 @@ describe("Organizations Organizations Endpoints", () => {
|
||||
oAuthClientsRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
|
||||
profilesRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
|
||||
|
||||
managerOrgAdmin = await userRepositoryFixture.create({
|
||||
email: managerOrgAdminEmail,
|
||||
username: managerOrgAdminEmail,
|
||||
});
|
||||
|
||||
managerOrg = await organizationsRepositoryFixture.create({
|
||||
name: `organizations-organizations-organization-${randomString()}`,
|
||||
isOrganization: true,
|
||||
isPlatform: true,
|
||||
});
|
||||
|
||||
await profilesRepositoryFixture.create({
|
||||
uid: "asd-asd",
|
||||
username: managerOrgAdminEmail,
|
||||
user: { connect: { id: managerOrgAdmin.id } },
|
||||
organization: { connect: { id: managerOrg.id } },
|
||||
movedFromUser: { connect: { id: managerOrgAdmin.id } },
|
||||
});
|
||||
|
||||
managerOrgBilling = await platformBillingRepositoryFixture.create(managerOrg.id, "SCALE");
|
||||
|
||||
await membershipsRepositoryFixture.create({
|
||||
role: "ADMIN",
|
||||
user: { connect: { id: managerOrgAdmin.id } },
|
||||
team: { connect: { id: managerOrg.id } },
|
||||
accepted: true,
|
||||
});
|
||||
|
||||
const { keyString } = await apiKeysRepositoryFixture.createApiKey(
|
||||
managerOrgAdmin.id,
|
||||
null,
|
||||
managerOrg.id
|
||||
// Setup manager organization with SCALE plan
|
||||
const managerSetup = await setupTestOrganization(
|
||||
managerOrgAdminEmail,
|
||||
`organizations-organizations-organization-${randomString()}`,
|
||||
"SCALE"
|
||||
);
|
||||
managerOrgAdminApiKey = `cal_test_${keyString}`;
|
||||
managerOrgAdmin = managerSetup.admin;
|
||||
managerOrg = managerSetup.org;
|
||||
managerOrgBilling = managerSetup.billing;
|
||||
managerOrgAdminApiKey = managerSetup.apiKey;
|
||||
|
||||
// Setup pay-per-user organization
|
||||
const payPerUserSetup = await setupTestOrganization(
|
||||
payPerUserPlanManagerOrgAdminEmail,
|
||||
`pay-per-user-plan-organization-${randomString()}`,
|
||||
"PER_ACTIVE_USER"
|
||||
);
|
||||
payPerUserPlanManagerOrgAdmin = payPerUserSetup.admin;
|
||||
payPerUserPlanManagerOrg = payPerUserSetup.org;
|
||||
payPerUserPlanManagerOrgAdminApiKey = payPerUserSetup.apiKey;
|
||||
|
||||
// Setup essentials organization
|
||||
const essentialsSetup = await setupTestOrganization(
|
||||
essentialsPlanManagerOrgAdminEmail,
|
||||
`essentials-per-user-plan-organization-${randomString()}`,
|
||||
"ESSENTIALS"
|
||||
);
|
||||
essentialsPlanManagerOrgAdmin = essentialsSetup.admin;
|
||||
essentialsPlanManagerOrg = essentialsSetup.org;
|
||||
essentialsPlanManagerOrgAdminApiKey = essentialsSetup.apiKey;
|
||||
|
||||
app = moduleRef.createNestApplication();
|
||||
bootstrap(app as NestExpressApplication);
|
||||
@@ -136,6 +145,57 @@ describe("Organizations Organizations Endpoints", () => {
|
||||
await app.init();
|
||||
});
|
||||
|
||||
async function setupTestOrganization(
|
||||
adminEmail: string,
|
||||
orgName: string,
|
||||
plan: "SCALE" | "PER_ACTIVE_USER" | "ESSENTIALS"
|
||||
) {
|
||||
const admin = await userRepositoryFixture.create({
|
||||
email: adminEmail,
|
||||
username: adminEmail,
|
||||
});
|
||||
|
||||
const org = await organizationsRepositoryFixture.create({
|
||||
name: orgName,
|
||||
isOrganization: true,
|
||||
isPlatform: true,
|
||||
});
|
||||
|
||||
await profilesRepositoryFixture.create({
|
||||
uid: `${randomString()}-uid`,
|
||||
username: adminEmail,
|
||||
user: { connect: { id: admin.id } },
|
||||
organization: { connect: { id: org.id } },
|
||||
movedFromUser: { connect: { id: admin.id } },
|
||||
});
|
||||
|
||||
const billing = await platformBillingRepositoryFixture.create(org.id, plan);
|
||||
|
||||
await membershipsRepositoryFixture.create({
|
||||
role: "ADMIN",
|
||||
user: { connect: { id: admin.id } },
|
||||
team: { connect: { id: org.id } },
|
||||
accepted: true,
|
||||
});
|
||||
|
||||
const { keyString } = await apiKeysRepositoryFixture.createApiKey(admin.id, null, org.id);
|
||||
const apiKey = `cal_test_${keyString}`;
|
||||
|
||||
return { admin, org, billing, apiKey };
|
||||
}
|
||||
|
||||
function createManagedOrgInput(
|
||||
namePrefix: string,
|
||||
metadata?: Record<string, string | number | boolean>
|
||||
): CreateOrganizationInput {
|
||||
const suffix = randomString(5);
|
||||
return {
|
||||
name: `${namePrefix} ${suffix}`,
|
||||
slug: `${namePrefix.toLowerCase().replace(/\s+/g, "-")}-${suffix}`,
|
||||
metadata: metadata || { key: "value" },
|
||||
};
|
||||
}
|
||||
|
||||
afterAll(() => {
|
||||
clear();
|
||||
});
|
||||
@@ -155,21 +215,44 @@ describe("Organizations Organizations Endpoints", () => {
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
const suffix = randomString(5);
|
||||
const metadataKey = "first-org-metadata-key";
|
||||
const metadataValue = "first-org-metadata-value";
|
||||
const createManagedOrganizationBody: CreateOrganizationInput = {
|
||||
name: `org ${suffix}`,
|
||||
slug: `org-${suffix}`,
|
||||
metadata: { [metadataKey]: metadataValue },
|
||||
};
|
||||
const createManagedOrganizationBody: CreateOrganizationInput = createManagedOrgInput("org", {
|
||||
[metadataKey]: metadataValue,
|
||||
});
|
||||
|
||||
const suffix2 = randomString(5);
|
||||
const createManagedOrganizationBodySecond: CreateOrganizationInput = {
|
||||
name: `org2 ${suffix2}`,
|
||||
slug: `org2-${suffix2}`,
|
||||
metadata: { key: "value" },
|
||||
};
|
||||
const createManagedOrganizationBodySecond: CreateOrganizationInput = createManagedOrgInput("org2");
|
||||
|
||||
const createManagedOrganizationBodyThird: CreateOrganizationInput = createManagedOrgInput("org3");
|
||||
|
||||
it("should not allow to create managed organization if plan is below SCALE", async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/v2/organizations/${essentialsPlanManagerOrg.id}/organizations`)
|
||||
.set("Authorization", `Bearer ${essentialsPlanManagerOrgAdminApiKey}`)
|
||||
.send(createManagedOrganizationBody)
|
||||
.expect(403);
|
||||
expect(response.body.error.message).toBe(
|
||||
`PlatformPlanGuard - organization with id=${essentialsPlanManagerOrg.id} does not have required plan for this operation. Minimum plan is SCALE while the organization has ESSENTIALS.`
|
||||
);
|
||||
});
|
||||
|
||||
it("should allow to create managed organization if plan is SCALE or above", async () => {
|
||||
return request(app.getHttpServer())
|
||||
.post(`/v2/organizations/${payPerUserPlanManagerOrg.id}/organizations`)
|
||||
.set("Authorization", `Bearer ${payPerUserPlanManagerOrgAdminApiKey}`)
|
||||
.send(createManagedOrganizationBodyThird)
|
||||
.expect(201)
|
||||
.then(async (response) => {
|
||||
const responseBody: ApiSuccessResponse<ManagedOrganizationWithApiKeyOutput> = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
const managedOrg3 = responseBody.data;
|
||||
expect(managedOrg3?.id).toBeDefined();
|
||||
expect(managedOrg3?.name).toEqual(createManagedOrganizationBodyThird.name);
|
||||
expect(managedOrg3?.slug).toEqual(createManagedOrganizationBodyThird.slug);
|
||||
expect(managedOrg3?.metadata).toEqual(createManagedOrganizationBodyThird.metadata);
|
||||
expect(managedOrg3?.apiKey).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
it("should create managed organization", async () => {
|
||||
return request(app.getHttpServer())
|
||||
@@ -625,7 +708,11 @@ describe("Organizations Organizations Endpoints", () => {
|
||||
|
||||
afterAll(async () => {
|
||||
await userRepositoryFixture.deleteByEmail(managerOrgAdmin.email);
|
||||
await userRepositoryFixture.deleteByEmail(payPerUserPlanManagerOrgAdmin.email);
|
||||
await userRepositoryFixture.deleteByEmail(essentialsPlanManagerOrgAdmin.email);
|
||||
await organizationsRepositoryFixture.delete(managerOrg.id);
|
||||
await organizationsRepositoryFixture.delete(payPerUserPlanManagerOrg.id);
|
||||
await organizationsRepositoryFixture.delete(essentialsPlanManagerOrg.id);
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
|
||||
+205
-1
@@ -25,7 +25,12 @@ import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.
|
||||
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
||||
import { randomString } from "test/utils/randomString";
|
||||
|
||||
import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_09_04 } from "@calcom/platform-constants";
|
||||
import {
|
||||
CAL_API_VERSION_HEADER,
|
||||
SUCCESS_STATUS,
|
||||
VERSION_2024_09_04,
|
||||
ERROR_STATUS,
|
||||
} from "@calcom/platform-constants";
|
||||
import type {
|
||||
CreateScheduleInput_2024_06_11,
|
||||
ReserveSlotOutput_2024_09_04 as ReserveSlotOutputData_2024_09_04,
|
||||
@@ -48,6 +53,7 @@ describe("Slots 2024-09-04 Endpoints", () => {
|
||||
const teammateEmailOne = `slots-2024-09-04-user-1-team-slots-${randomString()}`;
|
||||
let teammateApiKeyString: string;
|
||||
const teammateEmailTwo = `slots-2024-09-04-user-2-team-slots-${randomString()}`;
|
||||
let teammateTwoApiKeyString: string;
|
||||
|
||||
const outsiderEmail = `slots-2024-09-04-unrelated-team-slots-${randomString()}`;
|
||||
let outsider: User;
|
||||
@@ -61,6 +67,8 @@ describe("Slots 2024-09-04 Endpoints", () => {
|
||||
let collectiveEventTypeSlug: string;
|
||||
let collectiveEventTypeWithoutHostsId: number;
|
||||
let roundRobinEventTypeId: number;
|
||||
let roundRobinEventTypeWithoutFixedHostsId: number;
|
||||
let roundRobinEventTypeWithFixedAndNonFixedHostsId: number;
|
||||
let collectiveBookingId: number;
|
||||
let roundRobinBookingId: number;
|
||||
let fullyBookedRoundRobinBookingIdOne: number;
|
||||
@@ -115,6 +123,12 @@ describe("Slots 2024-09-04 Endpoints", () => {
|
||||
const { keyString } = await apiKeysRepositoryFixture.createApiKey(teammateOne.id, null);
|
||||
teammateApiKeyString = keyString;
|
||||
|
||||
const { keyString: keyStringForTeammateTwo } = await apiKeysRepositoryFixture.createApiKey(
|
||||
teammateTwo.id,
|
||||
null
|
||||
);
|
||||
teammateTwoApiKeyString = keyStringForTeammateTwo;
|
||||
|
||||
const { keyString: unrelatedUserKeyString } = await apiKeysRepositoryFixture.createApiKey(
|
||||
outsider.id,
|
||||
null
|
||||
@@ -217,6 +231,67 @@ describe("Slots 2024-09-04 Endpoints", () => {
|
||||
});
|
||||
roundRobinEventTypeId = roundRobinEventType.id;
|
||||
|
||||
const roundRobinEventTypeWithoutFixedHosts = await eventTypesRepositoryFixture.createTeamEventType({
|
||||
schedulingType: "ROUND_ROBIN",
|
||||
team: {
|
||||
connect: { id: team.id },
|
||||
},
|
||||
title: "RR Event Type Without Fixed Hosts",
|
||||
slug: `slots-2024-09-04-round-robin-event-type-${randomString()}`,
|
||||
length: 60,
|
||||
assignAllTeamMembers: true,
|
||||
bookingFields: [],
|
||||
locations: [],
|
||||
users: {
|
||||
connect: [{ id: teammateOne.id }, { id: teammateTwo.id }],
|
||||
},
|
||||
hosts: {
|
||||
create: [
|
||||
{
|
||||
userId: teammateOne.id,
|
||||
isFixed: false,
|
||||
},
|
||||
{
|
||||
userId: teammateTwo.id,
|
||||
isFixed: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
roundRobinEventTypeWithoutFixedHostsId = roundRobinEventTypeWithoutFixedHosts.id;
|
||||
|
||||
const roundRobinEventTypeWithFixedAndNonFixedHosts =
|
||||
await eventTypesRepositoryFixture.createTeamEventType({
|
||||
schedulingType: "ROUND_ROBIN",
|
||||
team: {
|
||||
connect: { id: team.id },
|
||||
},
|
||||
title: "RR Event Type With Fixed and Non-Fixed Hosts",
|
||||
slug: `slots-2024-09-04-round-robin-event-type-${randomString()}`,
|
||||
length: 60,
|
||||
assignAllTeamMembers: true,
|
||||
bookingFields: [],
|
||||
locations: [],
|
||||
users: {
|
||||
connect: [{ id: teammateOne.id }, { id: teammateTwo.id }],
|
||||
},
|
||||
hosts: {
|
||||
create: [
|
||||
{
|
||||
userId: teammateOne.id,
|
||||
isFixed: true,
|
||||
},
|
||||
{
|
||||
userId: teammateTwo.id,
|
||||
isFixed: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
roundRobinEventTypeWithFixedAndNonFixedHostsId = roundRobinEventTypeWithFixedAndNonFixedHosts.id;
|
||||
|
||||
const userSchedule: CreateScheduleInput_2024_06_11 = {
|
||||
name: "working time",
|
||||
timeZone: "Europe/Rome",
|
||||
@@ -541,6 +616,135 @@ describe("Slots 2024-09-04 Endpoints", () => {
|
||||
bookingsRepositoryFixture.deleteById(bookingTwo.id);
|
||||
});
|
||||
|
||||
it("should reserve all available slots for round robin event type with non-fixed hosts", async () => {
|
||||
const now = "2049-09-05T12:00:00.000Z";
|
||||
const newDate = DateTime.fromISO(now, { zone: "UTC" }).toJSDate();
|
||||
advanceTo(newDate);
|
||||
|
||||
const slotStartTime = "2050-09-05T10:00:00.000Z";
|
||||
|
||||
const reserveResponseOne = await request(app.getHttpServer())
|
||||
.post(`/v2/slots/reservations`)
|
||||
.set({ Authorization: `Bearer cal_test_${teammateApiKeyString}` })
|
||||
.send({
|
||||
eventTypeId: roundRobinEventTypeWithoutFixedHostsId,
|
||||
slotStart: slotStartTime,
|
||||
reservationDuration: 10,
|
||||
})
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_09_04)
|
||||
.expect(201);
|
||||
|
||||
const reserveResponseOneBody: ReserveSlotOutputResponse_2024_09_04 = reserveResponseOne.body;
|
||||
expect(reserveResponseOneBody.status).toEqual(SUCCESS_STATUS);
|
||||
const responseReservedSlotOne: ReserveSlotOutputData_2024_09_04 = reserveResponseOneBody.data;
|
||||
expect(responseReservedSlotOne.reservationUid).toBeDefined();
|
||||
if (!responseReservedSlotOne.reservationUid) {
|
||||
throw new Error("Reserved slot one uid is undefined");
|
||||
}
|
||||
|
||||
const dbSlotOne = await selectedSlotRepositoryFixture.getByUid(responseReservedSlotOne.reservationUid);
|
||||
expect(dbSlotOne).toBeDefined();
|
||||
if (dbSlotOne) {
|
||||
const dbReleaseAt = DateTime.fromJSDate(dbSlotOne.releaseAt, { zone: "UTC" }).toISO();
|
||||
const expectedReleaseAt = DateTime.fromISO(now, { zone: "UTC" }).plus({ minutes: 10 }).toISO();
|
||||
expect(dbReleaseAt).toEqual(expectedReleaseAt);
|
||||
}
|
||||
|
||||
const reserveResponseTwo = await request(app.getHttpServer())
|
||||
.post(`/v2/slots/reservations`)
|
||||
.set({ Authorization: `Bearer cal_test_${teammateTwoApiKeyString}` })
|
||||
.send({
|
||||
eventTypeId: roundRobinEventTypeWithoutFixedHostsId,
|
||||
slotStart: slotStartTime,
|
||||
reservationDuration: 10,
|
||||
})
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_09_04)
|
||||
.expect(201);
|
||||
|
||||
const reserveResponseTwoBody: ReserveSlotOutputResponse_2024_09_04 = reserveResponseTwo.body;
|
||||
expect(reserveResponseTwoBody.status).toEqual(SUCCESS_STATUS);
|
||||
const responseReservedSlotTwo: ReserveSlotOutputData_2024_09_04 = reserveResponseTwoBody.data;
|
||||
expect(responseReservedSlotTwo.reservationUid).toBeDefined();
|
||||
if (!responseReservedSlotTwo.reservationUid) {
|
||||
throw new Error("Reserved slot two uid is undefined");
|
||||
}
|
||||
|
||||
const dbSlotTwo = await selectedSlotRepositoryFixture.getByUid(responseReservedSlotTwo.reservationUid);
|
||||
expect(dbSlotTwo).toBeDefined();
|
||||
if (dbSlotTwo) {
|
||||
const dbReleaseAt = DateTime.fromJSDate(dbSlotTwo.releaseAt, { zone: "UTC" }).toISO();
|
||||
const expectedReleaseAt = DateTime.fromISO(now, { zone: "UTC" }).plus({ minutes: 10 }).toISO();
|
||||
expect(dbReleaseAt).toEqual(expectedReleaseAt);
|
||||
}
|
||||
|
||||
const reserveResponseThree = await request(app.getHttpServer())
|
||||
.post(`/v2/slots/reservations`)
|
||||
.set({ Authorization: `Bearer cal_test_${outsiderApiKeyString}` })
|
||||
.send({
|
||||
eventTypeId: roundRobinEventTypeWithoutFixedHostsId,
|
||||
slotStart: slotStartTime,
|
||||
reservationDuration: 10,
|
||||
})
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_09_04);
|
||||
|
||||
expect(reserveResponseThree.status).toEqual(403);
|
||||
expect(reserveResponseThree.body.status).toEqual(ERROR_STATUS);
|
||||
|
||||
await selectedSlotRepositoryFixture.deleteByUId(responseReservedSlotOne.reservationUid);
|
||||
await selectedSlotRepositoryFixture.deleteByUId(responseReservedSlotTwo.reservationUid);
|
||||
clear();
|
||||
});
|
||||
|
||||
it("should reserve available slot for round robin event type with fixed and non-fixed hosts and should not be able to reserve another slot", async () => {
|
||||
const now = "2049-09-05T12:00:00.000Z";
|
||||
const newDate = DateTime.fromISO(now, { zone: "UTC" }).toJSDate();
|
||||
advanceTo(newDate);
|
||||
|
||||
const slotStartTime = "2050-09-05T10:00:00.000Z";
|
||||
|
||||
const reserveResponseOne = await request(app.getHttpServer())
|
||||
.post(`/v2/slots/reservations`)
|
||||
.set({ Authorization: `Bearer cal_test_${teammateApiKeyString}` })
|
||||
.send({
|
||||
eventTypeId: roundRobinEventTypeWithFixedAndNonFixedHostsId,
|
||||
slotStart: slotStartTime,
|
||||
reservationDuration: 10,
|
||||
})
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_09_04)
|
||||
.expect(201);
|
||||
|
||||
const reserveResponseBodyOne: ReserveSlotOutputResponse_2024_09_04 = reserveResponseOne.body;
|
||||
expect(reserveResponseBodyOne.status).toEqual(SUCCESS_STATUS);
|
||||
const responseReservedSlotOne: ReserveSlotOutputData_2024_09_04 = reserveResponseBodyOne.data;
|
||||
expect(responseReservedSlotOne.reservationUid).toBeDefined();
|
||||
if (!responseReservedSlotOne.reservationUid) {
|
||||
throw new Error("Reserved slot uid is undefined");
|
||||
}
|
||||
|
||||
const dbSlotOne = await selectedSlotRepositoryFixture.getByUid(responseReservedSlotOne.reservationUid);
|
||||
expect(dbSlotOne).toBeDefined();
|
||||
if (dbSlotOne) {
|
||||
const dbReleaseAt = DateTime.fromJSDate(dbSlotOne.releaseAt, { zone: "UTC" }).toISO();
|
||||
const expectedReleaseAt = DateTime.fromISO(now, { zone: "UTC" }).plus({ minutes: 10 }).toISO();
|
||||
expect(dbReleaseAt).toEqual(expectedReleaseAt);
|
||||
}
|
||||
|
||||
const reserveResponseTwo = await request(app.getHttpServer())
|
||||
.post(`/v2/slots/reservations`)
|
||||
.send({
|
||||
eventTypeId: roundRobinEventTypeWithFixedAndNonFixedHostsId,
|
||||
slotStart: slotStartTime,
|
||||
})
|
||||
.set({ Authorization: `Bearer cal_test_${teammateTwoApiKeyString}` })
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_09_04);
|
||||
|
||||
expect(reserveResponseTwo.status).toEqual(422);
|
||||
expect(reserveResponseTwo.body.status).toEqual(ERROR_STATUS);
|
||||
|
||||
await selectedSlotRepositoryFixture.deleteByUId(responseReservedSlotOne.reservationUid);
|
||||
clear();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await userRepositoryFixture.deleteByEmail(teammateOne.email);
|
||||
await userRepositoryFixture.deleteByEmail(teammateTwo.email);
|
||||
|
||||
@@ -48,7 +48,7 @@ import { ApiResponse } from "@calcom/platform-types";
|
||||
@DocsTags("Slots")
|
||||
@ApiHeader({
|
||||
name: "cal-api-version",
|
||||
description: `Must be set to ${VERSION_2024_09_04}`,
|
||||
description: `Must be set to ${VERSION_2024_09_04}. If not set to this value, the endpoint will default to an older version.`,
|
||||
example: VERSION_2024_09_04,
|
||||
required: true,
|
||||
schema: {
|
||||
@@ -86,6 +86,8 @@ export class SlotsController_2024_09_04 {
|
||||
- duration: Only use for event types that allow multiple durations or for dynamic event types. If not passed for multiple duration event types defaults to default duration. For dynamic event types defaults to 30 aka each returned slot is 30 minutes long. So duration=60 means that returned slots will be each 60 minutes long.
|
||||
- format: Format of the slots. By default return is an object where each key is date and value is array of slots as string. If you want to get start and end of each slot use "range" as value.
|
||||
- bookingUidToReschedule: When rescheduling an existing booking, provide the booking's unique identifier to exclude its time slot from busy time calculations. This ensures the original booking time appears as available for rescheduling.
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
@ApiQuery({
|
||||
@@ -256,7 +258,10 @@ export class SlotsController_2024_09_04 {
|
||||
@ApiOperation({
|
||||
summary: "Reserve a slot",
|
||||
description: `Make a slot not available for others to book for a certain period of time. If you authenticate using oAuth credentials, api key or access token
|
||||
then you can also specify custom duration for how long the slot should be reserved for (defaults to 5 minutes).`,
|
||||
then you can also specify custom duration for how long the slot should be reserved for (defaults to 5 minutes).
|
||||
|
||||
<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>
|
||||
`,
|
||||
})
|
||||
@ApiHeader(OPTIONAL_X_CAL_CLIENT_ID_HEADER)
|
||||
@ApiHeader(OPTIONAL_X_CAL_CLIENT_ID_HEADER)
|
||||
@@ -278,6 +283,7 @@ export class SlotsController_2024_09_04 {
|
||||
@Get("/reservations/:uid")
|
||||
@ApiOperation({
|
||||
summary: "Get reserved slot",
|
||||
description: `<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>`,
|
||||
})
|
||||
async getReservedSlot(@Param("uid") uid: string): Promise<GetReservedSlotOutput_2024_09_04> {
|
||||
const reservedSlot = await this.slotsService.getReservedSlot(uid);
|
||||
@@ -293,6 +299,7 @@ export class SlotsController_2024_09_04 {
|
||||
@Patch("/reservations/:uid")
|
||||
@ApiOperation({
|
||||
summary: "Update a reserved slot",
|
||||
description: `<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>`,
|
||||
})
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async updateReservedSlot(
|
||||
@@ -312,6 +319,7 @@ export class SlotsController_2024_09_04 {
|
||||
@Delete("/reservations/:uid")
|
||||
@ApiOperation({
|
||||
summary: "Delete a reserved slot",
|
||||
description: `<Note>Please make sure to pass in the cal-api-version header value as mentioned in the Headers section. Not passing the correct value will default to an older version of this endpoint.</Note>`,
|
||||
})
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@DocsResponse({
|
||||
|
||||
@@ -23,6 +23,8 @@ import { DateTime } from "luxon";
|
||||
import { z } from "zod";
|
||||
|
||||
import { SlotFormat } from "@calcom/platform-enums";
|
||||
import { SchedulingType } from "@calcom/platform-libraries";
|
||||
import { validateRoundRobinSlotAvailability } from "@calcom/platform-libraries/slots";
|
||||
import type {
|
||||
GetSlotsInput_2024_09_04,
|
||||
GetSlotsInputWithRouting_2024_09_04,
|
||||
@@ -147,13 +149,26 @@ export class SlotsService_2024_09_04 {
|
||||
}
|
||||
|
||||
const nonSeatedEventAlreadyBooked = !eventType.seatsPerTimeSlot && booking;
|
||||
if (nonSeatedEventAlreadyBooked) {
|
||||
const isRoundRobinEvent = eventType.schedulingType === SchedulingType.ROUND_ROBIN;
|
||||
|
||||
if (nonSeatedEventAlreadyBooked && !isRoundRobinEvent) {
|
||||
throw new UnprocessableEntityException(`Can't reserve a slot if the event is already booked.`);
|
||||
}
|
||||
|
||||
const reservationDuration = input.reservationDuration ?? DEFAULT_RESERVATION_DURATION;
|
||||
if (isRoundRobinEvent) {
|
||||
try {
|
||||
await validateRoundRobinSlotAvailability(input.eventTypeId, startDate, endDate, eventType.hosts);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
throw new UnprocessableEntityException(error?.message);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
} else {
|
||||
await this.checkSlotOverlap(input.eventTypeId, startDate.toISO(), endDate.toISO());
|
||||
}
|
||||
|
||||
await this.checkSlotOverlap(input.eventTypeId, startDate.toISO(), endDate.toISO());
|
||||
const reservationDuration = input.reservationDuration ?? DEFAULT_RESERVATION_DURATION;
|
||||
|
||||
if (eventType.userId) {
|
||||
const slot = await this.slotsRepository.createSlot(
|
||||
|
||||
+125
@@ -328,6 +328,131 @@ describe("Teams Memberships Endpoints", () => {
|
||||
return request(app.getHttpServer()).get(`/v2/teams/${team.id}/memberships/123132145`).expect(404);
|
||||
});
|
||||
|
||||
it("should filter memberships by single email", async () => {
|
||||
return request(app.getHttpServer())
|
||||
.get(`/v2/teams/${team.id}/memberships?emails=${teamAdminEmail}`)
|
||||
.expect(200)
|
||||
.then((response) => {
|
||||
const responseBody: GetTeamMembershipsOutput = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data.length).toEqual(1);
|
||||
expect(responseBody.data[0].user.email).toEqual(teamAdminEmail);
|
||||
expect(responseBody.data[0].userId).toEqual(teamAdmin.id);
|
||||
expect(responseBody.data[0].role).toEqual("ADMIN");
|
||||
});
|
||||
});
|
||||
|
||||
it("should filter memberships by multiple emails", async () => {
|
||||
return request(app.getHttpServer())
|
||||
.get(`/v2/teams/${team.id}/memberships?emails=${teamAdminEmail},${teamMemberEmail}`)
|
||||
.expect(200)
|
||||
.then((response) => {
|
||||
const responseBody: GetTeamMembershipsOutput = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data.length).toEqual(2);
|
||||
|
||||
const emails = responseBody.data.map((membership) => membership.user.email);
|
||||
expect(emails).toContain(teamAdminEmail);
|
||||
expect(emails).toContain(teamMemberEmail);
|
||||
|
||||
const adminMembership = responseBody.data.find((m) => m.user.email === teamAdminEmail);
|
||||
const memberMembership = responseBody.data.find((m) => m.user.email === teamMemberEmail);
|
||||
|
||||
expect(adminMembership).toBeDefined();
|
||||
expect(memberMembership).toBeDefined();
|
||||
expect(adminMembership?.role).toEqual("ADMIN");
|
||||
expect(memberMembership?.role).toEqual("MEMBER");
|
||||
});
|
||||
});
|
||||
|
||||
it("should return empty array when filtering by non-existent email", async () => {
|
||||
const nonExistentEmail = `nonexistent-${randomString()}@test.com`;
|
||||
return request(app.getHttpServer())
|
||||
.get(`/v2/teams/${team.id}/memberships?emails=${nonExistentEmail}`)
|
||||
.expect(200)
|
||||
.then((response) => {
|
||||
const responseBody: GetTeamMembershipsOutput = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data.length).toEqual(0);
|
||||
});
|
||||
});
|
||||
|
||||
it("should return partial results when filtering by mix of existing and non-existent emails", async () => {
|
||||
const nonExistentEmail = `nonexistent-${randomString()}@test.com`;
|
||||
return request(app.getHttpServer())
|
||||
.get(`/v2/teams/${team.id}/memberships?emails=${teamAdminEmail},${nonExistentEmail}`)
|
||||
.expect(200)
|
||||
.then((response) => {
|
||||
const responseBody: GetTeamMembershipsOutput = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data.length).toEqual(1);
|
||||
expect(responseBody.data[0].user.email).toEqual(teamAdminEmail);
|
||||
});
|
||||
});
|
||||
|
||||
it("should work with pagination and email filtering combined", async () => {
|
||||
return request(app.getHttpServer())
|
||||
.get(`/v2/teams/${team.id}/memberships?emails=${teamAdminEmail},${teamMemberEmail}&skip=1&take=1`)
|
||||
.expect(200)
|
||||
.then((response) => {
|
||||
const responseBody: GetTeamMembershipsOutput = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data.length).toEqual(1);
|
||||
const returnedEmail = responseBody.data[0].user.email;
|
||||
expect([teamAdminEmail, teamMemberEmail]).toContain(returnedEmail);
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle empty emails array gracefully", async () => {
|
||||
return request(app.getHttpServer())
|
||||
.get(`/v2/teams/${team.id}/memberships?emails=`)
|
||||
.expect(200)
|
||||
.then((response) => {
|
||||
const responseBody: GetTeamMembershipsOutput = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data.length).toEqual(2);
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle URL encoded email addresses in filter", async () => {
|
||||
const encodedEmail = encodeURIComponent(teamAdminEmail);
|
||||
return request(app.getHttpServer())
|
||||
.get(`/v2/teams/${team.id}/memberships?emails=${encodedEmail}`)
|
||||
.expect(200)
|
||||
.then((response) => {
|
||||
const responseBody: GetTeamMembershipsOutput = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data.length).toEqual(1);
|
||||
expect(responseBody.data[0].user.email).toEqual(teamAdminEmail);
|
||||
});
|
||||
});
|
||||
|
||||
it("should filter by email and maintain all user properties", async () => {
|
||||
return request(app.getHttpServer())
|
||||
.get(`/v2/teams/${team.id}/memberships?emails=${teamMemberEmail}`)
|
||||
.expect(200)
|
||||
.then((response) => {
|
||||
const responseBody: GetTeamMembershipsOutput = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data.length).toEqual(1);
|
||||
const membership = responseBody.data[0];
|
||||
expect(membership.user.email).toEqual(teamMemberEmail);
|
||||
expect(membership.user.bio).toEqual(teamMember.bio);
|
||||
expect(membership.user.metadata).toEqual(teamMember.metadata);
|
||||
expect(membership.user.username).toEqual(teamMember.username);
|
||||
expect(membership.teamId).toEqual(team.id);
|
||||
expect(membership.userId).toEqual(teamMember.id);
|
||||
expect(membership.role).toEqual("MEMBER");
|
||||
});
|
||||
});
|
||||
|
||||
it("should validate email array size limits", async () => {
|
||||
const tooManyEmails = Array.from({ length: 21 }, (_, i) => `test${i}@example.com`).join(",");
|
||||
return request(app.getHttpServer())
|
||||
.get(`/v2/teams/${team.id}/memberships?emails=${tooManyEmails}`)
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await userRepositoryFixture.deleteByEmail(teamAdmin.email);
|
||||
await userRepositoryFixture.deleteByEmail(teammateInvitedViaApi.email);
|
||||
|
||||
+8
-4
@@ -4,6 +4,7 @@ import { Roles } from "@/modules/auth/decorators/roles/roles.decorator";
|
||||
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
|
||||
import { RolesGuard } from "@/modules/auth/guards/roles/roles.guard";
|
||||
import { CreateTeamMembershipInput } from "@/modules/teams/memberships/inputs/create-team-membership.input";
|
||||
import { GetTeamMembershipsInput } from "@/modules/teams/memberships/inputs/get-team-memberships.input";
|
||||
import { UpdateTeamMembershipInput } from "@/modules/teams/memberships/inputs/update-team-membership.input";
|
||||
import { CreateTeamMembershipOutput } from "@/modules/teams/memberships/outputs/create-team-membership.output";
|
||||
import { DeleteTeamMembershipOutput } from "@/modules/teams/memberships/outputs/delete-team-membership.output";
|
||||
@@ -32,7 +33,6 @@ import { plainToClass } from "class-transformer";
|
||||
|
||||
import { SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/platform-libraries/event-types";
|
||||
import { SkipTakePagination } from "@calcom/platform-types";
|
||||
|
||||
@Controller({
|
||||
path: "/v2/teams/:teamId/memberships",
|
||||
@@ -85,16 +85,20 @@ export class TeamsMembershipsController {
|
||||
}
|
||||
|
||||
@Get("/")
|
||||
@ApiOperation({ summary: "Get all memberships" })
|
||||
@ApiOperation({
|
||||
summary: "Get all memberships",
|
||||
description: "Retrieve team memberships with optional filtering by email addresses. Supports pagination.",
|
||||
})
|
||||
@Roles("TEAM_ADMIN")
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async getTeamMemberships(
|
||||
@Param("teamId", ParseIntPipe) teamId: number,
|
||||
@Query() queryParams: SkipTakePagination
|
||||
@Query() queryParams: GetTeamMembershipsInput
|
||||
): Promise<GetTeamMembershipsOutput> {
|
||||
const { skip, take } = queryParams;
|
||||
const { skip, take, emails } = queryParams;
|
||||
const orgTeamMemberships = await this.teamsMembershipsService.getPaginatedTeamMemberships(
|
||||
teamId,
|
||||
emails,
|
||||
skip ?? 0,
|
||||
take ?? 250
|
||||
);
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { GetUsersInput } from "@/modules/users/inputs/get-users.input";
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { Transform } from "class-transformer";
|
||||
import { ArrayMaxSize, ArrayNotEmpty, IsEmail, IsOptional } from "class-validator";
|
||||
|
||||
export class GetTeamMembershipsInput extends GetUsersInput {
|
||||
@IsOptional()
|
||||
@Transform(({ value }) => {
|
||||
if (value == null) return undefined;
|
||||
const rawValues = (Array.isArray(value) ? value : [value]).flatMap((entry) =>
|
||||
typeof entry === "string" ? entry.split(",") : []
|
||||
);
|
||||
const normalized = rawValues
|
||||
.map((email) => email.trim())
|
||||
.filter((email) => email.length > 0)
|
||||
.map((email) => email.toLowerCase());
|
||||
const deduplicated = [...new Set(normalized)];
|
||||
return deduplicated.length > 0 ? deduplicated : undefined;
|
||||
})
|
||||
@ArrayNotEmpty({ message: "emails cannot be empty." })
|
||||
@ArrayMaxSize(20, {
|
||||
message: "emails array cannot contain more than 20 email addresses for team membership filtering",
|
||||
})
|
||||
@IsEmail({}, { each: true, message: "Each email must be a valid email address" })
|
||||
@ApiPropertyOptional({
|
||||
type: [String],
|
||||
description:
|
||||
"Filter team memberships by email addresses. If you want to filter by multiple emails, separate them with a comma (max 20 emails for performance).",
|
||||
example: "?emails=user1@example.com,user2@example.com",
|
||||
})
|
||||
emails?: string[];
|
||||
}
|
||||
@@ -23,13 +23,15 @@ export class TeamsMembershipsService {
|
||||
return teamMembership;
|
||||
}
|
||||
|
||||
async getPaginatedTeamMemberships(teamId: number, skip = 0, take = 250) {
|
||||
const teamMemberships = await this.teamsMembershipsRepository.findTeamMembershipsPaginated(
|
||||
async getPaginatedTeamMemberships(teamId: number, emails?: string[], skip = 0, take = 250) {
|
||||
const emailArray = !emails ? [] : emails;
|
||||
|
||||
return await this.teamsMembershipsRepository.findTeamMembershipsPaginatedWithFilters(
|
||||
teamId,
|
||||
{ emails: emailArray },
|
||||
skip,
|
||||
take
|
||||
);
|
||||
return teamMemberships;
|
||||
}
|
||||
|
||||
async getTeamMembership(teamId: number, membershipId: number) {
|
||||
|
||||
@@ -6,6 +6,10 @@ import { Injectable } from "@nestjs/common";
|
||||
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
|
||||
export interface TeamMembershipFilters {
|
||||
emails?: string[];
|
||||
}
|
||||
|
||||
export const MembershipUserSelect: Prisma.UserSelect = {
|
||||
username: true,
|
||||
email: true,
|
||||
@@ -41,6 +45,30 @@ export class TeamsMembershipsRepository {
|
||||
});
|
||||
}
|
||||
|
||||
async findTeamMembershipsPaginatedWithFilters(
|
||||
teamId: number,
|
||||
filters: TeamMembershipFilters,
|
||||
skip: number,
|
||||
take: number
|
||||
) {
|
||||
const whereClause: Prisma.MembershipWhereInput = {
|
||||
teamId: teamId,
|
||||
};
|
||||
|
||||
if (filters.emails && filters.emails.length > 0) {
|
||||
whereClause.user = {
|
||||
email: { in: filters.emails },
|
||||
};
|
||||
}
|
||||
|
||||
return await this.dbRead.prisma.membership.findMany({
|
||||
where: whereClause,
|
||||
include: { user: { select: MembershipUserSelect } },
|
||||
skip,
|
||||
take,
|
||||
});
|
||||
}
|
||||
|
||||
async findTeamMembership(teamId: number, membershipId: number) {
|
||||
return this.dbRead.prisma.membership.findUnique({
|
||||
where: {
|
||||
|
||||
@@ -120,30 +120,4 @@ export class TeamsRepository {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async getTeamMemberEmails(teamId: number) {
|
||||
return this.dbRead.prisma.user.findMany({
|
||||
where: {
|
||||
teams: {
|
||||
some: {
|
||||
teamId,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
secondaryEmails: {
|
||||
where: {
|
||||
emailVerified: {
|
||||
not: null,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Locales } from "@/lib/enums/locales";
|
||||
import { CapitalizeTimeZone } from "@/lib/inputs/capitalize-timezone";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { Transform } from "class-transformer";
|
||||
import { IsOptional, IsTimeZone, IsString, IsEnum, IsIn, IsUrl, IsObject } from "class-validator";
|
||||
|
||||
import { ValidateMetadata } from "@calcom/platform-types";
|
||||
@@ -29,6 +30,7 @@ export class CreateManagedUserInput {
|
||||
})
|
||||
weekStart?: WeekDay;
|
||||
|
||||
@Transform(({ value }) => (value === null ? undefined : value))
|
||||
@IsTimeZone()
|
||||
@IsOptional()
|
||||
@CapitalizeTimeZone()
|
||||
|
||||
@@ -28,6 +28,7 @@ export class GetUsersInput {
|
||||
@ApiPropertyOptional({
|
||||
type: [String],
|
||||
description: "The email address or an array of email addresses to filter by",
|
||||
example: ["user1@example.com", "user2@example.com"],
|
||||
})
|
||||
emails?: string[];
|
||||
}
|
||||
|
||||
@@ -408,4 +408,30 @@ export class UsersRepository {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async getUserEmailsVerifiedForTeam(teamId: number) {
|
||||
return this.dbRead.prisma.user.findMany({
|
||||
where: {
|
||||
teams: {
|
||||
some: {
|
||||
teamId,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
secondaryEmails: {
|
||||
where: {
|
||||
emailVerified: {
|
||||
not: null,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -636,10 +636,6 @@ select:focus {
|
||||
@apply !border-r-default left-0.5 !border-y-0 !border-l-0;
|
||||
}
|
||||
|
||||
.intercom-lightweight-app {
|
||||
@apply z-40 !important;
|
||||
}
|
||||
|
||||
@import "../../web/styles/tokens.css";
|
||||
|
||||
@layer base {
|
||||
@@ -1027,10 +1023,6 @@ select:focus {
|
||||
@apply !border-r-default left-0.5 !border-y-0 !border-l-0;
|
||||
}
|
||||
|
||||
.intercom-lightweight-app {
|
||||
@apply z-40 !important;
|
||||
}
|
||||
|
||||
.prose :where(a:not([data-card])):not(:where([class~="not-prose"] *)) {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ export function ShellMainAppDir(props: LayoutProps) {
|
||||
className={classNames(
|
||||
props.backPath
|
||||
? "relative"
|
||||
: "pwa:bottom-[max(7rem,_calc(5rem_+_env(safe-area-inset-bottom)))] fixed bottom-20 z-40 ltr:right-4 rtl:left-4 md:z-auto md:ltr:right-0 md:rtl:left-0",
|
||||
: "pwa:bottom-[max(7rem,_calc(5rem_+_env(safe-area-inset-bottom)))] fixed bottom-32 z-40 ltr:right-4 rtl:left-4 md:z-auto md:ltr:right-0 md:rtl:left-0",
|
||||
"flex-shrink-0 [-webkit-app-region:no-drag] md:relative md:bottom-auto md:right-auto"
|
||||
)}>
|
||||
{props.CTA}
|
||||
|
||||
@@ -23,7 +23,8 @@ const ServerPage = async ({ searchParams: _searchParams }: ServerPageProps) => {
|
||||
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
|
||||
const searchParams = await _searchParams;
|
||||
const token = Array.isArray(searchParams?.token) ? searchParams.token[0] : searchParams?.token;
|
||||
const callbackUrl = token ? `/teams?token=${encodeURIComponent(token)}` : null;
|
||||
const autoAccept = Array.isArray(searchParams?.autoAccept) ? searchParams.autoAccept[0] : searchParams?.autoAccept;
|
||||
const callbackUrl = token ? `/teams?token=${encodeURIComponent(token)}${autoAccept ? `&autoAccept=${encodeURIComponent(autoAccept)}` : ''}` : null;
|
||||
|
||||
if (!session) {
|
||||
redirect(callbackUrl ? `/auth/login?callbackUrl=${callbackUrl}` : "/auth/login");
|
||||
|
||||
@@ -33,14 +33,21 @@ export const ServerTeamsListing = async ({
|
||||
session: Session;
|
||||
}) => {
|
||||
const token = Array.isArray(searchParams?.token) ? searchParams.token[0] : searchParams?.token;
|
||||
const autoAccept = Array.isArray(searchParams?.autoAccept) ? searchParams.autoAccept[0] : searchParams?.autoAccept;
|
||||
const userId = session.user.id;
|
||||
let invitationAccepted = false;
|
||||
|
||||
let teamNameFromInvite,
|
||||
errorMsgFromInvite = null;
|
||||
|
||||
if (token) {
|
||||
try {
|
||||
teamNameFromInvite = await TeamService.inviteMemberByToken(token, userId);
|
||||
if (autoAccept === "true") {
|
||||
await TeamService.acceptInvitationByToken(token, userId);
|
||||
invitationAccepted = true;
|
||||
} else {
|
||||
teamNameFromInvite = await TeamService.inviteMemberByToken(token, userId);
|
||||
}
|
||||
} catch (e) {
|
||||
errorMsgFromInvite = "Error while fetching teams";
|
||||
if (e instanceof TRPCError) errorMsgFromInvite = e.message;
|
||||
@@ -64,6 +71,7 @@ export const ServerTeamsListing = async ({
|
||||
return {
|
||||
Main: (
|
||||
<TeamsListing
|
||||
invitationAccepted={invitationAccepted}
|
||||
teams={teams}
|
||||
orgId={orgId ?? null}
|
||||
permissions={{
|
||||
|
||||
@@ -10,6 +10,7 @@ import type { UseFormReturn } from "react-hook-form";
|
||||
import { Toaster } from "sonner";
|
||||
import type { z } from "zod";
|
||||
|
||||
import { buildEmptyQueryValue, raqbQueryValueUtils } from "@calcom/app-store/_utils/raqb/raqbUtils";
|
||||
import { routingFormAppComponents } from "@calcom/app-store/routing-forms/appComponents";
|
||||
import DynamicAppComponent from "@calcom/app-store/routing-forms/components/DynamicAppComponent";
|
||||
import { EmptyState } from "@calcom/app-store/routing-forms/components/_components/EmptyState";
|
||||
@@ -44,7 +45,6 @@ import { useOrgBranding } from "@calcom/features/ee/organizations/context/provid
|
||||
import type { EventTypesByViewer } from "@calcom/features/eventtypes/lib/getEventTypesByViewer";
|
||||
import { areTheySiblingEntities } from "@calcom/lib/entityPermissionUtils.shared";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { buildEmptyQueryValue, raqbQueryValueUtils } from "@calcom/lib/raqb/raqbUtils";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
@@ -1190,7 +1190,7 @@ const Routes = ({
|
||||
}) || [];
|
||||
|
||||
// const isConnectedForm = (id: string) => form.connectedForms.map((f) => f.id).includes(id);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
|
||||
// const routers: any[] = [];
|
||||
/* Disable this feature for new forms till we get it fully working with Routing Form with Attributes. This isn't much used feature */
|
||||
// const routers = availableRouters.map((r) => {
|
||||
@@ -1235,7 +1235,7 @@ const Routes = ({
|
||||
});
|
||||
setRoutes((routes) => {
|
||||
// Even though it's obvious that fallbackRoute is defined here but TypeScript just can't figure it out.
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
|
||||
return [...routes, fallbackRoute!];
|
||||
});
|
||||
return null;
|
||||
@@ -1243,7 +1243,7 @@ const Routes = ({
|
||||
// Ensure fallback is last
|
||||
setRoutes((routes) => {
|
||||
// Even though it's obvious that fallbackRoute is defined here but TypeScript just can't figure it out.
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
|
||||
return [...routes.filter((route) => route.id !== fallbackRoute!.id), fallbackRoute!];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useHasPaidPlan } from "@calcom/lib/hooks/useHasPaidPlan";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { ArrowButton } from "@calcom/ui/components/arrow-button";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
@@ -46,6 +47,10 @@ function NewFormButton({ setNewFormDialogState }: { setNewFormDialogState: SetNe
|
||||
createFunction={(teamId) => {
|
||||
setNewFormDialogState({ action: "new", target: teamId ? String(teamId) : "" });
|
||||
}}
|
||||
withPermission={{
|
||||
permission: "routingForm.create",
|
||||
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,10 +8,7 @@ import { z } from "zod";
|
||||
|
||||
import { EventTypeWebWrapper } from "@calcom/atoms/event-types/wrappers/EventTypeWebWrapper";
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import { Resource } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { getResourcePermissions } from "@calcom/features/pbac/lib/resource-permissions";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { getEventTypePermissions } from "@calcom/features/pbac/lib/event-type-permissions";
|
||||
import { eventTypesRouter } from "@calcom/trpc/server/routers/viewer/eventTypes/_router";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
@@ -44,95 +41,6 @@ const getCachedEventType = unstable_cache(
|
||||
{ revalidate: 3600 } // Cache for 1 hour
|
||||
);
|
||||
|
||||
const getEventPermissions = async (userId: number, teamId: number | null) => {
|
||||
// Personal event - has all perms
|
||||
if (!teamId)
|
||||
return {
|
||||
eventTypes: {
|
||||
canRead: true,
|
||||
canCreate: true,
|
||||
canUpdate: true,
|
||||
canDelete: true,
|
||||
},
|
||||
workflows: {
|
||||
canRead: true,
|
||||
canCreate: true,
|
||||
canUpdate: true,
|
||||
canDelete: true,
|
||||
},
|
||||
};
|
||||
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
teamId,
|
||||
},
|
||||
select: {
|
||||
role: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) throw new Error("Membership not found");
|
||||
|
||||
const [eventTypePermissions, workflowPermissions] = await Promise.all([
|
||||
getResourcePermissions({
|
||||
userId,
|
||||
teamId,
|
||||
resource: Resource.EventType,
|
||||
userRole: membership.role,
|
||||
fallbackRoles: {
|
||||
read: {
|
||||
roles: [MembershipRole.MEMBER, MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
update: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
delete: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
create: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
},
|
||||
}),
|
||||
getResourcePermissions({
|
||||
userId,
|
||||
teamId,
|
||||
resource: Resource.Workflow,
|
||||
userRole: membership.role,
|
||||
fallbackRoles: {
|
||||
read: {
|
||||
roles: [MembershipRole.MEMBER, MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
update: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
delete: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
create: {
|
||||
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
eventTypes: {
|
||||
canRead: eventTypePermissions.canRead,
|
||||
canCreate: eventTypePermissions.canCreate,
|
||||
canUpdate: eventTypePermissions.canEdit,
|
||||
canDelete: eventTypePermissions.canDelete,
|
||||
},
|
||||
workflows: {
|
||||
canRead: workflowPermissions.canRead,
|
||||
canCreate: workflowPermissions.canCreate,
|
||||
canUpdate: workflowPermissions.canEdit,
|
||||
canDelete: workflowPermissions.canDelete,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const ServerPage = async ({ params }: PageProps) => {
|
||||
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
|
||||
if (!session?.user?.id) {
|
||||
@@ -153,7 +61,7 @@ const ServerPage = async ({ params }: PageProps) => {
|
||||
}
|
||||
|
||||
// Fetch permissions for the event type's team
|
||||
const permissions = await getEventPermissions(session.user.id, data.eventType.teamId);
|
||||
const permissions = await getEventTypePermissions(session.user.id, data.eventType.teamId);
|
||||
|
||||
return <EventTypeWebWrapper data={data} id={eventTypeId} permissions={permissions} />;
|
||||
};
|
||||
|
||||
+9
-11
@@ -175,6 +175,7 @@ const organizationAdminKeys = ["privacy", "OAuth Clients", "SSO", "directory_syn
|
||||
export interface SettingsPermissions {
|
||||
canViewRoles?: boolean;
|
||||
canViewOrganizationBilling?: boolean;
|
||||
canUpdateOrganization?: boolean;
|
||||
}
|
||||
|
||||
const useTabs = ({
|
||||
@@ -190,7 +191,6 @@ const useTabs = ({
|
||||
const { data: user } = trpc.viewer.me.get.useQuery({ includePasswordAdded: true });
|
||||
const orgBranding = useOrgBranding();
|
||||
const isAdmin = session.data?.user.role === UserPermissionRole.ADMIN;
|
||||
const isOrgAdminOrOwner = checkAdminOrOwner(orgBranding?.role);
|
||||
|
||||
const processTabsMemod = useMemo(() => {
|
||||
const processedTabs = getTabs(orgBranding).map((tab) => {
|
||||
@@ -203,10 +203,10 @@ const useTabs = ({
|
||||
};
|
||||
} else if (tab.href === "/settings/organizations") {
|
||||
const newArray = (tab?.children ?? []).filter(
|
||||
(child) => isOrgAdminOrOwner || !organizationAdminKeys.includes(child.name)
|
||||
(child) => permissions?.canUpdateOrganization || !organizationAdminKeys.includes(child.name)
|
||||
);
|
||||
|
||||
if (isOrgAdminOrOwner) {
|
||||
if (permissions?.canUpdateOrganization) {
|
||||
newArray.splice(4, 0, {
|
||||
name: "attributes",
|
||||
href: "/settings/organizations/attributes",
|
||||
@@ -238,7 +238,7 @@ const useTabs = ({
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (isOrgAdminOrOwner) {
|
||||
if (permissions?.canUpdateOrganization) {
|
||||
newArray.push({
|
||||
name: "billing",
|
||||
href: "/settings/organizations/billing",
|
||||
@@ -264,7 +264,7 @@ const useTabs = ({
|
||||
return { ...tab, children: filtered };
|
||||
} else if (tab.href === "/settings/developer") {
|
||||
const filtered = tab?.children?.filter(
|
||||
(childTab) => isOrgAdminOrOwner || childTab.name !== "admin_api"
|
||||
(childTab) => permissions?.canUpdateOrganization || childTab.name !== "admin_api"
|
||||
);
|
||||
return { ...tab, children: filtered };
|
||||
}
|
||||
@@ -274,12 +274,12 @@ const useTabs = ({
|
||||
// check if name is in adminRequiredKeys
|
||||
return processedTabs.filter((tab) => {
|
||||
if (organizationRequiredKeys.includes(tab.name)) return !!orgBranding;
|
||||
if (tab.name === "other_teams" && !isOrgAdminOrOwner) return false;
|
||||
if (tab.name === "other_teams" && !permissions?.canUpdateOrganization) return false;
|
||||
|
||||
if (isAdmin) return true;
|
||||
return !adminRequiredKeys.includes(tab.name);
|
||||
});
|
||||
}, [isAdmin, orgBranding, isOrgAdminOrOwner, user, isDelegationCredentialEnabled, isPbacEnabled, permissions]);
|
||||
}, [isAdmin, orgBranding, user, isDelegationCredentialEnabled, isPbacEnabled, permissions]);
|
||||
|
||||
return processTabsMemod;
|
||||
};
|
||||
@@ -560,8 +560,6 @@ const SettingsSidebarContainer = ({
|
||||
}
|
||||
}, [searchParams?.get("id"), otherTeams]);
|
||||
|
||||
const isOrgAdminOrOwner = checkAdminOrOwner(orgBranding?.role);
|
||||
|
||||
return (
|
||||
<nav
|
||||
style={{ maxHeight: `calc(100vh - ${bannersHeight}px)`, top: `${bannersHeight}px` }}
|
||||
@@ -638,12 +636,12 @@ const SettingsSidebarContainer = ({
|
||||
as="p"
|
||||
className="text-subtle truncate text-sm font-medium leading-5"
|
||||
loadingClassName="ms-3">
|
||||
{t(isOrgAdminOrOwner ? "my_teams" : tab.name)}
|
||||
{t("my_teams")}
|
||||
</Skeleton>
|
||||
</div>
|
||||
</Link>
|
||||
<TeamListCollapsible teamFeatures={teamFeatures} />
|
||||
{(!orgBranding?.id || isOrgAdminOrOwner) && (
|
||||
{(!orgBranding?.id || permissions?.canUpdateOrganization) && (
|
||||
<VerticalTabItem
|
||||
name={t("add_a_team")}
|
||||
href={`${WEBAPP_URL}/settings/teams/new`}
|
||||
|
||||
@@ -47,6 +47,7 @@ export default async function SettingsLayoutAppDir(props: SettingsLayoutProps) {
|
||||
let teamFeatures: Record<number, TeamFeatures> | null = null;
|
||||
let canViewRoles = false;
|
||||
let canViewOrganizationBilling = false;
|
||||
let canUpdateOrganization = false;
|
||||
const orgId = session?.user?.profile?.organizationId ?? session?.user.org?.id;
|
||||
|
||||
// For now we only grab organization features but it would be nice to fetch these on the server side for specific team feature flags
|
||||
@@ -68,6 +69,11 @@ export default async function SettingsLayoutAppDir(props: SettingsLayoutProps) {
|
||||
canViewRoles = roleActions[CrudAction.Read] ?? false;
|
||||
const orgActions = PermissionMapper.toActionMap(organizationPermissions, Resource.Organization);
|
||||
canViewOrganizationBilling = orgActions[CustomAction.ManageBilling] ?? isOrgAdminOrOwner;
|
||||
canUpdateOrganization = orgActions[CrudAction.Update] ?? isOrgAdminOrOwner;
|
||||
} else {
|
||||
canViewRoles = false;
|
||||
canViewOrganizationBilling = isOrgAdminOrOwner;
|
||||
canUpdateOrganization = isOrgAdminOrOwner;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,7 +82,7 @@ export default async function SettingsLayoutAppDir(props: SettingsLayoutProps) {
|
||||
<SettingsLayoutAppDirClient
|
||||
{...props}
|
||||
teamFeatures={teamFeatures ?? {}}
|
||||
permissions={{ canViewRoles, canViewOrganizationBilling }}
|
||||
permissions={{ canViewRoles, canViewOrganizationBilling, canUpdateOrganization }}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
+6
-2
@@ -1,8 +1,9 @@
|
||||
import { _generateMetadata } from "app/_utils";
|
||||
|
||||
import OrgAttributesEditPage from "@calcom/ee/organizations/pages/settings/attributes/attributes-edit-view";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { validateUserHasOrgAdmin } from "../../../../actions/validateUserHasOrgAdmin";
|
||||
import { validateUserHasOrgPerms } from "../../../../actions/validateUserHasOrgPerms";
|
||||
|
||||
export const generateMetadata = async ({ params }: { params: Promise<{ id: string }> }) =>
|
||||
await _generateMetadata(
|
||||
@@ -14,7 +15,10 @@ export const generateMetadata = async ({ params }: { params: Promise<{ id: strin
|
||||
);
|
||||
|
||||
const OrgAttributesEditPageWrapper = async () => {
|
||||
await validateUserHasOrgAdmin();
|
||||
await validateUserHasOrgPerms({
|
||||
permission: "organization.attributes.update",
|
||||
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
|
||||
});
|
||||
|
||||
return <OrgAttributesEditPage />;
|
||||
};
|
||||
|
||||
+6
-2
@@ -1,8 +1,9 @@
|
||||
import { _generateMetadata } from "app/_utils";
|
||||
|
||||
import OrgAttributesCreatePage from "@calcom/ee/organizations/pages/settings/attributes/attributes-create-view";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { validateUserHasOrgAdmin } from "../../../actions/validateUserHasOrgAdmin";
|
||||
import { validateUserHasOrgPerms } from "../../../actions/validateUserHasOrgPerms";
|
||||
|
||||
export const generateMetadata = async () =>
|
||||
await _generateMetadata(
|
||||
@@ -14,7 +15,10 @@ export const generateMetadata = async () =>
|
||||
);
|
||||
|
||||
const OrgAttributesCreatePageWrapper = async () => {
|
||||
await validateUserHasOrgAdmin();
|
||||
await validateUserHasOrgPerms({
|
||||
permission: "organization.attributes.create",
|
||||
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
|
||||
});
|
||||
|
||||
return <OrgAttributesCreatePage />;
|
||||
};
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@ import { getResourcePermissions } from "@calcom/features/pbac/lib/resource-permi
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { validateUserHasOrgAdmin } from "../../actions/validateUserHasOrgAdmin";
|
||||
import { validateUserHasOrg } from "../../actions/validateUserHasOrg";
|
||||
|
||||
export const generateMetadata = async () =>
|
||||
await _generateMetadata(
|
||||
@@ -20,7 +20,7 @@ export const generateMetadata = async () =>
|
||||
|
||||
const Page = async () => {
|
||||
const t = await getTranslate();
|
||||
const session = await validateUserHasOrgAdmin();
|
||||
const session = await validateUserHasOrg();
|
||||
|
||||
const { canRead, canEdit, canDelete, canCreate } = await getResourcePermissions({
|
||||
userId: session.user.id,
|
||||
|
||||
+6
-2
@@ -2,8 +2,9 @@ import { _generateMetadata, getTranslate } from "app/_utils";
|
||||
|
||||
import DelegationCredentialList from "@calcom/features/ee/organizations/pages/settings/delegationCredential";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { validateUserHasOrgAdmin } from "../../actions/validateUserHasOrgAdmin";
|
||||
import { validateUserHasOrgPerms } from "../../actions/validateUserHasOrgPerms";
|
||||
|
||||
export const generateMetadata = async () =>
|
||||
await _generateMetadata(
|
||||
@@ -17,7 +18,10 @@ export const generateMetadata = async () =>
|
||||
const Page = async () => {
|
||||
const t = await getTranslate();
|
||||
|
||||
await validateUserHasOrgAdmin();
|
||||
await validateUserHasOrgPerms({
|
||||
permission: "organization.update",
|
||||
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
|
||||
});
|
||||
|
||||
return (
|
||||
<SettingsHeader
|
||||
|
||||
+2
-2
@@ -6,7 +6,7 @@ import { getResourcePermissions } from "@calcom/features/pbac/lib/resource-permi
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { validateUserHasOrgAdmin } from "../../actions/validateUserHasOrgAdmin";
|
||||
import { validateUserHasOrg } from "../../actions/validateUserHasOrg";
|
||||
|
||||
export const generateMetadata = async () =>
|
||||
await _generateMetadata(
|
||||
@@ -19,7 +19,7 @@ export const generateMetadata = async () =>
|
||||
|
||||
const Page = async () => {
|
||||
const t = await getTranslate();
|
||||
const session = await validateUserHasOrgAdmin();
|
||||
const session = await validateUserHasOrg();
|
||||
|
||||
const { canEdit } = await getResourcePermissions({
|
||||
userId: session.user.id,
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@ import { getResourcePermissions } from "@calcom/features/pbac/lib/resource-permi
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { validateUserHasOrgAdmin } from "../../actions/validateUserHasOrgAdmin";
|
||||
import { validateUserHasOrg } from "../../actions/validateUserHasOrg";
|
||||
|
||||
export const generateMetadata = async () =>
|
||||
await _generateMetadata(
|
||||
@@ -21,7 +21,7 @@ export const generateMetadata = async () =>
|
||||
const Page = async () => {
|
||||
const t = await getTranslate();
|
||||
|
||||
const session = await validateUserHasOrgAdmin();
|
||||
const session = await validateUserHasOrg();
|
||||
|
||||
if (!session?.user.id || !session?.user.profile?.organizationId || !session?.user.org) {
|
||||
return redirect("/settings/profile");
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@ import { getResourcePermissions } from "@calcom/features/pbac/lib/resource-permi
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { validateUserHasOrgAdmin } from "../../actions/validateUserHasOrgAdmin";
|
||||
import { validateUserHasOrg } from "../../actions/validateUserHasOrg";
|
||||
|
||||
export const generateMetadata = async () =>
|
||||
await _generateMetadata(
|
||||
@@ -20,7 +20,7 @@ export const generateMetadata = async () =>
|
||||
|
||||
const Page = async () => {
|
||||
const t = await getTranslate();
|
||||
const session = await validateUserHasOrgAdmin();
|
||||
const session = await validateUserHasOrg();
|
||||
|
||||
if (!session?.user.id || !session?.user.profile?.organizationId || !session?.user.org) {
|
||||
return redirect("/settings/organizations/general");
|
||||
|
||||
+6
-2
@@ -65,7 +65,7 @@ export function RoleSheet({
|
||||
onOpenChange,
|
||||
teamId,
|
||||
scope = Scope.Organization,
|
||||
isPrivate = false
|
||||
isPrivate = false,
|
||||
}: RoleSheetProps) {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
@@ -191,6 +191,7 @@ export function RoleSheet({
|
||||
{...form.register("name")}
|
||||
placeholder={t("role_name_placeholder")}
|
||||
disabled={isSystemRole}
|
||||
maxLength={50}
|
||||
/>
|
||||
</div>
|
||||
<RoleColorPicker
|
||||
@@ -208,10 +209,13 @@ export function RoleSheet({
|
||||
<Label className="mb-0">{t("permissions")}</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="advanced_mode_checkbox"
|
||||
checked={form.watch("isAdvancedMode")}
|
||||
onCheckedChange={(checked: boolean) => form.setValue("isAdvancedMode", checked)}
|
||||
/>
|
||||
<span className="text-sm">{t("advanced")}</span>
|
||||
<label htmlFor="advanced_mode_checkbox" className="text-sm">
|
||||
{t("advanced")}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<TextField
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import { parseRequestData } from "app/api/parseRequestData";
|
||||
import { cookies } from "next/headers";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
@@ -10,6 +11,7 @@ import prisma from "@calcom/prisma";
|
||||
import { IdentityProvider } from "@calcom/prisma/enums";
|
||||
|
||||
const passwordResetRequestSchema = z.object({
|
||||
csrfToken: z.string(),
|
||||
password: z.string().refine(validPassword, () => ({
|
||||
message: "Password does not meet the requirements",
|
||||
})),
|
||||
@@ -18,8 +20,22 @@ const passwordResetRequestSchema = z.object({
|
||||
|
||||
async function handler(req: NextRequest) {
|
||||
const body = await parseRequestData(req);
|
||||
const {
|
||||
password: rawPassword,
|
||||
requestId: rawRequestId,
|
||||
csrfToken: submittedToken,
|
||||
} = passwordResetRequestSchema.parse(body);
|
||||
const cookieStore = await cookies();
|
||||
|
||||
const cookieToken = cookieStore.get("calcom.csrf_token")?.value;
|
||||
|
||||
if (submittedToken !== cookieToken) {
|
||||
return NextResponse.json({ error: "Invalid CSRF token" }, { status: 403 });
|
||||
}
|
||||
|
||||
// token verified, delete the cookie / a resubmit on failure requires a new csrf token.
|
||||
cookieStore.delete("calcom.csrf_token");
|
||||
|
||||
const { password: rawPassword, requestId: rawRequestId } = passwordResetRequestSchema.parse(body);
|
||||
// rate-limited there is a low, very low chance that a password request stays valid long enough
|
||||
// to brute force 3.8126967e+40 options.
|
||||
const maybeRequest = await prisma.resetPasswordRequest.findFirstOrThrow({
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { describe, test, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
import { CalendarCacheEventService } from "@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventService";
|
||||
|
||||
vi.mock("next/server", () => ({
|
||||
NextRequest: class MockNextRequest {
|
||||
url: string;
|
||||
method: string;
|
||||
nextUrl: { searchParams: URLSearchParams };
|
||||
private _headers: Map<string, string>;
|
||||
|
||||
constructor(url: string, options: { method?: string } = {}) {
|
||||
this.url = url;
|
||||
this.method = options.method || "GET";
|
||||
this._headers = new Map();
|
||||
this.nextUrl = { searchParams: new URLSearchParams(url.split("?")[1] || "") };
|
||||
}
|
||||
|
||||
headers = {
|
||||
get: (key: string): string | null => this._headers.get(key.toLowerCase()) || null,
|
||||
set: (key: string, value: string): void => {
|
||||
this._headers.set(key.toLowerCase(), value);
|
||||
},
|
||||
has: (key: string): boolean => this._headers.has(key.toLowerCase()),
|
||||
};
|
||||
},
|
||||
NextResponse: {
|
||||
json: vi.fn((body, init) => ({
|
||||
json: vi.fn().mockResolvedValue(body),
|
||||
status: init?.status || 200,
|
||||
})),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventService");
|
||||
vi.mock("@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventRepository");
|
||||
vi.mock("@calcom/lib/logger", () => ({
|
||||
default: {
|
||||
getSubLogger: vi.fn(() => ({
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
})),
|
||||
},
|
||||
}));
|
||||
vi.mock("@calcom/lib/server/perfObserver", () => ({
|
||||
performance: {
|
||||
mark: vi.fn(),
|
||||
measure: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock("@sentry/nextjs", () => ({
|
||||
wrapApiHandlerWithSentry: vi.fn((handler) => handler),
|
||||
captureException: vi.fn(),
|
||||
}));
|
||||
vi.mock("@calcom/lib/server/getServerErrorFromUnknown", () => ({
|
||||
getServerErrorFromUnknown: vi.fn((error) => ({
|
||||
message: error instanceof Error ? error.message : "Unknown error",
|
||||
statusCode: 500,
|
||||
url: "test-url",
|
||||
method: "GET",
|
||||
})),
|
||||
}));
|
||||
vi.mock("../../defaultResponderForAppDir", () => ({
|
||||
defaultResponderForAppDir: vi.fn((handler) => handler),
|
||||
}));
|
||||
vi.mock("@calcom/prisma", () => ({
|
||||
prisma: {},
|
||||
}));
|
||||
|
||||
const mockCalendarCacheEventService = vi.mocked(CalendarCacheEventService);
|
||||
|
||||
describe("/api/cron/calendar-subscriptions-cleanup", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.stubEnv("CRON_API_KEY", "test-cron-key");
|
||||
vi.stubEnv("CRON_SECRET", "test-cron-secret");
|
||||
});
|
||||
|
||||
describe("Authentication", () => {
|
||||
test("should return 403 when no API key is provided", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions-cleanup");
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("Forbidden");
|
||||
});
|
||||
|
||||
test("should return 403 when invalid API key is provided", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions-cleanup");
|
||||
request.headers.set("authorization", "invalid-key");
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("Forbidden");
|
||||
});
|
||||
|
||||
test("should accept CRON_API_KEY in authorization header", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions-cleanup");
|
||||
request.headers.set("authorization", "test-cron-key");
|
||||
|
||||
const mockCleanupStaleCache = vi.fn().mockResolvedValue(undefined);
|
||||
mockCalendarCacheEventService.prototype.cleanupStaleCache = mockCleanupStaleCache;
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockCleanupStaleCache).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("should accept CRON_SECRET as Bearer token", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions-cleanup");
|
||||
request.headers.set("authorization", "Bearer test-cron-secret");
|
||||
|
||||
const mockCleanupStaleCache = vi.fn().mockResolvedValue(undefined);
|
||||
mockCalendarCacheEventService.prototype.cleanupStaleCache = mockCleanupStaleCache;
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockCleanupStaleCache).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("should accept API key as query parameter", async () => {
|
||||
const request = new NextRequest(
|
||||
"http://localhost/api/cron/calendar-subscriptions-cleanup?apiKey=test-cron-key"
|
||||
);
|
||||
|
||||
const mockCleanupStaleCache = vi.fn().mockResolvedValue(undefined);
|
||||
mockCalendarCacheEventService.prototype.cleanupStaleCache = mockCleanupStaleCache;
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockCleanupStaleCache).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Cleanup functionality", () => {
|
||||
test("should successfully cleanup stale cache", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions-cleanup");
|
||||
request.headers.set("authorization", "test-cron-key");
|
||||
|
||||
const mockCleanupStaleCache = vi.fn().mockResolvedValue(undefined);
|
||||
mockCalendarCacheEventService.prototype.cleanupStaleCache = mockCleanupStaleCache;
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const body = await response.json();
|
||||
expect(body.ok).toBe(true);
|
||||
expect(mockCleanupStaleCache).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test("should handle cleanup errors gracefully", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions-cleanup");
|
||||
request.headers.set("authorization", "test-cron-key");
|
||||
|
||||
const mockError = new Error("Database connection failed");
|
||||
const mockCleanupStaleCache = vi.fn().mockRejectedValue(mockError);
|
||||
mockCalendarCacheEventService.prototype.cleanupStaleCache = mockCleanupStaleCache;
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("Database connection failed");
|
||||
});
|
||||
|
||||
test("should handle non-Error exceptions", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions-cleanup");
|
||||
request.headers.set("authorization", "test-cron-key");
|
||||
|
||||
const mockCleanupStaleCache = vi.fn().mockRejectedValue("String error");
|
||||
mockCalendarCacheEventService.prototype.cleanupStaleCache = mockCleanupStaleCache;
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("Unknown error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Service instantiation", () => {
|
||||
test("should instantiate CalendarCacheEventService with correct dependencies", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions-cleanup");
|
||||
request.headers.set("authorization", "test-cron-key");
|
||||
|
||||
const mockCleanupStaleCache = vi.fn().mockResolvedValue(undefined);
|
||||
mockCalendarCacheEventService.prototype.cleanupStaleCache = mockCleanupStaleCache;
|
||||
|
||||
const { GET } = await import("../route");
|
||||
await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(mockCalendarCacheEventService).toHaveBeenCalledWith({
|
||||
calendarCacheEventRepository: expect.any(Object),
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { CalendarCacheEventRepository } from "@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventRepository";
|
||||
import { CalendarCacheEventService } from "@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventService";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { defaultResponderForAppDir } from "@calcom/web/app/api/defaultResponderForAppDir";
|
||||
|
||||
/**
|
||||
* Cron webhook
|
||||
* Cleanup stale calendar cache
|
||||
*
|
||||
* @param request
|
||||
* @returns
|
||||
*/
|
||||
async function getHandler(request: NextRequest) {
|
||||
const apiKey = request.headers.get("authorization") || request.nextUrl.searchParams.get("apiKey");
|
||||
|
||||
if (![process.env.CRON_API_KEY, `Bearer ${process.env.CRON_SECRET}`].includes(`${apiKey}`)) {
|
||||
return NextResponse.json({ message: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
// instantiate dependencies
|
||||
const calendarCacheEventRepository = new CalendarCacheEventRepository(prisma);
|
||||
const calendarCacheEventService = new CalendarCacheEventService({
|
||||
calendarCacheEventRepository,
|
||||
});
|
||||
|
||||
try {
|
||||
await calendarCacheEventService.cleanupStaleCache();
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (e: unknown) {
|
||||
const message = e instanceof Error ? e.message : "Unknown error";
|
||||
console.error(`[calendar-subscriptions-cleanup] ${message}:`, e);
|
||||
return NextResponse.json({ message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = defaultResponderForAppDir(getHandler);
|
||||
@@ -0,0 +1,229 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { describe, test, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
import { CalendarSubscriptionService } from "@calcom/features/calendar-subscription/lib/CalendarSubscriptionService";
|
||||
|
||||
vi.mock("next/server", () => ({
|
||||
NextRequest: class MockNextRequest {
|
||||
url: string;
|
||||
method: string;
|
||||
nextUrl: { searchParams: URLSearchParams };
|
||||
private _headers: Map<string, string>;
|
||||
|
||||
constructor(url: string, options: { method?: string } = {}) {
|
||||
this.url = url;
|
||||
this.method = options.method || "GET";
|
||||
this._headers = new Map();
|
||||
this.nextUrl = { searchParams: new URLSearchParams(url.split("?")[1] || "") };
|
||||
}
|
||||
|
||||
headers = {
|
||||
get: (key: string): string | null => this._headers.get(key.toLowerCase()) || null,
|
||||
set: (key: string, value: string): void => {
|
||||
this._headers.set(key.toLowerCase(), value);
|
||||
},
|
||||
has: (key: string): boolean => this._headers.has(key.toLowerCase()),
|
||||
};
|
||||
},
|
||||
NextResponse: {
|
||||
json: vi.fn((body, init) => ({
|
||||
json: vi.fn().mockResolvedValue(body),
|
||||
status: init?.status || 200,
|
||||
})),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/calendar-subscription/lib/CalendarSubscriptionService");
|
||||
vi.mock("@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventService");
|
||||
vi.mock("@calcom/features/calendar-subscription/lib/sync/CalendarSyncService");
|
||||
vi.mock("@calcom/prisma", () => ({
|
||||
prisma: {},
|
||||
}));
|
||||
|
||||
const mockCalendarSubscriptionService = vi.mocked(CalendarSubscriptionService);
|
||||
|
||||
describe("/api/cron/calendar-subscriptions", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.resetModules();
|
||||
vi.stubEnv("CRON_API_KEY", "test-cron-key");
|
||||
vi.stubEnv("CRON_SECRET", "test-cron-secret");
|
||||
});
|
||||
|
||||
describe("Authentication", () => {
|
||||
test("should return 403 when no API key is provided", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions");
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("Forbiden");
|
||||
}, 10000);
|
||||
|
||||
test("should return 403 when invalid API key is provided", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions");
|
||||
request.headers.set("authorization", "invalid-key");
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("Forbiden");
|
||||
});
|
||||
|
||||
test("should accept valid API key", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions");
|
||||
request.headers.set("authorization", "test-cron-key");
|
||||
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockCheckForNewSubscriptions = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.checkForNewSubscriptions = mockCheckForNewSubscriptions;
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Feature flag checks", () => {
|
||||
test("should return early when cache AND sync are disabled", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions");
|
||||
request.headers.set("authorization", "test-cron-key");
|
||||
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(false);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(false);
|
||||
const mockCheckForNewSubscriptions = vi.fn();
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.checkForNewSubscriptions = mockCheckForNewSubscriptions;
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const body = await response.json();
|
||||
expect(body.ok).toBe(true);
|
||||
expect(mockCheckForNewSubscriptions).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("should proceed when both cache and sync are enabled", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions");
|
||||
request.headers.set("authorization", "test-cron-key");
|
||||
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockCheckForNewSubscriptions = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.checkForNewSubscriptions = mockCheckForNewSubscriptions;
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const body = await response.json();
|
||||
expect(body.ok).toBe(true);
|
||||
expect(mockCheckForNewSubscriptions).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Subscription checking functionality", () => {
|
||||
test("should successfully check for new subscriptions", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions");
|
||||
request.headers.set("authorization", "test-cron-key");
|
||||
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockCheckForNewSubscriptions = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.checkForNewSubscriptions = mockCheckForNewSubscriptions;
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const body = await response.json();
|
||||
expect(body.ok).toBe(true);
|
||||
expect(mockCheckForNewSubscriptions).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test("should handle subscription checking errors gracefully", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions");
|
||||
request.headers.set("authorization", "test-cron-key");
|
||||
|
||||
const mockError = new Error("Subscription service unavailable");
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockCheckForNewSubscriptions = vi.fn().mockRejectedValue(mockError);
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.checkForNewSubscriptions = mockCheckForNewSubscriptions;
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("Subscription service unavailable");
|
||||
});
|
||||
|
||||
test("should handle non-Error exceptions", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions");
|
||||
request.headers.set("authorization", "test-cron-key");
|
||||
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockCheckForNewSubscriptions = vi.fn().mockRejectedValue("String error");
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.checkForNewSubscriptions = mockCheckForNewSubscriptions;
|
||||
|
||||
const { GET } = await import("../route");
|
||||
const response = await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("Unknown error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Service instantiation", () => {
|
||||
test("should instantiate all services with correct dependencies", async () => {
|
||||
const request = new NextRequest("http://localhost/api/cron/calendar-subscriptions");
|
||||
request.headers.set("authorization", "test-cron-key");
|
||||
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockCheckForNewSubscriptions = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.checkForNewSubscriptions = mockCheckForNewSubscriptions;
|
||||
|
||||
const { GET } = await import("../route");
|
||||
await GET(request, { params: Promise.resolve({}) });
|
||||
|
||||
expect(mockCalendarSubscriptionService).toHaveBeenCalledWith({
|
||||
adapterFactory: expect.any(Object),
|
||||
selectedCalendarRepository: expect.any(Object),
|
||||
featuresRepository: expect.any(Object),
|
||||
calendarSyncService: expect.any(Object),
|
||||
calendarCacheEventService: expect.any(Object),
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { DefaultAdapterFactory } from "@calcom/features/calendar-subscription/adapters/AdaptersFactory";
|
||||
import { CalendarSubscriptionService } from "@calcom/features/calendar-subscription/lib/CalendarSubscriptionService";
|
||||
import { CalendarCacheEventRepository } from "@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventRepository";
|
||||
import { CalendarCacheEventService } from "@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventService";
|
||||
import { CalendarSyncService } from "@calcom/features/calendar-subscription/lib/sync/CalendarSyncService";
|
||||
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
|
||||
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/SelectedCalendarRepository";
|
||||
import { BookingRepository } from "@calcom/lib/server/repository/booking";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { defaultResponderForAppDir } from "@calcom/web/app/api/defaultResponderForAppDir";
|
||||
|
||||
/**
|
||||
* Cron webhook
|
||||
* Checks for new calendar subscriptions (rollouts)
|
||||
*
|
||||
* @param request
|
||||
* @returns
|
||||
*/
|
||||
async function getHandler(request: NextRequest) {
|
||||
const apiKey = request.headers.get("authorization") || request.nextUrl.searchParams.get("apiKey");
|
||||
|
||||
if (![process.env.CRON_API_KEY, `Bearer ${process.env.CRON_SECRET}`].includes(`${apiKey}`)) {
|
||||
return NextResponse.json({ message: "Forbiden" }, { status: 403 });
|
||||
}
|
||||
|
||||
// instantiate dependencies
|
||||
const bookingRepository = new BookingRepository(prisma);
|
||||
const calendarSyncService = new CalendarSyncService({
|
||||
bookingRepository,
|
||||
});
|
||||
const calendarCacheEventRepository = new CalendarCacheEventRepository(prisma);
|
||||
const calendarCacheEventService = new CalendarCacheEventService({
|
||||
calendarCacheEventRepository,
|
||||
});
|
||||
|
||||
const calendarSubscriptionService = new CalendarSubscriptionService({
|
||||
adapterFactory: new DefaultAdapterFactory(),
|
||||
selectedCalendarRepository: new SelectedCalendarRepository(prisma),
|
||||
featuresRepository: new FeaturesRepository(prisma),
|
||||
calendarSyncService,
|
||||
calendarCacheEventService,
|
||||
});
|
||||
|
||||
// are features globally enabled
|
||||
const [isCacheEnabled, isSyncEnabled] = await Promise.all([
|
||||
calendarSubscriptionService.isCacheEnabled(),
|
||||
calendarSubscriptionService.isSyncEnabled(),
|
||||
]);
|
||||
|
||||
if (!isCacheEnabled && !isSyncEnabled) {
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
try {
|
||||
await calendarSubscriptionService.checkForNewSubscriptions();
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : "Unknown error";
|
||||
return NextResponse.json({ message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = defaultResponderForAppDir(getHandler);
|
||||
@@ -2,4 +2,4 @@ import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
|
||||
import { handleQueuedFormResponseCleanup } from "@calcom/app-store/routing-forms/cron/queuedFormResponseCleanup";
|
||||
|
||||
export const POST = defaultResponderForAppDir(handleQueuedFormResponseCleanup);
|
||||
export const GET = defaultResponderForAppDir(handleQueuedFormResponseCleanup);
|
||||
|
||||
@@ -8,7 +8,7 @@ import { NextResponse } from "next/server";
|
||||
|
||||
import GoogleCalendarService from "@calcom/app-store/googlecalendar/lib/CalendarService";
|
||||
import { CalendarAppDelegationCredentialInvalidGrantError } from "@calcom/lib/CalendarAppError";
|
||||
import { findUniqueDelegationCalendarCredential } from "@calcom/lib/delegationCredential/server";
|
||||
import { findUniqueDelegationCalendarCredential } from "@calcom/app-store/delegationCredential";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
|
||||
@@ -3,19 +3,25 @@ import { NextResponse } from "next/server";
|
||||
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
|
||||
export async function GET() {
|
||||
const token = randomBytes(32).toString("hex");
|
||||
export async function GET(req: Request) {
|
||||
const url = new URL(req.url);
|
||||
const sameSiteParam = url.searchParams.get("sameSite");
|
||||
|
||||
const useSecureCookies = WEBAPP_URL.startsWith("https://");
|
||||
|
||||
// Validate the param, default to "lax"
|
||||
let sameSite: "lax" | "strict" | "none" = "lax";
|
||||
if (sameSiteParam === "strict" || (sameSiteParam === "none" && useSecureCookies)) {
|
||||
sameSite = sameSiteParam;
|
||||
}
|
||||
|
||||
const token = randomBytes(32).toString("hex");
|
||||
const res = NextResponse.json({ csrfToken: token });
|
||||
|
||||
// We need this cookie to be accessible from embeds where the booking flow is displayed within an iframe on a different origin.
|
||||
// For third‑party iframe contexts (embeds on other sites), browsers require SameSite=None and Secure to make the cookie available.
|
||||
// For local development on http://localhost we fall back to SameSite=Lax to avoid requiring https during development.
|
||||
const useSecureCookies = WEBAPP_URL.startsWith("https://");
|
||||
res.cookies.set("calcom.csrf_token", token, {
|
||||
httpOnly: true,
|
||||
secure: useSecureCookies,
|
||||
sameSite: useSecureCookies ? "none" : "lax",
|
||||
sameSite,
|
||||
path: "/",
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { wrapApiHandlerWithSentry } from "@sentry/nextjs";
|
||||
import { captureException } from "@sentry/nextjs";
|
||||
import type { Params } from "app/_types";
|
||||
import { ApiError } from "next/dist/server/api-utils";
|
||||
import type { NextRequest } from "next/server";
|
||||
@@ -21,10 +19,13 @@ export const defaultResponderForAppDir = <T extends NextResponse | Response = Ne
|
||||
let ok = false;
|
||||
try {
|
||||
performance.mark("Start");
|
||||
|
||||
const result = endpointRoute
|
||||
? await wrapApiHandlerWithSentry(async () => await handler(req, { params }), endpointRoute)()
|
||||
: await handler(req, { params });
|
||||
let result: T | undefined;
|
||||
if (process.env.NODE_ENV === "development" || !endpointRoute) {
|
||||
result = await handler(req, { params });
|
||||
} else {
|
||||
const { wrapApiHandlerWithSentry } = await import("@sentry/nextjs");
|
||||
result = await wrapApiHandlerWithSentry(async () => await handler(req, { params }), endpointRoute)();
|
||||
}
|
||||
|
||||
ok = true;
|
||||
if (result) {
|
||||
@@ -49,6 +50,7 @@ export const defaultResponderForAppDir = <T extends NextResponse | Response = Ne
|
||||
// Don't report 400-499 errors to Sentry/console
|
||||
if (!(serverError.statusCode >= 400 && serverError.statusCode < 500)) {
|
||||
console.error(serverError);
|
||||
const { captureException } = await import("@sentry/nextjs");
|
||||
captureException(error);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import {
|
||||
getAllTranscriptsAccessLinkFromMeetingId,
|
||||
submitBatchProcessorTranscriptionJob,
|
||||
} from "@calcom/app-store/videoClient";
|
||||
} from "@calcom/features/conferencing/lib/videoClient";
|
||||
import { generateVideoToken } from "@calcom/lib/videoTokens";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { getBooking } from "@calcom/web/lib/daily-webhook/getBooking";
|
||||
|
||||
@@ -4,9 +4,11 @@ import { NextResponse } from "next/server";
|
||||
import type Stripe from "stripe";
|
||||
import { z } from "zod";
|
||||
|
||||
import { Plan, SubscriptionStatus } from "@calcom/features/ee/billing/repository/IBillingRepository";
|
||||
import { InternalTeamBilling } from "@calcom/features/ee/billing/teams/internal-team-billing";
|
||||
import stripe from "@calcom/features/ee/payments/server/stripe";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { MembershipSchema } from "@calcom/prisma/zod/modelSchema/MembershipSchema";
|
||||
import { TeamSchema } from "@calcom/prisma/zod/modelSchema/TeamSchema";
|
||||
@@ -54,6 +56,19 @@ async function handler(request: NextRequest) {
|
||||
include: { members: true },
|
||||
});
|
||||
|
||||
if (checkoutSessionSubscription) {
|
||||
const internalBillingService = new InternalTeamBilling(finalizedTeam);
|
||||
await internalBillingService.saveTeamBilling({
|
||||
teamId: finalizedTeam.id,
|
||||
subscriptionId: checkoutSessionSubscription.id,
|
||||
subscriptionItemId: checkoutSessionSubscription.items.data[0].id,
|
||||
customerId: checkoutSessionSubscription.customer as string,
|
||||
// TODO: Implement true subscription status when webhook events are implemented
|
||||
status: SubscriptionStatus.ACTIVE,
|
||||
planName: Plan.TEAM,
|
||||
});
|
||||
}
|
||||
|
||||
const response = {
|
||||
message: `Team created successfully. We also made user with ID=${checkoutSessionMetadata.ownerId} the owner of this team.`,
|
||||
team: schemaTeamReadPublic.parse(finalizedTeam),
|
||||
|
||||
@@ -4,6 +4,8 @@ import { NextResponse } from "next/server";
|
||||
import type Stripe from "stripe";
|
||||
import { z } from "zod";
|
||||
|
||||
import { Plan, SubscriptionStatus } from "@calcom/features/ee/billing/repository/IBillingRepository";
|
||||
import { InternalTeamBilling } from "@calcom/features/ee/billing/teams/internal-team-billing";
|
||||
import stripe from "@calcom/features/ee/payments/server/stripe";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import prisma from "@calcom/prisma";
|
||||
@@ -84,6 +86,19 @@ async function getHandler(req: NextRequest) {
|
||||
},
|
||||
});
|
||||
|
||||
if (checkoutSession && subscription) {
|
||||
const internalBillingService = new InternalTeamBilling(team);
|
||||
await internalBillingService.saveTeamBilling({
|
||||
teamId: team.id,
|
||||
subscriptionId: subscription.id,
|
||||
subscriptionItemId: subscription.items.data[0].id,
|
||||
customerId: subscription.customer as string,
|
||||
// TODO: Implement true subscription status when webhook events are implemented
|
||||
status: SubscriptionStatus.ACTIVE,
|
||||
planName: Plan.TEAM,
|
||||
});
|
||||
}
|
||||
|
||||
// redirect to team screen
|
||||
return NextResponse.redirect(
|
||||
new URL(`/settings/teams/${team.id}/onboard-members?event=team_created`, req.nextUrl.origin),
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { describe, expect, test, vi, afterEach } from "vitest";
|
||||
|
||||
import { getDownloadLinkOfCalVideoByRecordingId } from "@calcom/app-store/videoClient";
|
||||
import { getDownloadLinkOfCalVideoByRecordingId } from "@calcom/features/conferencing/lib/videoClient";
|
||||
import { verifyVideoToken } from "@calcom/lib/videoTokens";
|
||||
|
||||
import { GET } from "../route";
|
||||
|
||||
vi.mock("@calcom/app-store/videoClient", () => ({
|
||||
vi.mock("@calcom/features/conferencing/lib/videoClient", () => ({
|
||||
getDownloadLinkOfCalVideoByRecordingId: vi.fn(),
|
||||
}));
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { getDownloadLinkOfCalVideoByRecordingId } from "@calcom/app-store/videoClient";
|
||||
import { getDownloadLinkOfCalVideoByRecordingId } from "@calcom/features/conferencing/lib/videoClient";
|
||||
import { verifyVideoToken } from "@calcom/lib/videoTokens";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { describe, test, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
import { CalendarSubscriptionService } from "@calcom/features/calendar-subscription/lib/CalendarSubscriptionService";
|
||||
|
||||
vi.mock("next/server", () => ({
|
||||
NextRequest: class MockNextRequest {
|
||||
url: string;
|
||||
method: string;
|
||||
nextUrl: { searchParams: URLSearchParams };
|
||||
private _headers: Map<string, string>;
|
||||
|
||||
constructor(url: string, options: { method?: string } = {}) {
|
||||
this.url = url;
|
||||
this.method = options.method || "POST";
|
||||
this._headers = new Map();
|
||||
this.nextUrl = { searchParams: new URLSearchParams(url.split("?")[1] || "") };
|
||||
}
|
||||
|
||||
headers = {
|
||||
get: (key: string): string | null => this._headers.get(key.toLowerCase()) || null,
|
||||
set: (key: string, value: string): void => {
|
||||
this._headers.set(key.toLowerCase(), value);
|
||||
},
|
||||
has: (key: string): boolean => this._headers.has(key.toLowerCase()),
|
||||
};
|
||||
},
|
||||
NextResponse: {
|
||||
json: vi.fn((body, init) => ({
|
||||
json: vi.fn().mockResolvedValue(body),
|
||||
status: init?.status || 200,
|
||||
})),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/calendar-subscription/lib/CalendarSubscriptionService");
|
||||
vi.mock("@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventService");
|
||||
vi.mock("@calcom/features/calendar-subscription/lib/sync/CalendarSyncService");
|
||||
vi.mock("@calcom/prisma", () => ({
|
||||
prisma: {},
|
||||
}));
|
||||
|
||||
const mockCalendarSubscriptionService = vi.mocked(CalendarSubscriptionService);
|
||||
|
||||
describe("/api/webhooks/calendar-subscription/[provider]", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
describe("Provider validation", () => {
|
||||
test("should accept google_calendar provider", async () => {
|
||||
const request = new NextRequest("http://localhost/api/webhooks/calendar-subscription/google_calendar", {
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(false);
|
||||
const mockProcessWebhook = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.processWebhook = mockProcessWebhook;
|
||||
|
||||
const { POST } = await import("../route");
|
||||
const response = await POST(request, {
|
||||
params: Promise.resolve({ provider: "google_calendar" }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockProcessWebhook).toHaveBeenCalledWith("google_calendar", request);
|
||||
}, 10000);
|
||||
|
||||
test("should accept office365_calendar provider", async () => {
|
||||
const request = new NextRequest(
|
||||
"http://localhost/api/webhooks/calendar-subscription/office365_calendar",
|
||||
{
|
||||
method: "POST",
|
||||
}
|
||||
);
|
||||
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(false);
|
||||
const mockProcessWebhook = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.processWebhook = mockProcessWebhook;
|
||||
|
||||
const { POST } = await import("../route");
|
||||
const response = await POST(request, {
|
||||
params: Promise.resolve({ provider: "office365_calendar" }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockProcessWebhook).toHaveBeenCalledWith("office365_calendar", request);
|
||||
});
|
||||
|
||||
test("should reject unsupported provider", async () => {
|
||||
const request = new NextRequest(
|
||||
"http://localhost/api/webhooks/calendar-subscription/unsupported_calendar",
|
||||
{
|
||||
method: "POST",
|
||||
}
|
||||
);
|
||||
|
||||
const { POST } = await import("../route");
|
||||
const response = await POST(request, {
|
||||
params: Promise.resolve({ provider: "unsupported_calendar" }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("Unsupported provider");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Feature flag handling", () => {
|
||||
test("should return 200 when neither cache nor sync is enabled", async () => {
|
||||
const request = new NextRequest("http://localhost/api/webhooks/calendar-subscription/google_calendar", {
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(false);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(false);
|
||||
const mockProcessWebhook = vi.fn();
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.processWebhook = mockProcessWebhook;
|
||||
|
||||
const { POST } = await import("../route");
|
||||
const response = await POST(request, {
|
||||
params: Promise.resolve({ provider: "google_calendar" }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("No cache or sync enabled");
|
||||
expect(mockProcessWebhook).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("should process webhook when cache is enabled", async () => {
|
||||
const request = new NextRequest("http://localhost/api/webhooks/calendar-subscription/google_calendar", {
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(false);
|
||||
const mockProcessWebhook = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.processWebhook = mockProcessWebhook;
|
||||
|
||||
const { POST } = await import("../route");
|
||||
const response = await POST(request, {
|
||||
params: Promise.resolve({ provider: "google_calendar" }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("Webhook processed");
|
||||
expect(mockProcessWebhook).toHaveBeenCalledWith("google_calendar", request);
|
||||
});
|
||||
|
||||
test("should process webhook when sync is enabled", async () => {
|
||||
const request = new NextRequest("http://localhost/api/webhooks/calendar-subscription/google_calendar", {
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(false);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockProcessWebhook = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.processWebhook = mockProcessWebhook;
|
||||
|
||||
const { POST } = await import("../route");
|
||||
const response = await POST(request, {
|
||||
params: Promise.resolve({ provider: "google_calendar" }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("Webhook processed");
|
||||
expect(mockProcessWebhook).toHaveBeenCalledWith("google_calendar", request);
|
||||
});
|
||||
|
||||
test("should process webhook when both cache and sync are enabled", async () => {
|
||||
const request = new NextRequest("http://localhost/api/webhooks/calendar-subscription/google_calendar", {
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockProcessWebhook = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.processWebhook = mockProcessWebhook;
|
||||
|
||||
const { POST } = await import("../route");
|
||||
const response = await POST(request, {
|
||||
params: Promise.resolve({ provider: "google_calendar" }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("Webhook processed");
|
||||
expect(mockProcessWebhook).toHaveBeenCalledWith("google_calendar", request);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Error handling", () => {
|
||||
test("should handle webhook processing errors gracefully", async () => {
|
||||
const request = new NextRequest("http://localhost/api/webhooks/calendar-subscription/google_calendar", {
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
const mockError = new Error("Webhook validation failed");
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(false);
|
||||
const mockProcessWebhook = vi.fn().mockRejectedValue(mockError);
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.processWebhook = mockProcessWebhook;
|
||||
|
||||
const { POST } = await import("../route");
|
||||
const response = await POST(request, {
|
||||
params: Promise.resolve({ provider: "google_calendar" }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("Webhook validation failed");
|
||||
});
|
||||
|
||||
test("should handle non-Error exceptions", async () => {
|
||||
const request = new NextRequest("http://localhost/api/webhooks/calendar-subscription/google_calendar", {
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(false);
|
||||
const mockProcessWebhook = vi.fn().mockRejectedValue("String error");
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.processWebhook = mockProcessWebhook;
|
||||
|
||||
const { POST } = await import("../route");
|
||||
const response = await POST(request, {
|
||||
params: Promise.resolve({ provider: "google_calendar" }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("Unknown error");
|
||||
});
|
||||
|
||||
test("should handle feature flag check errors", async () => {
|
||||
const request = new NextRequest("http://localhost/api/webhooks/calendar-subscription/google_calendar", {
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
const mockError = new Error("Feature flag service unavailable");
|
||||
const mockIsCacheEnabled = vi.fn().mockRejectedValue(mockError);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(false);
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
|
||||
const { POST } = await import("../route");
|
||||
const response = await POST(request, {
|
||||
params: Promise.resolve({ provider: "google_calendar" }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
const body = await response.json();
|
||||
expect(body.message).toBe("Feature flag service unavailable");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Service instantiation", () => {
|
||||
test("should instantiate all services with correct dependencies", async () => {
|
||||
const request = new NextRequest("http://localhost/api/webhooks/calendar-subscription/google_calendar", {
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
const mockIsCacheEnabled = vi.fn().mockResolvedValue(true);
|
||||
const mockIsSyncEnabled = vi.fn().mockResolvedValue(false);
|
||||
const mockProcessWebhook = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
mockCalendarSubscriptionService.prototype.isCacheEnabled = mockIsCacheEnabled;
|
||||
mockCalendarSubscriptionService.prototype.isSyncEnabled = mockIsSyncEnabled;
|
||||
mockCalendarSubscriptionService.prototype.processWebhook = mockProcessWebhook;
|
||||
|
||||
const { POST } = await import("../route");
|
||||
await POST(request, {
|
||||
params: Promise.resolve({ provider: "google_calendar" }),
|
||||
});
|
||||
|
||||
expect(mockCalendarSubscriptionService).toHaveBeenCalledWith({
|
||||
adapterFactory: expect.any(Object),
|
||||
selectedCalendarRepository: expect.any(Object),
|
||||
featuresRepository: expect.any(Object),
|
||||
calendarSyncService: expect.any(Object),
|
||||
calendarCacheEventService: expect.any(Object),
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { Params } from "app/_types";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import type { CalendarSubscriptionProvider } from "@calcom/features/calendar-subscription/adapters/AdaptersFactory";
|
||||
import { DefaultAdapterFactory } from "@calcom/features/calendar-subscription/adapters/AdaptersFactory";
|
||||
import { CalendarSubscriptionService } from "@calcom/features/calendar-subscription/lib/CalendarSubscriptionService";
|
||||
import { CalendarCacheEventRepository } from "@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventRepository";
|
||||
import { CalendarCacheEventService } from "@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventService";
|
||||
import { CalendarSyncService } from "@calcom/features/calendar-subscription/lib/sync/CalendarSyncService";
|
||||
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/SelectedCalendarRepository";
|
||||
import { BookingRepository } from "@calcom/lib/server/repository/booking";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { defaultResponderForAppDir } from "@calcom/web/app/api/defaultResponderForAppDir";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["calendar-webhook"] });
|
||||
|
||||
function extractAndValidateProviderFromParams(params: Params): CalendarSubscriptionProvider | null {
|
||||
if (!("provider" in params)) {
|
||||
return null;
|
||||
}
|
||||
const { provider } = params;
|
||||
if (provider === "google_calendar" || provider === "office365_calendar") {
|
||||
return provider;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles incoming POST requests for calendar webhooks.
|
||||
* It processes the webhook based on the calendar provider specified in the URL.
|
||||
* If the provider is unsupported, it returns a 400 response.
|
||||
* If the webhook is processed successfully, it returns a 200 response.
|
||||
* In case of errors during processing, it returns a 500 response with the error message.
|
||||
* @param {NextRequest} request - The incoming request object.
|
||||
* @param {Object} context - The context object containing route parameters.
|
||||
* @param {Promise<Params>} context.params - A promise that resolves to the route parameters.
|
||||
* @returns {Promise<NextResponse>} - A promise that resolves to the response object.
|
||||
*/
|
||||
async function postHandler(request: NextRequest, ctx: { params: Promise<Params> }) {
|
||||
const providerFromParams = extractAndValidateProviderFromParams(await ctx.params);
|
||||
if (!providerFromParams) {
|
||||
return NextResponse.json({ message: "Unsupported provider" }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
// instantiate dependencies
|
||||
const bookingRepository = new BookingRepository(prisma);
|
||||
const calendarSyncService = new CalendarSyncService({
|
||||
bookingRepository,
|
||||
});
|
||||
const calendarCacheEventRepository = new CalendarCacheEventRepository(prisma);
|
||||
const calendarCacheEventService = new CalendarCacheEventService({
|
||||
calendarCacheEventRepository,
|
||||
});
|
||||
|
||||
const calendarSubscriptionService = new CalendarSubscriptionService({
|
||||
adapterFactory: new DefaultAdapterFactory(),
|
||||
selectedCalendarRepository: new SelectedCalendarRepository(prisma),
|
||||
featuresRepository: new FeaturesRepository(prisma),
|
||||
calendarSyncService,
|
||||
calendarCacheEventService,
|
||||
});
|
||||
|
||||
// are features globally enabled
|
||||
const [isCacheEnabled, isSyncEnabled] = await Promise.all([
|
||||
calendarSubscriptionService.isCacheEnabled(),
|
||||
calendarSubscriptionService.isSyncEnabled(),
|
||||
]);
|
||||
|
||||
if (!isCacheEnabled && !isSyncEnabled) {
|
||||
log.debug("No cache or sync enabled");
|
||||
return NextResponse.json({ message: "No cache or sync enabled" }, { status: 200 });
|
||||
}
|
||||
|
||||
await calendarSubscriptionService.processWebhook(providerFromParams, request);
|
||||
return NextResponse.json({ message: "Webhook processed" }, { status: 200 });
|
||||
} catch (error) {
|
||||
log.error("Error processing webhook", { error });
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
return NextResponse.json({ message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export const POST = defaultResponderForAppDir(postHandler);
|
||||
@@ -2,8 +2,6 @@ import type { NextRequest } from "next/server";
|
||||
import { Retell } from "retell-sdk";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
import { PrismaAgentRepository } from "@calcom/lib/server/repository/PrismaAgentRepository";
|
||||
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
|
||||
import type { CalAiPhoneNumber, User, Team, Agent } from "@calcom/prisma/client";
|
||||
|
||||
import { POST } from "../route";
|
||||
@@ -81,16 +79,19 @@ vi.mock("@calcom/features/ee/billing/credit-service", () => ({
|
||||
})),
|
||||
}));
|
||||
|
||||
const mockFindByPhoneNumber = vi.fn();
|
||||
const mockFindByProviderAgentId = vi.fn();
|
||||
|
||||
vi.mock("@calcom/lib/server/repository/PrismaPhoneNumberRepository", () => ({
|
||||
PrismaPhoneNumberRepository: {
|
||||
findByPhoneNumber: vi.fn(),
|
||||
},
|
||||
PrismaPhoneNumberRepository: vi.fn().mockImplementation(() => ({
|
||||
findByPhoneNumber: mockFindByPhoneNumber,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/server/repository/PrismaAgentRepository", () => ({
|
||||
PrismaAgentRepository: {
|
||||
findByProviderAgentId: vi.fn(),
|
||||
},
|
||||
PrismaAgentRepository: vi.fn().mockImplementation(() => ({
|
||||
findByProviderAgentId: mockFindByProviderAgentId,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("next/server", () => ({
|
||||
@@ -196,7 +197,7 @@ describe("Retell AI Webhook Handler", () => {
|
||||
team: null,
|
||||
};
|
||||
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
mockFindByPhoneNumber.mockResolvedValue(mockPhoneNumber);
|
||||
|
||||
mockHasAvailableCredits.mockResolvedValue(true);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
@@ -255,7 +256,7 @@ describe("Retell AI Webhook Handler", () => {
|
||||
user: null,
|
||||
};
|
||||
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockTeamPhoneNumber);
|
||||
mockFindByPhoneNumber.mockResolvedValue(mockTeamPhoneNumber);
|
||||
|
||||
mockHasAvailableCredits.mockResolvedValue(true);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
@@ -314,12 +315,12 @@ describe("Retell AI Webhook Handler", () => {
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(PrismaPhoneNumberRepository.findByPhoneNumber).not.toHaveBeenCalled();
|
||||
expect(mockFindByPhoneNumber).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle phone number not found", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(null);
|
||||
mockFindByPhoneNumber.mockResolvedValue(null);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
@@ -365,7 +366,7 @@ describe("Retell AI Webhook Handler", () => {
|
||||
team: null,
|
||||
};
|
||||
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
mockFindByPhoneNumber.mockResolvedValue(mockPhoneNumber);
|
||||
|
||||
mockHasAvailableCredits.mockResolvedValue(false);
|
||||
|
||||
@@ -440,7 +441,7 @@ describe("Retell AI Webhook Handler", () => {
|
||||
team: null,
|
||||
};
|
||||
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
mockFindByPhoneNumber.mockResolvedValue(mockPhoneNumber);
|
||||
mockHasAvailableCredits.mockResolvedValue(true);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
@@ -494,7 +495,7 @@ describe("Retell AI Webhook Handler", () => {
|
||||
user: { id: 42, email: "u@example.com", name: "U" },
|
||||
team: null,
|
||||
};
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
mockFindByPhoneNumber.mockResolvedValue(mockPhoneNumber);
|
||||
mockHasAvailableCredits.mockResolvedValue(true);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
@@ -544,7 +545,7 @@ describe("Retell AI Webhook Handler", () => {
|
||||
user: { id: 1, email: "test@example.com", name: "Test User" },
|
||||
team: null,
|
||||
};
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
mockFindByPhoneNumber.mockResolvedValue(mockPhoneNumber);
|
||||
mockChargeCredits.mockResolvedValue({ userId: 1 });
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
@@ -596,7 +597,7 @@ describe("Retell AI Webhook Handler", () => {
|
||||
user: { id: 1, email: "test@example.com", name: "Test User" },
|
||||
team: null,
|
||||
};
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
mockFindByPhoneNumber.mockResolvedValue(mockPhoneNumber);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
@@ -661,7 +662,7 @@ describe("Retell AI Webhook Handler", () => {
|
||||
user: { id: 1, email: "test@example.com", name: "Test User" },
|
||||
team: null,
|
||||
};
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
mockFindByPhoneNumber.mockResolvedValue(mockPhoneNumber);
|
||||
|
||||
// Mock chargeCredits to throw an error
|
||||
mockChargeCredits.mockRejectedValue(new Error("Credit service error"));
|
||||
@@ -695,7 +696,7 @@ describe("Retell AI Webhook Handler", () => {
|
||||
describe("Web Call Tests", () => {
|
||||
const mockAgent: Pick<
|
||||
Agent,
|
||||
"id" | "name" | "providerAgentId" | "enabled" | "userId" | "teamId" | "createdAt" | "updatedAt"
|
||||
"id" | "name" | "providerAgentId" | "enabled" | "userId" | "teamId" | "createdAt" | "updatedAt" | "inboundEventTypeId"
|
||||
> = {
|
||||
id: "agent-123",
|
||||
name: "Test Agent",
|
||||
@@ -705,6 +706,7 @@ describe("Retell AI Webhook Handler", () => {
|
||||
teamId: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
inboundEventTypeId: null,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -713,7 +715,7 @@ describe("Retell AI Webhook Handler", () => {
|
||||
});
|
||||
|
||||
it("should process web call with valid agent and charge credits", async () => {
|
||||
vi.mocked(PrismaAgentRepository.findByProviderAgentId).mockResolvedValue(mockAgent);
|
||||
mockFindByProviderAgentId.mockResolvedValue(mockAgent);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
@@ -739,7 +741,7 @@ describe("Retell AI Webhook Handler", () => {
|
||||
const data = await response.json();
|
||||
expect(data.success).toBe(true);
|
||||
|
||||
expect(PrismaAgentRepository.findByProviderAgentId).toHaveBeenCalledWith({
|
||||
expect(mockFindByProviderAgentId).toHaveBeenCalledWith({
|
||||
providerAgentId: "agent_5e3e0d29d692172c2c24d8f9a7",
|
||||
});
|
||||
|
||||
@@ -755,8 +757,8 @@ describe("Retell AI Webhook Handler", () => {
|
||||
});
|
||||
|
||||
it("should handle web call with team agent", async () => {
|
||||
const teamAgent = { ...mockAgent, userId: 2, teamId: 10 };
|
||||
vi.mocked(PrismaAgentRepository.findByProviderAgentId).mockResolvedValue(teamAgent);
|
||||
const teamAgent = { ...mockAgent, userId: 2, teamId: 10, inboundEventTypeId: null };
|
||||
mockFindByProviderAgentId.mockResolvedValue(teamAgent);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
@@ -789,7 +791,7 @@ describe("Retell AI Webhook Handler", () => {
|
||||
});
|
||||
|
||||
it("should handle web call without from_number", async () => {
|
||||
vi.mocked(PrismaAgentRepository.findByProviderAgentId).mockResolvedValue(mockAgent);
|
||||
mockFindByProviderAgentId.mockResolvedValue(mockAgent);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
@@ -810,8 +812,8 @@ describe("Retell AI Webhook Handler", () => {
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(PrismaAgentRepository.findByProviderAgentId).toHaveBeenCalled();
|
||||
expect(PrismaPhoneNumberRepository.findByPhoneNumber).not.toHaveBeenCalled();
|
||||
expect(mockFindByProviderAgentId).toHaveBeenCalled();
|
||||
expect(mockFindByPhoneNumber).not.toHaveBeenCalled();
|
||||
expect(mockChargeCredits).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -833,12 +835,12 @@ describe("Retell AI Webhook Handler", () => {
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(PrismaAgentRepository.findByProviderAgentId).not.toHaveBeenCalled();
|
||||
expect(mockFindByProviderAgentId).not.toHaveBeenCalled();
|
||||
expect(mockChargeCredits).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle web call with agent not found", async () => {
|
||||
vi.mocked(PrismaAgentRepository.findByProviderAgentId).mockResolvedValue(null);
|
||||
mockFindByProviderAgentId.mockResolvedValue(null);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
@@ -860,7 +862,7 @@ describe("Retell AI Webhook Handler", () => {
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(PrismaAgentRepository.findByProviderAgentId).toHaveBeenCalledWith({
|
||||
expect(mockFindByProviderAgentId).toHaveBeenCalledWith({
|
||||
providerAgentId: "non-existent-agent",
|
||||
});
|
||||
expect(mockChargeCredits).not.toHaveBeenCalled();
|
||||
|
||||
@@ -9,6 +9,7 @@ import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { PrismaAgentRepository } from "@calcom/lib/server/repository/PrismaAgentRepository";
|
||||
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { CreditUsageType } from "@calcom/prisma/enums";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["retell-ai-webhook"] });
|
||||
@@ -133,7 +134,7 @@ async function handleCallAnalyzed(callData: any) {
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
message: `Invalid or missing call_cost.total_duration_seconds for call ${call_id}`
|
||||
message: `Invalid or missing call_cost.total_duration_seconds for call ${call_id}`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -146,11 +147,12 @@ async function handleCallAnalyzed(callData: any) {
|
||||
log.error(`Web call ${call_id} missing agent_id, cannot charge credits`);
|
||||
return {
|
||||
success: false,
|
||||
message: `Web call ${call_id} missing agent_id, cannot charge credits`
|
||||
message: `Web call ${call_id} missing agent_id, cannot charge credits`,
|
||||
};
|
||||
}
|
||||
|
||||
const agent = await PrismaAgentRepository.findByProviderAgentId({
|
||||
const agentRepo = new PrismaAgentRepository(prisma);
|
||||
const agent = await agentRepo.findByProviderAgentId({
|
||||
providerAgentId: agent_id,
|
||||
});
|
||||
|
||||
@@ -158,17 +160,17 @@ async function handleCallAnalyzed(callData: any) {
|
||||
log.error(`No agent found for providerAgentId ${agent_id}, call ${call_id}`);
|
||||
return {
|
||||
success: false,
|
||||
message: `No agent found for providerAgentId ${agent_id}, call ${call_id}`
|
||||
message: `No agent found for providerAgentId ${agent_id}, call ${call_id}`,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
userId = agent.userId ?? undefined;
|
||||
teamId = agent.teamId ?? undefined;
|
||||
|
||||
log.info(`Processing web call ${call_id} for agent ${agent_id}, user ${userId}, team ${teamId}`);
|
||||
} else {
|
||||
const phoneNumber = await PrismaPhoneNumberRepository.findByPhoneNumber({
|
||||
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
|
||||
const phoneNumber = await phoneNumberRepo.findByPhoneNumber({
|
||||
phoneNumber: from_number,
|
||||
});
|
||||
|
||||
|
||||
@@ -266,7 +266,7 @@ export default function CancelBooking(props: Props) {
|
||||
|
||||
telemetry.event(telemetryEventTypes.bookingCancelled, collectPageParameters());
|
||||
|
||||
const response = await fetch("/api/csrf", { cache: "no-store" });
|
||||
const response = await fetch("/api/csrf?sameSite=none", { cache: "no-store" });
|
||||
const { csrfToken } = await response.json();
|
||||
|
||||
const res = await fetch("/api/cancel", {
|
||||
|
||||
Regular → Executable
+2
-2
@@ -23,9 +23,9 @@ try {
|
||||
"*/5 * * * * *",
|
||||
async function () {
|
||||
await Promise.allSettled([
|
||||
fetchCron("/calendar-cache/cron"),
|
||||
fetchCron("/cron/calendar-subscriptions"),
|
||||
// fetchCron("/calendar-cache/cron"),
|
||||
// fetchCron("/cron/calVideoNoShowWebhookTriggers"),
|
||||
//
|
||||
fetchCron("/tasks/cron"),
|
||||
]);
|
||||
},
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// The added config here will be used whenever a users loads a page in their browser.
|
||||
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
|
||||
import * as Sentry from "@sentry/nextjs";
|
||||
import { initBotId } from "botid/client/core";
|
||||
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
Sentry.init({
|
||||
@@ -48,3 +49,13 @@ export function onRouterTransitionStart(url: string, navigationType: "push" | "r
|
||||
Sentry.captureRouterTransitionStart(url, navigationType);
|
||||
}
|
||||
}
|
||||
|
||||
process.env.NEXT_PUBLIC_VERCEL_USE_BOTID_IN_BOOKER === "1" &&
|
||||
initBotId({
|
||||
protect: [
|
||||
{
|
||||
path: "/api/book/event",
|
||||
method: "POST",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
export type BookingResponse = Awaited<
|
||||
ReturnType<typeof import("@calcom/features/bookings/lib/handleNewBooking").default>
|
||||
>;
|
||||
import type { RegularBookingCreateResult } from "@calcom/features/bookings/lib/dto/types";
|
||||
|
||||
export type BookingResponse = RegularBookingCreateResult;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import type { CSSProperties } from "react";
|
||||
import { useEffect, useReducer, type CSSProperties } from "react";
|
||||
import type { UseFormReturn } from "react-hook-form";
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
@@ -16,121 +17,176 @@ import type { getServerSideProps } from "@server/lib/auth/forgot-password/[id]/g
|
||||
|
||||
export type PageProps = inferSSRProps<typeof getServerSideProps>;
|
||||
|
||||
export default function Page({ requestId, isRequestExpired, csrfToken }: PageProps) {
|
||||
function Success() {
|
||||
const { t } = useLocale();
|
||||
const formMethods = useForm<{ new_password: string }>();
|
||||
const success = formMethods.formState.isSubmitSuccessful;
|
||||
const loading = formMethods.formState.isSubmitting;
|
||||
const passwordValue = formMethods.watch("new_password");
|
||||
const isEmpty = passwordValue?.length === 0;
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="font-cal text-emphasis mt-6 text-center text-3xl font-extrabold">
|
||||
{t("password_updated")}
|
||||
</h2>
|
||||
</div>
|
||||
<Button href="/auth/login" className="w-full justify-center">
|
||||
{t("login")}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const submitChangePassword = async ({ password, requestId }: { password: string; requestId: string }) => {
|
||||
function Expired() {
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="font-cal text-emphasis mt-6 text-center text-3xl font-extrabold">{t("whoops")}</h2>
|
||||
<h2 className="text-emphasis text-center text-3xl font-extrabold">{t("request_is_expired")}</h2>
|
||||
</div>
|
||||
<p>{t("request_is_expired_instructions")}</p>
|
||||
<Link href="/auth/forgot-password" passHref legacyBehavior>
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full justify-center px-4 py-2 text-sm font-medium text-blue-600 focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2">
|
||||
{t("try_again")}
|
||||
</button>
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
type FormValues = {
|
||||
newPassword: string;
|
||||
csrfToken: string;
|
||||
};
|
||||
|
||||
function PasswordResetForm({
|
||||
form: formMethods,
|
||||
requestId,
|
||||
}: {
|
||||
form: UseFormReturn<FormValues>;
|
||||
requestId: string;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const [refreshToken, forceRefresh] = useReducer((x) => x + 1, 0);
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
setError,
|
||||
formState: { isSubmitting: loading },
|
||||
} = formMethods;
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/api/csrf", { cache: "no-store" })
|
||||
.then((res) => res.json())
|
||||
.then(({ csrfToken }) => setValue("csrfToken", csrfToken))
|
||||
.catch(() => setValue("csrfToken", ""));
|
||||
}, [setValue, refreshToken]);
|
||||
|
||||
const submitChangePassword = async ({
|
||||
password,
|
||||
requestId,
|
||||
csrfToken,
|
||||
}: {
|
||||
password: string;
|
||||
requestId: string;
|
||||
csrfToken: string;
|
||||
}) => {
|
||||
const res = await fetch("/api/auth/reset-password", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ requestId, password }),
|
||||
body: JSON.stringify({ requestId, password, csrfToken }),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
const json = await res.json();
|
||||
if (!res.ok) return formMethods.setError("new_password", { type: "server", message: json.message });
|
||||
if (!res.ok) {
|
||||
// if the request fails, we want to force refresh of the CSRF token - this allows resubmit
|
||||
forceRefresh();
|
||||
return setError("newPassword", { type: "server", message: json.message });
|
||||
}
|
||||
};
|
||||
|
||||
const Success = () => {
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="font-cal text-emphasis mt-6 text-center text-3xl font-extrabold">
|
||||
{t("password_updated")}
|
||||
</h2>
|
||||
</div>
|
||||
<Button href="/auth/login" className="w-full justify-center">
|
||||
{t("login")}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
const passwordValue = watch("newPassword");
|
||||
const isEmpty = passwordValue?.length === 0;
|
||||
|
||||
const Expired = () => {
|
||||
return (
|
||||
<Form
|
||||
className="space-y-6"
|
||||
form={formMethods}
|
||||
style={
|
||||
{
|
||||
"--cal-brand": "#111827",
|
||||
"--cal-brand-emphasis": "#101010",
|
||||
"--cal-brand-text": "white",
|
||||
"--cal-brand-subtle": "#9CA3AF",
|
||||
} as CSSProperties
|
||||
}
|
||||
handleSubmit={async (values) => {
|
||||
await submitChangePassword({
|
||||
password: values.newPassword,
|
||||
csrfToken: values.csrfToken,
|
||||
requestId,
|
||||
});
|
||||
}}>
|
||||
<input {...formMethods.register("csrfToken")} name="csrfToken" type="hidden" hidden />
|
||||
<div className="mt-1">
|
||||
<PasswordField
|
||||
{...formMethods.register("newPassword", {
|
||||
minLength: {
|
||||
message: t("password_hint_min"),
|
||||
value: 7, // We don't have user here so we can't check if they are admin or not
|
||||
},
|
||||
pattern: {
|
||||
message: "Should contain a number, uppercase and lowercase letters",
|
||||
value: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).*$/gm,
|
||||
},
|
||||
})}
|
||||
label={t("new_password")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Button
|
||||
loading={loading}
|
||||
color="primary"
|
||||
type="submit"
|
||||
disabled={loading || isEmpty}
|
||||
className="w-full justify-center">
|
||||
{t("reset_password")}
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Page({ requestId, isRequestExpired }: PageProps) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const formMethods = useForm<FormValues>({
|
||||
defaultValues: {
|
||||
newPassword: "",
|
||||
csrfToken: "",
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
formState: { isSubmitSuccessful: success },
|
||||
} = formMethods;
|
||||
|
||||
if (isRequestExpired) {
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="font-cal text-emphasis mt-6 text-center text-3xl font-extrabold">{t("whoops")}</h2>
|
||||
<h2 className="text-emphasis text-center text-3xl font-extrabold">{t("request_is_expired")}</h2>
|
||||
</div>
|
||||
<p>{t("request_is_expired_instructions")}</p>
|
||||
<Link href="/auth/forgot-password" passHref legacyBehavior>
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full justify-center px-4 py-2 text-sm font-medium text-blue-600 focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2">
|
||||
{t("try_again")}
|
||||
</button>
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
<AuthContainer showLogo heading={t("reset_password")}>
|
||||
<Expired />
|
||||
</AuthContainer>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContainer showLogo heading={!success ? t("reset_password") : undefined}>
|
||||
{isRequestExpired && <Expired />}
|
||||
{!isRequestExpired && !success && (
|
||||
<>
|
||||
<Form
|
||||
className="space-y-6"
|
||||
form={formMethods}
|
||||
style={
|
||||
{
|
||||
"--cal-brand": "#111827",
|
||||
"--cal-brand-emphasis": "#101010",
|
||||
"--cal-brand-text": "white",
|
||||
"--cal-brand-subtle": "#9CA3AF",
|
||||
} as CSSProperties
|
||||
}
|
||||
handleSubmit={async (values) => {
|
||||
await submitChangePassword({
|
||||
password: values.new_password,
|
||||
requestId,
|
||||
});
|
||||
}}>
|
||||
<input name="csrfToken" type="hidden" defaultValue={csrfToken} hidden />
|
||||
<div className="mt-1">
|
||||
<PasswordField
|
||||
{...formMethods.register("new_password", {
|
||||
minLength: {
|
||||
message: t("password_hint_min"),
|
||||
value: 7, // We don't have user here so we can't check if they are admin or not
|
||||
},
|
||||
pattern: {
|
||||
message: "Should contain a number, uppercase and lowercase letters",
|
||||
value: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).*$/gm,
|
||||
},
|
||||
})}
|
||||
label={t("new_password")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Button
|
||||
loading={loading}
|
||||
color="primary"
|
||||
type="submit"
|
||||
disabled={loading || isEmpty}
|
||||
className="w-full justify-center">
|
||||
{t("reset_password")}
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</>
|
||||
)}
|
||||
{!isRequestExpired && success && (
|
||||
<>
|
||||
<Success />
|
||||
</>
|
||||
)}
|
||||
{success ? <Success /> : <PasswordResetForm form={formMethods} requestId={requestId} />}
|
||||
</AuthContainer>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
require("dotenv").config({ path: "../../.env" });
|
||||
const englishTranslation = require("./public/static/locales/en/common.json");
|
||||
const { withAxiom } = require("next-axiom");
|
||||
const { withBotId } = require("botid/next/config");
|
||||
const { version } = require("./package.json");
|
||||
const { PrismaPlugin } = require("@prisma/nextjs-monorepo-workaround-plugin");
|
||||
const {
|
||||
@@ -117,6 +118,11 @@ if (process.env.ANALYZE === "true") {
|
||||
}
|
||||
|
||||
plugins.push(withAxiom);
|
||||
|
||||
if (process.env.NEXT_PUBLIC_VERCEL_USE_BOTID_IN_BOOKER === "1") {
|
||||
plugins.push(withBotId);
|
||||
}
|
||||
|
||||
const orgDomainMatcherConfig = {
|
||||
root: nextJsOrgRewriteConfig.disableRootPathRewrite
|
||||
? null
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@calcom/web",
|
||||
"version": "5.7.6",
|
||||
"version": "5.7.11",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"analyze": "ANALYZE=true next build",
|
||||
@@ -87,6 +87,7 @@
|
||||
"async": "^3.2.4",
|
||||
"bcp-47-match": "^2.0.3",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"botid": "^1.5.7",
|
||||
"classnames": "^2.3.1",
|
||||
"dompurify": "^3.1.7",
|
||||
"dotenv-cli": "^6.0.0",
|
||||
@@ -108,7 +109,7 @@
|
||||
"memory-cache": "^0.2.0",
|
||||
"micro": "^10.0.1",
|
||||
"mime-types": "^2.1.35",
|
||||
"next": "^15.4.5",
|
||||
"next": "15.5.4",
|
||||
"next-auth": "^4.22.1",
|
||||
"next-axiom": "^0.17.0",
|
||||
"next-collect": "^0.2.1",
|
||||
@@ -138,7 +139,7 @@
|
||||
"react-select": "^5.7.0",
|
||||
"react-timezone-select": "^1.4.0",
|
||||
"react-turnstile": "^1.1.3",
|
||||
"react-use-intercom": "1.5.1",
|
||||
"react-use-intercom": "^5.5.0",
|
||||
"recoil": "^0.7.7",
|
||||
"remove-markdown": "^0.5.0",
|
||||
"retell-client-js-sdk": "^2.0.0",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user