refactor: Remove circular deps between @calcom/lib and @calcom/features [2] (#24438)
* move SystemField to features * migrate workflow service * merge two tests for team repository * update imports and migrate team repository * migrate delegation credential repository * migrate credential repository * migrate entityPermissionUtils * migrate hashedLink service and repository * migrate membership service * update imports * remove file * migrate buildEventUrlFromBooking * migrate getAllUserBookings to features * update imports * update organizationMock * migrate slots * migrate date-ranges to schedules dir * migrate getAggregatedAvailability * fix * refactor * migrate useCreateEventType hook to features * migrate assignValueToUser * migrate validateUsername to auth features * migrate system field back to lib * migrate getLabelValueMapFromResponses back to lib * update imports * use relative path * fix type checks * fix * fix * fix tests * update gh codeowners * fix * fix
This commit is contained in:
1 parent
79b319c1dd
commit
e91bf53d80
145 files changed
+412
-405
No files matched your search
@@ -32,7 +32,7 @@ import logger from "@calcom/lib/logger";
|
||||
import { randomString } from "@calcom/lib/random";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { hashEmail } from "@calcom/lib/server/PiiHasher";
|
||||
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
|
||||
import { CredentialRepository } from "@calcom/features/credentials/repositories/CredentialRepository";
|
||||
import { DeploymentRepository } from "@calcom/lib/server/repository/deployment";
|
||||
import { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
|
||||
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
|
||||
|
||||
@@ -6,6 +6,7 @@ import { getLocaleFromRequest } from "@calcom/features/auth/lib/getLocaleFromReq
|
||||
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
|
||||
import { createOrUpdateMemberships } from "@calcom/features/auth/signup/utils/createOrUpdateMemberships";
|
||||
import { prefillAvatar } from "@calcom/features/auth/signup/utils/prefillAvatar";
|
||||
import { validateAndGetCorrectedUsernameAndEmail } from "@calcom/features/auth/signup/utils/validateUsername";
|
||||
import { StripeBillingService } from "@calcom/features/ee/billing/stripe-billing-service";
|
||||
import { sentrySpan } from "@calcom/features/watchlist/lib/telemetry";
|
||||
import { checkIfEmailIsBlockedInWatchlistController } from "@calcom/features/watchlist/operations/check-if-email-in-watchlist.controller";
|
||||
@@ -15,7 +16,6 @@ import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import type { CustomNextApiHandler } from "@calcom/lib/server/username";
|
||||
import { usernameHandler } from "@calcom/lib/server/username";
|
||||
import { validateAndGetCorrectedUsernameAndEmail } from "@calcom/lib/validateUsername";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { CreationSource } from "@calcom/prisma/enums";
|
||||
import { IdentityProvider } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -3,12 +3,12 @@ import { NextResponse } from "next/server";
|
||||
import { checkPremiumUsername } from "@calcom/ee/common/lib/checkPremiumUsername";
|
||||
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
|
||||
import { createOrUpdateMemberships } from "@calcom/features/auth/signup/utils/createOrUpdateMemberships";
|
||||
import { validateAndGetCorrectedUsernameAndEmail } from "@calcom/features/auth/signup/utils/validateUsername";
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import { IS_PREMIUM_USERNAME_ENABLED } from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { isUsernameReservedDueToMigration } from "@calcom/lib/server/username";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import { validateAndGetCorrectedUsernameAndEmail } from "@calcom/lib/validateUsername";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { IdentityProvider } from "@calcom/prisma/enums";
|
||||
import { signupSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { validateAndGetCorrectedUsernameInTeam } from "@calcom/features/auth/signup/utils/validateUsername";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { validateAndGetCorrectedUsernameInTeam } from "@calcom/lib/validateUsername";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
|
||||
export async function findTokenByToken({ token }: { token: string }) {
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { getOrgUsernameFromEmail } from "@calcom/features/auth/signup/utils/getOrgUsernameFromEmail";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
export const getUsernameForOrgMember = async ({
|
||||
email,
|
||||
orgAutoAcceptEmail,
|
||||
isSignup,
|
||||
username,
|
||||
}: {
|
||||
username?: string;
|
||||
email: string;
|
||||
orgAutoAcceptEmail?: string;
|
||||
isSignup: boolean;
|
||||
}) => {
|
||||
if (isSignup) {
|
||||
// We ensure that the username is always derived from the email during signup.
|
||||
return getOrgUsernameFromEmail(email, orgAutoAcceptEmail || "");
|
||||
}
|
||||
if (!username) {
|
||||
throw new Error("Username is required");
|
||||
}
|
||||
// Right now it's not possible to change username in an org by the user but when that's allowed we would simply accept the provided username
|
||||
return username;
|
||||
};
|
||||
|
||||
export const validateAndGetCorrectedUsernameAndEmail = async ({
|
||||
username,
|
||||
email,
|
||||
organizationId,
|
||||
orgAutoAcceptEmail,
|
||||
isSignup,
|
||||
}: {
|
||||
username: string;
|
||||
email: string;
|
||||
organizationId?: number;
|
||||
orgAutoAcceptEmail?: string;
|
||||
isSignup: boolean;
|
||||
}) => {
|
||||
if (username.includes("+")) {
|
||||
return { isValid: false, username: undefined, email };
|
||||
}
|
||||
// There is an existingUser if, within an org context or not, the username matches
|
||||
// OR if the email matches AND either the email is verified
|
||||
// or both username and password are set
|
||||
const existingUser = await prisma.user.findFirst({
|
||||
where: {
|
||||
...(organizationId ? { organizationId } : {}),
|
||||
OR: [
|
||||
// When inviting to org, invited user gets created with username now, so in an org context we
|
||||
// can't check for username as it will exist on signup
|
||||
...(!organizationId ? [{ username }] : [{}]),
|
||||
{
|
||||
AND: [
|
||||
{ email },
|
||||
{
|
||||
OR: [
|
||||
{ emailVerified: { not: null } },
|
||||
{ AND: [{ password: { isNot: null } }, { username: { not: null } }] },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
select: {
|
||||
email: true,
|
||||
},
|
||||
});
|
||||
let validatedUsername = username;
|
||||
if (organizationId) {
|
||||
validatedUsername = await getUsernameForOrgMember({
|
||||
email,
|
||||
orgAutoAcceptEmail,
|
||||
isSignup,
|
||||
});
|
||||
}
|
||||
|
||||
return { isValid: !existingUser, username: validatedUsername, email: existingUser?.email };
|
||||
};
|
||||
|
||||
export const validateAndGetCorrectedUsernameInTeam = async (
|
||||
username: string,
|
||||
email: string,
|
||||
teamId: number,
|
||||
isSignup: boolean
|
||||
) => {
|
||||
try {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: {
|
||||
id: teamId,
|
||||
},
|
||||
select: {
|
||||
metadata: true,
|
||||
isOrganization: true,
|
||||
parentId: true,
|
||||
organizationSettings: true,
|
||||
parent: {
|
||||
select: {
|
||||
organizationSettings: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
console.log("validateAndGetCorrectedUsernameInTeam", {
|
||||
teamId,
|
||||
team,
|
||||
});
|
||||
const organization = team?.isOrganization ? team : team?.parent;
|
||||
if (organization) {
|
||||
// Organization context -> org-context username check
|
||||
const orgId = team?.parentId || teamId;
|
||||
return validateAndGetCorrectedUsernameAndEmail({
|
||||
username,
|
||||
email,
|
||||
organizationId: orgId,
|
||||
orgAutoAcceptEmail: organization?.organizationSettings?.orgAutoAcceptEmail || "",
|
||||
isSignup,
|
||||
});
|
||||
} else {
|
||||
// Regular team context -> regular username check
|
||||
return validateAndGetCorrectedUsernameAndEmail({ username, email, isSignup });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return { isValid: false, username: undefined, email: undefined };
|
||||
}
|
||||
};
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
|
||||
import { filterRedundantDateRanges } from "./filterRedundantDateRanges";
|
||||
|
||||
describe("filterRedundantDateRanges", () => {
|
||||
it("should remove date ranges that are completely contained within others", () => {
|
||||
const dateRanges = [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T12:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T11:15:00.000Z"), end: dayjs("2025-01-23T11:45:00.000Z") }, // Contained within the first range
|
||||
{ start: dayjs("2025-01-23T13:00:00.000Z"), end: dayjs("2025-01-23T14:00:00.000Z") },
|
||||
];
|
||||
|
||||
const result = filterRedundantDateRanges(dateRanges);
|
||||
|
||||
expect(result.length).toBe(2);
|
||||
expect(result[0].start.format()).toEqual(dayjs("2025-01-23T11:00:00.000Z").format());
|
||||
expect(result[0].end.format()).toEqual(dayjs("2025-01-23T12:00:00.000Z").format());
|
||||
expect(result[1].start.format()).toEqual(dayjs("2025-01-23T13:00:00.000Z").format());
|
||||
expect(result[1].end.format()).toEqual(dayjs("2025-01-23T14:00:00.000Z").format());
|
||||
});
|
||||
|
||||
it("should not remove overlapping ranges that aren't completely contained", () => {
|
||||
const dateRanges = [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T12:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T11:30:00.000Z"), end: dayjs("2025-01-23T12:30:00.000Z") }, // Overlaps but not contained
|
||||
{ start: dayjs("2025-01-23T13:00:00.000Z"), end: dayjs("2025-01-23T14:00:00.000Z") },
|
||||
];
|
||||
|
||||
const result = filterRedundantDateRanges(dateRanges);
|
||||
|
||||
expect(result.length).toBe(3);
|
||||
});
|
||||
|
||||
it("should return an empty array when given an empty array", () => {
|
||||
expect(filterRedundantDateRanges([])).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return the same array when there's only one range", () => {
|
||||
const dateRanges = [{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T12:00:00.000Z") }];
|
||||
|
||||
expect(filterRedundantDateRanges(dateRanges)).toEqual(dateRanges);
|
||||
});
|
||||
|
||||
it("should handle three identical ranges", () => {
|
||||
const dateRanges = [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T12:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T12:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T12:00:00.000Z") },
|
||||
];
|
||||
|
||||
const result = filterRedundantDateRanges(dateRanges);
|
||||
expect(result.length).toBe(1);
|
||||
expect(result[0].start.format()).toEqual(dayjs("2025-01-23T11:00:00.000Z").format());
|
||||
expect(result[0].end.format()).toEqual(dayjs("2025-01-23T12:00:00.000Z").format());
|
||||
});
|
||||
|
||||
it("should handle nested containment scenario", () => {
|
||||
const dateRanges = [
|
||||
{ start: dayjs("2025-01-23T10:00:00.000Z"), end: dayjs("2025-01-23T14:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T13:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T11:30:00.000Z"), end: dayjs("2025-01-23T12:30:00.000Z") },
|
||||
];
|
||||
|
||||
const result = filterRedundantDateRanges(dateRanges);
|
||||
expect(result.length).toBe(1);
|
||||
expect(result[0].start.format()).toEqual(dayjs("2025-01-23T10:00:00.000Z").format());
|
||||
expect(result[0].end.format()).toEqual(dayjs("2025-01-23T14:00:00.000Z").format());
|
||||
});
|
||||
|
||||
it("should handle ranges with same start time", () => {
|
||||
const dateRanges = [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T14:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T13:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T12:00:00.000Z") },
|
||||
];
|
||||
|
||||
const result = filterRedundantDateRanges(dateRanges);
|
||||
expect(result.length).toBe(1);
|
||||
expect(result[0].end.format()).toEqual(dayjs("2025-01-23T14:00:00.000Z").format());
|
||||
});
|
||||
|
||||
it("should handle ranges with same end time", () => {
|
||||
const dateRanges = [
|
||||
{ start: dayjs("2025-01-23T09:00:00.000Z"), end: dayjs("2025-01-23T12:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T10:00:00.000Z"), end: dayjs("2025-01-23T12:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T12:00:00.000Z") },
|
||||
];
|
||||
|
||||
const result = filterRedundantDateRanges(dateRanges);
|
||||
expect(result.length).toBe(1);
|
||||
expect(result[0].start.format()).toEqual(dayjs("2025-01-23T09:00:00.000Z").format());
|
||||
});
|
||||
|
||||
it("should preserve invalid ranges", () => {
|
||||
const dateRanges = [
|
||||
{ start: dayjs("2025-01-23T12:00:00.000Z"), end: dayjs("2025-01-23T11:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T10:00:00.000Z"), end: dayjs("2025-01-23T14:00:00.000Z") },
|
||||
];
|
||||
|
||||
const result = filterRedundantDateRanges(dateRanges);
|
||||
expect(result.length).toBe(2);
|
||||
});
|
||||
|
||||
it("should handle touching ranges", () => {
|
||||
const dateRanges = [
|
||||
{ start: dayjs("2025-01-23T10:00:00.000Z"), end: dayjs("2025-01-23T12:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T12:00:00.000Z"), end: dayjs("2025-01-23T14:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T11:30:00.000Z") },
|
||||
];
|
||||
|
||||
const result = filterRedundantDateRanges(dateRanges);
|
||||
expect(result.length).toBe(2);
|
||||
});
|
||||
|
||||
it("should handle overlapping but non-containing ranges", () => {
|
||||
const dateRanges = [
|
||||
{ start: dayjs("2025-01-23T10:00:00.000Z"), end: dayjs("2025-01-23T12:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T13:00:00.000Z") },
|
||||
];
|
||||
|
||||
const result = filterRedundantDateRanges(dateRanges);
|
||||
expect(result.length).toBe(2);
|
||||
expect(result[0].start.format()).toEqual(dayjs("2025-01-23T10:00:00.000Z").format());
|
||||
expect(result[1].start.format()).toEqual(dayjs("2025-01-23T11:00:00.000Z").format());
|
||||
});
|
||||
|
||||
it("should handle complex overlapping pattern that exposed cubic-dev-ai bug", () => {
|
||||
const dateRanges = [
|
||||
{ start: dayjs("2025-01-23T10:00:00.000Z"), end: dayjs("2025-01-23T12:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T13:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T09:00:00.000Z"), end: dayjs("2025-01-23T11:30:00.000Z") },
|
||||
];
|
||||
|
||||
const result = filterRedundantDateRanges(dateRanges);
|
||||
expect(result.length).toBe(3);
|
||||
expect(result[0].start.format()).toEqual(dayjs("2025-01-23T09:00:00.000Z").format());
|
||||
expect(result[1].start.format()).toEqual(dayjs("2025-01-23T10:00:00.000Z").format());
|
||||
expect(result[2].start.format()).toEqual(dayjs("2025-01-23T11:00:00.000Z").format());
|
||||
});
|
||||
});
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
import type { DateRange } from "@calcom/features/schedules/lib/date-ranges";
|
||||
import { IntervalTree, ContainmentSearchAlgorithm, createIntervalNodes } from "@calcom/lib/intervalTree";
|
||||
|
||||
/**
|
||||
* Filters out date ranges that are completely covered by other date ranges.
|
||||
* Uses an interval tree for O(n log n) worst-case complexity.
|
||||
* Unlike mergeOverlappingDateRanges, this doesn't merge overlapping ranges,
|
||||
* it only removes ranges that are completely contained within others.
|
||||
*/
|
||||
export function filterRedundantDateRanges(dateRanges: DateRange[]): DateRange[] {
|
||||
if (dateRanges.length <= 1) return dateRanges;
|
||||
|
||||
const sortedRanges = [...dateRanges].sort((a, b) => a.start.valueOf() - b.start.valueOf());
|
||||
const intervalNodes = createIntervalNodes(
|
||||
sortedRanges,
|
||||
(range) => range.start.valueOf(),
|
||||
(range) => range.end.valueOf()
|
||||
);
|
||||
const intervalTree = new IntervalTree(intervalNodes);
|
||||
const searchAlgorithm = new ContainmentSearchAlgorithm(intervalTree);
|
||||
|
||||
return sortedRanges.filter((range, index) => {
|
||||
if (range.end.valueOf() < range.start.valueOf()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const containingIntervals = searchAlgorithm.findContainingIntervals(
|
||||
range.start.valueOf(),
|
||||
range.end.valueOf(),
|
||||
index
|
||||
);
|
||||
|
||||
for (const containingNode of containingIntervals) {
|
||||
const otherRange = containingNode.item;
|
||||
const otherIndex = containingNode.index;
|
||||
|
||||
if (
|
||||
otherRange.start.valueOf() === range.start.valueOf() &&
|
||||
otherRange.end.valueOf() === range.end.valueOf()
|
||||
) {
|
||||
return otherIndex > index; // Keep current range only if other range has higher index
|
||||
}
|
||||
|
||||
// If we reach here, the other range actually contains this range
|
||||
return false;
|
||||
}
|
||||
|
||||
return true; // Keep this range
|
||||
});
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import type { DateRange } from "@calcom/features/schedules/lib/date-ranges";
|
||||
|
||||
import { mergeOverlappingDateRanges } from "./mergeOverlappingDateRanges";
|
||||
|
||||
const november2 = "2023-11-02";
|
||||
const november3 = "2023-11-03";
|
||||
|
||||
describe("mergeOverlappingDateRanges", () => {
|
||||
it("should merge all ranges into one when one range includes all others", () => {
|
||||
const dateRanges = [
|
||||
createDateRange(`${november2}T23:00:00.000Z`, `${november3}T07:00:00.000Z`), // Includes all others
|
||||
createDateRange(`${november2}T23:15:00.000Z`, `${november3}T00:00:00.000Z`),
|
||||
createDateRange(`${november3}T00:15:00.000Z`, `${november3}T01:00:00.000Z`),
|
||||
createDateRange(`${november3}T01:15:00.000Z`, `${november3}T02:00:00.000Z`),
|
||||
];
|
||||
|
||||
const mergedRanges = mergeOverlappingDateRanges(dateRanges);
|
||||
expect(mergedRanges).toHaveLength(1);
|
||||
expect(mergedRanges[0].start.isSame(dayjs(dateRanges[0].start))).toBe(true);
|
||||
expect(mergedRanges[0].end.isSame(dayjs(dateRanges[0].end))).toBe(true);
|
||||
});
|
||||
|
||||
it("should merge only overlapping ranges over 2 days and leave non-overlapping ranges as is", () => {
|
||||
const dateRanges = [
|
||||
createDateRange(`${november2}T23:00:00.000Z`, `${november3}T07:00:00.000Z`),
|
||||
createDateRange(`${november3}T05:00:00.000Z`, `${november3}T06:00:00.000Z`),
|
||||
createDateRange(`${november3}T08:00:00.000Z`, `${november3}T10:00:00.000Z`), // This range should not be merged
|
||||
];
|
||||
|
||||
const mergedRanges = mergeOverlappingDateRanges(dateRanges);
|
||||
expect(mergedRanges).toHaveLength(2);
|
||||
expect(mergedRanges[0].start.isSame(dayjs(dateRanges[0].start))).toBe(true);
|
||||
expect(mergedRanges[0].end.isSame(dayjs(dateRanges[0].end))).toBe(true);
|
||||
expect(mergedRanges[1].start.isSame(dayjs(dateRanges[2].start))).toBe(true);
|
||||
expect(mergedRanges[1].end.isSame(dayjs(dateRanges[2].end))).toBe(true);
|
||||
});
|
||||
|
||||
it("should merge ranges that overlap on the same day", () => {
|
||||
const dateRanges = [
|
||||
createDateRange(`${november2}T01:00:00.000Z`, `${november2}T04:00:00.000Z`),
|
||||
createDateRange(`${november2}T02:00:00.000Z`, `${november2}T03:00:00.000Z`), // This overlaps with the first range
|
||||
createDateRange(`${november2}T05:00:00.000Z`, `${november2}T06:00:00.000Z`), // This doesn't overlap with above
|
||||
];
|
||||
|
||||
const mergedRanges = mergeOverlappingDateRanges(dateRanges);
|
||||
expect(mergedRanges).toHaveLength(2);
|
||||
expect(mergedRanges[0].start.isSame(dayjs(dateRanges[0].start))).toBe(true);
|
||||
expect(mergedRanges[0].end.isSame(dayjs(dateRanges[0].end))).toBe(true);
|
||||
expect(mergedRanges[1].start.isSame(dayjs(dateRanges[2].start))).toBe(true);
|
||||
expect(mergedRanges[1].end.isSame(dayjs(dateRanges[2].end))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
function createDateRange(start: string, end: string): DateRange {
|
||||
return {
|
||||
start: dayjs(start),
|
||||
end: dayjs(end),
|
||||
};
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import type { DateRange } from "@calcom/features/schedules/lib/date-ranges";
|
||||
|
||||
export function mergeOverlappingDateRanges(dateRanges: DateRange[]) {
|
||||
dateRanges.sort((a, b) => a.start.valueOf() - b.start.valueOf());
|
||||
|
||||
const mergedDateRanges: DateRange[] = [];
|
||||
|
||||
let currentRange = dateRanges[0];
|
||||
if (!currentRange) {
|
||||
return [];
|
||||
}
|
||||
|
||||
for (let i = 1; i < dateRanges.length; i++) {
|
||||
const nextRange = dateRanges[i];
|
||||
|
||||
if (isCurrentRangeOverlappingNext(currentRange, nextRange)) {
|
||||
currentRange = {
|
||||
start: currentRange.start,
|
||||
end: currentRange.end.valueOf() > nextRange.end.valueOf() ? currentRange.end : nextRange.end,
|
||||
};
|
||||
} else {
|
||||
mergedDateRanges.push(currentRange);
|
||||
currentRange = nextRange;
|
||||
}
|
||||
}
|
||||
mergedDateRanges.push(currentRange);
|
||||
|
||||
return mergedDateRanges;
|
||||
}
|
||||
|
||||
function isCurrentRangeOverlappingNext(currentRange: DateRange, nextRange: DateRange): boolean {
|
||||
return (
|
||||
currentRange.start.valueOf() <= nextRange.start.valueOf() &&
|
||||
currentRange.end.valueOf() > nextRange.start.valueOf()
|
||||
);
|
||||
}
|
||||
+472
@@ -0,0 +1,472 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import type { Dayjs } from "@calcom/dayjs";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
|
||||
import { getAggregatedAvailability } from "./getAggregatedAvailability";
|
||||
|
||||
// Helper to check if a time range overlaps with availability
|
||||
const isAvailable = (availability: { start: Dayjs; end: Dayjs }[], range: { start: Dayjs; end: Dayjs }) => {
|
||||
return availability.some(({ start, end }) => {
|
||||
return start <= range.start && end >= range.end;
|
||||
});
|
||||
};
|
||||
|
||||
describe("getAggregatedAvailability", () => {
|
||||
// rr-host availability used to combine into erroneous slots, this confirms it no longer happens
|
||||
it("should not merge RR availability resulting in an unavailable slot due to overlap", () => {
|
||||
const userAvailability = [
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T11:20:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T16:10:00.000Z"), end: dayjs("2025-01-23T16:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:15:00.000Z"), end: dayjs("2025-01-23T11:30:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T13:20:00.000Z"), end: dayjs("2025-01-23T13:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false },
|
||||
},
|
||||
];
|
||||
|
||||
const result = getAggregatedAvailability(userAvailability, "ROUND_ROBIN");
|
||||
const timeRangeToCheckBusy = {
|
||||
start: dayjs("2025-01-23T11:00:00.000Z"),
|
||||
end: dayjs("2025-01-23T11:30:00.000Z"),
|
||||
};
|
||||
|
||||
expect(isAvailable(result, timeRangeToCheckBusy)).toBe(false);
|
||||
|
||||
const timeRangeToCheckAvailable = {
|
||||
start: dayjs("2025-01-23T11:00:00.000Z"),
|
||||
end: dayjs("2025-01-23T11:20:00.000Z"),
|
||||
};
|
||||
|
||||
expect(isAvailable(result, timeRangeToCheckAvailable)).toBe(true);
|
||||
});
|
||||
|
||||
it("it returns the right amount of date ranges even if the end time is before the start time", () => {
|
||||
const userAvailability = [
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-27T14:00:00.000Z"), end: dayjs("2025-01-27T04:30-05:00") },
|
||||
],
|
||||
user: { isFixed: false },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-27T14:00:00.000Z"), end: dayjs("2025-01-27T14:45:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false },
|
||||
},
|
||||
];
|
||||
|
||||
const result = getAggregatedAvailability(userAvailability, "ROUND_ROBIN");
|
||||
|
||||
expect(result).toEqual([
|
||||
{
|
||||
start: dayjs("2025-01-27T14:00:00.000Z"),
|
||||
end: dayjs("2025-01-27T09:30:00.000Z"),
|
||||
},
|
||||
{
|
||||
start: dayjs("2025-01-27T14:00:00.000Z"),
|
||||
end: dayjs("2025-01-27T14:45:00.000Z"),
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
// validates fixed host behaviour, they all have to be available
|
||||
it("correctly joins fixed host availability resulting in one or more combined date ranges", () => {
|
||||
const userAvailability = [
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T11:20:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T16:10:00.000Z"), end: dayjs("2025-01-23T16:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: true },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:15:00.000Z"), end: dayjs("2025-01-23T11:30:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T13:20:00.000Z"), end: dayjs("2025-01-23T13:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: true },
|
||||
},
|
||||
];
|
||||
|
||||
const result = getAggregatedAvailability(userAvailability, "ROUND_ROBIN");
|
||||
const timeRangeToCheckBusy = {
|
||||
start: dayjs("2025-01-23T11:00:00.000Z"),
|
||||
end: dayjs("2025-01-23T11:30:00.000Z"),
|
||||
};
|
||||
|
||||
expect(isAvailable(result, timeRangeToCheckBusy)).toBe(false);
|
||||
|
||||
expect(result[0].start.format()).toEqual(dayjs("2025-01-23T11:15:00.000Z").format());
|
||||
expect(result[0].end.format()).toEqual(dayjs("2025-01-23T11:20:00.000Z").format());
|
||||
});
|
||||
|
||||
// Combines rr hosts and fixed hosts, both fixed and one of the rr hosts has to be available for the whole period
|
||||
// All fixed user ranges are merged with each rr-host
|
||||
it("Fixed hosts and at least one rr host available between 11:00-11:30 & 12:30-13:00 on January 23, 2025", () => {
|
||||
// Both fixed user A and B are available 11:00-11:30 & 12:30-13:00 & 13:15-13:30
|
||||
// Only user C (rr) is available 11:00-11:30 and only user D (rr) is available 12:30-13:00
|
||||
// No rr users are available 13:15-13:30 and this date range should not be a result.
|
||||
const userAvailability = [
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T11:30:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T12:30:00.000Z"), end: dayjs("2025-01-23T13:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T13:15:00.000Z"), end: dayjs("2025-01-23T13:30:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T16:10:00.000Z"), end: dayjs("2025-01-23T16:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: true },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T11:30:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T12:30:00.000Z"), end: dayjs("2025-01-23T13:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T13:15:00.000Z"), end: dayjs("2025-01-23T13:30:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T13:20:00.000Z"), end: dayjs("2025-01-23T13:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: true },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T11:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T12:30:00.000Z"), end: dayjs("2025-01-23T13:00:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false },
|
||||
},
|
||||
];
|
||||
|
||||
const result = getAggregatedAvailability(userAvailability, "ROUND_ROBIN");
|
||||
const timeRangeToCheckAvailable = {
|
||||
start: dayjs("2025-01-23T11:00:00.000Z"),
|
||||
end: dayjs("2025-01-23T11:30:00.000Z"),
|
||||
};
|
||||
|
||||
expect(isAvailable(result, timeRangeToCheckAvailable)).toBe(true);
|
||||
|
||||
expect(result[0].start.format()).toEqual(dayjs("2025-01-23T11:00:00.000Z").format());
|
||||
expect(result[0].end.format()).toEqual(dayjs("2025-01-23T11:30:00.000Z").format());
|
||||
expect(result[1].start.format()).toEqual(dayjs("2025-01-23T12:30:00.000Z").format());
|
||||
expect(result[1].end.format()).toEqual(dayjs("2025-01-23T13:00:00.000Z").format());
|
||||
});
|
||||
|
||||
it("does not duplicate slots when multiple rr-hosts offer the same availability", () => {
|
||||
const userAvailability = [
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T11:30:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T12:30:00.000Z"), end: dayjs("2025-01-23T13:00:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T13:15:00.000Z"), end: dayjs("2025-01-23T13:30:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T16:10:00.000Z"), end: dayjs("2025-01-23T16:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: true },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T11:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T11:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false },
|
||||
},
|
||||
];
|
||||
|
||||
const result = getAggregatedAvailability(userAvailability, "ROUND_ROBIN");
|
||||
const timeRangeToCheckAvailable = {
|
||||
start: dayjs("2025-01-23T11:00:00.000Z"),
|
||||
end: dayjs("2025-01-23T11:30:00.000Z"),
|
||||
};
|
||||
|
||||
expect(isAvailable(result, timeRangeToCheckAvailable)).toBe(true);
|
||||
expect(result.length).toBe(1);
|
||||
});
|
||||
|
||||
it("requires at least one RR host from each group to be available", () => {
|
||||
// Test scenario with two groups:
|
||||
// Group 1: Host A (available 11:00-11:30), Host B (available 12:00-12:30)
|
||||
// Group 2: Host C (available 11:15-11:45), Host D (available 12:15-12:45)
|
||||
// Fixed host: available 11:00-13:00
|
||||
// Expected: Only slots where at least one host from each group is available
|
||||
const userAvailability = [
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T13:00:00.000Z") },
|
||||
],
|
||||
user: { isFixed: true },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T11:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false, groupId: "group1" },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T12:00:00.000Z"), end: dayjs("2025-01-23T12:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false, groupId: "group1" },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:15:00.000Z"), end: dayjs("2025-01-23T11:45:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false, groupId: "group2" },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T12:15:00.000Z"), end: dayjs("2025-01-23T12:45:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false, groupId: "group2" },
|
||||
},
|
||||
];
|
||||
|
||||
const result = getAggregatedAvailability(userAvailability, "ROUND_ROBIN");
|
||||
|
||||
const timeRangeAvailable = {
|
||||
start: dayjs("2025-01-23T11:15:00.000Z"),
|
||||
end: dayjs("2025-01-23T11:30:00.000Z"),
|
||||
};
|
||||
expect(isAvailable(result, timeRangeAvailable)).toBe(true);
|
||||
|
||||
const timeRangeAvailable2 = {
|
||||
start: dayjs("2025-01-23T12:15:00.000Z"),
|
||||
end: dayjs("2025-01-23T12:30:00.000Z"),
|
||||
};
|
||||
expect(isAvailable(result, timeRangeAvailable2)).toBe(true);
|
||||
|
||||
// Should NOT be available when only one group has hosts available
|
||||
const timeRangeNotAvailable = {
|
||||
start: dayjs("2025-01-23T11:00:00.000Z"),
|
||||
end: dayjs("2025-01-23T11:15:00.000Z"),
|
||||
};
|
||||
expect(isAvailable(result, timeRangeNotAvailable)).toBe(false);
|
||||
|
||||
// Should NOT be available when only one group has hosts available
|
||||
const timeRangeNotAvailable2 = {
|
||||
start: dayjs("2025-01-23T12:30:00.000Z"),
|
||||
end: dayjs("2025-01-23T12:45:00.000Z"),
|
||||
};
|
||||
expect(isAvailable(result, timeRangeNotAvailable2)).toBe(false);
|
||||
});
|
||||
|
||||
it("handles single group with multiple RR hosts (union behavior)", () => {
|
||||
// Test that when all RR hosts are in the same group, we get union behavior
|
||||
// Host A: available 11:00-11:20, 16:10-16:30
|
||||
// Host B: available 11:15-11:30, 13:20-13:30
|
||||
// Expected: Union of both hosts' availability
|
||||
const userAvailability = [
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T11:20:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T16:10:00.000Z"), end: dayjs("2025-01-23T16:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:15:00.000Z"), end: dayjs("2025-01-23T11:30:00.000Z") },
|
||||
{ start: dayjs("2025-01-23T13:20:00.000Z"), end: dayjs("2025-01-23T13:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false },
|
||||
},
|
||||
];
|
||||
|
||||
const result = getAggregatedAvailability(userAvailability, "ROUND_ROBIN");
|
||||
|
||||
// Should be available when either host is available
|
||||
const timeRangeAvailable = {
|
||||
start: dayjs("2025-01-23T11:00:00.000Z"),
|
||||
end: dayjs("2025-01-23T11:20:00.000Z"),
|
||||
};
|
||||
expect(isAvailable(result, timeRangeAvailable)).toBe(true);
|
||||
|
||||
const timeRangeAvailable2 = {
|
||||
start: dayjs("2025-01-23T13:20:00.000Z"),
|
||||
end: dayjs("2025-01-23T13:30:00.000Z"),
|
||||
};
|
||||
expect(isAvailable(result, timeRangeAvailable2)).toBe(true);
|
||||
|
||||
// Should NOT be available when neither host is available
|
||||
const timeRangeNotAvailable = {
|
||||
start: dayjs("2025-01-23T11:00:00.000Z"),
|
||||
end: dayjs("2025-01-23T11:30:00.000Z"),
|
||||
};
|
||||
expect(isAvailable(result, timeRangeNotAvailable)).toBe(false);
|
||||
});
|
||||
|
||||
it("handles mixed groups with some hosts having groupId and others not", () => {
|
||||
// Test scenario:
|
||||
// Group 1: Host A (available 11:00-11:45)
|
||||
// Group 2: Host B (available 11:15-12:00)
|
||||
// Default group: Host C (available 11:30-12:30), Host D (available 12:15-12:45)
|
||||
// Fixed host: available 11:00-13:00
|
||||
|
||||
const userAvailability = [
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T13:00:00.000Z") },
|
||||
],
|
||||
user: { isFixed: true },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T11:45:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false, groupId: "group1" },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:15:00.000Z"), end: dayjs("2025-01-23T12:00:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false, groupId: "group2" },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:30:00.000Z"), end: dayjs("2025-01-23T12:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T12:15:00.000Z"), end: dayjs("2025-01-23T12:45:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false },
|
||||
},
|
||||
];
|
||||
|
||||
const result = getAggregatedAvailability(userAvailability, "ROUND_ROBIN");
|
||||
|
||||
// Should be available when all groups have at least one host available
|
||||
// Fixed host + Group 1 + Group 2 + Default group all available in this time range
|
||||
const timeRangeAvailable = {
|
||||
start: dayjs("2025-01-23T11:30:00.000Z"),
|
||||
end: dayjs("2025-01-23T11:45:00.000Z"),
|
||||
};
|
||||
expect(isAvailable(result, timeRangeAvailable)).toBe(true);
|
||||
|
||||
// Should NOT be available when not all groups have hosts available
|
||||
// Only Group 1, Group 2, and fixed host available, but Default group not available
|
||||
const timeRangeNotAvailable = {
|
||||
start: dayjs("2025-01-23T11:15:00.000Z"),
|
||||
end: dayjs("2025-01-23T11:30:00.000Z"),
|
||||
};
|
||||
expect(isAvailable(result, timeRangeNotAvailable)).toBe(false);
|
||||
|
||||
// Should NOT be available when not all groups have hosts available
|
||||
// Only Group 1 and fixed host available, Group 2 and Default group not available
|
||||
const timeRangeNotAvailable2 = {
|
||||
start: dayjs("2025-01-23T11:00:00.000Z"),
|
||||
end: dayjs("2025-01-23T11:15:00.000Z"),
|
||||
};
|
||||
expect(isAvailable(result, timeRangeNotAvailable2)).toBe(false);
|
||||
|
||||
// Should NOT be available when not all groups have hosts available
|
||||
// Only Group 2 and fixed host available, Group 1 and Default group not available
|
||||
const timeRangeNotAvailable3 = {
|
||||
start: dayjs("2025-01-23T11:45:00.000Z"),
|
||||
end: dayjs("2025-01-23T12:00:00.000Z"),
|
||||
};
|
||||
expect(isAvailable(result, timeRangeNotAvailable3)).toBe(false);
|
||||
});
|
||||
|
||||
it("handles empty groups gracefully", () => {
|
||||
// Test scenario with empty groups
|
||||
const userAvailability = [
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T11:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: true },
|
||||
},
|
||||
];
|
||||
|
||||
const result = getAggregatedAvailability(userAvailability, "ROUND_ROBIN");
|
||||
|
||||
// Should only have fixed host availability
|
||||
const timeRangeAvailable = {
|
||||
start: dayjs("2025-01-23T11:00:00.000Z"),
|
||||
end: dayjs("2025-01-23T11:30:00.000Z"),
|
||||
};
|
||||
expect(isAvailable(result, timeRangeAvailable)).toBe(true);
|
||||
expect(result.length).toBe(1);
|
||||
});
|
||||
|
||||
it("handles scenario where one group has no available hosts", () => {
|
||||
// Test scenario where one group has no available hosts
|
||||
// Group 1: Host A (available 11:00-11:30)
|
||||
// Group 2: Host B (not available at all)
|
||||
// Fixed host: available 11:00-13:00
|
||||
const userAvailability = [
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T13:00:00.000Z") },
|
||||
],
|
||||
user: { isFixed: true },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [
|
||||
{ start: dayjs("2025-01-23T11:00:00.000Z"), end: dayjs("2025-01-23T11:30:00.000Z") },
|
||||
],
|
||||
user: { isFixed: false, groupId: "group1" },
|
||||
},
|
||||
{
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [], // No availability
|
||||
user: { isFixed: false, groupId: "group2" },
|
||||
},
|
||||
];
|
||||
|
||||
const result = getAggregatedAvailability(userAvailability, "ROUND_ROBIN");
|
||||
|
||||
// Should NOT be available when one group has no hosts available
|
||||
const timeRangeNotAvailable = {
|
||||
start: dayjs("2025-01-23T11:00:00.000Z"),
|
||||
end: dayjs("2025-01-23T11:30:00.000Z"),
|
||||
};
|
||||
expect(isAvailable(result, timeRangeNotAvailable)).toBe(false);
|
||||
});
|
||||
});
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
import type { DateRange } from "@calcom/features/schedules/lib/date-ranges";
|
||||
import { intersect } from "@calcom/features/schedules/lib/date-ranges";
|
||||
import { DEFAULT_GROUP_ID } from "@calcom/lib/constants";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
|
||||
import { filterRedundantDateRanges } from "./date-range-utils/filterRedundantDateRanges";
|
||||
import { mergeOverlappingDateRanges } from "./date-range-utils/mergeOverlappingDateRanges";
|
||||
|
||||
function uniqueAndSortedDateRanges(ranges: DateRange[]): DateRange[] {
|
||||
const seen = new Set<string>();
|
||||
|
||||
return ranges
|
||||
.sort((a, b) => {
|
||||
const startDiff = a.start.valueOf() - b.start.valueOf();
|
||||
return startDiff !== 0 ? startDiff : a.end.valueOf() - b.end.valueOf();
|
||||
})
|
||||
.filter((range) => {
|
||||
const key = `${range.start.valueOf()}-${range.end.valueOf()}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
export const getAggregatedAvailability = (
|
||||
userAvailability: {
|
||||
dateRanges: DateRange[];
|
||||
oooExcludedDateRanges: DateRange[];
|
||||
user?: { isFixed?: boolean; groupId?: string | null };
|
||||
}[],
|
||||
schedulingType: SchedulingType | null
|
||||
): DateRange[] => {
|
||||
const isTeamEvent =
|
||||
schedulingType === SchedulingType.COLLECTIVE ||
|
||||
schedulingType === SchedulingType.ROUND_ROBIN ||
|
||||
userAvailability.length > 1;
|
||||
|
||||
const fixedHosts = userAvailability.filter(
|
||||
({ user }) => !schedulingType || schedulingType === SchedulingType.COLLECTIVE || user?.isFixed
|
||||
);
|
||||
|
||||
const fixedDateRanges = mergeOverlappingDateRanges(
|
||||
intersect(fixedHosts.map((s) => (!isTeamEvent ? s.dateRanges : s.oooExcludedDateRanges)))
|
||||
);
|
||||
const dateRangesToIntersect = !!fixedDateRanges.length ? [fixedDateRanges] : [];
|
||||
const roundRobinHosts = userAvailability.filter(({ user }) => user?.isFixed !== true);
|
||||
if (roundRobinHosts.length) {
|
||||
// Group round robin hosts by their groupId
|
||||
const hostsByGroup = roundRobinHosts.reduce((groups, host) => {
|
||||
const groupId = host.user?.groupId || DEFAULT_GROUP_ID;
|
||||
if (!groups[groupId]) {
|
||||
groups[groupId] = [];
|
||||
}
|
||||
groups[groupId].push(host);
|
||||
return groups;
|
||||
}, {} as Record<string, typeof roundRobinHosts>);
|
||||
|
||||
// at least one host from each group needs to be available
|
||||
Object.values(hostsByGroup).forEach((groupHosts) => {
|
||||
if (groupHosts.length > 0) {
|
||||
const groupDateRanges = groupHosts.flatMap((s) =>
|
||||
!isTeamEvent ? s.dateRanges : s.oooExcludedDateRanges
|
||||
);
|
||||
dateRangesToIntersect.push(groupDateRanges ?? []);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const availability = intersect(dateRangesToIntersect);
|
||||
|
||||
const uniqueRanges = uniqueAndSortedDateRanges(availability);
|
||||
|
||||
return filterRedundantDateRanges(uniqueRanges);
|
||||
};
|
||||
@@ -12,9 +12,9 @@ import {
|
||||
import { getBusyTimesService } from "@calcom/features/di/containers/BusyTimes";
|
||||
import { EventTypeRepository } from "@calcom/features/eventtypes/repositories/eventTypeRepository";
|
||||
import type { IRedisService } from "@calcom/features/redis/IRedisService";
|
||||
import type { DateOverride, WorkingHours } from "@calcom/features/schedules/lib/date-ranges";
|
||||
import { buildDateRanges, subtract } from "@calcom/features/schedules/lib/date-ranges";
|
||||
import { getWorkingHours } from "@calcom/lib/availability";
|
||||
import type { DateOverride, WorkingHours } from "@calcom/lib/date-ranges";
|
||||
import { buildDateRanges, subtract } from "@calcom/lib/date-ranges";
|
||||
import { stringToDayjsZod } from "@calcom/lib/dayjs";
|
||||
import { ErrorCode } from "@calcom/lib/errorCodes";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
@@ -641,9 +641,9 @@ export class UserAvailabilityService {
|
||||
// you can obtain that from user availability defined outside of here
|
||||
fromUser: { id: user.id, displayName: user.name },
|
||||
// optional chaining destructuring toUser
|
||||
toUser: !!toUser ? { id: toUser.id, displayName: toUser.name, username: toUser.username } : null,
|
||||
reason: !!reason ? reason.reason : null,
|
||||
emoji: !!reason ? reason.emoji : null,
|
||||
toUser: toUser ? { id: toUser.id, displayName: toUser.name, username: toUser.username } : null,
|
||||
reason: reason ? reason.reason : null,
|
||||
emoji: reason ? reason.emoji : null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import getLocationOptionsForSelect from "@calcom/features/bookings/lib/getLocati
|
||||
import { FormBuilderField } from "@calcom/features/form-builder/FormBuilderField";
|
||||
import { fieldTypesConfigMap } from "@calcom/features/form-builder/fieldTypes";
|
||||
import { fieldsThatSupportLabelAsSafeHtml } from "@calcom/features/form-builder/fieldsThatSupportLabelAsSafeHtml";
|
||||
import { SystemField } from "@calcom/lib/SystemField";
|
||||
import { SystemField } from "@calcom/lib/bookings/SystemField";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
getPiiFreeCalendarEvent,
|
||||
} from "@calcom/lib/piiFreeData";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
|
||||
import { CredentialRepository } from "@calcom/features/credentials/repositories/CredentialRepository";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { DestinationCalendar, BookingReference } from "@calcom/prisma/client";
|
||||
import { createdEventSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import { constantsScenarios } from "@calcom/lib/__mocks__/constants";
|
||||
|
||||
import { describe, it, vi, expect, beforeEach } from "vitest";
|
||||
|
||||
import { getBrand } from "@calcom/features/ee/organizations/lib/getBrand";
|
||||
|
||||
import { buildEventUrlFromBooking } from "./buildEventUrlFromBooking";
|
||||
|
||||
vi.mock("@calcom/features/ee/organizations/lib/getBrand", () => ({
|
||||
getBrand: vi.fn(),
|
||||
}));
|
||||
|
||||
const WEBSITE_URL = "https://buildEventTest.example";
|
||||
beforeEach(() => {
|
||||
constantsScenarios.setWebsiteUrl(WEBSITE_URL);
|
||||
});
|
||||
|
||||
describe("buildEventUrlFromBooking", () => {
|
||||
describe("Non Organization", () => {
|
||||
it("should correctly build the event URL for a team event booking", async () => {
|
||||
const booking = {
|
||||
eventType: {
|
||||
slug: "30min",
|
||||
team: {
|
||||
slug: "engineering",
|
||||
parentId: 123,
|
||||
},
|
||||
},
|
||||
profileEnrichedBookingUser: {
|
||||
profile: {
|
||||
organizationId: null,
|
||||
username: "john",
|
||||
},
|
||||
},
|
||||
dynamicGroupSlugRef: null,
|
||||
};
|
||||
const expectedUrl = `${WEBSITE_URL}/team/engineering/30min`;
|
||||
const result = await buildEventUrlFromBooking(booking);
|
||||
expect(result).toBe(expectedUrl);
|
||||
});
|
||||
|
||||
it("should correctly build the event URL for a dynamic group booking", async () => {
|
||||
const booking = {
|
||||
eventType: {
|
||||
slug: "30min",
|
||||
team: null,
|
||||
},
|
||||
profileEnrichedBookingUser: {
|
||||
profile: {
|
||||
organizationId: null,
|
||||
username: "john",
|
||||
},
|
||||
},
|
||||
dynamicGroupSlugRef: "john+jane",
|
||||
};
|
||||
const expectedUrl = `${WEBSITE_URL}/john+jane/30min`;
|
||||
const result = await buildEventUrlFromBooking(booking);
|
||||
expect(result).toBe(expectedUrl);
|
||||
});
|
||||
|
||||
it("should correctly build the event URL for a personal booking", async () => {
|
||||
const booking = {
|
||||
eventType: {
|
||||
slug: "30min",
|
||||
team: null,
|
||||
},
|
||||
profileEnrichedBookingUser: {
|
||||
profile: {
|
||||
organizationId: null,
|
||||
username: "john",
|
||||
},
|
||||
},
|
||||
dynamicGroupSlugRef: null,
|
||||
};
|
||||
const expectedUrl = `${WEBSITE_URL}/john/30min`;
|
||||
const result = await buildEventUrlFromBooking(booking);
|
||||
expect(result).toBe(expectedUrl);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Organization", () => {
|
||||
const organizationId = 123;
|
||||
const orgOrigin = "https://acme.cal.local";
|
||||
beforeEach(() => {
|
||||
getBrand.mockResolvedValue({
|
||||
fullDomain: orgOrigin,
|
||||
});
|
||||
});
|
||||
it("should correctly build the event URL for a team event booking", async () => {
|
||||
const booking = {
|
||||
eventType: {
|
||||
slug: "30min",
|
||||
team: {
|
||||
slug: "engineering",
|
||||
parentId: 123,
|
||||
},
|
||||
},
|
||||
profileEnrichedBookingUser: {
|
||||
profile: {
|
||||
organizationId,
|
||||
username: "john",
|
||||
},
|
||||
},
|
||||
dynamicGroupSlugRef: null,
|
||||
};
|
||||
const expectedUrl = `${orgOrigin}/team/engineering/30min`;
|
||||
const result = await buildEventUrlFromBooking(booking);
|
||||
expect(result).toBe(expectedUrl);
|
||||
});
|
||||
|
||||
it("should correctly build the event URL for a dynamic group booking", async () => {
|
||||
const booking = {
|
||||
eventType: {
|
||||
slug: "30min",
|
||||
team: null,
|
||||
},
|
||||
profileEnrichedBookingUser: {
|
||||
profile: {
|
||||
organizationId,
|
||||
username: "john",
|
||||
},
|
||||
},
|
||||
dynamicGroupSlugRef: "john+jane",
|
||||
};
|
||||
const expectedUrl = `${orgOrigin}/john+jane/30min`;
|
||||
const result = await buildEventUrlFromBooking(booking);
|
||||
expect(result).toBe(expectedUrl);
|
||||
});
|
||||
|
||||
it("should correctly build the event URL for a personal booking", async () => {
|
||||
const booking = {
|
||||
eventType: {
|
||||
slug: "30min",
|
||||
team: null,
|
||||
},
|
||||
profileEnrichedBookingUser: {
|
||||
profile: {
|
||||
organizationId,
|
||||
username: "john",
|
||||
},
|
||||
},
|
||||
dynamicGroupSlugRef: null,
|
||||
};
|
||||
const expectedUrl = `${orgOrigin}/john/30min`;
|
||||
const result = await buildEventUrlFromBooking(booking);
|
||||
expect(result).toBe(expectedUrl);
|
||||
});
|
||||
});
|
||||
|
||||
it("should throw if the username isn't set", async () => {
|
||||
const booking = {
|
||||
eventType: {
|
||||
slug: "30min",
|
||||
team: null,
|
||||
},
|
||||
profileEnrichedBookingUser: {
|
||||
profile: {
|
||||
organizationId: null,
|
||||
username: null,
|
||||
},
|
||||
},
|
||||
dynamicGroupSlugRef: null,
|
||||
};
|
||||
await expect(() => buildEventUrlFromBooking(booking)).rejects.toThrow(
|
||||
"No username found for booking user."
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { getBookerBaseUrl } from "@calcom/features/ee/organizations/lib/getBookerUrlServer";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
|
||||
type BookingEventType = {
|
||||
slug: string;
|
||||
team: {
|
||||
slug: string | null;
|
||||
parentId: number | null;
|
||||
} | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* It has its profile always set and if organizationId is null, then username would be regular(non-org) username.
|
||||
*/
|
||||
type ProfileEnrichedBookingUser = {
|
||||
profile: { organizationId: number | null; username: string | null };
|
||||
} | null;
|
||||
|
||||
export function getOrganizationIdOfBooking(booking: {
|
||||
eventType: BookingEventType;
|
||||
profileEnrichedBookingUser: ProfileEnrichedBookingUser;
|
||||
}) {
|
||||
const { eventType, profileEnrichedBookingUser } = booking;
|
||||
return eventType.team
|
||||
? eventType.team.parentId
|
||||
: profileEnrichedBookingUser?.profile.organizationId ?? null;
|
||||
}
|
||||
|
||||
export async function buildEventUrlFromBooking(booking: {
|
||||
eventType: BookingEventType;
|
||||
profileEnrichedBookingUser: ProfileEnrichedBookingUser;
|
||||
dynamicGroupSlugRef: string | null;
|
||||
}) {
|
||||
const { eventType, dynamicGroupSlugRef, profileEnrichedBookingUser } = booking;
|
||||
const eventSlug = eventType.slug;
|
||||
const eventTeam = eventType.team;
|
||||
const bookingOrganizationId = getOrganizationIdOfBooking({ eventType, profileEnrichedBookingUser });
|
||||
|
||||
const bookerUrl = await getBookerBaseUrl(bookingOrganizationId);
|
||||
if (dynamicGroupSlugRef) {
|
||||
return `${bookerUrl}/${dynamicGroupSlugRef}/${eventSlug}`;
|
||||
}
|
||||
|
||||
if (eventTeam?.slug) {
|
||||
return `${bookerUrl}/team/${eventTeam.slug}/${eventSlug}`;
|
||||
}
|
||||
|
||||
const username = profileEnrichedBookingUser?.profile?.username;
|
||||
if (!username) {
|
||||
logger.error("No username found for booking user.", safeStringify({ profileEnrichedBookingUser }));
|
||||
throw new Error("No username found for booking user.");
|
||||
}
|
||||
return `${bookerUrl}/${username}/${eventSlug}`;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { Kysely } from "kysely";
|
||||
|
||||
import type { TextFilterValue } from "@calcom/features/data-table/lib/types";
|
||||
import type { DB } from "@calcom/kysely";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { getBookings } from "@calcom/trpc/server/routers/viewer/bookings/get.handler";
|
||||
|
||||
type InputByStatus = "upcoming" | "recurring" | "past" | "cancelled" | "unconfirmed";
|
||||
export type SortOptions = {
|
||||
sortStart?: "asc" | "desc";
|
||||
sortEnd?: "asc" | "desc";
|
||||
sortCreated?: "asc" | "desc";
|
||||
sortUpdated?: "asc" | "desc";
|
||||
};
|
||||
type GetOptions = {
|
||||
ctx: {
|
||||
user: { id: number; email: string; orgId?: number | null };
|
||||
prisma: PrismaClient;
|
||||
kysely: Kysely<DB>;
|
||||
};
|
||||
bookingListingByStatus: InputByStatus[];
|
||||
take: number;
|
||||
skip: number;
|
||||
filters: {
|
||||
status?: InputByStatus;
|
||||
teamIds?: number[] | undefined;
|
||||
userIds?: number[] | undefined;
|
||||
eventTypeIds?: number[] | undefined;
|
||||
attendeeEmail?: string | TextFilterValue;
|
||||
attendeeName?: string | TextFilterValue;
|
||||
bookingUid?: string | undefined;
|
||||
};
|
||||
sort?: SortOptions;
|
||||
};
|
||||
|
||||
const getAllUserBookings = async ({ ctx, filters, bookingListingByStatus, take, skip, sort }: GetOptions) => {
|
||||
const { prisma, user, kysely } = ctx;
|
||||
|
||||
const { bookings, recurringInfo, totalCount } = await getBookings({
|
||||
user,
|
||||
prisma,
|
||||
kysely,
|
||||
bookingListingByStatus,
|
||||
filters: filters,
|
||||
sort,
|
||||
take,
|
||||
skip,
|
||||
});
|
||||
|
||||
return {
|
||||
bookings,
|
||||
recurringInfo,
|
||||
totalCount,
|
||||
};
|
||||
};
|
||||
|
||||
export default getAllUserBookings;
|
||||
@@ -3,7 +3,7 @@ import type { z } from "zod";
|
||||
import {
|
||||
SMS_REMINDER_NUMBER_FIELD,
|
||||
CAL_AI_AGENT_PHONE_NUMBER_FIELD,
|
||||
} from "@calcom/lib/SystemField";
|
||||
} from "@calcom/lib/bookings/SystemField";
|
||||
import type { Workflow } from "@calcom/features/ee/workflows/lib/types";
|
||||
import { fieldsThatSupportLabelAsSafeHtml } from "@calcom/features/form-builder/fieldsThatSupportLabelAsSafeHtml";
|
||||
import { getFieldIdentifier } from "@calcom/features/form-builder/utils/getFieldIdentifier";
|
||||
|
||||
@@ -2,7 +2,8 @@ import { isValidPhoneNumber } from "libphonenumber-js";
|
||||
import z from "zod";
|
||||
|
||||
import type { ALL_VIEWS } from "@calcom/features/form-builder/schema";
|
||||
import { dbReadResponseSchema, fieldTypesSchemaMap } from "@calcom/features/form-builder/schema";
|
||||
import { fieldTypesSchemaMap } from "@calcom/features/form-builder/schema";
|
||||
import { dbReadResponseSchema } from "@calcom/lib/dbReadResponseSchema";
|
||||
import type { eventTypeBookingFields } from "@calcom/prisma/zod-utils";
|
||||
import { bookingResponses, emailSchemaRefinement } from "@calcom/prisma/zod-utils";
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type z from "zod";
|
||||
|
||||
import { SystemField } from "@calcom/lib/SystemField";
|
||||
import { SystemField } from "@calcom/lib/bookings/SystemField";
|
||||
import type { bookingResponsesDbSchema } from "@calcom/features/bookings/lib/getBookingResponsesSchema";
|
||||
import { contructEmailFromPhoneNumber } from "@calcom/lib/contructEmailFromPhoneNumber";
|
||||
import { getBookingWithResponses } from "@calcom/lib/getBooking";
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import type z from "zod";
|
||||
|
||||
import { TITLE_FIELD, SMS_REMINDER_NUMBER_FIELD } from "@calcom/lib/SystemField";
|
||||
import type { bookingResponse } from "@calcom/features/bookings/lib/getBookingResponsesSchema";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
export default function getLabelValueMapFromResponses(
|
||||
calEvent: Pick<CalendarEvent, "customInputs" | "userFieldsResponses" | "responses" | "eventTypeId">,
|
||||
isOrganizer = false
|
||||
) {
|
||||
const { customInputs, userFieldsResponses, responses, eventTypeId } = calEvent;
|
||||
|
||||
const isDynamicEvent = !eventTypeId;
|
||||
|
||||
let labelValueMap: Record<string, z.infer<typeof bookingResponse>> = {};
|
||||
if (userFieldsResponses) {
|
||||
if (!!responses?.[TITLE_FIELD] && !isDynamicEvent) {
|
||||
userFieldsResponses[TITLE_FIELD] = responses[TITLE_FIELD];
|
||||
}
|
||||
if (!!responses?.[SMS_REMINDER_NUMBER_FIELD] && !isDynamicEvent) {
|
||||
userFieldsResponses[SMS_REMINDER_NUMBER_FIELD] = responses[SMS_REMINDER_NUMBER_FIELD];
|
||||
}
|
||||
|
||||
for (const [, value] of Object.entries(userFieldsResponses)) {
|
||||
if (!value.label || (!isOrganizer && value.isHidden)) {
|
||||
continue;
|
||||
}
|
||||
labelValueMap[value.label] = value.value;
|
||||
}
|
||||
} else {
|
||||
labelValueMap = customInputs as Record<string, string | string[]>;
|
||||
}
|
||||
return labelValueMap;
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import type { FormResponse, Fields } from "@calcom/app-store/routing-forms/types
|
||||
import { zodRoutes } from "@calcom/app-store/routing-forms/zod";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { getBusyCalendarTimes } from "@calcom/features/calendars/lib/CalendarManager";
|
||||
import { mergeOverlappingRanges } from "@calcom/lib/date-ranges";
|
||||
import { mergeOverlappingRanges } from "@calcom/features/schedules/lib/date-ranges";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { raqbQueryValueSchema } from "@calcom/lib/raqb/zod";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
|
||||
@@ -6,7 +6,7 @@ import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
|
||||
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { WorkflowService } from "@calcom/lib/server/service/workflows";
|
||||
import { WorkflowService } from "@calcom/features/ee/workflows/lib/service/WorkflowService";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import { WebhookTriggerEvents, WorkflowTriggerEvents } from "@calcom/prisma/enums";
|
||||
import type { EventTypeMetadata } from "@calcom/prisma/zod-utils";
|
||||
|
||||
@@ -18,7 +18,7 @@ import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
|
||||
import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { WorkflowService } from "@calcom/lib/server/service/workflows";
|
||||
import { WorkflowService } from "@calcom/features/ee/workflows/lib/service/WorkflowService";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import type { SchedulingType } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -70,8 +70,8 @@ import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import type { PrismaAttributeRepository as AttributeRepository } from "@calcom/lib/server/repository/PrismaAttributeRepository";
|
||||
import type { HostRepository } from "@calcom/lib/server/repository/host";
|
||||
import type { PrismaOOORepository as OooRepository } from "@calcom/lib/server/repository/ooo";
|
||||
import { HashedLinkService } from "@calcom/lib/server/service/hashedLinkService";
|
||||
import { WorkflowService } from "@calcom/lib/server/service/workflows";
|
||||
import { HashedLinkService } from "@calcom/features/hashedLink/services/hashedLinkService";
|
||||
import { WorkflowService } from "@calcom/features/ee/workflows/lib/service/WorkflowService";
|
||||
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import type { DestinationCalendar, Prisma, User, AssignmentReasonEnum } from "@calcom/prisma/client";
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Logger } from "tslog";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import type { Dayjs } from "@calcom/dayjs";
|
||||
import { checkForConflicts } from "@calcom/features/bookings/lib/conflictChecker/checkForConflicts";
|
||||
import { buildDateRanges } from "@calcom/lib/date-ranges";
|
||||
import { buildDateRanges } from "@calcom/features/schedules/lib/date-ranges";
|
||||
import { getBusyTimesService } from "@calcom/features/di/containers/BusyTimes";
|
||||
import { getUserAvailabilityService } from "@calcom/features/di/containers/GetUserAvailability";
|
||||
import { ErrorCode } from "@calcom/lib/errorCodes";
|
||||
|
||||
@@ -4,7 +4,7 @@ import { handleWebhookTrigger } from "@calcom/features/bookings/lib/handleWebhoo
|
||||
import type { EventPayloadType } from "@calcom/features/webhooks/lib/sendPayload";
|
||||
import { ErrorCode } from "@calcom/lib/errorCodes";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { WorkflowService } from "@calcom/lib/server/service/workflows";
|
||||
import { WorkflowService } from "@calcom/features/ee/workflows/lib/service/WorkflowService";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { BookingStatus } from "@calcom/prisma/enums";
|
||||
|
||||
|
||||
@@ -6,9 +6,9 @@ import { sendNoShowFeeChargedEmail } from "@calcom/emails";
|
||||
import { ErrorCode } from "@calcom/lib/errorCodes";
|
||||
import { ErrorWithCode } from "@calcom/lib/errors";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
|
||||
import { CredentialRepository } from "@calcom/features/credentials/repositories/CredentialRepository";
|
||||
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
|
||||
import { handleNoShowFee } from "./handleNoShowFee";
|
||||
|
||||
@@ -30,7 +30,7 @@ vi.mock("@calcom/lib/server/i18n", () => ({
|
||||
getTranslation: vi.fn().mockResolvedValue((key: string) => key),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/server/repository/credential", () => ({
|
||||
vi.mock("@calcom/features/credentials/repositories/CredentialRepository", () => ({
|
||||
CredentialRepository: {
|
||||
findPaymentCredentialByAppIdAndUserIdOrTeamId: vi.fn(),
|
||||
findPaymentCredentialByAppIdAndTeamId: vi.fn(),
|
||||
@@ -43,7 +43,7 @@ vi.mock("@calcom/features/membership/repositories/MembershipRepository", () => (
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/server/repository/team", () => ({
|
||||
vi.mock("@calcom/features/ee/teams/repositories/TeamRepository", () => ({
|
||||
TeamRepository: vi.fn().mockImplementation(() => ({
|
||||
findParentOrganizationByTeamId: vi.fn(),
|
||||
})),
|
||||
|
||||
@@ -7,9 +7,9 @@ import { ErrorCode } from "@calcom/lib/errorCodes";
|
||||
import { ErrorWithCode } from "@calcom/lib/errors";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
|
||||
import { CredentialRepository } from "@calcom/features/credentials/repositories/CredentialRepository";
|
||||
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { getBusyCalendarTimes } from "@calcom/features/calendars/lib/CalendarManager";
|
||||
import { getDefinedBufferTimes } from "@calcom/features/eventtypes/lib/getDefinedBufferTimes";
|
||||
import { subtract } from "@calcom/lib/date-ranges";
|
||||
import { subtract } from "@calcom/features/schedules/lib/date-ranges";
|
||||
import { stringToDayjs } from "@calcom/lib/dayjs";
|
||||
import { intervalLimitKeyToUnit } from "@calcom/lib/intervalLimits/intervalLimit";
|
||||
import type { IntervalLimit } from "@calcom/lib/intervalLimits/intervalLimitSchema";
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
import { describe, test, expect, beforeEach } from "vitest";
|
||||
|
||||
import { PrismaAppRepository } from "@calcom/features/apps/repository/PrismaAppRepository";
|
||||
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
|
||||
import { CredentialRepository } from "@calcom/features/credentials/repositories/CredentialRepository";
|
||||
import { DestinationCalendarRepository } from "@calcom/lib/server/repository/destinationCalendar";
|
||||
import { EventTypeRepository } from "@calcom/features/eventtypes/repositories/eventTypeRepository";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
import { buildNonDelegationCredential } from "@calcom/lib/delegationCredential";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Prisma, PrismaClient } from "@calcom/prisma/client";
|
||||
import { safeCredentialSelect } from "@calcom/prisma/selects/credential";
|
||||
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["CredentialRepository"] });
|
||||
|
||||
type CredentialCreateInput = {
|
||||
type: string;
|
||||
key: object;
|
||||
userId: number;
|
||||
appId: string;
|
||||
delegationCredentialId?: string | null;
|
||||
};
|
||||
|
||||
type CredentialUpdateInput = {
|
||||
type?: string;
|
||||
key?: object;
|
||||
userId?: number;
|
||||
appId?: string;
|
||||
delegationCredentialId?: string | null;
|
||||
invalid?: boolean;
|
||||
};
|
||||
|
||||
export class CredentialRepository {
|
||||
constructor(private primaClient: PrismaClient) {}
|
||||
|
||||
async findByIdWithDelegationCredential(id: number) {
|
||||
return this.primaClient.credential.findUnique({
|
||||
where: { id },
|
||||
select: { ...credentialForCalendarServiceSelect, delegationCredential: true },
|
||||
});
|
||||
}
|
||||
|
||||
static async create(data: CredentialCreateInput) {
|
||||
const credential = await prisma.credential.create({ data: { ...data } });
|
||||
return buildNonDelegationCredential(credential);
|
||||
}
|
||||
static async findByAppIdAndUserId({ appId, userId }: { appId: string; userId: number }) {
|
||||
const credential = await prisma.credential.findFirst({
|
||||
where: {
|
||||
appId,
|
||||
userId,
|
||||
},
|
||||
});
|
||||
return buildNonDelegationCredential(credential);
|
||||
}
|
||||
|
||||
/**
|
||||
* Doesn't retrieve key field as that has credentials
|
||||
*/
|
||||
static async findFirstByIdWithUser({ id }: { id: number }) {
|
||||
const credential = await prisma.credential.findUnique({ where: { id }, select: safeCredentialSelect });
|
||||
return buildNonDelegationCredential(credential);
|
||||
}
|
||||
|
||||
/**
|
||||
* Includes 'key' field which is sensitive data.
|
||||
*/
|
||||
static async findFirstByIdWithKeyAndUser({ id }: { id: number }) {
|
||||
const credential = await prisma.credential.findUnique({
|
||||
where: { id },
|
||||
select: { ...safeCredentialSelect, key: true },
|
||||
});
|
||||
return buildNonDelegationCredential(credential);
|
||||
}
|
||||
|
||||
static async findFirstByAppIdAndUserId({ appId, userId }: { appId: string; userId: number }) {
|
||||
return await prisma.credential.findFirst({
|
||||
where: {
|
||||
appId,
|
||||
userId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findFirstByUserIdAndType({ userId, type }: { userId: number; type: string }) {
|
||||
const credential = await prisma.credential.findFirst({ where: { userId, type } });
|
||||
return buildNonDelegationCredential(credential);
|
||||
}
|
||||
|
||||
static async deleteById({ id }: { id: number }) {
|
||||
await prisma.credential.delete({ where: { id } });
|
||||
}
|
||||
|
||||
static async updateCredentialById({ id, data }: { id: number; data: CredentialUpdateInput }) {
|
||||
await prisma.credential.update({
|
||||
where: { id },
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
static async deleteAllByDelegationCredentialId({
|
||||
delegationCredentialId,
|
||||
}: {
|
||||
delegationCredentialId: string;
|
||||
}) {
|
||||
return prisma.credential.deleteMany({ where: { delegationCredentialId } });
|
||||
}
|
||||
|
||||
static async findCredentialForCalendarServiceById({ id }: { id: number }) {
|
||||
const dbCredential = await prisma.credential.findUnique({
|
||||
where: { id },
|
||||
select: credentialForCalendarServiceSelect,
|
||||
});
|
||||
|
||||
if (!dbCredential) {
|
||||
return dbCredential;
|
||||
}
|
||||
|
||||
return buildNonDelegationCredential(dbCredential);
|
||||
}
|
||||
|
||||
static async findByIdIncludeDelegationCredential({ id }: { id: number }) {
|
||||
const dbCredential = await prisma.credential.findUnique({
|
||||
where: { id },
|
||||
select: { ...credentialForCalendarServiceSelect, delegationCredential: true },
|
||||
});
|
||||
|
||||
return dbCredential;
|
||||
}
|
||||
|
||||
static async findAllDelegationByUserIdsListAndDelegationCredentialIdAndType({
|
||||
userIds,
|
||||
delegationCredentialId,
|
||||
type,
|
||||
}: {
|
||||
userIds: number[];
|
||||
delegationCredentialId: string;
|
||||
type: string;
|
||||
}) {
|
||||
return prisma.credential.findMany({
|
||||
where: {
|
||||
userId: {
|
||||
in: userIds,
|
||||
},
|
||||
delegationCredentialId,
|
||||
type,
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findAllDelegationByTypeIncludeUserAndTake({ type, take }: { type: string; take: number }) {
|
||||
const delegationUserCredentials = await prisma.credential.findMany({
|
||||
where: {
|
||||
delegationCredentialId: { not: null },
|
||||
type,
|
||||
},
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
email: true,
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
take,
|
||||
});
|
||||
return delegationUserCredentials.map(({ delegationCredentialId, ...rest }) => {
|
||||
return {
|
||||
...rest,
|
||||
// We queried only those where delegationCredentialId is not null
|
||||
|
||||
delegationCredentialId: delegationCredentialId!,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
static async findUniqueByUserIdAndDelegationCredentialId({
|
||||
userId,
|
||||
delegationCredentialId,
|
||||
}: {
|
||||
userId: number;
|
||||
delegationCredentialId: string;
|
||||
}) {
|
||||
const delegationUserCredentials = await prisma.credential.findMany({
|
||||
where: {
|
||||
userId,
|
||||
delegationCredentialId,
|
||||
},
|
||||
});
|
||||
|
||||
if (delegationUserCredentials.length > 1) {
|
||||
// Instead of crashing use the first one and log for observability
|
||||
// TODO: Plan to add a unique constraint on userId and delegationCredentialId
|
||||
log.error(`DelegationCredential: Multiple delegation user credentials found - this should not happen`, {
|
||||
userId,
|
||||
delegationCredentialId,
|
||||
});
|
||||
}
|
||||
|
||||
return delegationUserCredentials[0];
|
||||
}
|
||||
|
||||
static async updateWhereUserIdAndDelegationCredentialId({
|
||||
userId,
|
||||
delegationCredentialId,
|
||||
data,
|
||||
}: {
|
||||
userId: number;
|
||||
delegationCredentialId: string;
|
||||
data: {
|
||||
key: Prisma.InputJsonValue;
|
||||
};
|
||||
}) {
|
||||
return prisma.credential.updateMany({
|
||||
where: {
|
||||
userId,
|
||||
delegationCredentialId,
|
||||
},
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
static async createDelegationCredential({
|
||||
userId,
|
||||
delegationCredentialId,
|
||||
type,
|
||||
key,
|
||||
appId,
|
||||
}: {
|
||||
userId: number;
|
||||
delegationCredentialId: string;
|
||||
type: string;
|
||||
key: Prisma.InputJsonValue;
|
||||
appId: string;
|
||||
}) {
|
||||
return prisma.credential.create({ data: { userId, delegationCredentialId, type, key, appId } });
|
||||
}
|
||||
|
||||
static async updateWhereId({ id, data }: { id: number; data: { key: Prisma.InputJsonValue } }) {
|
||||
return prisma.credential.update({ where: { id }, data });
|
||||
}
|
||||
|
||||
static async findPaymentCredentialByAppIdAndTeamId({
|
||||
appId,
|
||||
teamId,
|
||||
}: {
|
||||
appId: string | null;
|
||||
teamId: number;
|
||||
}) {
|
||||
return await prisma.credential.findFirst({
|
||||
where: {
|
||||
teamId,
|
||||
appId,
|
||||
},
|
||||
include: {
|
||||
app: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findPaymentCredentialByAppIdAndUserId({
|
||||
appId,
|
||||
userId,
|
||||
}: {
|
||||
appId: string | null;
|
||||
userId: number;
|
||||
}) {
|
||||
return await prisma.credential.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
appId,
|
||||
},
|
||||
include: {
|
||||
app: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findPaymentCredentialByAppIdAndUserIdOrTeamId({
|
||||
appId,
|
||||
userId,
|
||||
teamId,
|
||||
}: {
|
||||
appId: string | null;
|
||||
userId: number;
|
||||
teamId?: number | null;
|
||||
}) {
|
||||
const idToSearchObject = teamId ? { teamId } : { userId };
|
||||
return await prisma.credential.findFirst({
|
||||
where: {
|
||||
...idToSearchObject,
|
||||
appId,
|
||||
},
|
||||
include: {
|
||||
app: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
+347
@@ -0,0 +1,347 @@
|
||||
import prismock from "../../../../tests/libs/__mocks__/prisma";
|
||||
|
||||
import { describe, expect, it, beforeEach, vi } from "vitest";
|
||||
|
||||
import { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
|
||||
import { encryptServiceAccountKey } from "@calcom/lib/server/serviceAccountKey";
|
||||
|
||||
import { DelegationCredentialRepository } from "./DelegationCredentialRepository";
|
||||
|
||||
vi.mock("@calcom/features/ee/organizations/repositories/OrganizationRepository", () => ({
|
||||
OrganizationRepository: {
|
||||
findByMemberEmail: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock service account key functions
|
||||
vi.mock("@calcom/lib/crypto", async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const actual = await importOriginal<any>();
|
||||
return {
|
||||
...actual,
|
||||
symmetricEncrypt: vi.fn((serviceAccountKey) => {
|
||||
console.log({ mockEncrypted: serviceAccountKey });
|
||||
return `encrypted(${serviceAccountKey})`;
|
||||
}),
|
||||
symmetricDecrypt: vi.fn((serviceAccountKey) => {
|
||||
return serviceAccountKey.replace(/^encrypted\((.*)\)$/, "$1");
|
||||
}),
|
||||
};
|
||||
});
|
||||
// Test Data Helpers
|
||||
const buildMockServiceAccountKey = () => ({
|
||||
client_email: "[email protected]",
|
||||
private_key: "private-key",
|
||||
client_id: "client-id",
|
||||
additional_field: "value",
|
||||
});
|
||||
|
||||
const buildMockEncryptedServiceAccountKey = () => ({
|
||||
client_email: "[email protected]",
|
||||
client_id: "client-id",
|
||||
encrypted_credentials: 'encrypted({"private_key":"private-key"})',
|
||||
additional_field: "value",
|
||||
});
|
||||
|
||||
const buildMockWorkspacePlatform = () => ({
|
||||
id: 1,
|
||||
name: "Test Platform",
|
||||
slug: "test-platform",
|
||||
});
|
||||
|
||||
const buildMockOrganization = () => ({
|
||||
id: 1,
|
||||
name: "Test Organization",
|
||||
isOrganization: true,
|
||||
});
|
||||
|
||||
const buildMockDelegationCredential = (overrides = {}) => ({
|
||||
id: "test-id",
|
||||
enabled: true,
|
||||
domain: "example.com",
|
||||
organizationId: 1,
|
||||
workspacePlatformId: 1,
|
||||
serviceAccountKey: buildMockServiceAccountKey(),
|
||||
workspacePlatform: buildMockWorkspacePlatform(),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
// Test Utilities
|
||||
const createTestDelegationCredential = async (overrides = {}) => {
|
||||
// Create organization first (as a team with isOrganization true)
|
||||
await prismock.team.create({
|
||||
data: buildMockOrganization(),
|
||||
});
|
||||
|
||||
// Create workspace platform
|
||||
await prismock.workspacePlatform.create({
|
||||
data: buildMockWorkspacePlatform(),
|
||||
});
|
||||
|
||||
const data = buildMockDelegationCredential(overrides);
|
||||
|
||||
return await prismock.delegationCredential.create({
|
||||
data: {
|
||||
...data,
|
||||
serviceAccountKey: encryptServiceAccountKey(data.serviceAccountKey),
|
||||
},
|
||||
include: {
|
||||
workspacePlatform: true,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const setupOrganizationMock = (returnValue: any) => {
|
||||
vi.mocked(OrganizationRepository.findByMemberEmail).mockResolvedValue(returnValue);
|
||||
};
|
||||
|
||||
describe("DelegationCredentialRepository", () => {
|
||||
beforeEach(() => {
|
||||
prismock.delegationCredential.deleteMany();
|
||||
prismock.workspacePlatform.deleteMany();
|
||||
prismock.team.deleteMany();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("Service Account Key Access Control", () => {
|
||||
beforeEach(async () => {
|
||||
await createTestDelegationCredential();
|
||||
});
|
||||
|
||||
describe("Regular Find Methods (No Service Account Key)", () => {
|
||||
describe("findById", () => {
|
||||
it("should not expose service account key in response", async () => {
|
||||
const result = await DelegationCredentialRepository.findById({ id: "test-id" });
|
||||
|
||||
expect(result).not.toHaveProperty("serviceAccountKey");
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
id: "test-id",
|
||||
enabled: true,
|
||||
domain: "example.com",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findAllByDomain", () => {
|
||||
it("should not expose service account key in any of the results", async () => {
|
||||
const results = await DelegationCredentialRepository.findAllByDomain({ domain: "example.com" });
|
||||
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
results.forEach((result) => {
|
||||
expect(result).not.toHaveProperty("serviceAccountKey");
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
domain: "example.com",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Sensitive Methods (With Service Account Key)", () => {
|
||||
describe("findByIdIncludeSensitiveServiceAccountKey", () => {
|
||||
it("should expose valid service account key", async () => {
|
||||
const result = await DelegationCredentialRepository.findByIdIncludeSensitiveServiceAccountKey({
|
||||
id: "test-id",
|
||||
});
|
||||
|
||||
expect(result).toHaveProperty("serviceAccountKey");
|
||||
expect(result?.serviceAccountKey).toEqual(buildMockServiceAccountKey());
|
||||
});
|
||||
});
|
||||
|
||||
describe("findByOrgIdIncludeSensitiveServiceAccountKey", () => {
|
||||
it("should expose validated service account keys", async () => {
|
||||
const results = await DelegationCredentialRepository.findByOrgIdIncludeSensitiveServiceAccountKey({
|
||||
organizationId: 1,
|
||||
});
|
||||
|
||||
expect(results.length).toEqual(1);
|
||||
const result = results[0];
|
||||
expect(result).toHaveProperty("serviceAccountKey");
|
||||
expect(result.serviceAccountKey).toEqual(buildMockEncryptedServiceAccountKey());
|
||||
});
|
||||
});
|
||||
|
||||
describe("findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey", () => {
|
||||
it("should expose validated service account key", async () => {
|
||||
const result =
|
||||
await DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey(
|
||||
{
|
||||
organizationId: 1,
|
||||
domain: "example.com",
|
||||
}
|
||||
);
|
||||
|
||||
expect(result).toHaveProperty("serviceAccountKey");
|
||||
expect(result?.serviceAccountKey).toEqual(buildMockServiceAccountKey());
|
||||
});
|
||||
});
|
||||
|
||||
describe("findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey", () => {
|
||||
it("should return valid delegation when email exists in organization", async () => {
|
||||
setupOrganizationMock({ id: 1 });
|
||||
|
||||
const result =
|
||||
await DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({
|
||||
email: "[email protected]",
|
||||
});
|
||||
|
||||
expect(result).toHaveProperty("serviceAccountKey");
|
||||
expect(result?.serviceAccountKey).toEqual(buildMockServiceAccountKey());
|
||||
expect(result?.domain).toBe("example.com");
|
||||
});
|
||||
|
||||
it("should return null when email not found in any organization", async () => {
|
||||
setupOrganizationMock(null);
|
||||
|
||||
const result =
|
||||
await DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({
|
||||
email: "[email protected]",
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("CRUD Operations", () => {
|
||||
describe("create", () => {
|
||||
it("should store delegation credential with all required fields and establish connections", async () => {
|
||||
// Create organization first (as a team with isOrganization true)
|
||||
await prismock.team.create({
|
||||
data: buildMockOrganization(),
|
||||
});
|
||||
|
||||
// Create workspace platform
|
||||
const workspacePlatform = await prismock.workspacePlatform.create({
|
||||
data: buildMockWorkspacePlatform(),
|
||||
});
|
||||
|
||||
const data = buildMockDelegationCredential();
|
||||
delete data.id; // ID is auto-generated
|
||||
delete data.workspacePlatform; // Don't include the relation in create
|
||||
|
||||
const result = await DelegationCredentialRepository.create(data);
|
||||
|
||||
expect(result).toEqual({
|
||||
id: expect.any(String),
|
||||
domain: data.domain,
|
||||
enabled: data.enabled,
|
||||
createdAt: expect.any(Date),
|
||||
lastEnabledAt: null,
|
||||
lastDisabledAt: null,
|
||||
updatedAt: null,
|
||||
organizationId: data.organizationId,
|
||||
workspacePlatform: {
|
||||
name: workspacePlatform.name,
|
||||
slug: workspacePlatform.slug,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("update", () => {
|
||||
it("should modify workspace platform connection when workspacePlatformId is provided", async () => {
|
||||
const created = await createTestDelegationCredential();
|
||||
|
||||
// Create new workspace platform
|
||||
const newWorkspacePlatform = await prismock.workspacePlatform.create({
|
||||
data: {
|
||||
id: 2,
|
||||
name: "New Platform",
|
||||
slug: "new-platform",
|
||||
},
|
||||
});
|
||||
|
||||
const result = await DelegationCredentialRepository.updateById({
|
||||
id: created.id,
|
||||
data: { workspacePlatformId: newWorkspacePlatform.id },
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
id: created.id,
|
||||
domain: created.domain,
|
||||
enabled: created.enabled,
|
||||
createdAt: expect.any(Date),
|
||||
lastEnabledAt: created.lastEnabledAt,
|
||||
lastDisabledAt: created.lastDisabledAt,
|
||||
updatedAt: null,
|
||||
organizationId: created.organizationId,
|
||||
workspacePlatform: {
|
||||
name: newWorkspacePlatform.name,
|
||||
slug: newWorkspacePlatform.slug,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should modify organization connection when organizationId is provided", async () => {
|
||||
const created = await createTestDelegationCredential();
|
||||
|
||||
// Create new organization (as a team with isOrganization true)
|
||||
const newOrganization = await prismock.team.create({
|
||||
data: {
|
||||
id: 2,
|
||||
name: "New Organization",
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await DelegationCredentialRepository.updateById({
|
||||
id: created.id,
|
||||
data: { organizationId: newOrganization.id },
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
id: created.id,
|
||||
lastEnabledAt: created.lastEnabledAt,
|
||||
lastDisabledAt: created.lastDisabledAt,
|
||||
domain: created.domain,
|
||||
enabled: created.enabled,
|
||||
createdAt: expect.any(Date),
|
||||
updatedAt: null,
|
||||
organizationId: newOrganization.id,
|
||||
workspacePlatform: {
|
||||
name: expect.any(String),
|
||||
slug: expect.any(String),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should modify specified fields while preserving others", async () => {
|
||||
const created = await createTestDelegationCredential();
|
||||
|
||||
const result = await DelegationCredentialRepository.updateById({
|
||||
id: created.id,
|
||||
data: { enabled: false },
|
||||
});
|
||||
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
id: created.id,
|
||||
enabled: false, // Changed
|
||||
domain: created.domain, // Preserved
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("delete", () => {
|
||||
it("should remove the delegation credential completely", async () => {
|
||||
const created = await createTestDelegationCredential();
|
||||
|
||||
await DelegationCredentialRepository.deleteById({ id: created.id });
|
||||
|
||||
const result = await prismock.delegationCredential.findUnique({
|
||||
where: { id: created.id },
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
import { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import {
|
||||
serviceAccountKeySchema,
|
||||
type ServiceAccountKey,
|
||||
type EncryptedServiceAccountKey,
|
||||
encryptServiceAccountKey,
|
||||
decryptServiceAccountKey,
|
||||
} from "@calcom/lib/server/serviceAccountKey";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
|
||||
export type { ServiceAccountKey };
|
||||
const repositoryLogger = logger.getSubLogger({ prefix: ["DelegationCredentialRepository"] });
|
||||
const delegationCredentialSafeSelect = {
|
||||
id: true,
|
||||
enabled: true,
|
||||
domain: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
organizationId: true,
|
||||
lastEnabledAt: true,
|
||||
lastDisabledAt: true,
|
||||
workspacePlatform: {
|
||||
select: {
|
||||
name: true,
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const delegationCredentialSelectIncludesServiceAccountKey = {
|
||||
...delegationCredentialSafeSelect,
|
||||
serviceAccountKey: true,
|
||||
};
|
||||
|
||||
function doesEmailMatchDelegationCredentialDomain({
|
||||
memberEmail,
|
||||
delegationCredentialEmailDomain,
|
||||
}: {
|
||||
memberEmail: string | null;
|
||||
delegationCredentialEmailDomain: string;
|
||||
}) {
|
||||
if (!memberEmail) return false;
|
||||
const memberEmailDomain = memberEmail.split("@")[1];
|
||||
return memberEmailDomain === delegationCredentialEmailDomain;
|
||||
}
|
||||
|
||||
export class DelegationCredentialRepository {
|
||||
private static encryptServiceAccountKey(serviceAccountKey: ServiceAccountKey): EncryptedServiceAccountKey {
|
||||
return encryptServiceAccountKey(serviceAccountKey);
|
||||
}
|
||||
|
||||
private static decryptServiceAccountKey(encryptedServiceAccountKey: Prisma.JsonValue): ServiceAccountKey {
|
||||
return decryptServiceAccountKey(encryptedServiceAccountKey);
|
||||
}
|
||||
|
||||
private static withParsedServiceAccountKey<T extends { serviceAccountKey: Prisma.JsonValue } | null>(
|
||||
delegationCredential: T
|
||||
) {
|
||||
if (!delegationCredential) {
|
||||
return null;
|
||||
}
|
||||
const { serviceAccountKey, ...rest } = delegationCredential;
|
||||
|
||||
// Decrypt the service account key if it exists
|
||||
const decryptedKey = this.decryptServiceAccountKey(serviceAccountKey);
|
||||
const parsedServiceAccountKey = serviceAccountKeySchema.safeParse(decryptedKey);
|
||||
|
||||
return {
|
||||
...rest,
|
||||
serviceAccountKey: parsedServiceAccountKey.success ? parsedServiceAccountKey.data : null,
|
||||
};
|
||||
}
|
||||
|
||||
static async create(data: {
|
||||
domain: string;
|
||||
enabled: boolean;
|
||||
organizationId: number;
|
||||
workspacePlatformId: number;
|
||||
serviceAccountKey: ServiceAccountKey;
|
||||
}) {
|
||||
const encryptedKey = this.encryptServiceAccountKey(data.serviceAccountKey);
|
||||
return await prisma.delegationCredential.create({
|
||||
data: {
|
||||
workspacePlatform: {
|
||||
connect: {
|
||||
id: data.workspacePlatformId,
|
||||
},
|
||||
},
|
||||
domain: data.domain,
|
||||
enabled: data.enabled,
|
||||
organization: {
|
||||
connect: {
|
||||
id: data.organizationId,
|
||||
},
|
||||
},
|
||||
// z.passthrough() is not allowed in Prisma, but we know this is trusted.
|
||||
serviceAccountKey: encryptedKey as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
select: delegationCredentialSafeSelect,
|
||||
});
|
||||
}
|
||||
|
||||
static async findById({ id }: { id: string }) {
|
||||
return await prisma.delegationCredential.findUnique({
|
||||
where: { id },
|
||||
select: delegationCredentialSafeSelect,
|
||||
});
|
||||
}
|
||||
|
||||
static async findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey({
|
||||
organizationId,
|
||||
domain,
|
||||
}: {
|
||||
organizationId: number;
|
||||
domain: string;
|
||||
}) {
|
||||
const delegationCredential = await prisma.delegationCredential.findUnique({
|
||||
where: { organizationId_domain: { organizationId, domain } },
|
||||
select: delegationCredentialSelectIncludesServiceAccountKey,
|
||||
});
|
||||
return DelegationCredentialRepository.withParsedServiceAccountKey(delegationCredential);
|
||||
}
|
||||
|
||||
static async findByIdIncludeSensitiveServiceAccountKey({ id }: { id: string }) {
|
||||
const delegationCredential = await prisma.delegationCredential.findUnique({
|
||||
where: { id },
|
||||
select: delegationCredentialSelectIncludesServiceAccountKey,
|
||||
});
|
||||
if (!delegationCredential) return null;
|
||||
return DelegationCredentialRepository.withParsedServiceAccountKey(delegationCredential);
|
||||
}
|
||||
|
||||
static async findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({ email }: { email: string }) {
|
||||
const log = repositoryLogger.getSubLogger({
|
||||
prefix: ["findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey"],
|
||||
});
|
||||
log.debug("called with", { email });
|
||||
const organization = await OrganizationRepository.findByMemberEmail({ email });
|
||||
if (!organization) {
|
||||
log.debug("Email not found in any organization:", email);
|
||||
return null;
|
||||
}
|
||||
|
||||
const emailDomain = email.split("@")[1];
|
||||
const delegationCredential = await prisma.delegationCredential.findUnique({
|
||||
where: {
|
||||
organizationId_domain: {
|
||||
organizationId: organization.id,
|
||||
domain: emailDomain,
|
||||
},
|
||||
},
|
||||
select: delegationCredentialSelectIncludesServiceAccountKey,
|
||||
});
|
||||
|
||||
return DelegationCredentialRepository.withParsedServiceAccountKey(delegationCredential);
|
||||
}
|
||||
|
||||
static async findAllByDomain({ domain }: { domain: string }) {
|
||||
return await prisma.delegationCredential.findMany({
|
||||
where: { domain },
|
||||
select: delegationCredentialSafeSelect,
|
||||
});
|
||||
}
|
||||
|
||||
static async updateById({
|
||||
id,
|
||||
data,
|
||||
}: {
|
||||
id: string;
|
||||
data: Partial<{
|
||||
workspacePlatformId: number;
|
||||
domain: string;
|
||||
enabled: boolean;
|
||||
organizationId: number;
|
||||
lastEnabledAt: Date;
|
||||
lastDisabledAt: Date;
|
||||
}>;
|
||||
}) {
|
||||
const { workspacePlatformId, organizationId, ...rest } = data;
|
||||
return await prisma.delegationCredential.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(workspacePlatformId && {
|
||||
workspacePlatform: {
|
||||
connect: {
|
||||
id: workspacePlatformId,
|
||||
},
|
||||
},
|
||||
}),
|
||||
...(organizationId && {
|
||||
organization: {
|
||||
connect: {
|
||||
id: organizationId,
|
||||
},
|
||||
},
|
||||
}),
|
||||
...rest,
|
||||
},
|
||||
select: delegationCredentialSafeSelect,
|
||||
});
|
||||
}
|
||||
|
||||
static async deleteById({ id }: { id: string }) {
|
||||
return await prisma.delegationCredential.delete({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
|
||||
static async findByOrgIdIncludeSensitiveServiceAccountKey({ organizationId }: { organizationId: number }) {
|
||||
return await prisma.delegationCredential.findMany({
|
||||
where: { organizationId },
|
||||
select: {
|
||||
...delegationCredentialSelectIncludesServiceAccountKey,
|
||||
workspacePlatform: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findAllEnabledIncludeDelegatedMembers() {
|
||||
const delegationCredentials = await prisma.delegationCredential.findMany({
|
||||
where: {
|
||||
enabled: true,
|
||||
},
|
||||
include: {
|
||||
workspacePlatform: {
|
||||
select: {
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
organization: {
|
||||
include: {
|
||||
members: {
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
accepted: true,
|
||||
},
|
||||
where: {
|
||||
// Note: We don't maintain anything on Membership that can identify if a Membership has been processed, so we send all and let it be on the caller to filter out
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return delegationCredentials.map((delegationCredential) => {
|
||||
// Members for whom delegation credential is applicable
|
||||
const delegatedMembers = delegationCredential.organization.members.filter((member) => {
|
||||
return doesEmailMatchDelegationCredentialDomain({
|
||||
memberEmail: member.user.email,
|
||||
delegationCredentialEmailDomain: delegationCredential.domain,
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
...delegationCredential,
|
||||
organization: {
|
||||
...delegationCredential.organization,
|
||||
delegatedMembers,
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
static async findAllDisabledAndIncludeNextBatchOfMembersToProcess() {
|
||||
const delegationCredentials = await prisma.delegationCredential.findMany({
|
||||
where: {
|
||||
enabled: false,
|
||||
},
|
||||
include: {
|
||||
workspacePlatform: {
|
||||
select: {
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
organization: {
|
||||
include: {
|
||||
members: {
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
accepted: true,
|
||||
},
|
||||
where: {
|
||||
// Note: We don't maintain anything on Membership that can identify if a Membership has been processed, so we send all and let it be on the caller to filter out
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return delegationCredentials.map((delegationCredential) => {
|
||||
const members = delegationCredential.organization.members;
|
||||
const membersThatAreActuallyPartOfDelegationCredential = members.filter((member) => {
|
||||
return doesEmailMatchDelegationCredentialDomain({
|
||||
memberEmail: member.user.email,
|
||||
delegationCredentialEmailDomain: delegationCredential.domain,
|
||||
});
|
||||
});
|
||||
return {
|
||||
...delegationCredential,
|
||||
organization: {
|
||||
...delegationCredential.organization,
|
||||
members: membersThatAreActuallyPartOfDelegationCredential,
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { DI_TOKENS } from "@calcom/features/di/tokens";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
|
||||
import { createModule } from "../di";
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import dayjs from "@calcom/dayjs";
|
||||
import * as EmailManager from "@calcom/emails/email-manager";
|
||||
import { CreditsRepository } from "@calcom/lib/server/repository/credits";
|
||||
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import { CreditType } from "@calcom/prisma/enums";
|
||||
|
||||
import { CreditService } from "./credit-service";
|
||||
@@ -61,7 +61,7 @@ vi.mock("@calcom/prisma/enums", async (importOriginal) => {
|
||||
|
||||
vi.mock("@calcom/lib/server/repository/credits");
|
||||
vi.mock("@calcom/features/membership/repositories/MembershipRepository");
|
||||
vi.mock("@calcom/lib/server/repository/team");
|
||||
vi.mock("@calcom/features/ee/teams/repositories/TeamRepository");
|
||||
vi.mock("@calcom/emails/email-manager");
|
||||
vi.mock("../workflows/lib/reminders/reminderScheduler", () => ({
|
||||
cancelScheduledMessagesAndScheduleEmails: vi.fn().mockResolvedValue(undefined),
|
||||
|
||||
@@ -13,7 +13,7 @@ import logger from "@calcom/lib/logger";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { CreditsRepository } from "@calcom/lib/server/repository/credits";
|
||||
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import prisma, { type PrismaTransaction } from "@calcom/prisma";
|
||||
import type { CreditUsageType } from "@calcom/prisma/enums";
|
||||
import { CreditType } from "@calcom/prisma/enums";
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,516 @@
|
||||
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { PrismaAttributeOptionRepository } from "@calcom/lib/server/repository/PrismaAttributeOptionRepository";
|
||||
import { PrismaAttributeRepository } from "@calcom/lib/server/repository/PrismaAttributeRepository";
|
||||
import { findAssignmentsForMember } from "@calcom/lib/service/attribute/server/utils";
|
||||
import type {
|
||||
AttributeId,
|
||||
AttributeName,
|
||||
BulkAttributeAssigner,
|
||||
AttributeOptionAssignment,
|
||||
} from "@calcom/lib/service/attribute/types";
|
||||
import {
|
||||
doesSupportMultipleValues,
|
||||
isAssignmentForLockedAttribute,
|
||||
isAssignmentForTheSamePool,
|
||||
isAssignmentSame,
|
||||
buildSlugFromValue,
|
||||
canSetValueBeyondOptions,
|
||||
} from "@calcom/lib/service/attribute/utils";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["entity/attribute"] });
|
||||
|
||||
type AttributesIncludingOptions = Awaited<ReturnType<typeof findAttributesByName>>[number];
|
||||
type AttributeOptionsToAssign = {
|
||||
attribute: { id: AttributeId; isLocked: boolean };
|
||||
optionsToAssign: { id: string | null; label: string }[];
|
||||
};
|
||||
|
||||
type AttributeOptionsToAssignWithIdEnsured = {
|
||||
attribute: { id: AttributeId; isLocked: boolean };
|
||||
optionsToAssign: { id: string; label: string }[];
|
||||
};
|
||||
type AttributeLabelToValueMap = Record<AttributeName, string | string[]>;
|
||||
|
||||
const findAttributesByName = async ({
|
||||
orgId,
|
||||
attributeNames,
|
||||
}: {
|
||||
orgId: number;
|
||||
attributeNames: AttributeName[];
|
||||
}) => {
|
||||
const attributeRepo = new PrismaAttributeRepository(prisma);
|
||||
const attributesFromDb = await attributeRepo.findManyByNamesAndOrgIdIncludeOptions({
|
||||
attributeNames,
|
||||
orgId,
|
||||
});
|
||||
|
||||
return attributesFromDb.map((attribute) => {
|
||||
const { name, options, ...rest } = attribute;
|
||||
|
||||
return {
|
||||
...rest,
|
||||
label: name,
|
||||
options: options.map((option) => {
|
||||
return {
|
||||
...option,
|
||||
label: option.value,
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const lookupByLabels = <TWithLabel extends { label: string }>({
|
||||
labels,
|
||||
items,
|
||||
}: {
|
||||
labels: string[];
|
||||
items: TWithLabel[];
|
||||
}) => {
|
||||
const map = new Map<string, TWithLabel | null>();
|
||||
labels.forEach((label) => {
|
||||
map.set(label, items.find((item) => item.label.toLowerCase() === label.toLowerCase()) ?? null);
|
||||
});
|
||||
return map;
|
||||
};
|
||||
|
||||
const lookupByLabel = <TWithLabel extends { label: string }>({
|
||||
label,
|
||||
items,
|
||||
}: {
|
||||
label: string;
|
||||
items: TWithLabel[];
|
||||
}) => {
|
||||
const map = lookupByLabels({ labels: [label], items });
|
||||
return map.get(label);
|
||||
};
|
||||
|
||||
export const buildPrismaQueriesForAttributeOptionToUser = ({
|
||||
existingAttributeOptionAssignments,
|
||||
attributeOptionsToAssign,
|
||||
updater,
|
||||
memberId,
|
||||
}: {
|
||||
orgId: number;
|
||||
memberId: number;
|
||||
existingAttributeOptionAssignments: AttributeOptionAssignment[];
|
||||
attributeOptionsToAssign: AttributeOptionsToAssignWithIdEnsured[];
|
||||
updater: BulkAttributeAssigner;
|
||||
}) => {
|
||||
const assignmentsToUpdateIds: string[] = [];
|
||||
if (!attributeOptionsToAssign.length) {
|
||||
log.debug("No attribute options to assign, skipping");
|
||||
return {
|
||||
attributeToUserCreateManyInput: [],
|
||||
attributeToUserUpdateManyInput: null,
|
||||
attributeToUserDeleteQueries: {
|
||||
locked: null,
|
||||
unlocked: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
const { attributeToUserCreateManyInput } = attributeOptionsToAssign.reduce(
|
||||
(acc, attributeOptionsToAssign) => {
|
||||
const existingAttributeOptionAssignment = existingAttributeOptionAssignments.find(
|
||||
(existingAttributeOptionForMember) => existingAttributeOptionForMember.attributeOption.attribute.id
|
||||
);
|
||||
|
||||
// Prevent overriding the only value for an unlocked attribute
|
||||
if (
|
||||
existingAttributeOptionAssignment &&
|
||||
!isAssignmentForLockedAttribute({
|
||||
assignment: existingAttributeOptionAssignment,
|
||||
}) &&
|
||||
!doesSupportMultipleValues({
|
||||
attribute: existingAttributeOptionAssignment.attributeOption.attribute,
|
||||
}) &&
|
||||
!isAssignmentForTheSamePool({
|
||||
assignment: existingAttributeOptionAssignment,
|
||||
updater,
|
||||
})
|
||||
) {
|
||||
console.warn(
|
||||
`Attribute ${existingAttributeOptionAssignment.attributeOption.attribute.id} already assigned to user ${memberId} and is not a multi-select attribute. So, skipping`
|
||||
);
|
||||
return acc;
|
||||
}
|
||||
|
||||
attributeOptionsToAssign.optionsToAssign.forEach((optionToAssign) => {
|
||||
// Prevent unnecessary recreation of the assignment, to avoid resetting the "weight"
|
||||
if (
|
||||
existingAttributeOptionAssignment &&
|
||||
isAssignmentSame({
|
||||
existingAssignment: existingAttributeOptionAssignment,
|
||||
newOption: optionToAssign,
|
||||
})
|
||||
) {
|
||||
log.debug(
|
||||
`Updating existing assignment ${existingAttributeOptionAssignment.id} as it has same value`
|
||||
);
|
||||
assignmentsToUpdateIds.push(existingAttributeOptionAssignment.id);
|
||||
return;
|
||||
}
|
||||
|
||||
acc.attributeToUserCreateManyInput.push({
|
||||
memberId,
|
||||
attributeOptionId: optionToAssign.id,
|
||||
...("dsyncId" in updater
|
||||
? { createdByDSyncId: updater.dsyncId, createdById: null }
|
||||
: {
|
||||
createdById: updater.userId,
|
||||
createdByDSyncId: null,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
return acc;
|
||||
},
|
||||
{
|
||||
attributeToUserCreateManyInput: [] as {
|
||||
memberId: number;
|
||||
attributeOptionId: string;
|
||||
createdByDSyncId: string | null;
|
||||
createdById: number | null;
|
||||
}[],
|
||||
}
|
||||
);
|
||||
|
||||
const lockedAttributeIds = attributeOptionsToAssign
|
||||
.filter((option) => option.attribute.isLocked)
|
||||
.map((option) => option.attribute.id);
|
||||
|
||||
const unlockedAttributeIds = attributeOptionsToAssign
|
||||
.filter((option) => !option.attribute.isLocked)
|
||||
.map((option) => option.attribute.id);
|
||||
|
||||
const unlockedAttributesAssignmentIdsInThePool = existingAttributeOptionAssignments
|
||||
.filter((assignment) => {
|
||||
return (
|
||||
isAssignmentForTheSamePool({
|
||||
assignment,
|
||||
updater,
|
||||
}) && unlockedAttributeIds.includes(assignment.attributeOption.attribute.id)
|
||||
);
|
||||
})
|
||||
.map((existingAttributeOptionForMember) => existingAttributeOptionForMember.id);
|
||||
|
||||
const unlockedAttributesAssignmentIdsInThePoolWhichAreAllowedToBeCreated =
|
||||
unlockedAttributesAssignmentIdsInThePool.filter((id) => !assignmentsToUpdateIds.includes(id));
|
||||
const attributeToUserDeleteQueryWhereClauseForUnlockedAttributes =
|
||||
unlockedAttributesAssignmentIdsInThePoolWhichAreAllowedToBeCreated.length
|
||||
? scopedWhereClause({
|
||||
memberId,
|
||||
whereClause: {
|
||||
id: {
|
||||
in: unlockedAttributesAssignmentIdsInThePoolWhichAreAllowedToBeCreated,
|
||||
},
|
||||
},
|
||||
})
|
||||
: null;
|
||||
|
||||
const attributeToUserDeleteQueryWhereClauseForLockedAttributes = lockedAttributeIds.length
|
||||
? scopedWhereClause({
|
||||
memberId,
|
||||
whereClause: {
|
||||
...(assignmentsToUpdateIds.length
|
||||
? {
|
||||
id: {
|
||||
notIn: assignmentsToUpdateIds,
|
||||
},
|
||||
}
|
||||
: null),
|
||||
// No matter who assigned the attribute(Cal.com or SCIM), we delete it because the source of truth is SCIM and only one SCIM can be be source of truth at one time.
|
||||
attributeOption: {
|
||||
attribute: {
|
||||
id: {
|
||||
in: lockedAttributeIds,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
: null;
|
||||
|
||||
const attributeToUserUpdateManyInput = assignmentsToUpdateIds.length
|
||||
? {
|
||||
where: scopedWhereClause({
|
||||
memberId,
|
||||
whereClause: {
|
||||
id: {
|
||||
in: assignmentsToUpdateIds,
|
||||
},
|
||||
},
|
||||
}),
|
||||
data: {
|
||||
...("dsyncId" in updater
|
||||
? { updatedByDSyncId: updater.dsyncId, updatedById: null }
|
||||
: {
|
||||
updatedById: updater.userId,
|
||||
updatedByDSyncId: null,
|
||||
}),
|
||||
},
|
||||
}
|
||||
: null;
|
||||
|
||||
log.debug("buildPrismaQueriesForAttributeOptionToUser", {
|
||||
assignmentsToUpdateIds,
|
||||
lockedAttributeIds,
|
||||
unlockedAttributesAssignmentIdsInThePool,
|
||||
unlockedAttributeIds,
|
||||
existingAttributeOptionAssignments,
|
||||
updater,
|
||||
attributeToUserDeleteQueryWhereClauseForLockedAttributes: safeStringify(
|
||||
attributeToUserDeleteQueryWhereClauseForLockedAttributes
|
||||
),
|
||||
attributeToUserDeleteQueryWhereClauseForUnlockedAttributes: safeStringify(
|
||||
attributeToUserDeleteQueryWhereClauseForUnlockedAttributes
|
||||
),
|
||||
attributeToUserCreateManyInput: safeStringify(attributeToUserCreateManyInput),
|
||||
attributeToUserUpdateManyInput,
|
||||
});
|
||||
|
||||
return {
|
||||
attributeToUserUpdateManyInput,
|
||||
attributeToUserCreateManyInput,
|
||||
attributeToUserDeleteQueries: {
|
||||
locked: attributeToUserDeleteQueryWhereClauseForLockedAttributes,
|
||||
unlocked: attributeToUserDeleteQueryWhereClauseForUnlockedAttributes,
|
||||
},
|
||||
};
|
||||
|
||||
function scopedWhereClause<TWhereClause extends object | null>({
|
||||
memberId,
|
||||
whereClause,
|
||||
}: {
|
||||
memberId: number;
|
||||
whereClause: TWhereClause;
|
||||
}) {
|
||||
return {
|
||||
...whereClause,
|
||||
memberId,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const buildPrismaQueryForAttributeOptionCreation = ({
|
||||
optionsToCreate,
|
||||
}: {
|
||||
optionsToCreate: Record<AttributeId, string[]>;
|
||||
}) => {
|
||||
const attributeOptionCreateManyInput = Object.entries(optionsToCreate).map(([attributeId, options]) =>
|
||||
options.map((option) => ({
|
||||
attributeId,
|
||||
value: option,
|
||||
slug: buildSlugFromValue({ value: option }),
|
||||
}))
|
||||
);
|
||||
return attributeOptionCreateManyInput.flat();
|
||||
};
|
||||
|
||||
const createMissingOptionsAndReturnAlongWithExisting = async <
|
||||
TattributeOptionsToAssign extends AttributeOptionsToAssign
|
||||
>({
|
||||
attributeOptionsToAssignIncludingNonExistentOptions,
|
||||
orgId,
|
||||
}: {
|
||||
attributeOptionsToAssignIncludingNonExistentOptions: TattributeOptionsToAssign[];
|
||||
orgId: number;
|
||||
}) => {
|
||||
const attributeOptionCreateManyInput = buildPrismaQueryForAttributeOptionCreation({
|
||||
optionsToCreate: attributeOptionsToAssignIncludingNonExistentOptions.reduce(
|
||||
(acc, attributeOptionsToAssign) => {
|
||||
const { attribute, optionsToAssign } = attributeOptionsToAssign;
|
||||
acc[attribute.id] = optionsToAssign.filter((option) => !option.id).map((option) => option.label);
|
||||
return acc;
|
||||
},
|
||||
{} as Record<AttributeId, string[]>
|
||||
),
|
||||
});
|
||||
|
||||
await PrismaAttributeOptionRepository.createMany({
|
||||
createManyInput: attributeOptionCreateManyInput,
|
||||
});
|
||||
|
||||
// We need fetch all the attribute options to ensure that we have the newly created options as well.
|
||||
const allAttributeOptions = (
|
||||
await PrismaAttributeOptionRepository.findMany({
|
||||
orgId,
|
||||
})
|
||||
).map((attributeOption) => ({
|
||||
...attributeOption,
|
||||
label: attributeOption.value,
|
||||
}));
|
||||
|
||||
return attributeOptionsToAssignIncludingNonExistentOptions.map(({ attribute, optionsToAssign }) => {
|
||||
const optionsWithIdsOfTheSameAttribute = optionsToAssign
|
||||
.map((option) =>
|
||||
allAttributeOptions.find(
|
||||
(attributeOption) =>
|
||||
attributeOption.attributeId === attribute.id &&
|
||||
attributeOption.label.toLowerCase() === option.label.toLowerCase()
|
||||
)
|
||||
)
|
||||
.filter((option): option is NonNullable<typeof option> => option !== null);
|
||||
return {
|
||||
attribute,
|
||||
optionsToAssign: optionsWithIdsOfTheSameAttribute,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const buildAttributeOptionsToAssign = async ({
|
||||
attributeLabelToValueMap,
|
||||
allAttributesBeingAssigned,
|
||||
orgId,
|
||||
}: {
|
||||
attributeLabelToValueMap: AttributeLabelToValueMap;
|
||||
allAttributesBeingAssigned: AttributesIncludingOptions[];
|
||||
orgId: number;
|
||||
}) => {
|
||||
const attributeOptionsToAssignIncludingNonExistentOptions = Object.entries(attributeLabelToValueMap)
|
||||
.map(([attributeLabel, value]) => {
|
||||
const valueAsArray = value instanceof Array ? value : [value];
|
||||
const attribute = lookupByLabel({ label: attributeLabel, items: allAttributesBeingAssigned });
|
||||
if (!attribute) {
|
||||
console.warn(`Attribute ${attributeLabel} not found, will not be assigned to user`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const labelToFoundOptionMap = lookupByLabels({ labels: valueAsArray, items: attribute.options });
|
||||
const labelsEntries = Array.from(labelToFoundOptionMap.entries());
|
||||
const optionsToAssign = labelsEntries
|
||||
.filter(([_, option]) => {
|
||||
return canSetValueBeyondOptions({ attribute }) ? true : !!option;
|
||||
})
|
||||
.map(([label]) => {
|
||||
const foundLabel = labelToFoundOptionMap.get(label) ?? null;
|
||||
return {
|
||||
label,
|
||||
...foundLabel,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
attribute,
|
||||
optionsToAssign: optionsToAssign.map((option) => ({
|
||||
label: option.label,
|
||||
id: option.id ?? null,
|
||||
})),
|
||||
};
|
||||
})
|
||||
.filter((option): option is NonNullable<typeof option> => option !== null);
|
||||
|
||||
return createMissingOptionsAndReturnAlongWithExisting({
|
||||
attributeOptionsToAssignIncludingNonExistentOptions,
|
||||
orgId,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* For a user in an org, it assigns all the attributes with their values as per the attributeLabelToValueMap.
|
||||
*/
|
||||
export const assignValueToUserInOrgBulk = async ({
|
||||
orgId,
|
||||
userId,
|
||||
attributeLabelToValueMap,
|
||||
updater,
|
||||
}: {
|
||||
orgId: number;
|
||||
userId: number;
|
||||
attributeLabelToValueMap: AttributeLabelToValueMap;
|
||||
updater: BulkAttributeAssigner;
|
||||
}) => {
|
||||
const membership = await MembershipRepository.findUniqueByUserIdAndTeamId({ userId, teamId: orgId });
|
||||
const defaultReturn = { numOfAttributeOptionsSet: 0, numOfAttributeOptionsDeleted: 0 };
|
||||
if (!membership) {
|
||||
console.error(`User ${userId} not a member of org ${orgId}, not assigning attribute options`);
|
||||
return defaultReturn;
|
||||
}
|
||||
|
||||
const { id: memberId } = membership;
|
||||
const attributeNames = Object.keys(attributeLabelToValueMap);
|
||||
|
||||
const allAttributesBeingAssigned = await findAttributesByName({
|
||||
orgId,
|
||||
attributeNames,
|
||||
});
|
||||
|
||||
if (!allAttributesBeingAssigned.length) {
|
||||
console.warn(`None of the attributes ${attributeNames.join(", ")} found in org ${orgId}`);
|
||||
return defaultReturn;
|
||||
}
|
||||
|
||||
const attributeOptionsToAssign = await buildAttributeOptionsToAssign({
|
||||
attributeLabelToValueMap,
|
||||
allAttributesBeingAssigned,
|
||||
orgId,
|
||||
});
|
||||
|
||||
// We need to fetch all the assigned options even those that aren't being set directly in call.
|
||||
// We need to decide on the fate of all existing assignments
|
||||
const existingAttributeOptionAssignments = await findAssignmentsForMember({ memberId });
|
||||
|
||||
const { attributeToUserUpdateManyInput, attributeToUserCreateManyInput, attributeToUserDeleteQueries } =
|
||||
buildPrismaQueriesForAttributeOptionToUser({
|
||||
orgId,
|
||||
memberId,
|
||||
attributeOptionsToAssign,
|
||||
existingAttributeOptionAssignments,
|
||||
updater,
|
||||
});
|
||||
|
||||
const { numOfAttributeOptionsDeleted, numOfAttributeOptionsSet, numOfAttributeOptionsUpdated } =
|
||||
await prisma.$transaction(async (tx) => {
|
||||
// First delete all existing options, to allow them to be set again.
|
||||
const deleteQueriesResult = await Promise.all(
|
||||
Object.entries(attributeToUserDeleteQueries).map(([_, attributeToUserDeleteQuery]) =>
|
||||
attributeToUserDeleteQuery
|
||||
? tx.attributeToUser.deleteMany({
|
||||
where: attributeToUserDeleteQuery,
|
||||
})
|
||||
: Promise.resolve({ count: 0 })
|
||||
)
|
||||
);
|
||||
|
||||
// Then set the new options.
|
||||
const { count: numOfAttributeOptionsSet } = await tx.attributeToUser.createMany({
|
||||
data: attributeToUserCreateManyInput,
|
||||
// In case the values already exist, we skip them instead of throwing an error.
|
||||
skipDuplicates: true,
|
||||
});
|
||||
|
||||
let numOfAttributeOptionsUpdated = 0;
|
||||
if (attributeToUserUpdateManyInput) {
|
||||
({ count: numOfAttributeOptionsUpdated } = await tx.attributeToUser.updateMany({
|
||||
where: attributeToUserUpdateManyInput?.where,
|
||||
data: attributeToUserUpdateManyInput?.data,
|
||||
}));
|
||||
}
|
||||
|
||||
const numOfAttributeOptionsDeleted = deleteQueriesResult.reduce(
|
||||
(acc, query) => acc + (query.count ?? 0),
|
||||
0
|
||||
);
|
||||
|
||||
return {
|
||||
numOfAttributeOptionsDeleted,
|
||||
numOfAttributeOptionsSet,
|
||||
numOfAttributeOptionsUpdated,
|
||||
};
|
||||
});
|
||||
|
||||
log.debug({
|
||||
numOfAttributeOptionsSet,
|
||||
numOfAttributeOptionsDeleted,
|
||||
numOfAttributeOptionsUpdated,
|
||||
});
|
||||
|
||||
return {
|
||||
numOfAttributeOptionsSet,
|
||||
numOfAttributeOptionsDeleted,
|
||||
numOfAttributeOptionsUpdated,
|
||||
};
|
||||
};
|
||||
@@ -1,11 +1,10 @@
|
||||
import type { DirectorySyncEvent, User } from "@boxyhq/saml-jackson";
|
||||
|
||||
import removeUserFromOrg from "@calcom/features/ee/dsync/lib/removeUserFromOrg";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import { assignValueToUserInOrgBulk } from "@calcom/lib/service/attribute/server/assignValueToUser";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { IdentityProvider } from "@calcom/prisma/enums";
|
||||
import { getTeamOrThrow } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
|
||||
@@ -13,6 +12,7 @@ import type { UserWithMembership } from "@calcom/trpc/server/routers/viewer/team
|
||||
import { sendExistingUserTeamInviteEmails } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
|
||||
import { sendSignupToOrganizationEmail } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
|
||||
|
||||
import { assignValueToUserInOrgBulk } from "./assignValueToUser";
|
||||
import getAttributesFromScimPayload from "./getAttributesFromScimPayload";
|
||||
import createUsersAndConnectToOrg from "./users/createUsersAndConnectToOrg";
|
||||
import dSyncUserSelect from "./users/dSyncUserSelect";
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { vi, beforeEach } from "vitest";
|
||||
import { mockReset, mockDeep } from "vitest-mock-extended";
|
||||
|
||||
import type * as organization from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
|
||||
|
||||
vi.mock("@calcom/features/ee/organizations/repositories/OrganizationRepository", () => organizationMock);
|
||||
type OrganizationModule = typeof organization;
|
||||
beforeEach(() => {
|
||||
mockReset(organizationMock);
|
||||
});
|
||||
|
||||
const organizationMock = mockDeep<OrganizationModule>();
|
||||
const OrganizationRepository = organizationMock.OrganizationRepository;
|
||||
|
||||
export const organizationScenarios = {
|
||||
OrganizationRepository: {
|
||||
findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail: {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
fakeReturnOrganization: (org: any, forInput: any) => {
|
||||
OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail.mockImplementation(
|
||||
(arg) => {
|
||||
if (forInput.email === arg.email) {
|
||||
return org;
|
||||
}
|
||||
const errorMsg = "Mock Error-fakeReturnOrganization: Unhandled input";
|
||||
console.log(errorMsg, { arg, forInput });
|
||||
throw new Error(errorMsg);
|
||||
}
|
||||
);
|
||||
},
|
||||
fakeNoMatch: () => {
|
||||
OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail.mockResolvedValue(null);
|
||||
},
|
||||
},
|
||||
} satisfies Partial<Record<keyof OrganizationModule["OrganizationRepository"], unknown>>,
|
||||
} satisfies Partial<Record<keyof OrganizationModule, unknown>>;
|
||||
|
||||
export default organizationMock;
|
||||
@@ -9,8 +9,8 @@ import React from "react";
|
||||
import type { ITimezone } from "react-timezone-select";
|
||||
|
||||
import type { Dayjs } from "@calcom/dayjs";
|
||||
import getSlots from "@calcom/features/schedules/lib/slots";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import getSlots from "@calcom/lib/slots";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
import SkeletonLoader from "./SkeletonLoaderAvailabilityTimes";
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { ReactNode } from "react";
|
||||
import type { UseFormReturn } from "react-hook-form";
|
||||
|
||||
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
|
||||
import type { CreateEventTypeFormValues } from "@calcom/lib/hooks/useCreateEventType";
|
||||
import type { CreateEventTypeFormValues } from "@calcom/features/eventtypes/hooks/useCreateEventType";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -6,7 +6,7 @@ import { getBookerBaseUrlSync } from "@calcom/features/ee/organizations/lib/getB
|
||||
import { parseBookingLimit } from "@calcom/lib/intervalLimits/isBookingLimits";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTeam, getOrg } from "@calcom/lib/server/repository/team";
|
||||
import { getTeam, getOrg } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
|
||||
@@ -0,0 +1,468 @@
|
||||
import prismaMock from "../../../../../tests/libs/__mocks__/prismaMock";
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
|
||||
import { getTeam, getOrg, TeamRepository } from "./TeamRepository";
|
||||
|
||||
const sampleTeamProps = {
|
||||
logo: null,
|
||||
logoUrl: null,
|
||||
calVideoLogo: null,
|
||||
appLogo: null,
|
||||
appIconLogo: null,
|
||||
bio: null,
|
||||
description: null,
|
||||
hideBranding: false,
|
||||
isPrivate: false,
|
||||
hideBookATeamMember: false,
|
||||
hideTeamProfileLink: false,
|
||||
createdAt: new Date(),
|
||||
theme: null,
|
||||
brandColor: "",
|
||||
darkBrandColor: "",
|
||||
timeFormat: null,
|
||||
timeZone: "",
|
||||
weekStart: "",
|
||||
parentId: null,
|
||||
metadata: null,
|
||||
isOrganization: false,
|
||||
organizationSettings: null,
|
||||
isPlatform: false,
|
||||
bannerUrl: null,
|
||||
rrResetInterval: 0,
|
||||
rrResetOccurrence: 0,
|
||||
rrResetLimitOn: null,
|
||||
rrResetLimitOccurrences: null,
|
||||
rrResetLimitDate: null,
|
||||
includeManagedEventsInLimits: false,
|
||||
rrTimestampBasis: null,
|
||||
pendingPayment: false,
|
||||
createdByOAuthClientId: null,
|
||||
smsLockState: null,
|
||||
smsLockReviewedByAdmin: false,
|
||||
bookingLimits: null,
|
||||
};
|
||||
|
||||
describe("TeamRepository", () => {
|
||||
let teamRepository: TeamRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
teamRepository = new TeamRepository(prismaMock);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("findById", () => {
|
||||
it("should return null if team is not found", async () => {
|
||||
prismaMock.team.findUnique.mockResolvedValue(null);
|
||||
const result = await teamRepository.findById({ id: 1 });
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should return parsed team if found", async () => {
|
||||
const mockTeam = {
|
||||
id: 1,
|
||||
name: "Test Team",
|
||||
slug: "test-team",
|
||||
logoUrl: "test-logo-url",
|
||||
parentId: 1,
|
||||
metadata: {
|
||||
requestedSlug: null,
|
||||
},
|
||||
isOrganization: true,
|
||||
organizationSettings: {},
|
||||
isPlatform: true,
|
||||
requestedSlug: null,
|
||||
};
|
||||
prismaMock.team.findUnique.mockResolvedValue(mockTeam as unknown as Team);
|
||||
const result = await teamRepository.findById({ id: 1 });
|
||||
expect(result).toEqual(mockTeam);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteById", () => {
|
||||
it("should delete team and related data", async () => {
|
||||
const mockDeletedTeam = { id: 1, name: "Deleted Team" };
|
||||
const deleteManyEventTypeMock = vi.fn();
|
||||
const deleteManyMembershipMock = vi.fn();
|
||||
const deleteTeamMock = vi.fn().mockResolvedValue(mockDeletedTeam as unknown as Team);
|
||||
prismaMock.$transaction.mockImplementation(async (callback) => {
|
||||
const mockTx = {
|
||||
...prismaMock,
|
||||
eventType: {
|
||||
...prismaMock.eventType,
|
||||
deleteMany: deleteManyEventTypeMock,
|
||||
},
|
||||
membership: {
|
||||
...prismaMock.membership,
|
||||
deleteMany: deleteManyMembershipMock,
|
||||
},
|
||||
team: {
|
||||
...prismaMock.team,
|
||||
delete: deleteTeamMock,
|
||||
},
|
||||
};
|
||||
return callback(mockTx);
|
||||
});
|
||||
|
||||
const result = await teamRepository.deleteById({ id: 1 });
|
||||
|
||||
expect(deleteManyEventTypeMock).toHaveBeenCalledWith({
|
||||
where: {
|
||||
teamId: 1,
|
||||
schedulingType: "MANAGED",
|
||||
},
|
||||
});
|
||||
expect(deleteManyMembershipMock).toHaveBeenCalledWith({
|
||||
where: {
|
||||
teamId: 1,
|
||||
},
|
||||
});
|
||||
expect(deleteTeamMock).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: 1,
|
||||
},
|
||||
});
|
||||
expect(result).toEqual(mockDeletedTeam);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findAllByParentId", () => {
|
||||
it("should return all teams with given parentId", async () => {
|
||||
const mockTeams = [{ id: 1 }, { id: 2 }];
|
||||
prismaMock.team.findMany.mockResolvedValue(mockTeams as unknown as Team[]);
|
||||
const result = await teamRepository.findAllByParentId({ parentId: 1 });
|
||||
expect(prismaMock.team.findMany).toHaveBeenCalledWith({
|
||||
where: { parentId: 1 },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
logoUrl: true,
|
||||
parentId: true,
|
||||
metadata: true,
|
||||
isOrganization: true,
|
||||
organizationSettings: true,
|
||||
isPlatform: true,
|
||||
},
|
||||
});
|
||||
expect(result).toEqual(mockTeams);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findTeamWithMembers", () => {
|
||||
it("should return team with its members", async () => {
|
||||
const mockTeam = { id: 1, members: [] };
|
||||
prismaMock.team.findUnique.mockResolvedValue(mockTeam as unknown as Team & { members: [] });
|
||||
const result = await teamRepository.findTeamWithMembers(1);
|
||||
expect(prismaMock.team.findUnique).toHaveBeenCalledWith({
|
||||
where: { id: 1 },
|
||||
select: {
|
||||
members: {
|
||||
select: {
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
id: true,
|
||||
metadata: true,
|
||||
parentId: true,
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
expect(result).toEqual(mockTeam);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getOrg", () => {
|
||||
it("should return an Organization correctly by slug even if there is a team with the same slug", async () => {
|
||||
prismaMock.team.findMany.mockResolvedValue([
|
||||
{
|
||||
id: 101,
|
||||
name: "Test Team",
|
||||
slug: "test-slug",
|
||||
isOrganization: true,
|
||||
} as Team,
|
||||
]);
|
||||
|
||||
const org = await getOrg({
|
||||
lookupBy: {
|
||||
slug: "test-slug",
|
||||
},
|
||||
forOrgWithSlug: null,
|
||||
teamSelect: {
|
||||
id: true,
|
||||
slug: true,
|
||||
},
|
||||
});
|
||||
|
||||
const firstFindManyCallArguments = prismaMock.team.findMany.mock.calls[0];
|
||||
|
||||
expect(firstFindManyCallArguments[0]).toEqual({
|
||||
where: {
|
||||
slug: "test-slug",
|
||||
isOrganization: true,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
metadata: true,
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
expect(org?.isOrganization).toBe(true);
|
||||
});
|
||||
|
||||
it("should not return an org result if metadata.isOrganization isn't true", async () => {
|
||||
prismaMock.team.findMany.mockResolvedValue([
|
||||
{
|
||||
...sampleTeamProps,
|
||||
id: 101,
|
||||
name: "Test Team",
|
||||
slug: "test-slug",
|
||||
metadata: {},
|
||||
} as Team,
|
||||
]);
|
||||
|
||||
const org = await getOrg({
|
||||
lookupBy: {
|
||||
slug: "test-slug",
|
||||
},
|
||||
forOrgWithSlug: null,
|
||||
teamSelect: {
|
||||
id: true,
|
||||
slug: true,
|
||||
},
|
||||
});
|
||||
|
||||
const firstFindManyCallArguments = prismaMock.team.findMany.mock.calls[0];
|
||||
|
||||
expect(firstFindManyCallArguments[0]).toEqual({
|
||||
where: {
|
||||
slug: "test-slug",
|
||||
isOrganization: true,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
metadata: true,
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
expect(org).toBe(null);
|
||||
});
|
||||
|
||||
it("should error if metadata isn't valid", async () => {
|
||||
prismaMock.team.findMany.mockResolvedValue([
|
||||
{
|
||||
...sampleTeamProps,
|
||||
id: 101,
|
||||
name: "Test Team",
|
||||
slug: "test-slug",
|
||||
metadata: [],
|
||||
} as Team,
|
||||
]);
|
||||
|
||||
await expect(() =>
|
||||
getOrg({
|
||||
lookupBy: {
|
||||
slug: "test-slug",
|
||||
},
|
||||
forOrgWithSlug: null,
|
||||
teamSelect: {
|
||||
id: true,
|
||||
slug: true,
|
||||
},
|
||||
})
|
||||
).rejects.toThrow("invalid_type");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getTeam", () => {
|
||||
it("should query a team correctly", async () => {
|
||||
prismaMock.team.findMany.mockResolvedValue([
|
||||
{
|
||||
...sampleTeamProps,
|
||||
id: 101,
|
||||
name: "Test Team",
|
||||
slug: "test-slug",
|
||||
metadata: {
|
||||
anything: "here",
|
||||
paymentId: "1",
|
||||
},
|
||||
} as Team,
|
||||
]);
|
||||
|
||||
const team = await getTeam({
|
||||
lookupBy: {
|
||||
slug: "test-slug",
|
||||
},
|
||||
forOrgWithSlug: null,
|
||||
teamSelect: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
},
|
||||
});
|
||||
|
||||
const firstFindManyCallArguments = prismaMock.team.findMany.mock.calls[0];
|
||||
|
||||
expect(firstFindManyCallArguments[0]).toEqual({
|
||||
where: {
|
||||
slug: "test-slug",
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
metadata: true,
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
expect(team).not.toBeNull();
|
||||
// 'anything' is not in the teamMetadata schema, so it should be stripped out
|
||||
expect(team?.metadata).toEqual({ paymentId: "1" });
|
||||
});
|
||||
|
||||
it("should not return a team result if the queried result isn't a team", async () => {
|
||||
prismaMock.team.findMany.mockResolvedValue([
|
||||
{
|
||||
...sampleTeamProps,
|
||||
id: 101,
|
||||
name: "Test Team",
|
||||
slug: "test-slug",
|
||||
isOrganization: true,
|
||||
} as Team,
|
||||
]);
|
||||
|
||||
const team = await getTeam({
|
||||
lookupBy: {
|
||||
slug: "test-slug",
|
||||
},
|
||||
forOrgWithSlug: null,
|
||||
teamSelect: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
},
|
||||
});
|
||||
|
||||
const firstFindManyCallArguments = prismaMock.team.findMany.mock.calls[0];
|
||||
|
||||
expect(firstFindManyCallArguments[0]).toEqual({
|
||||
where: {
|
||||
slug: "test-slug",
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
metadata: true,
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
expect(team).toBe(null);
|
||||
});
|
||||
|
||||
it("should return a team by slug within an org", async () => {
|
||||
prismaMock.team.findMany.mockResolvedValue([
|
||||
{
|
||||
...sampleTeamProps,
|
||||
id: 101,
|
||||
name: "Test Team",
|
||||
slug: "test-slug",
|
||||
parentId: 100,
|
||||
metadata: null,
|
||||
} as Team,
|
||||
]);
|
||||
|
||||
await getTeam({
|
||||
lookupBy: {
|
||||
slug: "team-in-test-org",
|
||||
},
|
||||
forOrgWithSlug: "test-org",
|
||||
teamSelect: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
},
|
||||
});
|
||||
|
||||
const firstFindManyCallArguments = prismaMock.team.findMany.mock.calls[0];
|
||||
|
||||
expect(firstFindManyCallArguments[0]).toEqual({
|
||||
where: {
|
||||
slug: "team-in-test-org",
|
||||
parent: {
|
||||
OR: [
|
||||
{
|
||||
slug: "test-org",
|
||||
},
|
||||
{
|
||||
metadata: {
|
||||
path: ["requestedSlug"],
|
||||
equals: "test-org",
|
||||
},
|
||||
},
|
||||
],
|
||||
isOrganization: true,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
metadata: true,
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should return a team by requestedSlug within an org", async () => {
|
||||
prismaMock.team.findMany.mockResolvedValue([]);
|
||||
await getTeam({
|
||||
lookupBy: {
|
||||
slug: "test-team",
|
||||
},
|
||||
forOrgWithSlug: "test-org",
|
||||
teamSelect: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
},
|
||||
});
|
||||
const firstFindManyCallArguments = prismaMock.team.findMany.mock.calls[0];
|
||||
|
||||
expect(firstFindManyCallArguments[0]).toEqual({
|
||||
where: {
|
||||
slug: "test-team",
|
||||
parent: {
|
||||
isOrganization: true,
|
||||
OR: [
|
||||
{
|
||||
slug: "test-org",
|
||||
},
|
||||
{
|
||||
metadata: {
|
||||
path: ["requestedSlug"],
|
||||
equals: "test-org",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
metadata: true,
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,487 @@
|
||||
import type { z } from "zod";
|
||||
|
||||
import { whereClauseForOrgWithSlugOrRequestedSlug } from "@calcom/ee/organizations/lib/orgDomains";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { getParsedTeam } from "@calcom/lib/server/repository/teamUtils";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
type TeamGetPayloadWithParsedMetadata<TeamSelect extends Prisma.TeamSelect> =
|
||||
| (Omit<Prisma.TeamGetPayload<{ select: TeamSelect }>, "metadata" | "isOrganization"> & {
|
||||
metadata: z.infer<typeof teamMetadataSchema>;
|
||||
isOrganization: boolean;
|
||||
})
|
||||
| null;
|
||||
|
||||
type GetTeamOrOrgArg<TeamSelect extends Prisma.TeamSelect> = {
|
||||
lookupBy: (
|
||||
| {
|
||||
id: number;
|
||||
}
|
||||
| {
|
||||
slug: string;
|
||||
}
|
||||
) & {
|
||||
havingMemberWithId?: number;
|
||||
};
|
||||
/**
|
||||
* If we are fetching a team, this is the slug of the organization that the team belongs to.
|
||||
*/
|
||||
forOrgWithSlug: string | null;
|
||||
/**
|
||||
* If true, means that we need to fetch an organization with the given slug. Otherwise, we need to fetch a team with the given slug.
|
||||
*/
|
||||
isOrg: boolean;
|
||||
teamSelect: TeamSelect;
|
||||
};
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["repository", "team"] });
|
||||
|
||||
/**
|
||||
* Gets the team or organization with the given slug or id reliably along with parsed metadata.
|
||||
*/
|
||||
async function getTeamOrOrg<TeamSelect extends Prisma.TeamSelect>({
|
||||
lookupBy,
|
||||
forOrgWithSlug: forOrgWithSlug,
|
||||
isOrg,
|
||||
teamSelect,
|
||||
}: GetTeamOrOrgArg<TeamSelect>): Promise<TeamGetPayloadWithParsedMetadata<TeamSelect>> {
|
||||
const where: Prisma.TeamFindFirstArgs["where"] = {};
|
||||
teamSelect = {
|
||||
...teamSelect,
|
||||
metadata: true,
|
||||
isOrganization: true,
|
||||
} satisfies TeamSelect;
|
||||
if (lookupBy.havingMemberWithId) where.members = { some: { userId: lookupBy.havingMemberWithId } };
|
||||
|
||||
if ("id" in lookupBy) {
|
||||
where.id = lookupBy.id;
|
||||
} else {
|
||||
where.slug = lookupBy.slug;
|
||||
}
|
||||
|
||||
if (isOrg) {
|
||||
// We must fetch only the organization here.
|
||||
// Note that an organization and a team that doesn't belong to an organization, both have parentId null
|
||||
// If the organization has null slug(but requestedSlug is 'test') and the team also has slug 'test', we can't distinguish them without explicitly checking the metadata.isOrganization
|
||||
// Note that, this isn't possible now to have same requestedSlug as the slug of a team not part of an organization. This is legacy teams handling mostly. But it is still safer to be sure that you are fetching an Organization only in case of isOrgView
|
||||
where.isOrganization = true;
|
||||
// We must fetch only the team here.
|
||||
} else {
|
||||
if (forOrgWithSlug) {
|
||||
where.parent = whereClauseForOrgWithSlugOrRequestedSlug(forOrgWithSlug);
|
||||
}
|
||||
}
|
||||
|
||||
log.debug({
|
||||
orgSlug: forOrgWithSlug,
|
||||
teamLookupBy: lookupBy,
|
||||
isOrgView: isOrg,
|
||||
where,
|
||||
});
|
||||
|
||||
const teams = await prisma.team.findMany({
|
||||
where,
|
||||
select: teamSelect,
|
||||
});
|
||||
|
||||
const teamsWithParsedMetadata = teams
|
||||
.map((team) => {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore ts types are way too complciated for this now
|
||||
const parsedMetadata = teamMetadataSchema.parse(team.metadata ?? {});
|
||||
return {
|
||||
...team,
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore It does exist
|
||||
isOrganization: team.isOrganization as boolean,
|
||||
metadata: parsedMetadata,
|
||||
};
|
||||
})
|
||||
// In cases where there are many teams with the same slug, we need to find out the one and only one that matches our criteria
|
||||
.filter((team) => {
|
||||
// We need an org if isOrgView otherwise we need a team
|
||||
return isOrg ? team.isOrganization : !team.isOrganization;
|
||||
});
|
||||
|
||||
if (teamsWithParsedMetadata.length > 1) {
|
||||
log.error("Found more than one team/Org. We should be doing something wrong.", {
|
||||
isOrgView: isOrg,
|
||||
where,
|
||||
teams: teamsWithParsedMetadata.map((team) => {
|
||||
const t = team as unknown as { id: number; slug: string };
|
||||
return {
|
||||
id: t.id,
|
||||
slug: t.slug,
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
const team = teamsWithParsedMetadata[0];
|
||||
if (!team) return null;
|
||||
// HACK: I am not sure how to make Prisma in peace with TypeScript with this repository pattern
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return team as any;
|
||||
}
|
||||
|
||||
export async function getTeam<TeamSelect extends Prisma.TeamSelect>({
|
||||
lookupBy,
|
||||
forOrgWithSlug: forOrgWithSlug,
|
||||
teamSelect,
|
||||
}: Omit<GetTeamOrOrgArg<TeamSelect>, "isOrg">): Promise<TeamGetPayloadWithParsedMetadata<TeamSelect>> {
|
||||
return getTeamOrOrg({
|
||||
lookupBy,
|
||||
forOrgWithSlug: forOrgWithSlug,
|
||||
isOrg: false,
|
||||
teamSelect,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getOrg<TeamSelect extends Prisma.TeamSelect>({
|
||||
lookupBy,
|
||||
forOrgWithSlug: forOrgWithSlug,
|
||||
teamSelect,
|
||||
}: Omit<GetTeamOrOrgArg<TeamSelect>, "isOrg">): Promise<TeamGetPayloadWithParsedMetadata<TeamSelect>> {
|
||||
return getTeamOrOrg({
|
||||
lookupBy,
|
||||
forOrgWithSlug: forOrgWithSlug,
|
||||
isOrg: true,
|
||||
teamSelect,
|
||||
});
|
||||
}
|
||||
|
||||
const teamSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
logoUrl: true,
|
||||
parentId: true,
|
||||
metadata: true,
|
||||
isOrganization: true,
|
||||
organizationSettings: true,
|
||||
isPlatform: true,
|
||||
} satisfies Prisma.TeamSelect;
|
||||
|
||||
export class TeamRepository {
|
||||
constructor(private prismaClient: PrismaClient) {}
|
||||
|
||||
async findById({ id }: { id: number }) {
|
||||
const team = await this.prismaClient.team.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
select: teamSelect,
|
||||
});
|
||||
if (!team) {
|
||||
return null;
|
||||
}
|
||||
return getParsedTeam(team);
|
||||
}
|
||||
|
||||
async findByIdIncludePlatformBilling({ id }: { id: number }) {
|
||||
const team = await this.prismaClient.team.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
select: { ...teamSelect, platformBilling: true },
|
||||
});
|
||||
if (!team) {
|
||||
return null;
|
||||
}
|
||||
return getParsedTeam(team);
|
||||
}
|
||||
|
||||
async findAllByParentId({
|
||||
parentId,
|
||||
select = teamSelect,
|
||||
}: {
|
||||
parentId: number;
|
||||
select?: Prisma.TeamSelect;
|
||||
}) {
|
||||
return await this.prismaClient.team.findMany({
|
||||
where: {
|
||||
parentId,
|
||||
},
|
||||
select,
|
||||
});
|
||||
}
|
||||
|
||||
async findByIdAndParentId({
|
||||
id,
|
||||
parentId,
|
||||
select = teamSelect,
|
||||
}: {
|
||||
id: number;
|
||||
parentId: number;
|
||||
select?: Prisma.TeamSelect;
|
||||
}) {
|
||||
return await this.prismaClient.team.findFirst({
|
||||
where: {
|
||||
id,
|
||||
parentId,
|
||||
},
|
||||
select,
|
||||
});
|
||||
}
|
||||
|
||||
async findFirstBySlugAndParentSlug({
|
||||
slug,
|
||||
parentSlug,
|
||||
select = teamSelect,
|
||||
}: {
|
||||
slug: string;
|
||||
parentSlug: string | null;
|
||||
select?: Prisma.TeamSelect;
|
||||
}) {
|
||||
return await this.prismaClient.team.findFirst({
|
||||
where: {
|
||||
slug,
|
||||
parent: parentSlug ? whereClauseForOrgWithSlugOrRequestedSlug(parentSlug) : null,
|
||||
},
|
||||
select,
|
||||
});
|
||||
}
|
||||
|
||||
async deleteById({ id }: { id: number }) {
|
||||
const deletedTeam = await this.prismaClient.$transaction(async (tx) => {
|
||||
await tx.eventType.deleteMany({
|
||||
where: {
|
||||
teamId: id,
|
||||
schedulingType: "MANAGED",
|
||||
},
|
||||
});
|
||||
|
||||
// delete all memberships
|
||||
await tx.membership.deleteMany({
|
||||
where: {
|
||||
teamId: id,
|
||||
},
|
||||
});
|
||||
|
||||
const deletedTeam = await tx.team.delete({
|
||||
where: {
|
||||
id: id,
|
||||
},
|
||||
});
|
||||
|
||||
return deletedTeam;
|
||||
});
|
||||
|
||||
return deletedTeam;
|
||||
}
|
||||
|
||||
async findTeamWithMembers(teamId: number) {
|
||||
return await this.prismaClient.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: {
|
||||
members: {
|
||||
select: {
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
id: true,
|
||||
metadata: true,
|
||||
parentId: true,
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findTeamsByUserId({ userId, includeOrgs }: { userId: number; includeOrgs?: boolean }) {
|
||||
const memberships = await this.prismaClient.membership.findMany({
|
||||
where: {
|
||||
// Show all the teams this user belongs to regardless of the team being part of the user's org or not
|
||||
// We don't want to restrict in the listing here. If we need to restrict a situation where a user is part of the org along with being part of a non-org team, we should do that instead of filtering out from here
|
||||
// This became necessary when we started migrating user to Org, without migrating some teams of the user to the org
|
||||
// Also, we would allow a user to be part of multiple orgs, then also it would be necessary.
|
||||
userId: userId,
|
||||
},
|
||||
include: {
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
logoUrl: true,
|
||||
isOrganization: true,
|
||||
metadata: true,
|
||||
inviteTokens: true,
|
||||
parent: true,
|
||||
parentId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { role: "desc" },
|
||||
});
|
||||
|
||||
return memberships
|
||||
.filter((mmship) => {
|
||||
if (includeOrgs) return true;
|
||||
return !mmship.team.isOrganization;
|
||||
})
|
||||
.map(({ team: { inviteTokens, ...team }, ...membership }) => ({
|
||||
role: membership.role,
|
||||
accepted: membership.accepted,
|
||||
...team,
|
||||
metadata: teamMetadataSchema.parse(team.metadata),
|
||||
/** To prevent breaking we only return non-email attached token here, if we have one */
|
||||
inviteToken: inviteTokens.find((token) => token.identifier === `invite-link-for-teamId-${team.id}`),
|
||||
}));
|
||||
}
|
||||
|
||||
async findTeamWithOrganizationSettings(teamId: number) {
|
||||
return await this.prismaClient.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: {
|
||||
parent: {
|
||||
select: {
|
||||
isOrganization: true,
|
||||
organizationSettings: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findParentOrganizationByTeamId(teamId: number) {
|
||||
const team = await this.prismaClient.team.findUnique({
|
||||
where: {
|
||||
id: teamId,
|
||||
},
|
||||
select: {
|
||||
parent: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return team?.parent;
|
||||
}
|
||||
|
||||
async findOrganizationSettingsBySlug({ slug }: { slug: string }) {
|
||||
return await this.prismaClient.team.findFirst({
|
||||
where: {
|
||||
slug,
|
||||
isOrganization: true,
|
||||
},
|
||||
select: {
|
||||
organizationSettings: {
|
||||
select: {
|
||||
adminGetsNoSlotsNotification: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findTeamSlugById({ id }: { id: number }) {
|
||||
return await this.prismaClient.team.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
select: {
|
||||
slug: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async getTeamByIdIfUserIsAdmin({ userId, teamId }: { userId: number; teamId: number }) {
|
||||
return await this.prismaClient.team.findUnique({
|
||||
where: {
|
||||
id: teamId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
metadata: true,
|
||||
members: {
|
||||
where: {
|
||||
userId,
|
||||
role: {
|
||||
in: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findTeamWithParentHideBranding({ teamId }: { teamId: number }) {
|
||||
return await this.prismaClient.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: {
|
||||
hideBranding: true,
|
||||
parent: {
|
||||
select: {
|
||||
hideBranding: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findOrganization({ teamId, userId }: { teamId?: number; userId: number }) {
|
||||
return await this.prismaClient.team.findFirst({
|
||||
where: {
|
||||
isOrganization: true,
|
||||
children: {
|
||||
some: {
|
||||
id: teamId,
|
||||
},
|
||||
},
|
||||
members: {
|
||||
some: {
|
||||
userId,
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async isSlugAvailableForUpdate({
|
||||
slug,
|
||||
teamId,
|
||||
parentId,
|
||||
}: {
|
||||
slug: string;
|
||||
teamId: number;
|
||||
parentId?: number | null;
|
||||
}) {
|
||||
const whereClause: Prisma.TeamWhereInput = {
|
||||
slug: {
|
||||
equals: slug,
|
||||
mode: "insensitive",
|
||||
},
|
||||
parentId: parentId ?? null,
|
||||
NOT: { id: teamId },
|
||||
};
|
||||
|
||||
const conflictingTeam = await this.prismaClient.team.findFirst({
|
||||
where: whereClause,
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
return !conflictingTeam;
|
||||
}
|
||||
|
||||
async findOrgTeamsExcludingTeam({ parentId, excludeTeamId }: { parentId: number; excludeTeamId: number }) {
|
||||
return await this.prismaClient.team.findMany({
|
||||
where: {
|
||||
parentId,
|
||||
id: {
|
||||
not: excludeTeamId,
|
||||
},
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
import { TeamBilling } from "@calcom/features/ee/billing/teams";
|
||||
import { deleteDomain } from "@calcom/lib/domainManager/organization";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import { WorkflowService } from "@calcom/lib/server/service/workflows";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import { WorkflowService } from "@calcom/features/ee/workflows/lib/service/WorkflowService";
|
||||
|
||||
import { TeamService } from "./teamService";
|
||||
|
||||
@@ -14,8 +14,8 @@ vi.mock("@calcom/prisma", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/ee/billing/teams");
|
||||
vi.mock("@calcom/lib/server/repository/team");
|
||||
vi.mock("@calcom/lib/server/service/workflows");
|
||||
vi.mock("@calcom/features/ee/teams/repositories/TeamRepository");
|
||||
vi.mock("@calcom/features/ee/workflows/lib/service/WorkflowService");
|
||||
vi.mock("@calcom/lib/domainManager/organization");
|
||||
vi.mock("@calcom/features/ee/teams/lib/removeMember");
|
||||
class Database {
|
||||
|
||||
@@ -6,8 +6,8 @@ import { TeamBilling } from "@calcom/features/ee/billing/teams";
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/features/ee/teams/lib/queries";
|
||||
import { createAProfileForAnExistingUser } from "@calcom/features/profile/lib/createAProfileForAnExistingUser";
|
||||
import { deleteDomain } from "@calcom/lib/domainManager/organization";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import { WorkflowService } from "@calcom/lib/server/service/workflows";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import { WorkflowService } from "@calcom/features/ee/workflows/lib/service/WorkflowService";
|
||||
import type { Membership, Team, User, VerificationToken, Profile } from "@calcom/prisma/client";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -16,8 +16,8 @@ import { TRPCError } from "@trpc/server";
|
||||
import { TeamService } from "./teamService";
|
||||
|
||||
vi.mock("@calcom/features/ee/billing/teams");
|
||||
vi.mock("@calcom/lib/server/repository/team");
|
||||
vi.mock("@calcom/lib/server/service/workflows");
|
||||
vi.mock("@calcom/features/ee/teams/repositories/TeamRepository");
|
||||
vi.mock("@calcom/features/ee/workflows/lib/service/WorkflowService");
|
||||
vi.mock("@calcom/lib/domainManager/organization");
|
||||
vi.mock("@calcom/features/ee/teams/lib/removeMember");
|
||||
vi.mock("@calcom/features/profile/lib/createAProfileForAnExistingUser");
|
||||
|
||||
@@ -8,8 +8,8 @@ import { createAProfileForAnExistingUser } from "@calcom/features/profile/lib/cr
|
||||
import { deleteDomain } from "@calcom/lib/domainManager/organization";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import { WorkflowService } from "@calcom/lib/server/service/workflows";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import { WorkflowService } from "@calcom/features/ee/workflows/lib/service/WorkflowService";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { Prisma } from "@calcom/prisma/client";
|
||||
import type { Membership } from "@calcom/prisma/client";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { CAL_AI_AGENT_PHONE_NUMBER_FIELD } from "@calcom/lib/SystemField";
|
||||
import { CAL_AI_AGENT_PHONE_NUMBER_FIELD } from "@calcom/lib/bookings/SystemField";
|
||||
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
|
||||
import tasker from "@calcom/features/tasker";
|
||||
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
import { describe, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
import { scheduleWorkflowReminders } from "@calcom/features/ee/workflows/lib/reminders/reminderScheduler";
|
||||
import { tasker } from "@calcom/features/tasker";
|
||||
import { WorkflowTriggerEvents, WorkflowActions, WorkflowTemplates, TimeUnit } from "@calcom/prisma/enums";
|
||||
import { test } from "@calcom/web/test/fixtures/fixtures";
|
||||
|
||||
import { WorkflowService } from "./WorkflowService";
|
||||
|
||||
vi.mock("@calcom/features/ee/workflows/lib/reminders/reminderScheduler");
|
||||
vi.mock("@calcom/features/tasker");
|
||||
|
||||
const mockScheduleWorkflowReminders = vi.mocked(scheduleWorkflowReminders);
|
||||
const mockTasker = vi.mocked(tasker);
|
||||
|
||||
// Mock the getHideBranding function to return false
|
||||
vi.mock("@calcom/features/profile/lib/hideBranding", () => ({
|
||||
getHideBranding: vi.fn().mockResolvedValue(false),
|
||||
}));
|
||||
|
||||
describe("WorkflowService.scheduleFormWorkflows", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const mockForm = {
|
||||
id: "form-123",
|
||||
userId: 101,
|
||||
teamId: null,
|
||||
fields: [
|
||||
{ type: "email", identifier: "email" },
|
||||
{ type: "phone", identifier: "phone" },
|
||||
],
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
timeFormat: 12,
|
||||
locale: "en",
|
||||
},
|
||||
};
|
||||
|
||||
const mockResponses = {
|
||||
email: {
|
||||
value: "[email protected]",
|
||||
response: "[email protected]",
|
||||
},
|
||||
phone: {
|
||||
value: "+1234567890",
|
||||
response: "+1234567890",
|
||||
},
|
||||
};
|
||||
|
||||
test("should call scheduleWorkflowReminders for FORM_SUBMITTED triggers with correct phone number", async () => {
|
||||
const workflows = [
|
||||
{
|
||||
id: 1,
|
||||
name: "Form Submitted",
|
||||
userId: 101,
|
||||
teamId: null,
|
||||
trigger: WorkflowTriggerEvents.FORM_SUBMITTED,
|
||||
time: null,
|
||||
timeUnit: null,
|
||||
steps: [
|
||||
{
|
||||
id: 1,
|
||||
action: WorkflowActions.SMS_ATTENDEE,
|
||||
sendTo: null,
|
||||
reminderBody: "Thank you!",
|
||||
emailSubject: "Form Received",
|
||||
template: WorkflowTemplates.CUSTOM,
|
||||
verifiedAt: new Date(),
|
||||
includeCalendarEvent: false,
|
||||
numberVerificationPending: false,
|
||||
numberRequired: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
await WorkflowService.scheduleFormWorkflows({
|
||||
workflows,
|
||||
responses: mockResponses,
|
||||
form: mockForm,
|
||||
});
|
||||
|
||||
expect(mockScheduleWorkflowReminders).toHaveBeenCalledWith({
|
||||
smsReminderNumber: "+1234567890",
|
||||
formData: {
|
||||
responses: mockResponses,
|
||||
user: { email: "[email protected]", timeFormat: 12, locale: "en" },
|
||||
},
|
||||
hideBranding: false,
|
||||
workflows: [workflows[0]],
|
||||
});
|
||||
});
|
||||
|
||||
test("should create task for FORM_SUBMITTED_NO_EVENT triggers", async () => {
|
||||
const workflows = [
|
||||
{
|
||||
id: 2,
|
||||
name: "Form Follow-up",
|
||||
userId: 101,
|
||||
teamId: null,
|
||||
trigger: WorkflowTriggerEvents.FORM_SUBMITTED_NO_EVENT,
|
||||
time: 30,
|
||||
timeUnit: TimeUnit.MINUTE,
|
||||
steps: [
|
||||
{
|
||||
id: 2,
|
||||
action: WorkflowActions.EMAIL_ATTENDEE,
|
||||
sendTo: null,
|
||||
reminderBody: "Follow up message",
|
||||
emailSubject: "Follow Up",
|
||||
template: WorkflowTemplates.CUSTOM,
|
||||
verifiedAt: new Date(),
|
||||
includeCalendarEvent: false,
|
||||
numberVerificationPending: false,
|
||||
numberRequired: false,
|
||||
sender: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
mockTasker.create.mockResolvedValue({ id: "task-123" });
|
||||
|
||||
await WorkflowService.scheduleFormWorkflows({
|
||||
workflows,
|
||||
responses: mockResponses,
|
||||
responseId: 123,
|
||||
form: mockForm,
|
||||
});
|
||||
|
||||
expect(mockTasker.create).toHaveBeenCalledWith(
|
||||
"triggerFormSubmittedNoEventWorkflow",
|
||||
{
|
||||
responseId: 123,
|
||||
responses: mockResponses,
|
||||
smsReminderNumber: "+1234567890",
|
||||
hideBranding: false,
|
||||
submittedAt: expect.any(Date),
|
||||
form: {
|
||||
id: "form-123",
|
||||
userId: 101,
|
||||
teamId: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
timeFormat: 12,
|
||||
locale: "en",
|
||||
},
|
||||
},
|
||||
workflow: workflows[0],
|
||||
},
|
||||
{ scheduledAt: expect.any(Date) }
|
||||
);
|
||||
});
|
||||
|
||||
test("should handle forms without phone fields by passing null smsReminderNumber", async () => {
|
||||
const formWithoutPhone = {
|
||||
...mockForm,
|
||||
fields: [
|
||||
{ type: "email", identifier: "email" },
|
||||
{ type: "text", identifier: "name" },
|
||||
],
|
||||
};
|
||||
|
||||
const workflows = [
|
||||
{
|
||||
id: 1,
|
||||
name: "Form Submitted",
|
||||
userId: 101,
|
||||
teamId: null,
|
||||
trigger: WorkflowTriggerEvents.FORM_SUBMITTED,
|
||||
time: null,
|
||||
timeUnit: null,
|
||||
steps: [
|
||||
{
|
||||
id: 1,
|
||||
action: WorkflowActions.EMAIL_ATTENDEE,
|
||||
sendTo: null,
|
||||
reminderBody: "Thank you!",
|
||||
emailSubject: "Form Received",
|
||||
template: WorkflowTemplates.CUSTOM,
|
||||
verifiedAt: new Date(),
|
||||
includeCalendarEvent: false,
|
||||
numberVerificationPending: false,
|
||||
numberRequired: false,
|
||||
sender: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
await WorkflowService.scheduleFormWorkflows({
|
||||
workflows,
|
||||
responses: mockResponses,
|
||||
form: formWithoutPhone,
|
||||
});
|
||||
|
||||
expect(mockScheduleWorkflowReminders).toHaveBeenCalledWith({
|
||||
smsReminderNumber: null,
|
||||
formData: {
|
||||
responses: mockResponses,
|
||||
user: { email: "[email protected]", timeFormat: 12, locale: "en" },
|
||||
},
|
||||
hideBranding: false,
|
||||
workflows: [workflows[0]],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,234 @@
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { getAllWorkflows } from "@calcom/ee/workflows/lib/getAllWorkflows";
|
||||
import type { ScheduleWorkflowRemindersArgs } from "@calcom/ee/workflows/lib/reminders/reminderScheduler";
|
||||
import { scheduleWorkflowReminders } from "@calcom/ee/workflows/lib/reminders/reminderScheduler";
|
||||
import type { timeUnitLowerCase } from "@calcom/ee/workflows/lib/reminders/smsReminderManager";
|
||||
import type { Workflow } from "@calcom/ee/workflows/lib/types";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import { WorkflowRepository } from "@calcom/features/ee/workflows/repositories/WorkflowRepository";
|
||||
import { getHideBranding } from "@calcom/features/profile/lib/hideBranding";
|
||||
import { tasker } from "@calcom/features/tasker";
|
||||
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { WorkflowTriggerEvents, WorkflowType } from "@calcom/prisma/enums";
|
||||
import type { FORM_SUBMITTED_WEBHOOK_RESPONSES } from "@calcom/routing-forms/lib/formSubmissionUtils";
|
||||
|
||||
// TODO (Sean): Move most of the logic migrated in 16861 to this service
|
||||
export class WorkflowService {
|
||||
static _beforeAfterEventTriggers: WorkflowTriggerEvents[] = [
|
||||
WorkflowTriggerEvents.AFTER_EVENT,
|
||||
WorkflowTriggerEvents.BEFORE_EVENT,
|
||||
];
|
||||
|
||||
static async getAllWorkflowsFromRoutingForm(routingForm: {
|
||||
id: string;
|
||||
userId: number | null;
|
||||
teamId: number | null;
|
||||
}) {
|
||||
const routingFormWorkflows = await WorkflowRepository.findWorkflowsActiveOnRoutingForm({
|
||||
routingFormId: routingForm.id,
|
||||
});
|
||||
|
||||
const teamId = routingForm.teamId;
|
||||
const userId = routingForm.userId;
|
||||
const orgId = await getOrgIdFromMemberOrTeamId({ memberId: userId, teamId });
|
||||
|
||||
const allWorkflows = await getAllWorkflows({
|
||||
entityWorkflows: routingFormWorkflows,
|
||||
userId,
|
||||
teamId,
|
||||
orgId,
|
||||
workflowsLockedForUser: false,
|
||||
type: WorkflowType.ROUTING_FORM,
|
||||
});
|
||||
|
||||
return allWorkflows;
|
||||
}
|
||||
|
||||
static async deleteWorkflowRemindersOfRemovedTeam(teamId: number) {
|
||||
const teamRepository = new TeamRepository(prisma);
|
||||
const team = await teamRepository.findById({ id: teamId });
|
||||
|
||||
if (team?.parentId) {
|
||||
const activeWorkflowsOnTeam = await WorkflowRepository.findActiveWorkflowsOnTeam({
|
||||
parentTeamId: team.parentId,
|
||||
teamId: team.id,
|
||||
});
|
||||
|
||||
for (const workflow of activeWorkflowsOnTeam) {
|
||||
const workflowSteps = workflow.steps;
|
||||
let remainingActiveOnIds = [];
|
||||
|
||||
if (workflow.isActiveOnAll) {
|
||||
const teamRepository = new TeamRepository(prisma);
|
||||
const allRemainingOrgTeams = await teamRepository.findOrgTeamsExcludingTeam({
|
||||
parentId: team.parentId,
|
||||
excludeTeamId: team.id,
|
||||
});
|
||||
remainingActiveOnIds = allRemainingOrgTeams.map((team) => team.id);
|
||||
} else {
|
||||
remainingActiveOnIds = workflow.activeOnTeams
|
||||
.filter((activeOn) => activeOn.teamId !== team.id)
|
||||
.map((activeOn) => activeOn.teamId);
|
||||
}
|
||||
const remindersToDelete = await WorkflowRepository.getRemindersFromRemovedTeams(
|
||||
[team.id],
|
||||
workflowSteps,
|
||||
remainingActiveOnIds
|
||||
);
|
||||
await WorkflowRepository.deleteAllWorkflowReminders(remindersToDelete);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async scheduleFormWorkflows({
|
||||
workflows,
|
||||
responses,
|
||||
form,
|
||||
responseId,
|
||||
}: {
|
||||
responseId: number;
|
||||
workflows: Workflow[];
|
||||
responses: FORM_SUBMITTED_WEBHOOK_RESPONSES;
|
||||
form: {
|
||||
id: string;
|
||||
userId: number;
|
||||
teamId?: number | null;
|
||||
fields?: { type: string; identifier?: string }[];
|
||||
user: {
|
||||
email: string;
|
||||
timeFormat: number | null;
|
||||
locale: string | null;
|
||||
};
|
||||
};
|
||||
}) {
|
||||
if (workflows.length <= 0) return;
|
||||
|
||||
const workflowsToTrigger: Workflow[] = [];
|
||||
|
||||
workflowsToTrigger.push(
|
||||
...workflows.filter((workflow) => workflow.trigger === WorkflowTriggerEvents.FORM_SUBMITTED)
|
||||
);
|
||||
|
||||
let smsReminderNumber: string | null = null;
|
||||
if (form.fields) {
|
||||
const phoneField = form.fields.find((field) => field.type === "phone");
|
||||
if (phoneField && phoneField.identifier) {
|
||||
const phoneResponse = responses[phoneField.identifier];
|
||||
if (phoneResponse?.response && typeof phoneResponse.response === "string") {
|
||||
smsReminderNumber = phoneResponse.response as string;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const hideBranding = await getHideBranding({
|
||||
userId: form.userId,
|
||||
teamId: form.teamId ?? undefined,
|
||||
});
|
||||
|
||||
await scheduleWorkflowReminders({
|
||||
smsReminderNumber,
|
||||
formData: {
|
||||
responses,
|
||||
user: { email: form.user.email, timeFormat: form.user.timeFormat, locale: form.user.locale ?? "en" },
|
||||
},
|
||||
hideBranding,
|
||||
workflows: workflowsToTrigger,
|
||||
});
|
||||
|
||||
const workflowsToSchedule: Workflow[] = [];
|
||||
|
||||
workflowsToSchedule.push(
|
||||
...workflows.filter((workflow) => workflow.trigger === WorkflowTriggerEvents.FORM_SUBMITTED_NO_EVENT)
|
||||
);
|
||||
|
||||
const promisesFormSubmittedNoEvent = workflowsToSchedule.map((workflow) => {
|
||||
const timeUnit: timeUnitLowerCase = (workflow.timeUnit?.toLowerCase() as timeUnitLowerCase) ?? "minute";
|
||||
|
||||
const scheduledAt = dayjs()
|
||||
.add(workflow.time ?? 15, timeUnit)
|
||||
.toDate();
|
||||
|
||||
return tasker.create(
|
||||
"triggerFormSubmittedNoEventWorkflow",
|
||||
{
|
||||
responseId,
|
||||
responses,
|
||||
smsReminderNumber,
|
||||
hideBranding,
|
||||
form: {
|
||||
id: form.id,
|
||||
userId: form.userId,
|
||||
teamId: form.teamId ?? undefined,
|
||||
user: {
|
||||
email: form.user.email,
|
||||
timeFormat: form.user.timeFormat,
|
||||
locale: form.user.locale ?? "en",
|
||||
},
|
||||
},
|
||||
workflow,
|
||||
submittedAt: new Date(),
|
||||
},
|
||||
{ scheduledAt }
|
||||
);
|
||||
});
|
||||
await Promise.all(promisesFormSubmittedNoEvent);
|
||||
}
|
||||
|
||||
static async scheduleWorkflowsForNewBooking({
|
||||
isNormalBookingOrFirstRecurringSlot,
|
||||
isConfirmedByDefault,
|
||||
isRescheduleEvent,
|
||||
workflows,
|
||||
...args
|
||||
}: ScheduleWorkflowRemindersArgs & {
|
||||
isConfirmedByDefault: boolean;
|
||||
isRescheduleEvent: boolean;
|
||||
isNormalBookingOrFirstRecurringSlot: boolean;
|
||||
}) {
|
||||
if (workflows.length <= 0) return;
|
||||
|
||||
const workflowsToTrigger: Workflow[] = [];
|
||||
|
||||
if (isRescheduleEvent) {
|
||||
workflowsToTrigger.push(
|
||||
...workflows.filter(
|
||||
(workflow) =>
|
||||
workflow.trigger === WorkflowTriggerEvents.RESCHEDULE_EVENT ||
|
||||
this._beforeAfterEventTriggers.includes(workflow.trigger)
|
||||
)
|
||||
);
|
||||
} else if (!isConfirmedByDefault) {
|
||||
workflowsToTrigger.push(
|
||||
...workflows.filter((workflow) => workflow.trigger === WorkflowTriggerEvents.BOOKING_REQUESTED)
|
||||
);
|
||||
} else if (isConfirmedByDefault) {
|
||||
workflowsToTrigger.push(
|
||||
...workflows.filter(
|
||||
(workflow) =>
|
||||
this._beforeAfterEventTriggers.includes(workflow.trigger) ||
|
||||
(isNormalBookingOrFirstRecurringSlot && workflow.trigger === WorkflowTriggerEvents.NEW_EVENT)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (workflowsToTrigger.length === 0) return;
|
||||
|
||||
await scheduleWorkflowReminders({
|
||||
...args,
|
||||
workflows: workflowsToTrigger,
|
||||
});
|
||||
}
|
||||
|
||||
static async scheduleWorkflowsFilteredByTriggerEvent({
|
||||
workflows,
|
||||
triggers,
|
||||
...args
|
||||
}: ScheduleWorkflowRemindersArgs & { triggers: WorkflowTriggerEvents[] }) {
|
||||
if (workflows.length <= 0) return;
|
||||
await scheduleWorkflowReminders({
|
||||
...args,
|
||||
workflows: workflows.filter((workflow) => triggers.includes(workflow.trigger)),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { z } from "zod";
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
|
||||
import { TeamEventTypeForm } from "@calcom/features/ee/teams/components/TeamEventTypeForm";
|
||||
import { useCreateEventType } from "@calcom/lib/hooks/useCreateEventType";
|
||||
import { useCreateEventType } from "@calcom/features/eventtypes/hooks/useCreateEventType";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useTypedQuery } from "@calcom/lib/hooks/useTypedQuery";
|
||||
import type { EventType } from "@calcom/prisma/client";
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { UseFormReturn } from "react-hook-form";
|
||||
|
||||
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
|
||||
import { MAX_EVENT_DURATION_MINUTES, MIN_EVENT_DURATION_MINUTES } from "@calcom/lib/constants";
|
||||
import type { CreateEventTypeFormValues } from "@calcom/lib/hooks/useCreateEventType";
|
||||
import type { CreateEventTypeFormValues } from "@calcom/features/eventtypes/hooks/useCreateEventType";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { md } from "@calcom/lib/markdownIt";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import type { z } from "zod";
|
||||
|
||||
import { createEventTypeInput } from "@calcom/features/eventtypes/lib/types";
|
||||
import { useDebounce } from "@calcom/lib/hooks/useDebounce";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import type { EventType } from "@calcom/prisma/client";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import { unlockedManagedEventTypeProps } from "@calcom/prisma/zod-utils";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
export type CreateEventTypeFormValues = z.infer<typeof createEventTypeInput>;
|
||||
|
||||
export const useCreateEventTypeForm = () => {
|
||||
const form = useForm<CreateEventTypeFormValues>({
|
||||
defaultValues: {
|
||||
length: 15,
|
||||
},
|
||||
resolver: zodResolver(createEventTypeInput),
|
||||
});
|
||||
|
||||
const schedulingTypeWatch = form.watch("schedulingType");
|
||||
const isManagedEventType = schedulingTypeWatch === SchedulingType.MANAGED;
|
||||
|
||||
useEffect(() => {
|
||||
if (isManagedEventType) {
|
||||
form.setValue("metadata.managedEventConfig.unlockedFields", unlockedManagedEventTypeProps);
|
||||
} else {
|
||||
form.setValue("metadata", null);
|
||||
}
|
||||
}, [schedulingTypeWatch]);
|
||||
|
||||
return { form, isManagedEventType };
|
||||
};
|
||||
|
||||
export const useCreateEventType = (
|
||||
onSuccessMutation: (eventType: EventType) => void,
|
||||
onErrorMutation: (message: string) => void
|
||||
) => {
|
||||
const utils = trpc.useUtils();
|
||||
const { t } = useLocale();
|
||||
const { form, isManagedEventType } = useCreateEventTypeForm();
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const debouncedSearchTerm = useDebounce(searchTerm, 500);
|
||||
|
||||
const createMutation = trpc.viewer.eventTypes.heavy.create.useMutation({
|
||||
onSuccess: async ({ eventType }) => {
|
||||
onSuccessMutation(eventType);
|
||||
|
||||
await utils.viewer.eventTypes.getEventTypesFromGroup.fetchInfinite({
|
||||
group: { teamId: eventType.teamId, parentId: eventType.parentId },
|
||||
searchQuery: debouncedSearchTerm,
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
form.reset();
|
||||
},
|
||||
onError: (err) => {
|
||||
let error = err.message;
|
||||
if (err instanceof HttpError) {
|
||||
error = `${err.statusCode}: ${err.message}`;
|
||||
}
|
||||
|
||||
if (err.data?.code === "BAD_REQUEST") {
|
||||
error = `${err.data.code}: ${t("error_event_type_url_duplicate")}`;
|
||||
}
|
||||
|
||||
if (err.data?.code === "UNAUTHORIZED") {
|
||||
error = `${err.data.code}: ${t("error_event_type_unauthorized_create")}`;
|
||||
}
|
||||
onErrorMutation(error);
|
||||
},
|
||||
});
|
||||
|
||||
return { form, createMutation, isManagedEventType };
|
||||
};
|
||||
@@ -257,20 +257,3 @@ export const fieldTypesSchemaMap: Partial<
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* DB Read schema has no field type based validation because user might change the type of a field from Type1 to Type2 after some data has been collected with Type1.
|
||||
* Parsing that type1 data with type2 schema will fail.
|
||||
* So, we just validate that the response conforms to one of the field types' schema.
|
||||
*/
|
||||
export const dbReadResponseSchema = z.union([
|
||||
z.string(),
|
||||
z.boolean(),
|
||||
z.string().array(),
|
||||
z.object({
|
||||
optionValue: z.string(),
|
||||
value: z.string(),
|
||||
}),
|
||||
// For variantsConfig case
|
||||
z.record(z.string()),
|
||||
]);
|
||||
@@ -9,7 +9,7 @@ import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { WorkflowService } from "@calcom/lib/server/service/workflows";
|
||||
import { WorkflowService } from "@calcom/features/ee/workflows/lib/service/WorkflowService";
|
||||
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { WebhookTriggerEvents, WorkflowTriggerEvents } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
|
||||
export type HashedLinkInputType = {
|
||||
link: string;
|
||||
expiresAt?: Date | null;
|
||||
maxUsageCount?: number | null;
|
||||
};
|
||||
|
||||
export const hashedLinkSelect = {
|
||||
id: true,
|
||||
link: true,
|
||||
eventTypeId: true,
|
||||
expiresAt: true,
|
||||
maxUsageCount: true,
|
||||
usageCount: true,
|
||||
eventType: {
|
||||
select: {
|
||||
userId: true,
|
||||
teamId: true,
|
||||
users: {
|
||||
select: {
|
||||
username: true,
|
||||
profiles: {
|
||||
select: {
|
||||
id: true,
|
||||
organizationId: true,
|
||||
username: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
hideBranding: true,
|
||||
parent: {
|
||||
select: {
|
||||
hideBranding: true,
|
||||
},
|
||||
},
|
||||
members: {
|
||||
select: {
|
||||
user: {
|
||||
select: {
|
||||
timeZone: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
take: 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
hosts: {
|
||||
select: {
|
||||
user: {
|
||||
select: {
|
||||
timeZone: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
profile: {
|
||||
select: {
|
||||
user: {
|
||||
select: {
|
||||
timeZone: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
owner: {
|
||||
select: {
|
||||
timeZone: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
} satisfies Prisma.HashedLinkSelect;
|
||||
|
||||
export class HashedLinkRepository {
|
||||
constructor(private readonly prismaClient: PrismaClient) {}
|
||||
|
||||
static create() {
|
||||
return new HashedLinkRepository(prisma);
|
||||
}
|
||||
|
||||
async deleteLinks(eventTypeId: number, linksToDelete: string[]) {
|
||||
if (linksToDelete.length === 0) return;
|
||||
|
||||
return await this.prismaClient.hashedLink.deleteMany({
|
||||
where: {
|
||||
eventTypeId,
|
||||
link: { in: linksToDelete },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async createLink(
|
||||
eventTypeId: number,
|
||||
linkData: { link: string; expiresAt: Date | null; maxUsageCount?: number | null }
|
||||
) {
|
||||
const data: Prisma.HashedLinkCreateManyInput = {
|
||||
eventTypeId,
|
||||
link: linkData.link,
|
||||
expiresAt: linkData.expiresAt,
|
||||
};
|
||||
|
||||
if (linkData.maxUsageCount && Number.isFinite(linkData.maxUsageCount)) {
|
||||
data.maxUsageCount = linkData.maxUsageCount;
|
||||
}
|
||||
|
||||
return await this.prismaClient.hashedLink.create({ data });
|
||||
}
|
||||
|
||||
async updateLink(
|
||||
eventTypeId: number,
|
||||
linkData: { link: string; expiresAt: Date | null; maxUsageCount?: number | null }
|
||||
) {
|
||||
const updateData: Prisma.HashedLinkUpdateManyMutationInput = {
|
||||
expiresAt: linkData.expiresAt,
|
||||
};
|
||||
|
||||
if (typeof linkData.maxUsageCount === "number" && linkData.maxUsageCount !== null) {
|
||||
updateData.maxUsageCount = linkData.maxUsageCount;
|
||||
}
|
||||
|
||||
return await this.prismaClient.hashedLink.updateMany({
|
||||
where: {
|
||||
eventTypeId,
|
||||
link: linkData.link,
|
||||
},
|
||||
data: updateData,
|
||||
});
|
||||
}
|
||||
|
||||
async findLinksByEventTypeId(eventTypeId: number) {
|
||||
return await this.prismaClient.hashedLink.findMany({
|
||||
where: {
|
||||
eventTypeId,
|
||||
},
|
||||
select: {
|
||||
link: true,
|
||||
expiresAt: true,
|
||||
maxUsageCount: true,
|
||||
usageCount: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findLinkWithEventTypeDetails(linkId: string) {
|
||||
return await this.prismaClient.hashedLink.findUnique({
|
||||
where: {
|
||||
link: linkId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
link: true,
|
||||
expiresAt: true,
|
||||
maxUsageCount: true,
|
||||
usageCount: true,
|
||||
eventTypeId: true,
|
||||
eventType: {
|
||||
select: {
|
||||
teamId: true,
|
||||
userId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findLinkWithDetails(linkId: string) {
|
||||
return await this.prismaClient.hashedLink.findUnique({
|
||||
where: {
|
||||
link: linkId,
|
||||
},
|
||||
select: hashedLinkSelect,
|
||||
});
|
||||
}
|
||||
|
||||
async findLinksWithEventTypeDetails(linkIds: string[]) {
|
||||
return await this.prismaClient.hashedLink.findMany({
|
||||
where: {
|
||||
link: {
|
||||
in: linkIds,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
link: true,
|
||||
expiresAt: true,
|
||||
maxUsageCount: true,
|
||||
usageCount: true,
|
||||
eventTypeId: true,
|
||||
eventType: {
|
||||
select: {
|
||||
teamId: true,
|
||||
userId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findLinkWithValidationData(linkId: string) {
|
||||
return await this.prismaClient.hashedLink.findUnique({
|
||||
where: {
|
||||
link: linkId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
expiresAt: true,
|
||||
maxUsageCount: true,
|
||||
usageCount: true,
|
||||
eventType: {
|
||||
select: {
|
||||
userId: true,
|
||||
teamId: true,
|
||||
hosts: {
|
||||
select: {
|
||||
user: {
|
||||
select: {
|
||||
timeZone: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
profile: {
|
||||
select: {
|
||||
user: {
|
||||
select: {
|
||||
timeZone: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
owner: {
|
||||
select: {
|
||||
timeZone: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async incrementUsage(linkId: number, maxUsageCount: number) {
|
||||
return await this.prismaClient.hashedLink.update({
|
||||
where: {
|
||||
id: linkId,
|
||||
usageCount: { lt: maxUsageCount },
|
||||
},
|
||||
data: {
|
||||
usageCount: { increment: 1 },
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import {
|
||||
HashedLinkRepository,
|
||||
type HashedLinkInputType,
|
||||
} from "@calcom/features/hashedLink/repositories/hashedLinkRepository";
|
||||
import { MembershipService } from "@calcom/features/membership/services/membershipService";
|
||||
import { ErrorCode } from "@calcom/lib/errorCodes";
|
||||
import { validateHashedLinkData } from "@calcom/lib/hashedLinksUtils";
|
||||
|
||||
type NormalizedLink = {
|
||||
link: string;
|
||||
expiresAt: Date | null;
|
||||
maxUsageCount?: number | null;
|
||||
};
|
||||
|
||||
export class HashedLinkService {
|
||||
constructor(
|
||||
private readonly hashedLinkRepository: HashedLinkRepository = HashedLinkRepository.create(),
|
||||
private readonly membershipService: MembershipService = new MembershipService()
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Normalizes link input to a consistent format
|
||||
* @param input - String link or object with link and options
|
||||
* @returns Normalized link object
|
||||
*/
|
||||
private normalizeLinkInput(input: string | HashedLinkInputType): NormalizedLink {
|
||||
return typeof input === "string"
|
||||
? { link: input, expiresAt: null }
|
||||
: {
|
||||
link: input.link,
|
||||
expiresAt: input.expiresAt ?? null,
|
||||
maxUsageCount: input.maxUsageCount,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles multiple private links operations - orchestrates create, update, and delete
|
||||
* @param eventTypeId - The ID of the event type
|
||||
* @param multiplePrivateLinks - Array of links to create/update (can be strings or objects with expiration)
|
||||
* @param connectedMultiplePrivateLinks - Array of existing link IDs for this event type
|
||||
*/
|
||||
async handleMultiplePrivateLinks({
|
||||
eventTypeId,
|
||||
multiplePrivateLinks,
|
||||
connectedMultiplePrivateLinks,
|
||||
}: {
|
||||
eventTypeId: number;
|
||||
multiplePrivateLinks?: (string | HashedLinkInputType)[];
|
||||
connectedMultiplePrivateLinks: string[];
|
||||
}) {
|
||||
if (!eventTypeId || eventTypeId <= 0) {
|
||||
throw new Error("Invalid event type ID");
|
||||
}
|
||||
|
||||
if (!multiplePrivateLinks || multiplePrivateLinks.length === 0) {
|
||||
await this.hashedLinkRepository.deleteLinks(eventTypeId, connectedMultiplePrivateLinks);
|
||||
return;
|
||||
}
|
||||
|
||||
const normalizedLinks = multiplePrivateLinks.map((input) => this.normalizeLinkInput(input));
|
||||
const currentLinks = normalizedLinks.map((l) => l.link);
|
||||
|
||||
const currentLinksSet = new Set(currentLinks);
|
||||
|
||||
const linksToDelete = connectedMultiplePrivateLinks.filter((link) => !currentLinksSet.has(link));
|
||||
await this.hashedLinkRepository.deleteLinks(eventTypeId, linksToDelete);
|
||||
|
||||
const existingLinksSet = new Set(connectedMultiplePrivateLinks);
|
||||
|
||||
for (const linkData of normalizedLinks) {
|
||||
const exists = existingLinksSet.has(linkData.link);
|
||||
if (!exists) {
|
||||
await this.hashedLinkRepository.createLink(eventTypeId, linkData);
|
||||
} else {
|
||||
await this.hashedLinkRepository.updateLink(eventTypeId, linkData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a link without incrementing usage count
|
||||
* Handles both time-based and usage-based expiration with timezone awareness
|
||||
* @param linkId - The hashed link ID to validate
|
||||
* @returns The validated link data
|
||||
* @throws Error with ErrorCode.PrivateLinkExpired if link is expired or invalid
|
||||
*/
|
||||
async validate(linkId: string) {
|
||||
if (!linkId || typeof linkId !== "string") {
|
||||
throw new Error("Invalid link ID");
|
||||
}
|
||||
|
||||
const hashedLink = await this.hashedLinkRepository.findLinkWithValidationData(linkId);
|
||||
|
||||
if (!hashedLink) {
|
||||
throw new Error(ErrorCode.PrivateLinkExpired);
|
||||
}
|
||||
|
||||
validateHashedLinkData(hashedLink);
|
||||
|
||||
return hashedLink;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a link and increments usage count if valid
|
||||
* Handles both time-based and usage-based expiration with timezone awareness
|
||||
* @param linkId - The hashed link ID to validate
|
||||
* @returns The validated link data
|
||||
* @throws Error with ErrorCode.PrivateLinkExpired if link is expired or invalid
|
||||
*/
|
||||
async validateAndIncrementUsage(linkId: string) {
|
||||
const hashedLink = await this.validate(linkId);
|
||||
if (hashedLink.expiresAt) return hashedLink; // Time-based links don't need usage count increment
|
||||
|
||||
if (hashedLink.maxUsageCount && hashedLink.maxUsageCount > 0) {
|
||||
try {
|
||||
await this.hashedLinkRepository.incrementUsage(hashedLink.id, hashedLink.maxUsageCount);
|
||||
} catch (updateError) {
|
||||
throw new Error(ErrorCode.PrivateLinkExpired);
|
||||
}
|
||||
}
|
||||
|
||||
return hashedLink;
|
||||
}
|
||||
|
||||
async findLinkWithDetails(linkId: string) {
|
||||
const hashedLink = await this.hashedLinkRepository.findLinkWithDetails(linkId);
|
||||
if (!hashedLink) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return hashedLink;
|
||||
}
|
||||
|
||||
async createLinkForEventType(eventTypeId: number, input: string | HashedLinkInputType) {
|
||||
const normalized = this.normalizeLinkInput(input);
|
||||
return this.hashedLinkRepository.createLink(eventTypeId, normalized);
|
||||
}
|
||||
|
||||
async updateLinkForEventType(eventTypeId: number, input: string | HashedLinkInputType) {
|
||||
const normalized = this.normalizeLinkInput(input);
|
||||
return this.hashedLinkRepository.updateLink(eventTypeId, normalized);
|
||||
}
|
||||
|
||||
async deleteLinkForEventType(eventTypeId: number, linkId: string) {
|
||||
return this.hashedLinkRepository.deleteLinks(eventTypeId, [linkId]);
|
||||
}
|
||||
|
||||
async listLinksByEventType(eventTypeId: number) {
|
||||
return this.hashedLinkRepository.findLinksByEventTypeId(eventTypeId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a user has permission to access a link
|
||||
* @param link - Link object with event type information
|
||||
* @param userId - The user ID to check permissions for
|
||||
* @returns true if user has permission, false otherwise
|
||||
*/
|
||||
async checkUserPermissionForLink(
|
||||
link: { eventType: { teamId?: number | null; userId?: number | null } },
|
||||
userId: number
|
||||
): Promise<boolean> {
|
||||
if (!link?.eventType || !userId || userId <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If it's a user event type, check if user owns it
|
||||
if (link.eventType.userId) {
|
||||
return link.eventType.userId === userId;
|
||||
}
|
||||
|
||||
//No user ownership and no team - deny access
|
||||
if (!link.eventType.teamId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const membership = await this.membershipService.checkMembership(link.eventType.teamId, userId);
|
||||
return membership.isMember;
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import { extractDateRangeFromColumnFilters } from "@calcom/features/insights/lib
|
||||
import type { DateRange } from "@calcom/features/insights/server/insightsDateUtils";
|
||||
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
|
||||
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { Prisma } from "@calcom/prisma/client";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
} from "@calcom/features/data-table/lib/utils";
|
||||
import type { DateRange } from "@calcom/features/insights/server/insightsDateUtils";
|
||||
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { Prisma } from "@calcom/prisma/client";
|
||||
import type { BookingStatus } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -373,35 +373,6 @@ export class MembershipRepository {
|
||||
return membershipsWithSelectedCalendars;
|
||||
}
|
||||
|
||||
static async findMembershipsForBothOrgAndTeam({ orgId, teamId }: { orgId: number; teamId: number }) {
|
||||
const memberships = await prisma.membership.findMany({
|
||||
where: {
|
||||
teamId: {
|
||||
in: [orgId, teamId],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
type Membership = (typeof memberships)[number];
|
||||
|
||||
const { teamMemberships, orgMemberships } = memberships.reduce(
|
||||
(acc, membership) => {
|
||||
if (membership.teamId === teamId) {
|
||||
acc.teamMemberships.push(membership);
|
||||
} else if (membership.teamId === orgId) {
|
||||
acc.orgMemberships.push(membership);
|
||||
}
|
||||
return acc;
|
||||
},
|
||||
{ teamMemberships: [] as Membership[], orgMemberships: [] as Membership[] }
|
||||
);
|
||||
|
||||
return {
|
||||
teamMemberships,
|
||||
orgMemberships,
|
||||
};
|
||||
}
|
||||
|
||||
static async getAdminOrOwnerMembership(userId: number, teamId: number) {
|
||||
return prisma.membership.findFirst({
|
||||
where: {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
export type MembershipCheckResult = {
|
||||
isMember: boolean;
|
||||
isAdmin: boolean;
|
||||
isOwner: boolean;
|
||||
role?: MembershipRole;
|
||||
};
|
||||
|
||||
export class MembershipService {
|
||||
constructor(private readonly membershipRepository: MembershipRepository = new MembershipRepository()) {}
|
||||
|
||||
/**
|
||||
* Checks the membership status of a user within a specific team.
|
||||
*/
|
||||
async checkMembership(teamId: number, userId: number): Promise<MembershipCheckResult> {
|
||||
const membership = await MembershipRepository.findUniqueByUserIdAndTeamId({ teamId, userId });
|
||||
|
||||
if (!membership || !membership.accepted) {
|
||||
return {
|
||||
isMember: false,
|
||||
isAdmin: false,
|
||||
isOwner: false,
|
||||
role: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const { role } = membership;
|
||||
const isOwner = role === MembershipRole.OWNER;
|
||||
const isAdmin = isOwner || role === MembershipRole.ADMIN;
|
||||
|
||||
return {
|
||||
isMember: true,
|
||||
isAdmin,
|
||||
isOwner,
|
||||
role,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
export type Entity = {
|
||||
userId: number | null;
|
||||
teamId: number | null;
|
||||
};
|
||||
|
||||
export async function canEditEntity(entity: Entity, userId: number) {
|
||||
if (entity.teamId) {
|
||||
const permissionService = new PermissionCheckService();
|
||||
const hasEditPermission = await permissionService.checkPermission({
|
||||
teamId: entity.teamId,
|
||||
userId,
|
||||
permission: "routingForm.update",
|
||||
fallbackRoles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
});
|
||||
|
||||
return hasEditPermission;
|
||||
} else if (entity.userId === userId) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function canAccessEntity(entity: Entity, userId: number) {
|
||||
if (entity.teamId) {
|
||||
const permissionService = new PermissionCheckService();
|
||||
const hasReadPermission = await permissionService.checkPermission({
|
||||
teamId: entity.teamId,
|
||||
userId,
|
||||
permission: "routingForm.read",
|
||||
fallbackRoles: [MembershipRole.ADMIN, MembershipRole.OWNER, MembershipRole.MEMBER],
|
||||
});
|
||||
|
||||
return hasReadPermission;
|
||||
} else if (entity.userId === userId) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function canCreateEntity({
|
||||
targetTeamId,
|
||||
userId,
|
||||
}: {
|
||||
targetTeamId: number | null | undefined;
|
||||
userId: number;
|
||||
}) {
|
||||
if (targetTeamId) {
|
||||
const permissionService = new PermissionCheckService();
|
||||
const hasEditPermission = await permissionService.checkPermission({
|
||||
teamId: targetTeamId,
|
||||
userId,
|
||||
permission: "routingForm.create",
|
||||
fallbackRoles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
});
|
||||
|
||||
return hasEditPermission;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whenever the entity is fetched this clause should be there to ensure that
|
||||
* 1. No item that doesn't belong to the user or the team is fetched
|
||||
* Having just a reusable where allows it to be used with different types of prisma queries.
|
||||
*/
|
||||
export const entityPrismaWhereClause = ({ userId }: { userId: number }) => ({
|
||||
OR: [
|
||||
{ userId: userId },
|
||||
{
|
||||
team: {
|
||||
members: {
|
||||
some: {
|
||||
userId: userId,
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { ProfileRepository } from "@calcom/features/profile/repositories/Profile
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { RedirectType } from "@calcom/prisma/enums";
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
|
||||
const log = logger.getSubLogger({ name: "hideBranding" });
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,467 @@
|
||||
import type { Dayjs } from "@calcom/dayjs";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import type { IOutOfOfficeData } from "@calcom/features/availability/lib/getUserAvailability";
|
||||
import type { Availability } from "@calcom/prisma/client";
|
||||
|
||||
export type DateRange = {
|
||||
start: Dayjs;
|
||||
end: Dayjs;
|
||||
};
|
||||
|
||||
export type DateOverride = Pick<Availability, "date" | "startTime" | "endTime">;
|
||||
export type WorkingHours = Pick<Availability, "days" | "startTime" | "endTime">;
|
||||
|
||||
type TravelSchedule = { startDate: Dayjs; endDate?: Dayjs; timeZone: string };
|
||||
|
||||
function getAdjustedTimezone(date: Dayjs, timeZone: string, travelSchedules: TravelSchedule[]) {
|
||||
let adjustedTimezone = timeZone;
|
||||
|
||||
for (const travelSchedule of travelSchedules) {
|
||||
if (
|
||||
!date.isBefore(travelSchedule.startDate) &&
|
||||
(!travelSchedule.endDate || !date.isAfter(travelSchedule.endDate))
|
||||
) {
|
||||
adjustedTimezone = travelSchedule.timeZone;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return adjustedTimezone;
|
||||
}
|
||||
|
||||
// reducer
|
||||
export function processWorkingHours(
|
||||
results: Record<number, DateRange>,
|
||||
{
|
||||
item,
|
||||
timeZone,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
travelSchedules,
|
||||
}: {
|
||||
item: WorkingHours;
|
||||
timeZone: string;
|
||||
dateFrom: Dayjs;
|
||||
dateTo: Dayjs;
|
||||
travelSchedules: TravelSchedule[];
|
||||
}
|
||||
) {
|
||||
const utcDateTo = dateTo.utc();
|
||||
let endTimeToKeyMap: Map<number, number[]> | undefined;
|
||||
|
||||
for (let date = dateFrom.startOf("day"); utcDateTo.isAfter(date); date = date.add(1, "day")) {
|
||||
const fromOffset = dateFrom.startOf("day").utcOffset();
|
||||
|
||||
const adjustedTimezone = getAdjustedTimezone(date, timeZone, travelSchedules);
|
||||
|
||||
const offset = date.tz(adjustedTimezone).utcOffset();
|
||||
|
||||
// it always has to be start of the day (midnight) even when DST changes
|
||||
const dateInTz = date.add(fromOffset - offset, "minutes").tz(adjustedTimezone);
|
||||
if (!item.days.includes(dateInTz.day())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let start = dateInTz
|
||||
.add(item.startTime.getUTCHours(), "hours")
|
||||
.add(item.startTime.getUTCMinutes(), "minutes");
|
||||
|
||||
let end = dateInTz.add(item.endTime.getUTCHours(), "hours").add(item.endTime.getUTCMinutes(), "minutes");
|
||||
|
||||
const offsetBeginningOfDay = dayjs(start.format("YYYY-MM-DD hh:mm")).tz(adjustedTimezone).utcOffset();
|
||||
const offsetDiff = start.utcOffset() - offsetBeginningOfDay; // there will be 60 min offset on the day day of DST change
|
||||
|
||||
start = start.add(offsetDiff, "minute");
|
||||
end = end.add(offsetDiff, "minute");
|
||||
|
||||
const startResult = dayjs.max(start, dateFrom);
|
||||
let endResult = dayjs.min(end, dateTo.tz(adjustedTimezone));
|
||||
|
||||
// INFO: We only allow users to set availability up to 11:59PM which ends up not making them available
|
||||
// up to midnight.
|
||||
if (endResult.hour() === 23 && endResult.minute() === 59) {
|
||||
endResult = endResult.add(1, "minute");
|
||||
}
|
||||
|
||||
if (endResult.isBefore(startResult)) {
|
||||
// if an event ends before start, it's not a result.
|
||||
continue;
|
||||
}
|
||||
|
||||
const endTimeKey = endResult.valueOf();
|
||||
|
||||
// Create a map of end times to range keys for O(1) lookup
|
||||
if (!endTimeToKeyMap) {
|
||||
endTimeToKeyMap = new Map<number, number[]>();
|
||||
for (const [key, range] of Object.entries(results)) {
|
||||
const endTime = range.end.valueOf();
|
||||
if (!endTimeToKeyMap.has(endTime)) {
|
||||
endTimeToKeyMap.set(endTime, []);
|
||||
}
|
||||
endTimeToKeyMap.get(endTime)!.push(Number(key));
|
||||
}
|
||||
}
|
||||
|
||||
// Check for overlapping ranges with the same end time using O(1) lookup
|
||||
const keysWithSameEndTime = endTimeToKeyMap.get(endTimeKey) || [];
|
||||
let foundOverlapping = false;
|
||||
|
||||
for (const key of keysWithSameEndTime) {
|
||||
const existingRange = results[key];
|
||||
if (
|
||||
startResult.valueOf() <= existingRange.end.valueOf() &&
|
||||
endResult.valueOf() >= existingRange.start.valueOf()
|
||||
) {
|
||||
// Merge by taking the earliest start time and keeping the same end time
|
||||
results[key] = {
|
||||
start: dayjs.min(existingRange.start, startResult),
|
||||
end: endResult,
|
||||
};
|
||||
foundOverlapping = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (foundOverlapping) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (results[startResult.valueOf()]) {
|
||||
// if a result already exists, we merge the end time
|
||||
const oldKey = startResult.valueOf();
|
||||
const newKey = endResult.valueOf();
|
||||
|
||||
results[newKey] = {
|
||||
start: results[oldKey].start,
|
||||
end: dayjs.max(results[oldKey].end, endResult),
|
||||
};
|
||||
|
||||
if (endTimeToKeyMap) {
|
||||
const oldEndTime = results[oldKey].end.valueOf();
|
||||
const oldKeys = endTimeToKeyMap.get(oldEndTime) || [];
|
||||
const filteredKeys = oldKeys.filter((k) => k !== oldKey);
|
||||
if (filteredKeys.length === 0) {
|
||||
endTimeToKeyMap.delete(oldEndTime);
|
||||
} else {
|
||||
endTimeToKeyMap.set(oldEndTime, filteredKeys);
|
||||
}
|
||||
|
||||
if (!endTimeToKeyMap.has(endTimeKey)) {
|
||||
endTimeToKeyMap.set(endTimeKey, []);
|
||||
}
|
||||
endTimeToKeyMap.get(endTimeKey)!.push(newKey);
|
||||
}
|
||||
|
||||
delete results[oldKey]; // delete the previous end time
|
||||
continue;
|
||||
}
|
||||
// otherwise we create a new result
|
||||
const newKey = endResult.valueOf();
|
||||
results[newKey] = {
|
||||
start: startResult,
|
||||
end: endResult,
|
||||
};
|
||||
|
||||
if (endTimeToKeyMap) {
|
||||
if (!endTimeToKeyMap.has(endTimeKey)) {
|
||||
endTimeToKeyMap.set(endTimeKey, []);
|
||||
}
|
||||
endTimeToKeyMap.get(endTimeKey)!.push(newKey);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
export function processDateOverride({
|
||||
item,
|
||||
itemDateAsUtc,
|
||||
timeZone,
|
||||
travelSchedules,
|
||||
}: {
|
||||
item: DateOverride;
|
||||
itemDateAsUtc: Dayjs;
|
||||
timeZone: string;
|
||||
travelSchedules: TravelSchedule[];
|
||||
}) {
|
||||
const overrideDate = dayjs(item.date);
|
||||
|
||||
const adjustedTimezone = getAdjustedTimezone(overrideDate, timeZone, travelSchedules);
|
||||
|
||||
const itemDateStartOfDay = itemDateAsUtc.startOf("day");
|
||||
const startDate = itemDateStartOfDay
|
||||
.add(item.startTime.getUTCHours(), "hours")
|
||||
.add(item.startTime.getUTCMinutes(), "minutes")
|
||||
.second(0)
|
||||
.tz(adjustedTimezone, true);
|
||||
|
||||
let endDate = itemDateStartOfDay;
|
||||
const endTimeHours = item.endTime.getUTCHours();
|
||||
const endTimeMinutes = item.endTime.getUTCMinutes();
|
||||
|
||||
if (endTimeHours === 23 && endTimeMinutes === 59) {
|
||||
endDate = endDate.add(1, "day").tz(timeZone, true);
|
||||
} else {
|
||||
endDate = itemDateStartOfDay
|
||||
.add(endTimeHours, "hours")
|
||||
.add(endTimeMinutes, "minutes")
|
||||
.second(0)
|
||||
.tz(adjustedTimezone, true);
|
||||
}
|
||||
|
||||
return {
|
||||
start: startDate,
|
||||
end: endDate,
|
||||
};
|
||||
}
|
||||
|
||||
// This function processes out-of-office dates and returns a date range for each OOO date.
|
||||
function processOOO(outOfOffice: Dayjs, timeZone: string) {
|
||||
const OOOdate = outOfOffice.tz(timeZone, true);
|
||||
return {
|
||||
start: OOOdate,
|
||||
end: OOOdate,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildDateRanges({
|
||||
availability,
|
||||
timeZone /* Organizer timeZone */,
|
||||
dateFrom /* Attendee dateFrom */,
|
||||
dateTo /* `` dateTo */,
|
||||
travelSchedules,
|
||||
outOfOffice,
|
||||
}: {
|
||||
timeZone: string;
|
||||
availability: (DateOverride | WorkingHours)[];
|
||||
dateFrom: Dayjs;
|
||||
dateTo: Dayjs;
|
||||
travelSchedules: TravelSchedule[];
|
||||
outOfOffice?: IOutOfOfficeData;
|
||||
}): { dateRanges: DateRange[]; oooExcludedDateRanges: DateRange[] } {
|
||||
const dateFromOrganizerTZ = dateFrom.tz(timeZone);
|
||||
|
||||
const groupedWorkingHours = groupByDate(
|
||||
Object.values(
|
||||
availability.reduce((processed: Record<number, DateRange>, item) => {
|
||||
if (!("days" in item)) {
|
||||
return processed;
|
||||
}
|
||||
|
||||
processed = processWorkingHours(processed, {
|
||||
item,
|
||||
timeZone,
|
||||
dateFrom: dateFromOrganizerTZ,
|
||||
dateTo,
|
||||
travelSchedules,
|
||||
});
|
||||
|
||||
return processed;
|
||||
}, {})
|
||||
)
|
||||
);
|
||||
|
||||
const groupedOOO = groupByDate(
|
||||
outOfOffice
|
||||
? Object.keys(outOfOffice).map((outOfOffice) => processOOO(dayjs.utc(outOfOffice), timeZone))
|
||||
: []
|
||||
);
|
||||
|
||||
const groupedDateOverrides = groupByDate(
|
||||
Object.values(
|
||||
availability.reduce((processed: Record<number, DateRange>, item) => {
|
||||
// early return if item is not a date override
|
||||
if (!("date" in item && !!item.date)) {
|
||||
return processed;
|
||||
}
|
||||
const itemDateAsUtc = dayjs.utc(item.date);
|
||||
// TODO: Remove the .subtract(1, "day") and .add(1, "day") part and
|
||||
// refactor this to actually work with correct dates.
|
||||
// As of 2024-02-20, there are mismatches between local and UTC dates for overrides
|
||||
// and the dateFrom and dateTo fields, resulting in this if not returning true, which
|
||||
// results in "no available users found" errors.
|
||||
if (
|
||||
itemDateAsUtc.isBetween(
|
||||
dateFrom.subtract(1, "day").startOf("day"),
|
||||
dateTo.add(1, "day").endOf("day"),
|
||||
null,
|
||||
"[]"
|
||||
)
|
||||
) {
|
||||
// unlike working hours, date overrides are always one. No loop per day.
|
||||
const newProcessedDateOverride = processDateOverride({
|
||||
item,
|
||||
itemDateAsUtc,
|
||||
timeZone,
|
||||
travelSchedules,
|
||||
});
|
||||
if (processed[newProcessedDateOverride.start.valueOf()]) {
|
||||
// if a result already exists, we merge the end time
|
||||
processed[newProcessedDateOverride.start.valueOf()].end = dayjs.max(
|
||||
processed[newProcessedDateOverride.start.valueOf()].end,
|
||||
newProcessedDateOverride.end
|
||||
);
|
||||
return processed;
|
||||
}
|
||||
processed[newProcessedDateOverride.end.valueOf()] = newProcessedDateOverride;
|
||||
}
|
||||
return processed;
|
||||
}, {})
|
||||
)
|
||||
);
|
||||
|
||||
const dateRanges = Object.values({
|
||||
...groupedWorkingHours,
|
||||
...groupedDateOverrides,
|
||||
}).map(
|
||||
// remove 0-length overrides that were kept to cancel out working dates until now.
|
||||
(ranges) => ranges.filter((range) => range.start.valueOf() !== range.end.valueOf())
|
||||
);
|
||||
|
||||
const oooExcludedDateRanges = Object.values({
|
||||
...groupedWorkingHours,
|
||||
...groupedDateOverrides,
|
||||
...groupedOOO,
|
||||
}).map(
|
||||
// remove 0-length overrides && OOO dates that were kept to cancel out working dates until now.
|
||||
(ranges) => ranges.filter((range) => range.start.valueOf() !== range.end.valueOf())
|
||||
);
|
||||
|
||||
return { dateRanges: dateRanges.flat(), oooExcludedDateRanges: oooExcludedDateRanges.flat() };
|
||||
}
|
||||
|
||||
export function groupByDate(ranges: DateRange[]): { [x: string]: DateRange[] } {
|
||||
const results = ranges.reduce(
|
||||
(
|
||||
previousValue: {
|
||||
[date: string]: DateRange[];
|
||||
},
|
||||
currentValue
|
||||
) => {
|
||||
const dateString = dayjs(currentValue.start).format("YYYY-MM-DD");
|
||||
|
||||
previousValue[dateString] =
|
||||
typeof previousValue[dateString] === "undefined"
|
||||
? [currentValue]
|
||||
: [...previousValue[dateString], currentValue];
|
||||
return previousValue;
|
||||
},
|
||||
{}
|
||||
);
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
export function intersect(ranges: DateRange[][]): DateRange[] {
|
||||
if (!ranges.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
type ProcessedDateRange = DateRange & { startValue: number; endValue: number };
|
||||
|
||||
// Pre-sort all user ranges and cache timestamp values.
|
||||
const sortedRanges: ProcessedDateRange[][] = ranges.map((userRanges) =>
|
||||
userRanges
|
||||
.map((r) => ({
|
||||
...r,
|
||||
startValue: r.start.valueOf(),
|
||||
endValue: r.end.valueOf(),
|
||||
}))
|
||||
.sort((a, b) => a.startValue - b.startValue)
|
||||
);
|
||||
|
||||
let commonAvailability: ProcessedDateRange[] = sortedRanges[0];
|
||||
|
||||
for (let i = 1; i < sortedRanges.length; i++) {
|
||||
// Early exit if no common availability is left.
|
||||
if (commonAvailability.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const userRanges = sortedRanges[i];
|
||||
const intersectedRanges: ProcessedDateRange[] = [];
|
||||
|
||||
let commonIndex = 0;
|
||||
let userIndex = 0;
|
||||
|
||||
while (commonIndex < commonAvailability.length && userIndex < userRanges.length) {
|
||||
const commonRange = commonAvailability[commonIndex];
|
||||
const userRange = userRanges[userIndex];
|
||||
|
||||
const intersectStartValue = Math.max(commonRange.startValue, userRange.startValue);
|
||||
const intersectEndValue = Math.min(commonRange.endValue, userRange.endValue);
|
||||
|
||||
if (intersectStartValue < intersectEndValue) {
|
||||
const intersectStart =
|
||||
commonRange.startValue > userRange.startValue ? commonRange.start : userRange.start;
|
||||
const intersectEnd = commonRange.endValue < userRange.endValue ? commonRange.end : userRange.end;
|
||||
intersectedRanges.push({
|
||||
start: intersectStart,
|
||||
end: intersectEnd,
|
||||
startValue: intersectStartValue,
|
||||
endValue: intersectEndValue,
|
||||
});
|
||||
}
|
||||
|
||||
if (commonRange.endValue <= userRange.endValue) {
|
||||
commonIndex++;
|
||||
} else {
|
||||
userIndex++;
|
||||
}
|
||||
}
|
||||
commonAvailability = intersectedRanges;
|
||||
}
|
||||
|
||||
// Strip the cached values before returning to match the expected DateRange[] type.
|
||||
return commonAvailability.map(({ start, end }) => ({ start, end }));
|
||||
}
|
||||
|
||||
export function subtract(
|
||||
sourceRanges: (DateRange & { [x: string]: unknown })[],
|
||||
excludedRanges: DateRange[]
|
||||
) {
|
||||
const result = [];
|
||||
const sortedExcludedRanges = [...excludedRanges].sort((a, b) => a.start.valueOf() - b.start.valueOf());
|
||||
|
||||
for (const { start: sourceStart, end: sourceEnd, ...passThrough } of sourceRanges) {
|
||||
let currentStart = sourceStart;
|
||||
|
||||
for (const excludedRange of sortedExcludedRanges) {
|
||||
if (excludedRange.start.valueOf() >= sourceEnd.valueOf()) break;
|
||||
if (excludedRange.end.valueOf() <= currentStart.valueOf()) continue;
|
||||
|
||||
if (excludedRange.start.valueOf() > currentStart.valueOf()) {
|
||||
result.push({ start: currentStart, end: excludedRange.start, ...passThrough });
|
||||
}
|
||||
|
||||
if (excludedRange.end.valueOf() > currentStart.valueOf()) {
|
||||
currentStart = excludedRange.end;
|
||||
}
|
||||
}
|
||||
|
||||
if (sourceEnd.valueOf() > currentStart.valueOf()) {
|
||||
result.push({ start: currentStart, end: sourceEnd, ...passThrough });
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function mergeOverlappingRanges(ranges: { start: Date; end: Date }[]): { start: Date; end: Date }[] {
|
||||
if (ranges.length === 0) return [];
|
||||
|
||||
const sortedRanges = ranges.sort((a, b) => a.start.valueOf() - b.start.valueOf());
|
||||
|
||||
const mergedRanges: { start: Date; end: Date }[] = [sortedRanges[0]];
|
||||
|
||||
for (let i = 1; i < sortedRanges.length; i++) {
|
||||
const lastMergedRange = mergedRanges[mergedRanges.length - 1];
|
||||
const currentRange = sortedRanges[i];
|
||||
|
||||
if (currentRange.start.getTime() <= lastMergedRange.end.getTime()) {
|
||||
lastMergedRange.end = new Date(Math.max(lastMergedRange.end.getTime(), currentRange.end.getTime()));
|
||||
} else {
|
||||
mergedRanges.push(currentRange);
|
||||
}
|
||||
}
|
||||
return mergedRanges;
|
||||
}
|
||||
@@ -0,0 +1,843 @@
|
||||
import { describe, expect, it, beforeAll, vi } from "vitest";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import type { DateRange } from "@calcom/features/schedules/lib/date-ranges";
|
||||
|
||||
import getSlots from "./slots";
|
||||
|
||||
let dateRangesNextDay: DateRange[];
|
||||
|
||||
let dateRangesMockDay: DateRange[];
|
||||
|
||||
beforeAll(() => {
|
||||
vi.setSystemTime(dayjs.utc("2021-06-20T11:59:59Z").toDate());
|
||||
|
||||
dateRangesMockDay = [{ start: dayjs.utc().startOf("day"), end: dayjs.utc().endOf("day") }];
|
||||
|
||||
dateRangesNextDay = [
|
||||
{
|
||||
start: dayjs.utc().add(1, "day").startOf("day"),
|
||||
end: dayjs.utc().add(1, "day").endOf("day"),
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
describe("Tests the slot logic", () => {
|
||||
it("can fit 24 hourly slots for an empty day", async () => {
|
||||
expect(
|
||||
getSlots({
|
||||
inviteeDate: dayjs.utc().add(1, "day"),
|
||||
frequency: 60,
|
||||
minimumBookingNotice: 0,
|
||||
eventLength: 60,
|
||||
dateRanges: dateRangesNextDay,
|
||||
})
|
||||
).toHaveLength(24);
|
||||
});
|
||||
|
||||
it("can fit 24 hourly slots for an empty day with interval != eventLength", async () => {
|
||||
expect(
|
||||
getSlots({
|
||||
inviteeDate: dayjs.utc().add(1, "day"),
|
||||
frequency: 60,
|
||||
minimumBookingNotice: 0,
|
||||
eventLength: 30,
|
||||
dateRanges: dateRangesNextDay,
|
||||
})
|
||||
).toHaveLength(24);
|
||||
});
|
||||
|
||||
it("only shows future booking slots on the same day", async () => {
|
||||
// The mock date is 1s to midday, so 12 slots should be open given 0 booking notice.
|
||||
|
||||
expect(
|
||||
getSlots({
|
||||
inviteeDate: dayjs.utc(),
|
||||
frequency: 60,
|
||||
minimumBookingNotice: 0,
|
||||
dateRanges: dateRangesMockDay,
|
||||
eventLength: 60,
|
||||
offsetStart: 0,
|
||||
})
|
||||
).toHaveLength(12);
|
||||
});
|
||||
|
||||
it("adds minimum booking notice correctly", async () => {
|
||||
// 24h in a day.
|
||||
expect(
|
||||
getSlots({
|
||||
inviteeDate: dayjs.utc().add(1, "day").startOf("day"),
|
||||
frequency: 60,
|
||||
minimumBookingNotice: 1500,
|
||||
dateRanges: dateRangesNextDay,
|
||||
eventLength: 60,
|
||||
offsetStart: 0,
|
||||
})
|
||||
).toHaveLength(11);
|
||||
});
|
||||
|
||||
it("shows correct time slots for 20 minutes long events with working hours that do not end at a full hour ", async () => {
|
||||
// 72 20-minutes events in a 24h day
|
||||
const result = getSlots({
|
||||
inviteeDate: dayjs().add(1, "day"),
|
||||
frequency: 20,
|
||||
minimumBookingNotice: 0,
|
||||
dateRanges: dateRangesNextDay,
|
||||
eventLength: 20,
|
||||
offsetStart: 0,
|
||||
});
|
||||
expect(result).toHaveLength(72);
|
||||
});
|
||||
|
||||
it("can create multiple time slot groups when multiple date ranges are given", async () => {
|
||||
const nextDay = dayjs.utc().add(1, "day").startOf("day");
|
||||
const dateRanges = [
|
||||
// 11:00-11:20,11:20-11:40,11:40-12:00
|
||||
{
|
||||
start: nextDay.hour(11),
|
||||
end: nextDay.hour(12),
|
||||
},
|
||||
// 14:00-14:20,14:20-14:40,14:40-15:00
|
||||
{
|
||||
start: nextDay.hour(14),
|
||||
end: nextDay.hour(15),
|
||||
},
|
||||
];
|
||||
const result = getSlots({
|
||||
inviteeDate: nextDay,
|
||||
frequency: 20,
|
||||
minimumBookingNotice: 0,
|
||||
dateRanges: dateRanges,
|
||||
eventLength: 20,
|
||||
offsetStart: 0,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(6);
|
||||
});
|
||||
|
||||
it("can merge multiple time slot groups when multiple date ranges are given that overlap", async () => {
|
||||
const nextDay = dayjs.utc().add(1, "day").startOf("day");
|
||||
const dateRanges = [
|
||||
// 11:00-11:20,11:20-11:40,11:40-12:00
|
||||
{
|
||||
start: nextDay.hour(11),
|
||||
end: nextDay.hour(12),
|
||||
},
|
||||
// 12:00-12:20,12:20-12:40
|
||||
{
|
||||
start: nextDay.hour(11).minute(20),
|
||||
end: nextDay.hour(12).minute(40),
|
||||
},
|
||||
];
|
||||
const result = getSlots({
|
||||
inviteeDate: nextDay,
|
||||
frequency: 20,
|
||||
minimumBookingNotice: 0,
|
||||
dateRanges: dateRanges,
|
||||
eventLength: 20,
|
||||
offsetStart: 0,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(5);
|
||||
});
|
||||
|
||||
// for now, stay consistent with current behaviour and enable the slot 11:00, 11:45
|
||||
// however, optimal slot allocation is 11:15-12:00,12:00-12:45 (as both hosts can be routed to at this time)
|
||||
it("finds correct slots when two unequal date ranges are given", async () => {
|
||||
const nextDay = dayjs.utc().add(1, "day").startOf("day");
|
||||
const dateRanges = [
|
||||
// 11:00-13:00
|
||||
{
|
||||
start: nextDay.hour(11),
|
||||
end: nextDay.hour(13),
|
||||
},
|
||||
// 11:15-13:00
|
||||
{
|
||||
start: nextDay.hour(11).minute(15),
|
||||
end: nextDay.hour(13),
|
||||
},
|
||||
];
|
||||
const result = getSlots({
|
||||
inviteeDate: nextDay,
|
||||
frequency: 45,
|
||||
minimumBookingNotice: 0,
|
||||
dateRanges: dateRanges,
|
||||
eventLength: 45,
|
||||
offsetStart: 0,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
});
|
||||
it("finds correct slots when two unequal date ranges are given (inverse)", async () => {
|
||||
const nextDay = dayjs.utc().add(1, "day").startOf("day");
|
||||
|
||||
const dateRangesInverseOrder = [
|
||||
// 11:15-13:00
|
||||
{
|
||||
start: nextDay.hour(11).minute(15),
|
||||
end: nextDay.hour(13),
|
||||
},
|
||||
// 11:00-13:00
|
||||
{
|
||||
start: nextDay.hour(11),
|
||||
end: nextDay.hour(13),
|
||||
},
|
||||
];
|
||||
|
||||
const resultInverseOrder = getSlots({
|
||||
inviteeDate: nextDay,
|
||||
frequency: 45,
|
||||
minimumBookingNotice: 0,
|
||||
dateRanges: dateRangesInverseOrder,
|
||||
eventLength: 45,
|
||||
offsetStart: 0,
|
||||
});
|
||||
|
||||
expect(resultInverseOrder).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("finds correct slots over the span of multiple days", async () => {
|
||||
const inviteeDate = dayjs.utc().add(1, "day").startOf("day");
|
||||
|
||||
const dateRanges = [
|
||||
// 11:30-14:00
|
||||
{
|
||||
start: inviteeDate.hour(11).minute(30),
|
||||
end: inviteeDate.hour(14),
|
||||
},
|
||||
// 9:15-13:00
|
||||
{
|
||||
start: inviteeDate.hour(9).minute(15),
|
||||
end: inviteeDate.hour(11),
|
||||
},
|
||||
// 11:30-14:00
|
||||
{
|
||||
start: inviteeDate.add(1, "day").hour(11).minute(30),
|
||||
end: inviteeDate.add(1, "day").hour(14),
|
||||
},
|
||||
// 11:15-13:00
|
||||
{
|
||||
start: inviteeDate.add(1, "day").hour(9).minute(15),
|
||||
end: inviteeDate.add(1, "day").hour(11),
|
||||
},
|
||||
];
|
||||
|
||||
// each day availability should go 10:00, 12:00, 13:00
|
||||
|
||||
const result = getSlots({
|
||||
// right now from the perspective of invitee local time.
|
||||
inviteeDate,
|
||||
frequency: 60,
|
||||
minimumBookingNotice: 0,
|
||||
dateRanges: dateRanges,
|
||||
eventLength: 60,
|
||||
offsetStart: 0,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(6);
|
||||
});
|
||||
|
||||
it("shows correct time slots for 20 minutes long events with working hours that do not end at a full hour", async () => {
|
||||
const result = getSlots({
|
||||
inviteeDate: dayjs().add(1, "day"),
|
||||
frequency: 20,
|
||||
minimumBookingNotice: 0,
|
||||
dateRanges: [{ start: dayjs("2021-06-21T00:00:00.000Z"), end: dayjs("2021-06-21T23:45:00.000Z") }],
|
||||
eventLength: 20,
|
||||
offsetStart: 0,
|
||||
});
|
||||
|
||||
// 71 20-minutes events in a 24h - 15m day
|
||||
expect(result).toHaveLength(71);
|
||||
});
|
||||
|
||||
it("tests the final slot of the day is included", async () => {
|
||||
const slots = getSlots({
|
||||
inviteeDate: dayjs.tz("2023-07-13T00:00:00.000", "Europe/Brussels"),
|
||||
eventLength: 15,
|
||||
offsetStart: 0,
|
||||
dateRanges: [
|
||||
{ start: dayjs("2023-07-13T07:00:00.000Z"), end: dayjs("2023-07-13T15:00:00.000Z") },
|
||||
{ start: dayjs("2023-07-13T18:30:00.000Z"), end: dayjs("2023-07-13T20:59:59.000Z") },
|
||||
],
|
||||
minimumBookingNotice: 120,
|
||||
frequency: 15,
|
||||
}).reverse();
|
||||
|
||||
expect(slots[0].time.format()).toBe("2023-07-13T22:45:00+02:00");
|
||||
});
|
||||
|
||||
it("tests slots for half hour timezones", async () => {
|
||||
const slots = getSlots({
|
||||
inviteeDate: dayjs.tz("2023-07-13T00:00:00.000", "Asia/Kolkata"),
|
||||
frequency: 60,
|
||||
minimumBookingNotice: 0,
|
||||
eventLength: 60,
|
||||
dateRanges: [
|
||||
{
|
||||
start: dayjs.tz("2023-07-13T07:30:00.000", "Asia/Kolkata"),
|
||||
end: dayjs.tz("2023-07-13T09:30:00.000", "Asia/Kolkata"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(slots).toHaveLength(1);
|
||||
expect(slots[0].time.format()).toBe("2023-07-13T08:00:00+05:30");
|
||||
});
|
||||
|
||||
it("tests slots for 5 minute events", async () => {
|
||||
const slots = getSlots({
|
||||
inviteeDate: dayjs.tz("2023-07-13T00:00:00.000+05:30", "Europe/London"),
|
||||
frequency: 5,
|
||||
minimumBookingNotice: 0,
|
||||
eventLength: 5,
|
||||
dateRanges: [
|
||||
// fits 1 slot
|
||||
{
|
||||
start: dayjs.tz("2023-07-13T07:00:00.000", "Europe/London"),
|
||||
end: dayjs.tz("2023-07-13T07:05:00.000", "Europe/London"),
|
||||
},
|
||||
// fits 4 slots
|
||||
{
|
||||
start: dayjs.tz("2023-07-13T07:10:00.000", "Europe/London"),
|
||||
end: dayjs.tz("2023-07-13T07:30:00.000", "Europe/London"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(slots).toHaveLength(5);
|
||||
});
|
||||
|
||||
it("tests slots for events with an event length that is not divisible by 5", async () => {
|
||||
const slots = getSlots({
|
||||
inviteeDate: dayjs.utc().startOf("day"),
|
||||
frequency: 8,
|
||||
minimumBookingNotice: 0,
|
||||
eventLength: 8,
|
||||
dateRanges: [
|
||||
{
|
||||
start: dayjs.utc("2023-07-13T07:22:00.000"),
|
||||
end: dayjs.utc("2023-07-13T08:00:00.000"),
|
||||
},
|
||||
],
|
||||
});
|
||||
/*
|
||||
* 2023-07-13T07:22:00.000Z
|
||||
* 2023-07-13T07:30:00.000Z
|
||||
* 2023-07-13T07:38:00.000Z
|
||||
* 2023-07-13T07:46:00.000Z
|
||||
*/
|
||||
expect(slots).toHaveLength(4);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Tests the slot logic with custom env variable", () => {
|
||||
beforeAll(() => {
|
||||
vi.stubEnv("NEXT_PUBLIC_AVAILABILITY_SCHEDULE_INTERVAL", "10");
|
||||
});
|
||||
|
||||
it("test using a 10 minute interval", async () => {
|
||||
expect(Number(process.env.NEXT_PUBLIC_AVAILABILITY_SCHEDULE_INTERVAL)).toBe(10);
|
||||
expect(
|
||||
getSlots({
|
||||
inviteeDate: dayjs.utc().add(1, "day"),
|
||||
frequency: 10,
|
||||
minimumBookingNotice: 0,
|
||||
eventLength: 10,
|
||||
offsetStart: 0,
|
||||
dateRanges: [{ start: dayjs("2023-07-13T00:10:00.000Z"), end: dayjs("2023-07-13T02:00:00.000Z") }],
|
||||
})
|
||||
).toHaveLength(11);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Tests the slots function performance", () => {
|
||||
it("handles hundreds of date ranges efficiently", async () => {
|
||||
const startTime = process.hrtime();
|
||||
|
||||
const startDay = dayjs.utc().add(1, "day").startOf("day");
|
||||
const dateRanges: DateRange[] = [];
|
||||
|
||||
for (let day = 0; day < 7; day++) {
|
||||
const currentDay = startDay.add(day, "day");
|
||||
|
||||
for (let hour = 0; hour < 24; hour++) {
|
||||
for (let minute = 0; minute < 60; minute += 5) {
|
||||
if (dateRanges.length >= 2000) break;
|
||||
|
||||
dateRanges.push({
|
||||
start: currentDay.hour(hour).minute(minute),
|
||||
end: currentDay
|
||||
.hour(hour)
|
||||
.minute(minute + 4)
|
||||
.second(59),
|
||||
});
|
||||
}
|
||||
if (dateRanges.length >= 2000) break;
|
||||
}
|
||||
if (dateRanges.length >= 2000) break;
|
||||
}
|
||||
|
||||
const result = getSlots({
|
||||
inviteeDate: startDay,
|
||||
frequency: 5,
|
||||
minimumBookingNotice: 0,
|
||||
dateRanges: dateRanges,
|
||||
eventLength: 5,
|
||||
offsetStart: 0,
|
||||
});
|
||||
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
|
||||
const endTime = process.hrtime(startTime);
|
||||
const executionTimeInMs = endTime[0] * 1000 + endTime[1] / 1000000;
|
||||
|
||||
expect(executionTimeInMs).toBeLessThan(3000); // less than 3 seconds for 2000 date ranges
|
||||
|
||||
console.log(
|
||||
`Performance test completed in ${executionTimeInMs}ms with ${result.length} slots generated from ${dateRanges.length} date ranges`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Tests the date-range slot logic with showOptimizedSlots", () => {
|
||||
it("should respect start of the hour for 60minutes slots for availabilities like 09:30-17:00, when showOptimizedSlots set to true", async () => {
|
||||
const slots = getSlots({
|
||||
showOptimizedSlots: true,
|
||||
inviteeDate: dayjs.tz("2024-09-12T00:00:00.000-07:00", "America/Los_Angeles"),
|
||||
eventLength: 60,
|
||||
offsetStart: 0,
|
||||
// equivalent dateRanges in UTC-7
|
||||
// start:09:30, end:17:00
|
||||
// with 09:00 - 09:30 busy time
|
||||
dateRanges: [{ start: dayjs("2024-09-12T16:30:00.000Z"), end: dayjs("2024-09-13T00:00:00.000Z") }],
|
||||
minimumBookingNotice: 0,
|
||||
frequency: 60,
|
||||
});
|
||||
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2024-09-12T10:00:00-07:00",
|
||||
"2024-09-12T11:00:00-07:00",
|
||||
"2024-09-12T12:00:00-07:00",
|
||||
"2024-09-12T13:00:00-07:00",
|
||||
"2024-09-12T14:00:00-07:00",
|
||||
"2024-09-12T15:00:00-07:00",
|
||||
"2024-09-12T16:00:00-07:00",
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows 4 60minutes slots for availability like 08:00-12:30 with 10:00-10:10 busytime, when showOptimizedSlots set to true", async () => {
|
||||
const slots = getSlots({
|
||||
showOptimizedSlots: true,
|
||||
inviteeDate: dayjs.tz("2024-09-12T00:00:00.000-07:00", "America/Los_Angeles"),
|
||||
eventLength: 60,
|
||||
offsetStart: 0,
|
||||
// equivalent dateRanges in UTC-7
|
||||
// start:08:00, end:10:00
|
||||
// start:10:10, end:12:30
|
||||
// with 10:00 - 10:10 busy time
|
||||
dateRanges: [
|
||||
{ start: dayjs("2024-09-12T15:00:00.000Z"), end: dayjs("2024-09-12T17:00:00.000Z") },
|
||||
{ start: dayjs("2024-09-12T17:10:00.000Z"), end: dayjs("2024-09-12T19:30:00.000Z") },
|
||||
],
|
||||
minimumBookingNotice: 0,
|
||||
frequency: 60,
|
||||
});
|
||||
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2024-09-12T08:00:00-07:00",
|
||||
"2024-09-12T09:00:00-07:00",
|
||||
"2024-09-12T10:15:00-07:00",
|
||||
"2024-09-12T11:15:00-07:00",
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows 3 60minutes slots for availability like 08:00-12:30 with 10:00-10:10 busytime, when showOptimizedSlots set to false", async () => {
|
||||
const slots = getSlots({
|
||||
showOptimizedSlots: false,
|
||||
inviteeDate: dayjs.tz("2024-09-12T00:00:00.000-07:00", "America/Los_Angeles"),
|
||||
eventLength: 60,
|
||||
offsetStart: 0,
|
||||
// equivalent dateRanges in UTC-7
|
||||
// start:08:00, end:10:00
|
||||
// start:10:10, end:12:30
|
||||
// with 10:00 - 10:10 busy time
|
||||
dateRanges: [
|
||||
{ start: dayjs("2024-09-12T15:00:00.000Z"), end: dayjs("2024-09-12T17:00:00.000Z") },
|
||||
{ start: dayjs("2024-09-12T17:10:00.000Z"), end: dayjs("2024-09-12T19:30:00.000Z") },
|
||||
],
|
||||
minimumBookingNotice: 0,
|
||||
frequency: 60,
|
||||
});
|
||||
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2024-09-12T08:00:00-07:00",
|
||||
"2024-09-12T09:00:00-07:00",
|
||||
"2024-09-12T11:00:00-07:00",
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows 3 60minutes slots for availability like 08:00-12:00 with 10:00-10:10 busytime, when showOptimizedSlots set to true", async () => {
|
||||
const slots = getSlots({
|
||||
showOptimizedSlots: true,
|
||||
inviteeDate: dayjs.tz("2024-09-12T00:00:00.000-07:00", "America/Los_Angeles"),
|
||||
eventLength: 60,
|
||||
offsetStart: 0,
|
||||
// equivalent dateRanges in UTC-7
|
||||
// start:08:00, end:10:00
|
||||
// start:10:10, end:12:00
|
||||
// with 10:00 - 10:10 busy time
|
||||
dateRanges: [
|
||||
{ start: dayjs("2024-09-12T15:00:00.000Z"), end: dayjs("2024-09-12T17:00:00.000Z") },
|
||||
{ start: dayjs("2024-09-12T17:10:00.000Z"), end: dayjs("2024-09-12T19:00:00.000Z") },
|
||||
],
|
||||
minimumBookingNotice: 0,
|
||||
frequency: 60,
|
||||
});
|
||||
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2024-09-12T08:00:00-07:00",
|
||||
"2024-09-12T09:00:00-07:00",
|
||||
"2024-09-12T11:00:00-07:00",
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows 3 60minutes slots for availability like 08:00-12:00 with 10:00-10:10 busytime, when showOptimizedSlots set to false", async () => {
|
||||
const slots = getSlots({
|
||||
showOptimizedSlots: false,
|
||||
inviteeDate: dayjs.tz("2024-09-12T00:00:00.000-07:00", "America/Los_Angeles"),
|
||||
eventLength: 60,
|
||||
offsetStart: 0,
|
||||
// equivalent dateRanges in UTC-7
|
||||
// start:08:00, end:10:00
|
||||
// start:10:10, end:12:00
|
||||
// with 10:00 - 10:10 busy time
|
||||
dateRanges: [
|
||||
{ start: dayjs("2024-09-12T15:00:00.000Z"), end: dayjs("2024-09-12T17:00:00.000Z") },
|
||||
{ start: dayjs("2024-09-12T17:10:00.000Z"), end: dayjs("2024-09-12T19:00:00.000Z") },
|
||||
],
|
||||
minimumBookingNotice: 0,
|
||||
frequency: 60,
|
||||
});
|
||||
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2024-09-12T08:00:00-07:00",
|
||||
"2024-09-12T09:00:00-07:00",
|
||||
"2024-09-12T11:00:00-07:00",
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows 9 30minutes slots for availability like 08:00-12:45 with 10:00-10:10 busytime, when showOptimizedSlots set to true", async () => {
|
||||
const slots = getSlots({
|
||||
showOptimizedSlots: true,
|
||||
inviteeDate: dayjs.tz("2024-09-12T00:00:00.000-07:00", "America/Los_Angeles"),
|
||||
eventLength: 30,
|
||||
offsetStart: 0,
|
||||
// equivalent dateRanges in UTC-7
|
||||
// start:08:00, end:10:00
|
||||
// start:10:10, end:12:45
|
||||
// with 10:00 - 10:10 busy time
|
||||
dateRanges: [
|
||||
{ start: dayjs("2024-09-12T15:00:00.000Z"), end: dayjs("2024-09-12T17:00:00.000Z") },
|
||||
{ start: dayjs("2024-09-12T17:10:00.000Z"), end: dayjs("2024-09-12T19:45:00.000Z") },
|
||||
],
|
||||
minimumBookingNotice: 0,
|
||||
frequency: 30,
|
||||
});
|
||||
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2024-09-12T08:00:00-07:00",
|
||||
"2024-09-12T08:30:00-07:00",
|
||||
"2024-09-12T09:00:00-07:00",
|
||||
"2024-09-12T09:30:00-07:00",
|
||||
"2024-09-12T10:15:00-07:00",
|
||||
"2024-09-12T10:45:00-07:00",
|
||||
"2024-09-12T11:15:00-07:00",
|
||||
"2024-09-12T11:45:00-07:00",
|
||||
"2024-09-12T12:15:00-07:00",
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows 8 30minutes slots for availability like 08:00-12:45 with 10:00-10:10 busytime, when showOptimizedSlots set to false", async () => {
|
||||
const slots = getSlots({
|
||||
showOptimizedSlots: false,
|
||||
inviteeDate: dayjs.tz("2024-09-12T00:00:00.000-07:00", "America/Los_Angeles"),
|
||||
eventLength: 30,
|
||||
offsetStart: 0,
|
||||
// equivalent dateRanges in UTC-7
|
||||
// start:08:00, end:10:00
|
||||
// start:10:10, end:12:45
|
||||
// with 10:00 - 10:10 busy time
|
||||
dateRanges: [
|
||||
{ start: dayjs("2024-09-12T15:00:00.000Z"), end: dayjs("2024-09-12T17:00:00.000Z") },
|
||||
{ start: dayjs("2024-09-12T17:10:00.000Z"), end: dayjs("2024-09-12T19:45:00.000Z") },
|
||||
],
|
||||
minimumBookingNotice: 0,
|
||||
frequency: 30,
|
||||
});
|
||||
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2024-09-12T08:00:00-07:00",
|
||||
"2024-09-12T08:30:00-07:00",
|
||||
"2024-09-12T09:00:00-07:00",
|
||||
"2024-09-12T09:30:00-07:00",
|
||||
"2024-09-12T10:30:00-07:00",
|
||||
"2024-09-12T11:00:00-07:00",
|
||||
"2024-09-12T11:30:00-07:00",
|
||||
"2024-09-12T12:00:00-07:00",
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows 13 20minutes slots for availability like 08:00-12:30 with 10:00-10:10 busytime, when showOptimizedSlots set to true", async () => {
|
||||
const slots = getSlots({
|
||||
showOptimizedSlots: true,
|
||||
inviteeDate: dayjs.tz("2024-09-12T00:00:00.000-07:00", "America/Los_Angeles"),
|
||||
eventLength: 20,
|
||||
offsetStart: 0,
|
||||
// equivalent dateRanges in UTC-7
|
||||
// start:08:00, end:10:00
|
||||
// start:10:10, end:12:30
|
||||
// with 10:00 - 10:10 busy time
|
||||
dateRanges: [
|
||||
{ start: dayjs("2024-09-12T15:00:00.000Z"), end: dayjs("2024-09-12T17:00:00.000Z") },
|
||||
{ start: dayjs("2024-09-12T17:10:00.000Z"), end: dayjs("2024-09-12T19:30:00.000Z") },
|
||||
],
|
||||
minimumBookingNotice: 0,
|
||||
frequency: 20,
|
||||
});
|
||||
|
||||
expect(slots.length).toStrictEqual(13);
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2024-09-12T08:00:00-07:00",
|
||||
"2024-09-12T08:20:00-07:00",
|
||||
"2024-09-12T08:40:00-07:00",
|
||||
"2024-09-12T09:00:00-07:00",
|
||||
"2024-09-12T09:20:00-07:00",
|
||||
"2024-09-12T09:40:00-07:00",
|
||||
"2024-09-12T10:10:00-07:00",
|
||||
"2024-09-12T10:30:00-07:00",
|
||||
"2024-09-12T10:50:00-07:00",
|
||||
"2024-09-12T11:10:00-07:00",
|
||||
"2024-09-12T11:30:00-07:00",
|
||||
"2024-09-12T11:50:00-07:00",
|
||||
"2024-09-12T12:10:00-07:00",
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows 12 20minutes slots for availability like 08:00-12:30 with 10:00-10:10 busytime, when showOptimizedSlots set to false", async () => {
|
||||
const slots = getSlots({
|
||||
showOptimizedSlots: false,
|
||||
inviteeDate: dayjs.tz("2024-09-12T00:00:00.000-07:00", "America/Los_Angeles"),
|
||||
eventLength: 20,
|
||||
offsetStart: 0,
|
||||
// equivalent dateRanges in UTC-7
|
||||
// start:08:00, end:10:00
|
||||
// start:10:10, end:12:30
|
||||
// with 10:00 - 10:10 busy time
|
||||
dateRanges: [
|
||||
{ start: dayjs("2024-09-12T15:00:00.000Z"), end: dayjs("2024-09-12T17:00:00.000Z") },
|
||||
{ start: dayjs("2024-09-12T17:10:00.000Z"), end: dayjs("2024-09-12T19:30:00.000Z") },
|
||||
],
|
||||
minimumBookingNotice: 0,
|
||||
frequency: 20,
|
||||
});
|
||||
|
||||
expect(slots.length).toStrictEqual(12);
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2024-09-12T08:00:00-07:00",
|
||||
"2024-09-12T08:20:00-07:00",
|
||||
"2024-09-12T08:40:00-07:00",
|
||||
"2024-09-12T09:00:00-07:00",
|
||||
"2024-09-12T09:20:00-07:00",
|
||||
"2024-09-12T09:40:00-07:00",
|
||||
"2024-09-12T10:20:00-07:00",
|
||||
"2024-09-12T10:40:00-07:00",
|
||||
"2024-09-12T11:00:00-07:00",
|
||||
"2024-09-12T11:20:00-07:00",
|
||||
"2024-09-12T11:40:00-07:00",
|
||||
"2024-09-12T12:00:00-07:00",
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows 8 60minutes slots for availability like 09:30-17:30, when showOptimizedSlots set to true", async () => {
|
||||
const slots = getSlots({
|
||||
showOptimizedSlots: true,
|
||||
inviteeDate: dayjs.tz("2024-09-12T00:00:00.000-07:00", "America/Los_Angeles"),
|
||||
eventLength: 60,
|
||||
offsetStart: 0,
|
||||
// equivalent dateRanges in UTC-7
|
||||
// start:09:30, end:17:30
|
||||
dateRanges: [{ start: dayjs("2024-09-12T16:30:00.000Z"), end: dayjs("2024-09-13T00:30:00.000Z") }],
|
||||
minimumBookingNotice: 0,
|
||||
frequency: 60,
|
||||
});
|
||||
|
||||
expect(slots.length).toStrictEqual(8);
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2024-09-12T09:30:00-07:00",
|
||||
"2024-09-12T10:30:00-07:00",
|
||||
"2024-09-12T11:30:00-07:00",
|
||||
"2024-09-12T12:30:00-07:00",
|
||||
"2024-09-12T13:30:00-07:00",
|
||||
"2024-09-12T14:30:00-07:00",
|
||||
"2024-09-12T15:30:00-07:00",
|
||||
"2024-09-12T16:30:00-07:00",
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows 7 60minutes slots for availability like 09:30-17:30, when showOptimizedSlots set to false", async () => {
|
||||
const slots = getSlots({
|
||||
showOptimizedSlots: false,
|
||||
inviteeDate: dayjs.tz("2024-09-12T00:00:00.000-07:00", "America/Los_Angeles"),
|
||||
eventLength: 60,
|
||||
offsetStart: 0,
|
||||
// equivalent dateRanges in UTC-7
|
||||
// start:09:30, end:17:30
|
||||
dateRanges: [{ start: dayjs("2024-09-12T16:30:00.000Z"), end: dayjs("2024-09-13T00:30:00.000Z") }],
|
||||
minimumBookingNotice: 0,
|
||||
frequency: 60,
|
||||
});
|
||||
|
||||
expect(slots.length).toStrictEqual(7);
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2024-09-12T10:00:00-07:00",
|
||||
"2024-09-12T11:00:00-07:00",
|
||||
"2024-09-12T12:00:00-07:00",
|
||||
"2024-09-12T13:00:00-07:00",
|
||||
"2024-09-12T14:00:00-07:00",
|
||||
"2024-09-12T15:00:00-07:00",
|
||||
"2024-09-12T16:00:00-07:00",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should respect start of the hour for 60minutes slots for availabilities like 07:45-15:30, even when showOptimizedSlots set to true", async () => {
|
||||
const slots = getSlots({
|
||||
showOptimizedSlots: true,
|
||||
inviteeDate: dayjs.tz("2024-09-12T00:00:00.000-07:00", "America/Los_Angeles"),
|
||||
eventLength: 60,
|
||||
offsetStart: 0,
|
||||
// equivalent dateRanges in UTC-7
|
||||
// start:07:45, end:15:30
|
||||
dateRanges: [{ start: dayjs("2024-09-12T14:45:00.000Z"), end: dayjs("2024-09-12T22:30:00.000Z") }],
|
||||
minimumBookingNotice: 0,
|
||||
frequency: 60,
|
||||
});
|
||||
|
||||
expect(slots.length).toStrictEqual(7);
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2024-09-12T08:00:00-07:00",
|
||||
"2024-09-12T09:00:00-07:00",
|
||||
"2024-09-12T10:00:00-07:00",
|
||||
"2024-09-12T11:00:00-07:00",
|
||||
"2024-09-12T12:00:00-07:00",
|
||||
"2024-09-12T13:00:00-07:00",
|
||||
"2024-09-12T14:00:00-07:00",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should respect start of the hour for 60minutes slots for availabilities like 07:45-15:30, when showOptimizedSlots set to false", async () => {
|
||||
const slots = getSlots({
|
||||
showOptimizedSlots: false,
|
||||
inviteeDate: dayjs.tz("2024-09-12T00:00:00.000-07:00", "America/Los_Angeles"),
|
||||
eventLength: 60,
|
||||
offsetStart: 0,
|
||||
// equivalent dateRanges in UTC-7
|
||||
// start:07:45, end:15:30
|
||||
dateRanges: [{ start: dayjs("2024-09-12T14:45:00.000Z"), end: dayjs("2024-09-12T22:30:00.000Z") }],
|
||||
minimumBookingNotice: 0,
|
||||
frequency: 60,
|
||||
});
|
||||
|
||||
expect(slots.length).toStrictEqual(7);
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2024-09-12T08:00:00-07:00",
|
||||
"2024-09-12T09:00:00-07:00",
|
||||
"2024-09-12T10:00:00-07:00",
|
||||
"2024-09-12T11:00:00-07:00",
|
||||
"2024-09-12T12:00:00-07:00",
|
||||
"2024-09-12T13:00:00-07:00",
|
||||
"2024-09-12T14:00:00-07:00",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should respect start of the hour for 60minutes slots for availabilities like 09:05-12:55, even when showOptimizedSlots set to true", async () => {
|
||||
const slots = getSlots({
|
||||
showOptimizedSlots: true,
|
||||
inviteeDate: dayjs.tz("2024-09-12T00:00:00.000-07:00", "America/Los_Angeles"),
|
||||
eventLength: 60,
|
||||
offsetStart: 0,
|
||||
// equivalent dateRanges in UTC-7
|
||||
// start:09:05, end:12:55
|
||||
dateRanges: [{ start: dayjs("2024-09-12T16:05:00.000Z"), end: dayjs("2024-09-12T19:55:00.000Z") }],
|
||||
minimumBookingNotice: 0,
|
||||
frequency: 60,
|
||||
});
|
||||
|
||||
expect(slots.length).toStrictEqual(3);
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2024-09-12T09:15:00-07:00",
|
||||
"2024-09-12T10:15:00-07:00",
|
||||
"2024-09-12T11:15:00-07:00",
|
||||
]);
|
||||
});
|
||||
|
||||
it("adjusts slot start time to next 5-minute boundary for current day bookings with non-aligned start time", async () => {
|
||||
// Set system time to 2021-06-20 11:20:00 UTC
|
||||
vi.setSystemTime(dayjs.utc("2021-06-20T11:20:00.000Z").toDate());
|
||||
|
||||
const slots = getSlots({
|
||||
inviteeDate: dayjs.tz("2021-06-20T00:00:00.000Z", "America/Los_Angeles"),
|
||||
frequency: 15,
|
||||
minimumBookingNotice: 0,
|
||||
eventLength: 15,
|
||||
dateRanges: [
|
||||
{
|
||||
start: dayjs.tz("2021-06-20T11:22:00.000", "America/Los_Angeles"),
|
||||
end: dayjs.tz("2021-06-20T12:55:00.000", "America/Los_Angeles"),
|
||||
},
|
||||
],
|
||||
offsetStart: 0,
|
||||
showOptimizedSlots: true,
|
||||
});
|
||||
|
||||
expect(slots.length).toStrictEqual(6);
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2021-06-20T11:25:00-07:00",
|
||||
"2021-06-20T11:40:00-07:00",
|
||||
"2021-06-20T11:55:00-07:00",
|
||||
"2021-06-20T12:10:00-07:00",
|
||||
"2021-06-20T12:25:00-07:00",
|
||||
"2021-06-20T12:40:00-07:00",
|
||||
]);
|
||||
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("should respect start of the hour for current day bookings with non-aligned start time", async () => {
|
||||
// Set system time to 2021-06-20 11:20:00 UTC
|
||||
vi.setSystemTime(dayjs.utc("2021-06-20T11:20:00.000Z").toDate());
|
||||
|
||||
const slots = getSlots({
|
||||
inviteeDate: dayjs.tz("2021-06-20T00:00:00.000Z", "America/Los_Angeles"),
|
||||
frequency: 60,
|
||||
minimumBookingNotice: 0,
|
||||
eventLength: 60,
|
||||
dateRanges: [
|
||||
{
|
||||
start: dayjs.tz("2021-06-20T11:22:36.234", "America/Los_Angeles"), //with seconds
|
||||
end: dayjs.tz("2021-06-20T14:00:00.000", "America/Los_Angeles"),
|
||||
},
|
||||
],
|
||||
offsetStart: 0,
|
||||
showOptimizedSlots: true,
|
||||
});
|
||||
|
||||
expect(slots.length).toStrictEqual(2);
|
||||
expect(slots.map((slot) => slot.time.format())).toStrictEqual([
|
||||
"2021-06-20T12:00:00-07:00",
|
||||
"2021-06-20T13:00:00-07:00",
|
||||
]);
|
||||
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,250 @@
|
||||
import type { Dayjs } from "@calcom/dayjs";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import type {
|
||||
IFromUser,
|
||||
IOutOfOfficeData,
|
||||
IToUser,
|
||||
} from "@calcom/features/availability/lib/getUserAvailability";
|
||||
import type { DateRange } from "@calcom/features/schedules/lib/date-ranges";
|
||||
import { getTimeZone } from "@calcom/lib/dayjs";
|
||||
import { withReporting } from "@calcom/lib/sentryWrapper";
|
||||
|
||||
export type GetSlots = {
|
||||
inviteeDate: Dayjs;
|
||||
frequency: number;
|
||||
dateRanges: DateRange[];
|
||||
minimumBookingNotice: number;
|
||||
eventLength: number;
|
||||
offsetStart?: number;
|
||||
datesOutOfOffice?: IOutOfOfficeData;
|
||||
showOptimizedSlots?: boolean | null;
|
||||
};
|
||||
export type TimeFrame = { userIds?: number[]; startTime: number; endTime: number };
|
||||
|
||||
const minimumOfOne = (input: number) => (input < 1 ? 1 : input);
|
||||
|
||||
function getCorrectedSlotStartTime({
|
||||
slotStartTime,
|
||||
range,
|
||||
showOptimizedSlots,
|
||||
interval,
|
||||
}: {
|
||||
showOptimizedSlots: boolean | null | undefined;
|
||||
interval: number;
|
||||
slotStartTime: Dayjs;
|
||||
range: DateRange;
|
||||
}) {
|
||||
if (showOptimizedSlots) {
|
||||
let correctedSlotStartTime = slotStartTime;
|
||||
// if showOptimizedSlots option is selected, the slotStartTime should not be modified,
|
||||
// so that maximum possible slots are shown.
|
||||
// The below logic in this entire `if branch` only tries to add an increment if sufficient minutes are available (after max possible slots are consumed),
|
||||
// so that slots are shown respecting the 'Start of the Hour'.
|
||||
const minutesRequiredToMoveToNextSlot = interval - (slotStartTime.minute() % interval);
|
||||
const minutesRequiredToMoveTo15MinSlot = 15 - (slotStartTime.minute() % 15);
|
||||
const minutesRequiredToMoveTo5MinSlot = 5 - (slotStartTime.minute() % 5);
|
||||
const extraMinutesAvailable = range.end.diff(slotStartTime, "minutes") % interval;
|
||||
|
||||
if (extraMinutesAvailable >= minutesRequiredToMoveToNextSlot) {
|
||||
// For cases like, Availability -> 9:05 - 12:00, 60Min EventTypes.
|
||||
// Total available minutes are 175, so only 2 60Min slots can be provided max
|
||||
// And still 175-120 = 55mins are available, hence 'slotStartTime' is pushed to 10:00 to respect 'Start of the Hour'.
|
||||
// Slots will be shown as '10:00, 11:00' instead of '09:05, 10:05'
|
||||
correctedSlotStartTime = slotStartTime.add(minutesRequiredToMoveToNextSlot, "minute");
|
||||
} else if (extraMinutesAvailable >= minutesRequiredToMoveTo15MinSlot) {
|
||||
// For cases like, Availability -> 9:05 - 11:55, 60Min EventTypes.
|
||||
// Total available minutes are 170, so only 2 60Min slots can be provided max
|
||||
// And still 175-120 = 50mins are available, but it is less 55mins which is required to push to 10:00
|
||||
// so slotStartTime is pushed to next 15Min slot 09:15, instead of showing slots like 9:05,10:05 now slots will be 9:15,10:15
|
||||
correctedSlotStartTime = slotStartTime.add(minutesRequiredToMoveTo15MinSlot, "minute");
|
||||
} else if (extraMinutesAvailable >= minutesRequiredToMoveTo5MinSlot) {
|
||||
// so slotStartTime is pushed to next 5Min, instead of showing slots like 11:22,11:37 now slots will be 11:25,11:40
|
||||
correctedSlotStartTime = slotStartTime.add(minutesRequiredToMoveTo5MinSlot, "minute");
|
||||
}
|
||||
return correctedSlotStartTime;
|
||||
}
|
||||
|
||||
return slotStartTime.startOf("hour").add(Math.ceil(slotStartTime.minute() / interval) * interval, "minute");
|
||||
}
|
||||
|
||||
function buildSlotsWithDateRanges({
|
||||
dateRanges,
|
||||
frequency,
|
||||
eventLength,
|
||||
timeZone,
|
||||
minimumBookingNotice,
|
||||
offsetStart,
|
||||
datesOutOfOffice,
|
||||
showOptimizedSlots,
|
||||
}: {
|
||||
dateRanges: DateRange[];
|
||||
frequency: number;
|
||||
eventLength: number;
|
||||
timeZone: string;
|
||||
minimumBookingNotice: number;
|
||||
offsetStart?: number;
|
||||
datesOutOfOffice?: IOutOfOfficeData;
|
||||
showOptimizedSlots?: boolean | null;
|
||||
}) {
|
||||
// keep the old safeguards in; may be needed.
|
||||
frequency = minimumOfOne(frequency);
|
||||
eventLength = minimumOfOne(eventLength);
|
||||
offsetStart = offsetStart ? minimumOfOne(offsetStart) : 0;
|
||||
|
||||
const orderedDateRanges = dateRanges.sort((a, b) => a.start.valueOf() - b.start.valueOf());
|
||||
|
||||
// there can only ever be one slot at a given start time, and based on duration also only a single length.
|
||||
const slots = new Map<
|
||||
string,
|
||||
{
|
||||
time: Dayjs;
|
||||
userIds?: number[];
|
||||
away?: boolean;
|
||||
fromUser?: IFromUser;
|
||||
toUser?: IToUser;
|
||||
reason?: string;
|
||||
emoji?: string;
|
||||
}
|
||||
>();
|
||||
|
||||
let interval = Number(process.env.NEXT_PUBLIC_AVAILABILITY_SCHEDULE_INTERVAL) || 1;
|
||||
const intervalsWithDefinedStartTimes = [60, 30, 20, 15, 10, 5];
|
||||
|
||||
for (let i = 0; i < intervalsWithDefinedStartTimes.length; i++) {
|
||||
if (frequency % intervalsWithDefinedStartTimes[i] === 0) {
|
||||
interval = intervalsWithDefinedStartTimes[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const startTimeWithMinNotice = dayjs.utc().add(minimumBookingNotice, "minute");
|
||||
|
||||
const slotBoundaries = new Map<number, true>();
|
||||
|
||||
orderedDateRanges.forEach((range) => {
|
||||
const dateYYYYMMDD = range.start.format("YYYY-MM-DD");
|
||||
|
||||
let slotStartTime = range.start.utc().isAfter(startTimeWithMinNotice)
|
||||
? range.start
|
||||
: startTimeWithMinNotice;
|
||||
|
||||
// For current day bookings, normalizing the seconds to zero to avoid issues with time calculations
|
||||
slotStartTime = slotStartTime.set("second", 0).set("millisecond", 0);
|
||||
|
||||
// Convert to target timezone BEFORE checking if rounding is needed
|
||||
// This ensures we check minute alignment in the local timezone, not UTC
|
||||
// This prevents issues with half-hour offset timezones like Asia/Kolkata (GMT+5:30)
|
||||
slotStartTime = slotStartTime.tz(timeZone);
|
||||
|
||||
if (slotStartTime.minute() % interval !== 0) {
|
||||
slotStartTime = getCorrectedSlotStartTime({
|
||||
showOptimizedSlots,
|
||||
interval,
|
||||
slotStartTime,
|
||||
range,
|
||||
});
|
||||
}
|
||||
|
||||
slotStartTime = slotStartTime.add(offsetStart ?? 0, "minutes");
|
||||
|
||||
// Find the nearest appropriate slot boundary if this time falls within an existing slot
|
||||
const slotBoundariesValueArray = Array.from(slotBoundaries.keys());
|
||||
if (slotBoundariesValueArray.length > 0) {
|
||||
slotBoundariesValueArray.sort((a, b) => a - b);
|
||||
|
||||
let prevBoundary = null;
|
||||
for (let i = slotBoundariesValueArray.length - 1; i >= 0; i--) {
|
||||
if (slotBoundariesValueArray[i] < slotStartTime.valueOf()) {
|
||||
prevBoundary = slotBoundariesValueArray[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (prevBoundary) {
|
||||
const prevBoundaryEnd = dayjs(prevBoundary).add(frequency + (offsetStart ?? 0), "minutes");
|
||||
if (prevBoundaryEnd.isAfter(slotStartTime)) {
|
||||
const dayjsPrevBoundary = dayjs(prevBoundary);
|
||||
if (!dayjsPrevBoundary.isBefore(range.start)) {
|
||||
slotStartTime = dayjsPrevBoundary;
|
||||
} else {
|
||||
slotStartTime = prevBoundaryEnd;
|
||||
}
|
||||
slotStartTime = slotStartTime.tz(timeZone);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while (!slotStartTime.add(eventLength, "minutes").subtract(1, "second").utc().isAfter(range.end)) {
|
||||
const slotKey = slotStartTime.toISOString();
|
||||
if (slots.has(slotKey)) {
|
||||
slotStartTime = slotStartTime.add(frequency + (offsetStart ?? 0), "minutes");
|
||||
continue;
|
||||
}
|
||||
|
||||
slotBoundaries.set(slotStartTime.valueOf(), true);
|
||||
|
||||
const dateOutOfOfficeExists = datesOutOfOffice?.[dateYYYYMMDD];
|
||||
let slotData: {
|
||||
time: Dayjs;
|
||||
userIds?: number[];
|
||||
away?: boolean;
|
||||
fromUser?: IFromUser;
|
||||
toUser?: IToUser;
|
||||
reason?: string;
|
||||
emoji?: string;
|
||||
} = {
|
||||
time: slotStartTime,
|
||||
};
|
||||
|
||||
if (dateOutOfOfficeExists) {
|
||||
const { toUser, fromUser, reason, emoji } = dateOutOfOfficeExists;
|
||||
|
||||
slotData = {
|
||||
time: slotStartTime,
|
||||
away: true,
|
||||
...(fromUser && { fromUser }),
|
||||
...(toUser && { toUser }),
|
||||
...(reason && { reason }),
|
||||
...(emoji && { emoji }),
|
||||
};
|
||||
}
|
||||
|
||||
slots.set(slotKey, slotData);
|
||||
slotStartTime = slotStartTime.add(frequency + (offsetStart ?? 0), "minutes");
|
||||
}
|
||||
});
|
||||
|
||||
return Array.from(slots.values());
|
||||
}
|
||||
|
||||
const getSlots = ({
|
||||
inviteeDate,
|
||||
frequency,
|
||||
minimumBookingNotice,
|
||||
dateRanges,
|
||||
eventLength,
|
||||
offsetStart = 0,
|
||||
datesOutOfOffice,
|
||||
showOptimizedSlots,
|
||||
}: GetSlots): {
|
||||
time: Dayjs;
|
||||
userIds?: number[];
|
||||
away?: boolean;
|
||||
fromUser?: IFromUser;
|
||||
toUser?: IToUser;
|
||||
reason?: string;
|
||||
emoji?: string;
|
||||
}[] => {
|
||||
return buildSlotsWithDateRanges({
|
||||
dateRanges,
|
||||
frequency,
|
||||
eventLength,
|
||||
timeZone: getTimeZone(inviteeDate),
|
||||
minimumBookingNotice,
|
||||
offsetStart,
|
||||
datesOutOfOffice,
|
||||
showOptimizedSlots,
|
||||
});
|
||||
};
|
||||
|
||||
export default withReporting(getSlots, "getSlots");
|
||||
@@ -1,6 +1,6 @@
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
|
||||
import { CredentialRepository } from "@calcom/features/credentials/repositories/CredentialRepository";
|
||||
|
||||
import AnalyticsManager from "./analyticsManager";
|
||||
import { sendAnalyticsEventSchema } from "./schema";
|
||||
|
||||
@@ -10,7 +10,7 @@ import { DataTableProvider } from "@calcom/features/data-table/DataTableProvider
|
||||
import { DataTable, DataTableToolbar } from "@calcom/features/data-table/components";
|
||||
import { useDataTable } from "@calcom/features/data-table/hooks";
|
||||
import { APP_NAME, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import type { DateRange } from "@calcom/lib/date-ranges";
|
||||
import type { DateRange } from "@calcom/features/schedules/lib/date-ranges";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { CURRENT_TIMEZONE } from "@calcom/lib/timezoneConstants";
|
||||
import type { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useStore } from "zustand";
|
||||
|
||||
import type { Dayjs } from "@calcom/dayjs";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import type { DateRange } from "@calcom/lib/date-ranges";
|
||||
import type { DateRange } from "@calcom/features/schedules/lib/date-ranges";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
|
||||
import { DAY_CELL_WIDTH } from "../constants";
|
||||
|
||||
Reference in new issue
Block a user