refactor: Remove circular deps between @calcom/lib and @calcom/features [1] (#24399)
* add eslint config * migrate autoLock to features * migrate teamService to features * migrate userCreationService * migrate insights services to features * migrate ProfileRepository * update imports * migrate filter segmen tests * migrate filter segment repository * migrate getBusyTimes * migrate getLocaleFromRequest * refactor csvUtils * make filename clearer * migrate getLuckyUser integration test * migrate autoLock test to features * wip * refactors * migrate useBookerUrl * migrate more * wip * Migrate eventTypeRepository * membership repository * update imports * update imports * migrate * move organization repository * update imports * update imports * wip * wip * wip * wip * wip * wip * wip * wip * fix * fix * fix * fix * fix * fix * fix * fix * fix * fix tests * fix type checks * fix * fix * migrate * update imports * fix tests * fix * fix * fix * fix * fix * fix * fix * fix * fix * fix * fix
This commit is contained in:
1 parent
1dc20e3aec
commit
ff38d6c7db
339 files changed
+876
-833
No files matched your search
@@ -0,0 +1,335 @@
|
||||
import type { RatelimitResponse } from "@unkey/ratelimit";
|
||||
import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
|
||||
import { hashAPIKey } from "@calcom/features/ee/api-keys/lib/apiKeys";
|
||||
import { RedisService } from "@calcom/features/redis/RedisService";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
import { handleAutoLock } from "./autoLock";
|
||||
|
||||
// Mock the dependencies
|
||||
vi.mock("@calcom/features/redis/RedisService");
|
||||
vi.mock("@calcom/features/ee/api-keys/lib/apiKeys", () => ({
|
||||
hashAPIKey: vi.fn((key) => `hashed_${key}`),
|
||||
}));
|
||||
vi.mock("@calcom/prisma", () => ({
|
||||
default: {
|
||||
user: {
|
||||
update: vi.fn(),
|
||||
},
|
||||
apiKey: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
describe("autoLock", () => {
|
||||
const mockRedis = {
|
||||
get: vi.fn(),
|
||||
set: vi.fn(),
|
||||
del: vi.fn(),
|
||||
expire: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset all mocks before each test
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(RedisService).mockImplementation(() => mockRedis as any);
|
||||
|
||||
// Mock environment variables
|
||||
process.env.UPSTASH_REDIS_REST_TOKEN = "test-token";
|
||||
process.env.UPSTASH_REDIS_REST_URL = "test-url";
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.UPSTASH_REDIS_REST_TOKEN;
|
||||
delete process.env.UPSTASH_REDIS_REST_URL;
|
||||
});
|
||||
|
||||
describe("handleAutoLock", () => {
|
||||
it("should return early if Upstash env variables are not set", async () => {
|
||||
delete process.env.UPSTASH_REDIS_REST_TOKEN;
|
||||
|
||||
const rateLimitResponse: RatelimitResponse = {
|
||||
success: false,
|
||||
remaining: 0,
|
||||
limit: 5,
|
||||
reset: 0,
|
||||
};
|
||||
|
||||
await handleAutoLock({
|
||||
identifier: "[email protected]",
|
||||
identifierType: "email",
|
||||
rateLimitResponse,
|
||||
});
|
||||
expect(mockRedis.get).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle identifier with keyword correctly", async () => {
|
||||
const rateLimitResponse: RatelimitResponse = {
|
||||
success: false,
|
||||
remaining: 0,
|
||||
limit: 5,
|
||||
reset: 0,
|
||||
};
|
||||
|
||||
mockRedis.get.mockResolvedValue("0");
|
||||
|
||||
await handleAutoLock({
|
||||
identifier: "[email protected]",
|
||||
identifierType: "email",
|
||||
rateLimitResponse,
|
||||
identifierKeyword: "addSecondaryEmail",
|
||||
});
|
||||
|
||||
expect(mockRedis.get).toHaveBeenCalledWith("autolock:email:addSecondaryEmail:[email protected]");
|
||||
});
|
||||
|
||||
it("should increment counter when below threshold", async () => {
|
||||
const rateLimitResponse: RatelimitResponse = {
|
||||
success: false,
|
||||
remaining: 0,
|
||||
limit: 5,
|
||||
reset: 0,
|
||||
};
|
||||
|
||||
mockRedis.get.mockResolvedValue("2");
|
||||
|
||||
await handleAutoLock({
|
||||
identifier: "[email protected]",
|
||||
identifierType: "email",
|
||||
rateLimitResponse,
|
||||
});
|
||||
|
||||
expect(mockRedis.set).toHaveBeenCalledWith("autolock:email:[email protected]", "3");
|
||||
expect(mockRedis.expire).toHaveBeenCalledWith("autolock:email:[email protected]", 1800);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should lock user when threshold is reached", async () => {
|
||||
const rateLimitResponse: RatelimitResponse = {
|
||||
success: false,
|
||||
remaining: 0,
|
||||
limit: 5,
|
||||
reset: 0,
|
||||
};
|
||||
|
||||
mockRedis.get.mockResolvedValue("4");
|
||||
|
||||
await handleAutoLock({
|
||||
identifier: "[email protected]",
|
||||
identifierType: "email",
|
||||
rateLimitResponse,
|
||||
});
|
||||
|
||||
expect(prisma.user.update).toHaveBeenCalledWith({
|
||||
where: { email: "[email protected]" },
|
||||
data: { locked: true },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true,
|
||||
},
|
||||
});
|
||||
expect(mockRedis.del).toHaveBeenCalledWith("autolock:email:[email protected]");
|
||||
});
|
||||
|
||||
it("should respect custom threshold and duration", async () => {
|
||||
const rateLimitResponse: RatelimitResponse = {
|
||||
success: false,
|
||||
remaining: 0,
|
||||
limit: 5,
|
||||
reset: 0,
|
||||
};
|
||||
|
||||
mockRedis.get.mockResolvedValue("1");
|
||||
|
||||
await handleAutoLock({
|
||||
identifier: "[email protected]",
|
||||
identifierType: "email",
|
||||
rateLimitResponse,
|
||||
autolockThreshold: 3,
|
||||
autolockDuration: 30 * 60 * 1000, // 30 minutes
|
||||
});
|
||||
|
||||
expect(mockRedis.set).toHaveBeenCalledWith("autolock:email:[email protected]", "2");
|
||||
expect(mockRedis.expire).toHaveBeenCalledWith("autolock:email:[email protected]", 1800);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should lock API key and associated user", async () => {
|
||||
const rateLimitResponse: RatelimitResponse = {
|
||||
success: false,
|
||||
remaining: 0,
|
||||
limit: 5,
|
||||
reset: 0,
|
||||
};
|
||||
|
||||
mockRedis.get.mockResolvedValue("4");
|
||||
const testApiKey = "test_api_key_123";
|
||||
|
||||
// Mock API key lookup
|
||||
vi.mocked(prisma.apiKey.findUnique).mockResolvedValue({
|
||||
hashedKey: `hashed_${testApiKey}`,
|
||||
user: { id: 456 },
|
||||
} as any);
|
||||
|
||||
await handleAutoLock({
|
||||
identifier: testApiKey,
|
||||
identifierType: "apiKey",
|
||||
rateLimitResponse,
|
||||
});
|
||||
|
||||
// Verify the API key was hashed
|
||||
expect(hashAPIKey).toHaveBeenCalledWith(testApiKey);
|
||||
|
||||
// Verify the associated user was locked
|
||||
expect(prisma.user.update).toHaveBeenCalledWith({
|
||||
where: { id: 456 },
|
||||
data: { locked: true },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should throw error when API key has no associated user", async () => {
|
||||
const rateLimitResponse: RatelimitResponse = {
|
||||
success: false,
|
||||
remaining: 0,
|
||||
limit: 5,
|
||||
reset: 0,
|
||||
};
|
||||
|
||||
mockRedis.get.mockResolvedValue("4"); // Over threshold to trigger lock
|
||||
const testApiKey = "test_api_key_123";
|
||||
|
||||
// Mock API key lookup with no user
|
||||
vi.mocked(prisma.apiKey.findUnique).mockResolvedValue(null);
|
||||
|
||||
// Expect handleAutoLock to throw the error from lockUser
|
||||
await expect(async () => {
|
||||
await handleAutoLock({
|
||||
identifier: testApiKey,
|
||||
identifierType: "apiKey",
|
||||
rateLimitResponse,
|
||||
});
|
||||
}).rejects.toThrow("No user found for this API key.");
|
||||
});
|
||||
|
||||
it("should not increment counter when rate limit is successful", async () => {
|
||||
const rateLimitResponse: RatelimitResponse = {
|
||||
success: true,
|
||||
remaining: 5,
|
||||
limit: 5,
|
||||
reset: 0,
|
||||
};
|
||||
|
||||
await handleAutoLock({
|
||||
identifier: "[email protected]",
|
||||
identifierType: "email",
|
||||
rateLimitResponse,
|
||||
});
|
||||
|
||||
expect(mockRedis.get).not.toHaveBeenCalled();
|
||||
expect(mockRedis.set).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should initialize counter when it doesn't exist", async () => {
|
||||
const rateLimitResponse: RatelimitResponse = {
|
||||
success: false,
|
||||
remaining: 0,
|
||||
limit: 5,
|
||||
reset: 0,
|
||||
};
|
||||
|
||||
mockRedis.get.mockResolvedValue(null);
|
||||
|
||||
await handleAutoLock({
|
||||
identifier: "[email protected]",
|
||||
identifierType: "email",
|
||||
rateLimitResponse,
|
||||
});
|
||||
|
||||
expect(mockRedis.set).toHaveBeenCalledWith("autolock:email:[email protected]", "1");
|
||||
expect(mockRedis.expire).toHaveBeenCalledWith("autolock:email:[email protected]", 1800);
|
||||
});
|
||||
|
||||
it("should handle Redis errors gracefully", async () => {
|
||||
const rateLimitResponse: RatelimitResponse = {
|
||||
success: false,
|
||||
remaining: 0,
|
||||
limit: 5,
|
||||
reset: 0,
|
||||
};
|
||||
|
||||
mockRedis.get.mockRejectedValue(new Error("Redis connection error"));
|
||||
|
||||
const result = await handleAutoLock({
|
||||
identifier: "[email protected]",
|
||||
identifierType: "email",
|
||||
rateLimitResponse,
|
||||
});
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("lockUser", () => {
|
||||
it("should lock user by email", async () => {
|
||||
const rateLimitResponse: RatelimitResponse = {
|
||||
success: false,
|
||||
remaining: 0,
|
||||
limit: 5,
|
||||
reset: 0,
|
||||
};
|
||||
|
||||
mockRedis.get.mockResolvedValue("4");
|
||||
|
||||
await handleAutoLock({
|
||||
identifier: "[email protected]",
|
||||
identifierType: "email",
|
||||
rateLimitResponse,
|
||||
});
|
||||
|
||||
expect(prisma.user.update).toHaveBeenCalledWith({
|
||||
where: { email: "[email protected]" },
|
||||
data: { locked: true },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should lock user by userId", async () => {
|
||||
const rateLimitResponse: RatelimitResponse = {
|
||||
success: false,
|
||||
remaining: 0,
|
||||
limit: 5,
|
||||
reset: 0,
|
||||
};
|
||||
|
||||
mockRedis.get.mockResolvedValue("4");
|
||||
|
||||
await handleAutoLock({
|
||||
identifier: "123",
|
||||
identifierType: "userId",
|
||||
rateLimitResponse,
|
||||
});
|
||||
|
||||
expect(prisma.user.update).toHaveBeenCalledWith({
|
||||
where: { id: 123 },
|
||||
data: { locked: true },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,177 @@
|
||||
import type { RatelimitResponse } from "@unkey/ratelimit";
|
||||
|
||||
import { RedisService } from "@calcom/features/redis/RedisService";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
import { hashAPIKey } from "./apiKeys";
|
||||
|
||||
// This is the number of times a user can exceed the rate limit before being locked
|
||||
const DEFAULT_AUTOLOCK_THRESHOLD = 5;
|
||||
// This is the duration of the rate limit check window
|
||||
const DEFAULT_CHECK_THRESHOLD_WINDOW_DURATION = 60 * 30 * 1000; // 30 minutes in milliseconds
|
||||
|
||||
interface HandleAutoLockInput {
|
||||
identifier: string;
|
||||
identifierType: "email" | "userId" | "SMS" | "apiKey";
|
||||
rateLimitResponse: RatelimitResponse;
|
||||
identifierKeyword?: string; // For instances where we have like "addSecondaryEmail.${email}"
|
||||
autolockThreshold?: number;
|
||||
autolockDuration?: number; // in milliseconds
|
||||
}
|
||||
|
||||
export enum LockReason {
|
||||
RATE_LIMIT = "Auto-locking user due to rate limit exceeded",
|
||||
SPAM_WORKFLOW_BODY = "Auto-locking user due to spam detected in workflow body",
|
||||
}
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["[autoLock]"] });
|
||||
|
||||
/**
|
||||
* The "Requests to Hit Limit × Threshold" shows how many requests would be needed to trigger an auto-lock if a user consistently hits
|
||||
* its their rate limit. For example, in the "core" * namespace, a user would need to make at least 50 requests (10 limit × 5 threshold)
|
||||
* within the 30-minute window to get auto-locked.
|
||||
*/
|
||||
export async function handleAutoLock({
|
||||
identifier: _identifier,
|
||||
identifierType,
|
||||
rateLimitResponse,
|
||||
identifierKeyword,
|
||||
autolockThreshold = DEFAULT_AUTOLOCK_THRESHOLD,
|
||||
autolockDuration = DEFAULT_CHECK_THRESHOLD_WINDOW_DURATION,
|
||||
}: HandleAutoLockInput): Promise<boolean> {
|
||||
const { success, remaining } = rateLimitResponse;
|
||||
|
||||
const UPSTASH_ENV_FOUND = process.env.UPSTASH_REDIS_REST_TOKEN && process.env.UPSTASH_REDIS_REST_URL;
|
||||
|
||||
if (!UPSTASH_ENV_FOUND) {
|
||||
log.warn("Skipping auto lock because UPSTASH env variables are not set");
|
||||
return false;
|
||||
}
|
||||
|
||||
const identifier = identifierKeyword
|
||||
? _identifier.toString().replace(`${identifierKeyword}.`, "")
|
||||
: _identifier;
|
||||
|
||||
if (!success && remaining <= 0) {
|
||||
const redis = new RedisService();
|
||||
const lockKey = `autolock:${identifierType}${
|
||||
identifierKeyword ? `:${identifierKeyword}` : ""
|
||||
}:${identifier}.count`;
|
||||
|
||||
try {
|
||||
const count = await redis.get(lockKey);
|
||||
const currentCount = count ? parseInt(count.toString(), 10) : 0;
|
||||
|
||||
log.info(
|
||||
`Rate limit exceeded for ${identifierType}: ${identifier}. Current count: ${currentCount}/${autolockThreshold}`
|
||||
);
|
||||
|
||||
// If they have exceeded the threshold, lock them
|
||||
if (currentCount + 1 >= autolockThreshold) {
|
||||
log.warn(
|
||||
`Auto-locking ${identifierType}: ${identifier}. Threshold reached: ${
|
||||
currentCount + 1
|
||||
}/${autolockThreshold}`
|
||||
);
|
||||
await lockUser(identifierType, identifier, LockReason.RATE_LIMIT);
|
||||
await redis.del(lockKey);
|
||||
return true;
|
||||
}
|
||||
|
||||
await redis.set(lockKey, (currentCount + 1).toString());
|
||||
await redis.expire(lockKey, Math.floor(autolockDuration / 1000));
|
||||
return false;
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.message === "No user found for this API key.") {
|
||||
log.error(`Error in auto-lock: No user found for API key: ${identifier}`);
|
||||
throw err;
|
||||
}
|
||||
log.error(`Error in auto-lock process: ${err instanceof Error ? err.message : String(err)}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function lockUser(identifierType: string, identifier: string, lockReason: LockReason) {
|
||||
if (!identifier) {
|
||||
return;
|
||||
}
|
||||
|
||||
type UserType = {
|
||||
id: number;
|
||||
email: string;
|
||||
username: string | null;
|
||||
} | null;
|
||||
|
||||
let user: UserType = null;
|
||||
|
||||
switch (identifierType) {
|
||||
case "userId":
|
||||
user = await prisma.user.update({
|
||||
where: { id: Number(identifier) },
|
||||
data: { locked: true },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true,
|
||||
},
|
||||
});
|
||||
break;
|
||||
case "email":
|
||||
user = await prisma.user.update({
|
||||
where: { email: identifier },
|
||||
data: { locked: true },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true,
|
||||
},
|
||||
});
|
||||
break;
|
||||
case "apiKey":
|
||||
const hashedApiKey = hashAPIKey(identifier);
|
||||
const apiKey = await prisma.apiKey.findUnique({
|
||||
where: { hashedKey: hashedApiKey },
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!apiKey?.user) {
|
||||
throw new Error("No user found for this API key.");
|
||||
}
|
||||
|
||||
user = await prisma.user.update({
|
||||
where: { id: apiKey.user.id },
|
||||
data: { locked: true },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true,
|
||||
},
|
||||
});
|
||||
break;
|
||||
// Leaving SMS here but it is handled differently via checkRateLimitForSMS that auto locks
|
||||
case "SMS":
|
||||
break;
|
||||
default:
|
||||
throw new Error("Invalid identifier type for locking");
|
||||
}
|
||||
|
||||
if (user && process.env.NEXT_PUBLIC_SENTRY_DSN) {
|
||||
log.warn(lockReason, {
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
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/lib/server/repository/membership";
|
||||
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import { CreditType } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -60,7 +60,7 @@ vi.mock("@calcom/prisma/enums", async (importOriginal) => {
|
||||
});
|
||||
|
||||
vi.mock("@calcom/lib/server/repository/credits");
|
||||
vi.mock("@calcom/lib/server/repository/membership");
|
||||
vi.mock("@calcom/features/membership/repositories/MembershipRepository");
|
||||
vi.mock("@calcom/lib/server/repository/team");
|
||||
vi.mock("@calcom/emails/email-manager");
|
||||
vi.mock("../workflows/lib/reminders/reminderScheduler", () => ({
|
||||
|
||||
@@ -12,7 +12,7 @@ import { IS_SMS_CREDITS_ENABLED } from "@calcom/lib/constants";
|
||||
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/lib/server/repository/membership";
|
||||
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import prisma, { type PrismaTransaction } from "@calcom/prisma";
|
||||
import type { CreditUsageType } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -4,7 +4,7 @@ import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { addNewMembersToEventTypes } from "@calcom/features/ee/teams/lib/queries";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { IdentityProvider, MembershipRole } from "@calcom/prisma/enums";
|
||||
import {
|
||||
|
||||
@@ -4,7 +4,7 @@ import removeUserFromOrg from "@calcom/features/ee/dsync/lib/removeUserFromOrg";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
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";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import { createAProfileForAnExistingUser } from "@calcom/lib/createAProfileForAnExistingUser";
|
||||
import { createAProfileForAnExistingUser } from "@calcom/features/profile/lib/createAProfileForAnExistingUser";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { sendExistingUserTeamInviteEmails } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
|
||||
import type { UserWithMembership } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { TeamService } from "@calcom/lib/server/service/teamService";
|
||||
import { TeamService } from "@calcom/features/ee/teams/services/teamService";
|
||||
|
||||
const removeUserFromOrg = async ({ userId, orgId }: { userId: number; orgId: number }) => {
|
||||
return TeamService.removeMembers({ teamIds: [orgId], userIds: [userId], isOrg: true });
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
|
||||
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { IdentityProvider } from "@calcom/prisma/enums";
|
||||
import { CreationSource, MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import { createAProfileForAnExistingUser } from "@calcom/lib/createAProfileForAnExistingUser";
|
||||
import { createAProfileForAnExistingUser } from "@calcom/features/profile/lib/createAProfileForAnExistingUser";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { UserWithMembership } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import { ensureOrganizationIsReviewed } from "@calcom/ee/organizations/lib/ensur
|
||||
import { getOrgFullOrigin, subdomainSuffix } from "@calcom/ee/organizations/lib/orgDomains";
|
||||
import { getSession } from "@calcom/features/auth/lib/getSession";
|
||||
import { getSpecificPermissions } from "@calcom/features/pbac/lib/resource-permissions";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { User } from "@calcom/prisma/client";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { OrganizationOnboardingRepository } from "@calcom/lib/server/repository/organizationOnboarding";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { OrganizationOnboarding } from "@calcom/prisma/client";
|
||||
import { UserPermissionRole, type BillingPeriod } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -2,7 +2,7 @@ import { UserPermissionRole } from "@calcom/kysely/types";
|
||||
import { ORGANIZATION_SELF_SERVE_MIN_SEATS, ORGANIZATION_SELF_SERVE_PRICE } from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { OrganizationRepository } from "@calcom/lib/server/repository/organization";
|
||||
import { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { OrganizationRepository } from "@calcom/lib/server/repository/organization";
|
||||
import { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
|
||||
|
||||
/**
|
||||
* It assumes that a user can only impersonate the members of the organization he is logged in to.
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { getOrgFullOrigin } from "@calcom/ee/organizations/lib/orgDomains";
|
||||
|
||||
export const getBookerBaseUrlSync = (
|
||||
orgSlug: string | null,
|
||||
options?: {
|
||||
protocol: boolean;
|
||||
}
|
||||
) => {
|
||||
return getOrgFullOrigin(orgSlug ?? "", options);
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
import { getBrand } from "@calcom/features/ee/organizations/lib/getBrand";
|
||||
import { WEBSITE_URL } from "@calcom/lib/constants";
|
||||
|
||||
export const getBookerBaseUrl = async (organizationId: number | null) => {
|
||||
const orgBrand = await getBrand(organizationId);
|
||||
return orgBrand?.fullDomain ?? WEBSITE_URL;
|
||||
};
|
||||
|
||||
export const getTeamBookerUrl = async (team: { organizationId: number | null }) => {
|
||||
const orgBrand = await getBrand(team.organizationId);
|
||||
return orgBrand?.fullDomain ?? WEBSITE_URL;
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
import { subdomainSuffix, getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
export const getBrand = async (orgId: number | null) => {
|
||||
if (!orgId) {
|
||||
return null;
|
||||
}
|
||||
const org = await prisma.team.findUnique({
|
||||
where: {
|
||||
id: orgId,
|
||||
},
|
||||
select: {
|
||||
logoUrl: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
metadata: true,
|
||||
isPlatform: true,
|
||||
},
|
||||
});
|
||||
if (!org) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// platform orgs don't have a brand nor a domain
|
||||
if (org.isPlatform) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const metadata = teamMetadataSchema.parse(org.metadata);
|
||||
const slug = (org.slug || metadata?.requestedSlug) as string;
|
||||
const fullDomain = getOrgFullOrigin(slug);
|
||||
const domainSuffix = subdomainSuffix();
|
||||
|
||||
return {
|
||||
...org,
|
||||
metadata,
|
||||
slug,
|
||||
fullDomain,
|
||||
domainSuffix,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, it, vi, expect } from "vitest";
|
||||
|
||||
import * as getBookerBaseUrlSyncExport from "@calcom/features/ee/organizations/lib/getBookerBaseUrlSync";
|
||||
|
||||
import { getTeamUrlSync } from "./getTeamUrlSync";
|
||||
|
||||
vi.mock("@calcom/features/ee/organizations/lib/getBookerBaseUrlSync", async () => {
|
||||
return {
|
||||
getBookerBaseUrlSync: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
describe("getBookerUrl:client", () => {
|
||||
describe("getTeamUrlSync", () => {
|
||||
it("if orgSlug is null, it should return a URL with /team in it", () => {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
getBookerBaseUrlSyncExport.getBookerBaseUrlSync.mockReturnValueOnce("https://abc.com");
|
||||
const url = getTeamUrlSync({ orgSlug: null, teamSlug: "myTeam" });
|
||||
expect(url).toBe("https://abc.com/team/myTeam");
|
||||
});
|
||||
|
||||
it("if orgSlug is set, it should return a URL without /team in it", () => {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
getBookerBaseUrlSyncExport.getBookerBaseUrlSync.mockReturnValueOnce("https://acme.com");
|
||||
const url = getTeamUrlSync({ orgSlug: "acme", teamSlug: "myTeam" });
|
||||
expect(url).toBe("https://acme.com/myTeam");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import { getBookerBaseUrlSync } from "@calcom/features/ee/organizations/lib/getBookerBaseUrlSync";
|
||||
|
||||
export const getTeamUrlSync = (
|
||||
{
|
||||
orgSlug,
|
||||
teamSlug,
|
||||
}: {
|
||||
orgSlug: string | null;
|
||||
teamSlug: string | null;
|
||||
},
|
||||
options?: {
|
||||
protocol: boolean;
|
||||
}
|
||||
) => {
|
||||
const bookerUrl = getBookerBaseUrlSync(orgSlug, options);
|
||||
teamSlug = teamSlug || "";
|
||||
if (orgSlug) {
|
||||
return `${bookerUrl}/${teamSlug}`;
|
||||
}
|
||||
return `${bookerUrl}/team/${teamSlug}`;
|
||||
};
|
||||
@@ -16,9 +16,9 @@ import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { DeploymentRepository } from "@calcom/lib/server/repository/deployment";
|
||||
import { OrganizationRepository } from "@calcom/lib/server/repository/organization";
|
||||
import { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
|
||||
import { OrganizationOnboardingRepository } from "@calcom/lib/server/repository/organizationOnboarding";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
import { createDomain } from "@calcom/lib/domainManager/organization";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { UserPermissionRole } from "@calcom/prisma/enums";
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import { trackFormbricksAction } from "@calcom/lib/formbricks-client";
|
||||
import type { OrganizationRepository } from "@calcom/lib/server/repository/organization";
|
||||
import type { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { OrganizationRepository } from "@calcom/lib/server/repository/organization";
|
||||
import type { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
|
||||
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
|
||||
|
||||
import OtherTeamList from "./OtherTeamList";
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import prismock from "../../../../../tests/libs/__mocks__/prisma";
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
|
||||
import { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
|
||||
vi.mock("@calcom/lib/server/repository/teamUtils", () => ({
|
||||
getParsedTeam: (org: any) => org,
|
||||
}));
|
||||
|
||||
async function createOrganization(
|
||||
data: Prisma.TeamCreateInput & {
|
||||
organizationSettings: {
|
||||
create: Prisma.OrganizationSettingsCreateWithoutOrganizationInput;
|
||||
};
|
||||
}
|
||||
) {
|
||||
return await prismock.team.create({
|
||||
data: {
|
||||
isOrganization: true,
|
||||
...data,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function createReviewedOrganization({
|
||||
name = "Test Org",
|
||||
orgAutoAcceptEmail,
|
||||
}: {
|
||||
name: string;
|
||||
orgAutoAcceptEmail: string;
|
||||
}) {
|
||||
return await createOrganization({
|
||||
name,
|
||||
organizationSettings: {
|
||||
create: {
|
||||
orgAutoAcceptEmail,
|
||||
isOrganizationVerified: true,
|
||||
isAdminReviewed: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function createTeam({
|
||||
name = "Test Team",
|
||||
orgAutoAcceptEmail,
|
||||
}: {
|
||||
name: string;
|
||||
orgAutoAcceptEmail: string;
|
||||
}) {
|
||||
return await prismock.team.create({
|
||||
data: {
|
||||
name,
|
||||
isOrganization: false,
|
||||
organizationSettings: {
|
||||
create: {
|
||||
orgAutoAcceptEmail,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetAllMocks();
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
await prismock.reset();
|
||||
});
|
||||
|
||||
describe("Organization.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail", () => {
|
||||
it("should return null if no organization matches the email domain", async () => {
|
||||
const result = await OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail({
|
||||
email: "[email protected]",
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should throw an error if multiple organizations match the email domain", async () => {
|
||||
await createReviewedOrganization({ name: "Test Org 1", orgAutoAcceptEmail: "example.com" });
|
||||
await createReviewedOrganization({ name: "Test Org 2", orgAutoAcceptEmail: "example.com" });
|
||||
|
||||
await expect(
|
||||
OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail({ email: "[email protected]" })
|
||||
).rejects.toThrow("Multiple organizations found with the same auto accept email domain");
|
||||
});
|
||||
|
||||
it("should return the parsed organization if a single match is found", async () => {
|
||||
const organization = await createReviewedOrganization({
|
||||
name: "Test Org",
|
||||
orgAutoAcceptEmail: "example.com",
|
||||
});
|
||||
|
||||
const result = await OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail({
|
||||
email: "[email protected]",
|
||||
});
|
||||
|
||||
expect(result).toEqual(organization);
|
||||
});
|
||||
|
||||
it("should not confuse a team with organization", async () => {
|
||||
await createTeam({ name: "Test Team", orgAutoAcceptEmail: "example.com" });
|
||||
|
||||
const result = await OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail({
|
||||
email: "[email protected]",
|
||||
});
|
||||
|
||||
expect(result).toEqual(null);
|
||||
});
|
||||
|
||||
it("should correctly match orgAutoAcceptEmail", async () => {
|
||||
await createReviewedOrganization({ name: "Test Org", orgAutoAcceptEmail: "noexample.com" });
|
||||
|
||||
const result = await OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail({
|
||||
email: "[email protected]",
|
||||
});
|
||||
|
||||
expect(result).toEqual(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Organization.getVerifiedOrganizationByAutoAcceptEmailDomain", () => {
|
||||
it("should return organization when domain matches and organization is verified", async () => {
|
||||
const verifiedOrganization = await createOrganization({
|
||||
name: "Test Org",
|
||||
organizationSettings: { create: { orgAutoAcceptEmail: "cal.com", isOrganizationVerified: true } },
|
||||
});
|
||||
|
||||
const result = await OrganizationRepository.getVerifiedOrganizationByAutoAcceptEmailDomain("cal.com");
|
||||
|
||||
expect(result).toEqual({
|
||||
id: verifiedOrganization.id,
|
||||
organizationSettings: {
|
||||
orgAutoAcceptEmail: "cal.com",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should not return organization when organization is not verified", async () => {
|
||||
await createOrganization({
|
||||
name: "Test Org",
|
||||
organizationSettings: { create: { orgAutoAcceptEmail: "cal.com", isOrganizationVerified: false } },
|
||||
});
|
||||
|
||||
const result = await OrganizationRepository.getVerifiedOrganizationByAutoAcceptEmailDomain("cal.com");
|
||||
|
||||
expect(result).toEqual(null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,478 @@
|
||||
import type { z } from "zod";
|
||||
|
||||
import { getOrgUsernameFromEmail } from "@calcom/features/auth/signup/utils/getOrgUsernameFromEmail";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import { createAProfileForAnExistingUser } from "@calcom/features/profile/lib/createAProfileForAnExistingUser";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getParsedTeam } from "@calcom/lib/server/repository/teamUtils";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import type { CreationSource } from "@calcom/prisma/enums";
|
||||
import type { teamMetadataStrictSchema } from "@calcom/prisma/zod-utils";
|
||||
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
const orgSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
logoUrl: true,
|
||||
};
|
||||
|
||||
export class OrganizationRepository {
|
||||
static async createWithExistingUserAsOwner({
|
||||
orgData,
|
||||
owner,
|
||||
}: {
|
||||
orgData: {
|
||||
name: string;
|
||||
slug: string | null;
|
||||
isOrganizationConfigured: boolean;
|
||||
isOrganizationAdminReviewed: boolean;
|
||||
autoAcceptEmail: string;
|
||||
seats: number | null;
|
||||
pricePerSeat: number | null;
|
||||
isPlatform: boolean;
|
||||
billingPeriod?: "MONTHLY" | "ANNUALLY";
|
||||
logoUrl: string | null;
|
||||
bio: string | null;
|
||||
requestedSlug?: string | null;
|
||||
};
|
||||
owner: {
|
||||
id: number;
|
||||
email: string;
|
||||
nonOrgUsername: string;
|
||||
};
|
||||
}) {
|
||||
logger.debug("createWithExistingUserAsOwner", safeStringify({ orgData, owner }));
|
||||
const organization = await this.create(orgData);
|
||||
const ownerProfile = await createAProfileForAnExistingUser({
|
||||
user: {
|
||||
id: owner.id,
|
||||
email: owner.email,
|
||||
currentUsername: owner.nonOrgUsername,
|
||||
},
|
||||
organizationId: organization.id,
|
||||
});
|
||||
|
||||
await prisma.membership.create({
|
||||
data: {
|
||||
createdAt: new Date(),
|
||||
userId: owner.id,
|
||||
role: MembershipRole.OWNER,
|
||||
accepted: true,
|
||||
teamId: organization.id,
|
||||
},
|
||||
});
|
||||
return { organization, ownerProfile };
|
||||
}
|
||||
|
||||
static async createWithNonExistentOwner({
|
||||
orgData,
|
||||
owner,
|
||||
creationSource,
|
||||
}: {
|
||||
orgData: {
|
||||
name: string;
|
||||
slug: string;
|
||||
isOrganizationConfigured: boolean;
|
||||
isOrganizationAdminReviewed: boolean;
|
||||
autoAcceptEmail: string;
|
||||
seats: number | null;
|
||||
billingPeriod?: "MONTHLY" | "ANNUALLY";
|
||||
pricePerSeat: number | null;
|
||||
isPlatform: boolean;
|
||||
logoUrl: string | null;
|
||||
bio: string | null;
|
||||
};
|
||||
owner: {
|
||||
email: string;
|
||||
};
|
||||
creationSource: CreationSource;
|
||||
}) {
|
||||
logger.debug("createWithNonExistentOwner", safeStringify({ orgData, owner }));
|
||||
const organization = await this.create(orgData);
|
||||
const ownerUsernameInOrg = getOrgUsernameFromEmail(owner.email, orgData.autoAcceptEmail);
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const ownerInDb = await userRepo.create({
|
||||
email: owner.email,
|
||||
username: ownerUsernameInOrg,
|
||||
organizationId: organization.id,
|
||||
locked: false,
|
||||
creationSource,
|
||||
});
|
||||
|
||||
await prisma.membership.create({
|
||||
data: {
|
||||
createdAt: new Date(),
|
||||
userId: ownerInDb.id,
|
||||
role: MembershipRole.OWNER,
|
||||
accepted: true,
|
||||
teamId: organization.id,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
orgOwner: ownerInDb,
|
||||
organization,
|
||||
ownerProfile: {
|
||||
username: ownerUsernameInOrg,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
static async create(orgData: {
|
||||
name: string;
|
||||
slug: string | null;
|
||||
isOrganizationConfigured: boolean;
|
||||
isOrganizationAdminReviewed: boolean;
|
||||
autoAcceptEmail: string;
|
||||
seats: number | null;
|
||||
billingPeriod?: "MONTHLY" | "ANNUALLY";
|
||||
pricePerSeat: number | null;
|
||||
isPlatform: boolean;
|
||||
logoUrl: string | null;
|
||||
bio: string | null;
|
||||
requestedSlug?: string | null;
|
||||
}) {
|
||||
return await prisma.team.create({
|
||||
data: {
|
||||
name: orgData.name,
|
||||
isOrganization: true,
|
||||
slug: orgData.slug,
|
||||
// This is huge and causes issues, we need to have the logic to convert logo to logoUrl and then use that url ehre.
|
||||
// logoUrl: orgData.logoUrl,
|
||||
bio: orgData.bio,
|
||||
organizationSettings: {
|
||||
create: {
|
||||
isAdminReviewed: orgData.isOrganizationAdminReviewed,
|
||||
isOrganizationVerified: true,
|
||||
isOrganizationConfigured: orgData.isOrganizationConfigured,
|
||||
orgAutoAcceptEmail: orgData.autoAcceptEmail,
|
||||
},
|
||||
},
|
||||
metadata: {
|
||||
isPlatform: orgData.isPlatform,
|
||||
|
||||
// We still have a case where we don't have slug set directly on organization. The reason is because we want to create an org first(with same slug as another regular team) and then move the team to org.
|
||||
// Because in such cases there is a fallback existing at multiple places to use requestedSlug, we set it here still :(
|
||||
requestedSlug: orgData.requestedSlug,
|
||||
|
||||
// We set these here still because some parts of code read it from metadata. This data exists in OrganizationOnboarding as well and should be used from there ideally
|
||||
// We also need to think about existing Organizations that might not have OrganizationOnboarding, before taking any decision
|
||||
orgSeats: orgData.seats,
|
||||
orgPricePerSeat: orgData.pricePerSeat,
|
||||
billingPeriod: orgData.billingPeriod,
|
||||
},
|
||||
isPlatform: orgData.isPlatform,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findById({ id }: { id: number }) {
|
||||
return prisma.team.findUnique({
|
||||
where: {
|
||||
id,
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findBySlug({ slug }: { slug: string }) {
|
||||
// Slug is unique but could be null as well, so we can't use findUnique
|
||||
return prisma.team.findFirst({
|
||||
where: {
|
||||
slug,
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findBySlugIncludeOnboarding({ slug }: { slug: string }) {
|
||||
return prisma.team.findFirst({
|
||||
where: { slug, isOrganization: true },
|
||||
include: {
|
||||
organizationOnboarding: {
|
||||
select: {
|
||||
id: true,
|
||||
isDomainConfigured: true,
|
||||
isPlatform: true,
|
||||
slug: true,
|
||||
teams: true,
|
||||
invitedMembers: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findByIdIncludeOrganizationSettings({ id }: { id: number }) {
|
||||
return prisma.team.findUnique({
|
||||
where: {
|
||||
id,
|
||||
isOrganization: true,
|
||||
},
|
||||
select: {
|
||||
...orgSelect,
|
||||
organizationSettings: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail({ email }: { email: string }) {
|
||||
const emailDomain = email.split("@").at(-1);
|
||||
const orgs = await prisma.team.findMany({
|
||||
where: {
|
||||
isOrganization: true,
|
||||
isPlatform: false,
|
||||
organizationSettings: {
|
||||
orgAutoAcceptEmail: emailDomain,
|
||||
isOrganizationVerified: true,
|
||||
isAdminReviewed: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
if (orgs.length > 1) {
|
||||
logger.error(
|
||||
"Multiple organizations found with the same auto accept email domain",
|
||||
safeStringify({ orgs, emailDomain })
|
||||
);
|
||||
// Detect and fail just in case this situation arises. We should really identify the problem in this case and fix the data.
|
||||
throw new Error("Multiple organizations found with the same auto accept email domain");
|
||||
}
|
||||
const org = orgs[0];
|
||||
if (!org) {
|
||||
return null;
|
||||
}
|
||||
return getParsedTeam(org);
|
||||
}
|
||||
|
||||
static async findCurrentOrg({ userId, orgId }: { userId: number; orgId: number }) {
|
||||
const membership = await prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_teamId: {
|
||||
userId,
|
||||
teamId: orgId,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
team: true,
|
||||
},
|
||||
});
|
||||
|
||||
const organizationSettings = await prisma.organizationSettings.findUnique({
|
||||
where: {
|
||||
organizationId: orgId,
|
||||
},
|
||||
select: {
|
||||
lockEventTypeCreationForUsers: true,
|
||||
adminGetsNoSlotsNotification: true,
|
||||
isAdminReviewed: true,
|
||||
allowSEOIndexing: true,
|
||||
orgProfileRedirectsToVerifiedDomain: true,
|
||||
orgAutoAcceptEmail: true,
|
||||
disablePhoneOnlySMSNotifications: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new Error("You do not have a membership to your organization");
|
||||
}
|
||||
|
||||
const metadata = teamMetadataSchema.parse(membership?.team.metadata);
|
||||
|
||||
return {
|
||||
canAdminImpersonate: !!organizationSettings?.isAdminReviewed,
|
||||
organizationSettings: {
|
||||
lockEventTypeCreationForUsers: organizationSettings?.lockEventTypeCreationForUsers,
|
||||
adminGetsNoSlotsNotification: organizationSettings?.adminGetsNoSlotsNotification,
|
||||
allowSEOIndexing: organizationSettings?.allowSEOIndexing,
|
||||
orgProfileRedirectsToVerifiedDomain: organizationSettings?.orgProfileRedirectsToVerifiedDomain,
|
||||
orgAutoAcceptEmail: organizationSettings?.orgAutoAcceptEmail,
|
||||
disablePhoneOnlySMSNotifications: organizationSettings?.disablePhoneOnlySMSNotifications,
|
||||
},
|
||||
user: {
|
||||
role: membership?.role,
|
||||
accepted: membership?.accepted,
|
||||
},
|
||||
...membership?.team,
|
||||
metadata,
|
||||
};
|
||||
}
|
||||
|
||||
static async findTeamsInOrgIamNotPartOf({ userId, parentId }: { userId: number; parentId: number | null }) {
|
||||
const teamsInOrgIamNotPartOf = await prisma.team.findMany({
|
||||
where: {
|
||||
parentId,
|
||||
members: {
|
||||
none: {
|
||||
userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
parentId: true,
|
||||
id: true,
|
||||
name: true,
|
||||
logoUrl: true,
|
||||
slug: true,
|
||||
},
|
||||
});
|
||||
|
||||
return teamsInOrgIamNotPartOf;
|
||||
}
|
||||
|
||||
static async adminFindById({ id }: { id: number }) {
|
||||
const org = await prisma.team.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
metadata: true,
|
||||
isOrganization: true,
|
||||
members: {
|
||||
where: {
|
||||
role: "OWNER",
|
||||
},
|
||||
select: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
organizationSettings: {
|
||||
select: {
|
||||
isOrganizationConfigured: true,
|
||||
isOrganizationVerified: true,
|
||||
orgAutoAcceptEmail: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!org) {
|
||||
throw new Error("Organization not found");
|
||||
}
|
||||
|
||||
const parsedMetadata = teamMetadataSchema.parse(org.metadata);
|
||||
if (!org?.isOrganization) {
|
||||
throw new Error("Organization not found");
|
||||
}
|
||||
return { ...org, metadata: parsedMetadata };
|
||||
}
|
||||
|
||||
static async findByMemberEmail({ email }: { email: string }) {
|
||||
const organization = await prisma.team.findFirst({
|
||||
where: {
|
||||
isOrganization: true,
|
||||
members: {
|
||||
some: {
|
||||
user: { email },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return organization ?? null;
|
||||
}
|
||||
|
||||
static async findByMemberEmailId({ email }: { email: string }) {
|
||||
const log = logger.getSubLogger({ prefix: ["findByMemberEmailId"] });
|
||||
log.debug("called with", { email });
|
||||
const organization = await prisma.team.findFirst({
|
||||
where: {
|
||||
isOrganization: true,
|
||||
members: {
|
||||
some: {
|
||||
user: {
|
||||
email,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return organization;
|
||||
}
|
||||
|
||||
static async findCalVideoLogoByOrgId({ id }: { id: number }) {
|
||||
const org = await prisma.team.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
select: {
|
||||
calVideoLogo: true,
|
||||
},
|
||||
});
|
||||
|
||||
return org?.calVideoLogo;
|
||||
}
|
||||
|
||||
static async getVerifiedOrganizationByAutoAcceptEmailDomain(domain: string) {
|
||||
return await prisma.team.findFirst({
|
||||
where: {
|
||||
organizationSettings: {
|
||||
isOrganizationVerified: true,
|
||||
orgAutoAcceptEmail: domain,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
organizationSettings: {
|
||||
select: {
|
||||
orgAutoAcceptEmail: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async setSlug({ id, slug }: { id: number; slug: string }) {
|
||||
return await prisma.team.update({
|
||||
where: { id, isOrganization: true },
|
||||
data: { slug },
|
||||
});
|
||||
}
|
||||
|
||||
static async updateStripeSubscriptionDetails({
|
||||
id,
|
||||
stripeSubscriptionId,
|
||||
stripeSubscriptionItemId,
|
||||
existingMetadata,
|
||||
}: {
|
||||
id: number;
|
||||
stripeSubscriptionId: string;
|
||||
stripeSubscriptionItemId: string;
|
||||
existingMetadata: z.infer<typeof teamMetadataStrictSchema>;
|
||||
}) {
|
||||
return await prisma.team.update({
|
||||
where: { id, isOrganization: true },
|
||||
data: {
|
||||
metadata: {
|
||||
...existingMetadata,
|
||||
subscriptionId: stripeSubscriptionId,
|
||||
subscriptionItemId: stripeSubscriptionItemId,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async checkIfPrivate({ orgId }: { orgId: number }) {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: {
|
||||
id: orgId,
|
||||
isOrganization: true,
|
||||
},
|
||||
select: {
|
||||
isPrivate: true,
|
||||
},
|
||||
});
|
||||
|
||||
return team?.isPrivate ?? false;
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import type { SyntheticEvent } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import getStripe from "@calcom/app-store/stripepayment/lib/client";
|
||||
import { useBookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
|
||||
import { useBookingSuccessRedirect } from "@calcom/features/bookings/lib/bookingSuccessRedirect";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import { getClientSecretFromPayment } from "@calcom/features/ee/payments/pages/getClientSecretFromPayment";
|
||||
import { shouldHideBrandingForEvent } from "@calcom/lib/hideBranding";
|
||||
import { shouldHideBrandingForEvent } from "@calcom/features/profile/lib/hideBranding";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { BookingStatus } from "@calcom/prisma/enums";
|
||||
import { paymentDataSelect } from "@calcom/prisma/selects/payment";
|
||||
|
||||
@@ -18,7 +18,7 @@ import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAn
|
||||
import { describe, vi, expect } from "vitest";
|
||||
|
||||
import { OrganizerDefaultConferencingAppType } from "@calcom/app-store/locations";
|
||||
import { BookingRepository } from "@calcom/lib/server/repository/booking";
|
||||
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
|
||||
import { SchedulingType, BookingStatus, WorkflowMethods } from "@calcom/prisma/enums";
|
||||
import { test } from "@calcom/web/test/fixtures/fixtures";
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ import { scheduleWorkflowReminders } from "@calcom/features/ee/workflows/lib/rem
|
||||
import { getEventName } from "@calcom/features/eventtypes/lib/eventNaming";
|
||||
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
|
||||
import { SENDER_NAME } from "@calcom/lib/constants";
|
||||
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
|
||||
import { getBookerBaseUrl } from "@calcom/features/ee/organizations/lib/getBookerUrlServer";
|
||||
import { IdempotencyKeyService } from "@calcom/lib/idempotencyKey/idempotencyKeyService";
|
||||
import { isPrismaObjOrUndefined } from "@calcom/lib/isPrismaObj";
|
||||
import logger from "@calcom/lib/logger";
|
||||
|
||||
@@ -17,7 +17,7 @@ import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAn
|
||||
|
||||
import { describe, vi, expect } from "vitest";
|
||||
|
||||
import { BookingRepository } from "@calcom/lib/server/repository/booking";
|
||||
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
|
||||
import { SchedulingType, BookingStatus, WorkflowMethods } from "@calcom/prisma/enums";
|
||||
import { test } from "@calcom/web/test/fixtures/fixtures";
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import createUsersAndConnectToOrg from "@calcom/features/ee/dsync/lib/users/createUsersAndConnectToOrg";
|
||||
import { HOSTED_CAL_FEATURES } from "@calcom/lib/constants";
|
||||
import { OrganizationRepository } from "@calcom/lib/server/repository/organization";
|
||||
import { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { IdentityProvider } from "@calcom/prisma/enums";
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ import InviteLinkSettingsModal from "@calcom/ee/teams/components/InviteLinkSetti
|
||||
import { MemberInvitationModalWithoutMembers } from "@calcom/ee/teams/components/MemberInvitationModal";
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { getTeamUrlSync } from "@calcom/features/ee/organizations/lib/getTeamUrlSync";
|
||||
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
|
||||
import { getTeamUrlSync } from "@calcom/lib/getBookerUrl/client";
|
||||
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useRefreshData } from "@calcom/lib/hooks/useRefreshData";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
|
||||
import { WorkflowRepository } from "@calcom/features/ee/workflows/repositories/WorkflowRepository";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
// cancel/delete all workflowReminders of the removed member that come from that team (org teams only)
|
||||
|
||||
@@ -2,12 +2,12 @@ import { z } from "zod";
|
||||
|
||||
import { getAppFromSlug } from "@calcom/app-store/utils";
|
||||
import { DATABASE_CHUNK_SIZE } from "@calcom/lib/constants";
|
||||
import { getBookerBaseUrlSync } from "@calcom/lib/getBookerUrl/client";
|
||||
import { getBookerBaseUrlSync } from "@calcom/features/ee/organizations/lib/getBookerBaseUrlSync";
|
||||
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 { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
|
||||
@@ -10,11 +10,11 @@ import { z } from "zod";
|
||||
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { getTeamUrlSync } from "@calcom/features/ee/organizations/lib/getTeamUrlSync";
|
||||
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
|
||||
import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
|
||||
import { trackFormbricksAction } from "@calcom/lib/formbricks-client";
|
||||
import { getTeamUrlSync } from "@calcom/lib/getBookerUrl/client";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import { md } from "@calcom/lib/markdownIt";
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { prisma } from "@calcom/prisma/__mocks__/prisma";
|
||||
|
||||
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 { TeamService } from "./teamService";
|
||||
|
||||
vi.mock("@calcom/prisma", () => ({
|
||||
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/lib/domainManager/organization");
|
||||
vi.mock("@calcom/features/ee/teams/lib/removeMember");
|
||||
class Database {
|
||||
teams = new Map();
|
||||
domains = new Set();
|
||||
billings = new Map();
|
||||
workflowReminders = new Map();
|
||||
clear() {
|
||||
this.teams.clear();
|
||||
this.domains.clear();
|
||||
this.billings.clear();
|
||||
this.workflowReminders.clear();
|
||||
}
|
||||
}
|
||||
// In-memory database for testing
|
||||
const database = new Database();
|
||||
|
||||
const mockTeamBilling = {
|
||||
cancel: vi.fn(),
|
||||
updateQuantity: vi.fn(),
|
||||
publish: vi.fn(),
|
||||
downgrade: vi.fn(),
|
||||
};
|
||||
|
||||
// Mock implementations that modify the in-memory database
|
||||
const mockTeamRepo = {
|
||||
deleteById: vi.fn().mockImplementation(async ({ id }) => {
|
||||
const team = database.teams.get(id);
|
||||
if (team) {
|
||||
database.teams.delete(id);
|
||||
return team;
|
||||
}
|
||||
throw new Error(`Team with id ${id} not found`);
|
||||
}),
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(TeamRepository).mockImplementation(() => mockTeamRepo as any);
|
||||
|
||||
vi.mocked(deleteDomain).mockImplementation(async (slug) => {
|
||||
database.domains.delete(slug);
|
||||
});
|
||||
|
||||
vi.mocked(WorkflowService.deleteWorkflowRemindersOfRemovedTeam).mockImplementation(async (teamId) => {
|
||||
database.workflowReminders.delete(teamId);
|
||||
});
|
||||
|
||||
vi.mocked(TeamBilling.findAndInit).mockImplementation(async (teamId) => {
|
||||
// Create a team-specific billing mock
|
||||
const teamSpecificBilling = {
|
||||
...mockTeamBilling,
|
||||
teamId,
|
||||
cancel: vi.fn().mockImplementation(() => {
|
||||
const billing = database.billings.get(teamId);
|
||||
if (billing) {
|
||||
billing.cancelled = true;
|
||||
}
|
||||
}),
|
||||
};
|
||||
return teamSpecificBilling;
|
||||
});
|
||||
|
||||
describe("TeamService", () => {
|
||||
beforeEach(() => {
|
||||
database.clear();
|
||||
|
||||
database.teams.set(1, {
|
||||
id: 1,
|
||||
name: "Deleted Team",
|
||||
isOrganization: true,
|
||||
slug: "deleted-team",
|
||||
});
|
||||
database.domains.add("deleted-team");
|
||||
database.billings.set(1, { teamId: 1, cancelled: false });
|
||||
database.workflowReminders.set(1, ["reminder1", "reminder2"]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("delete", () => {
|
||||
it("should delete team, cancel billing, and clean up", async () => {
|
||||
const result = await TeamService.delete({ id: 1 });
|
||||
|
||||
// Verify the team was deleted from the database
|
||||
expect(database.teams.has(1)).toBe(false);
|
||||
|
||||
// Verify the domain was deleted
|
||||
expect(database.domains.has("deleted-team")).toBe(false);
|
||||
|
||||
// Verify billing was cancelled
|
||||
expect(database.billings.get(1)?.cancelled).toBe(true);
|
||||
|
||||
// Verify workflow reminders were deleted
|
||||
expect(database.workflowReminders.has(1)).toBe(false);
|
||||
|
||||
// Verify the returned team data
|
||||
expect(result).toEqual({
|
||||
id: 1,
|
||||
name: "Deleted Team",
|
||||
isOrganization: true,
|
||||
slug: "deleted-team",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,400 @@
|
||||
import prismaMock from "../../../../../tests/libs/__mocks__/prismaMock";
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
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 type { Membership, Team, User, VerificationToken, Profile } from "@calcom/prisma/client";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
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/lib/domainManager/organization");
|
||||
vi.mock("@calcom/features/ee/teams/lib/removeMember");
|
||||
vi.mock("@calcom/features/profile/lib/createAProfileForAnExistingUser");
|
||||
vi.mock("@calcom/features/ee/teams/lib/queries");
|
||||
|
||||
const mockTeamBilling = {
|
||||
cancel: vi.fn(),
|
||||
updateQuantity: vi.fn(),
|
||||
publish: vi.fn(),
|
||||
downgrade: vi.fn(),
|
||||
};
|
||||
|
||||
vi.mocked(TeamBilling.findAndInit).mockResolvedValue(mockTeamBilling);
|
||||
|
||||
describe("TeamService", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(TeamBilling.findAndInit).mockResolvedValue(mockTeamBilling);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("delete", () => {
|
||||
it("should delete team, cancel billing, and clean up", async () => {
|
||||
const mockDeletedTeam = {
|
||||
id: 1,
|
||||
name: "Deleted Team",
|
||||
isOrganization: true,
|
||||
slug: "deleted-team",
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const mockTeamRepo = {
|
||||
deleteById: vi.fn().mockResolvedValue(mockDeletedTeam),
|
||||
} as Pick<TeamRepository, "deleteById">;
|
||||
vi.mocked(TeamRepository).mockImplementation(() => mockTeamRepo);
|
||||
|
||||
const result = await TeamService.delete({ id: 1 });
|
||||
|
||||
expect(TeamBilling.findAndInit).toHaveBeenCalledWith(1);
|
||||
expect(mockTeamBilling.cancel).toHaveBeenCalled();
|
||||
expect(WorkflowService.deleteWorkflowRemindersOfRemovedTeam).toHaveBeenCalledWith(1);
|
||||
expect(mockTeamRepo.deleteById).toHaveBeenCalledWith({ id: 1 });
|
||||
expect(deleteDomain).toHaveBeenCalledWith("deleted-team");
|
||||
expect(result).toEqual(mockDeletedTeam);
|
||||
});
|
||||
});
|
||||
|
||||
describe("inviteMemberByToken", () => {
|
||||
it("should throw error if verification token is not found", async () => {
|
||||
prismaMock.verificationToken.findFirst.mockResolvedValue(null);
|
||||
await expect(TeamService.inviteMemberByToken("invalid-token", 1)).rejects.toThrow(TRPCError);
|
||||
});
|
||||
|
||||
it("should create provisional membership and update billing", async () => {
|
||||
const mockToken = {
|
||||
teamId: 1,
|
||||
team: { name: "Test Team" },
|
||||
expiresInDays: null,
|
||||
expires: new Date(Date.now() + 86400000),
|
||||
token: "valid-token",
|
||||
identifier: "[email protected]",
|
||||
id: "1",
|
||||
};
|
||||
prismaMock.verificationToken.findFirst.mockResolvedValue(mockToken);
|
||||
prismaMock.membership.create.mockResolvedValue({} as Membership);
|
||||
|
||||
const result = await TeamService.inviteMemberByToken("valid-token", 1);
|
||||
|
||||
expect(prismaMock.membership.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
accepted: false,
|
||||
createdAt: expect.any(Date),
|
||||
role: MembershipRole.MEMBER,
|
||||
teamId: 1,
|
||||
userId: 1,
|
||||
},
|
||||
});
|
||||
expect(mockTeamBilling.updateQuantity).toHaveBeenCalled();
|
||||
expect(result).toBe("Test Team");
|
||||
});
|
||||
});
|
||||
|
||||
describe("acceptTeamMembership", () => {
|
||||
it("should accept membership and update event types for regular team", async () => {
|
||||
const mockMembership = {
|
||||
team: { id: 1, parentId: null, isOrganization: false },
|
||||
};
|
||||
|
||||
prismaMock.membership.update.mockResolvedValue(mockMembership as Membership & { team: Team });
|
||||
vi.mocked(updateNewTeamMemberEventTypes).mockResolvedValue(undefined);
|
||||
|
||||
await TeamService.acceptTeamMembership({
|
||||
userId: 1,
|
||||
teamId: 1,
|
||||
userEmail: "[email protected]",
|
||||
username: "testuser",
|
||||
});
|
||||
|
||||
expect(prismaMock.membership.update).toHaveBeenCalledWith({
|
||||
where: { userId_teamId: { userId: 1, teamId: 1 } },
|
||||
data: { accepted: true },
|
||||
select: { team: true },
|
||||
});
|
||||
expect(updateNewTeamMemberEventTypes).toHaveBeenCalledWith(1, 1);
|
||||
});
|
||||
|
||||
it("should accept membership and create profile for organization", async () => {
|
||||
const mockMembership = {
|
||||
team: { id: 1, parentId: null, isOrganization: true },
|
||||
};
|
||||
|
||||
prismaMock.membership.update.mockResolvedValue(mockMembership as Membership & { team: Team });
|
||||
vi.mocked(createAProfileForAnExistingUser).mockResolvedValue({} as Profile);
|
||||
vi.mocked(updateNewTeamMemberEventTypes).mockResolvedValue(undefined);
|
||||
|
||||
await TeamService.acceptTeamMembership({
|
||||
userId: 1,
|
||||
teamId: 1,
|
||||
userEmail: "[email protected]",
|
||||
username: "testuser",
|
||||
});
|
||||
|
||||
expect(createAProfileForAnExistingUser).toHaveBeenCalledWith({
|
||||
user: {
|
||||
id: 1,
|
||||
email: "[email protected]",
|
||||
currentUsername: "testuser",
|
||||
},
|
||||
organizationId: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("should accept membership and handle parent team for subteam", async () => {
|
||||
const mockMembership = {
|
||||
team: { id: 1, parentId: 2, isOrganization: false },
|
||||
};
|
||||
|
||||
prismaMock.membership.update
|
||||
.mockResolvedValueOnce(mockMembership as Membership & { team: Team })
|
||||
.mockResolvedValueOnce({} as Membership);
|
||||
vi.mocked(createAProfileForAnExistingUser).mockResolvedValue({} as Profile);
|
||||
vi.mocked(updateNewTeamMemberEventTypes).mockResolvedValue(undefined);
|
||||
|
||||
await TeamService.acceptTeamMembership({
|
||||
userId: 1,
|
||||
teamId: 1,
|
||||
userEmail: "[email protected]",
|
||||
username: "testuser",
|
||||
});
|
||||
|
||||
expect(prismaMock.membership.update).toHaveBeenCalledTimes(2);
|
||||
expect(prismaMock.membership.update).toHaveBeenNthCalledWith(2, {
|
||||
where: { userId_teamId: { userId: 1, teamId: 2 } },
|
||||
data: { accepted: true },
|
||||
});
|
||||
expect(createAProfileForAnExistingUser).toHaveBeenCalledWith({
|
||||
user: {
|
||||
id: 1,
|
||||
email: "[email protected]",
|
||||
currentUsername: "testuser",
|
||||
},
|
||||
organizationId: 2,
|
||||
});
|
||||
});
|
||||
});
|
||||
describe("leaveTeamMembership", () => {
|
||||
it("should delete membership when rejecting invitation", async () => {
|
||||
const mockMembership = {
|
||||
team: { id: 1, parentId: null },
|
||||
};
|
||||
|
||||
prismaMock.membership.delete.mockResolvedValue(mockMembership as Membership & { team: Team });
|
||||
|
||||
await TeamService.leaveTeamMembership({
|
||||
userId: 1,
|
||||
teamId: 1,
|
||||
});
|
||||
|
||||
expect(prismaMock.membership.delete).toHaveBeenCalledWith({
|
||||
where: { userId_teamId: { userId: 1, teamId: 1 } },
|
||||
select: { team: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("should delete parent membership when rejecting subteam invitation", async () => {
|
||||
const mockMembership = {
|
||||
team: { id: 1, parentId: 2 },
|
||||
};
|
||||
|
||||
prismaMock.membership.delete
|
||||
.mockResolvedValueOnce(mockMembership as Membership & { team: Team })
|
||||
.mockResolvedValueOnce({} as Membership);
|
||||
|
||||
await TeamService.leaveTeamMembership({
|
||||
userId: 1,
|
||||
teamId: 1,
|
||||
});
|
||||
|
||||
expect(prismaMock.membership.delete).toHaveBeenCalledTimes(2);
|
||||
expect(prismaMock.membership.delete).toHaveBeenNthCalledWith(2, {
|
||||
where: { userId_teamId: { userId: 1, teamId: 2 } },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("acceptInvitationByToken", () => {
|
||||
it("should throw error if verification token is not found", async () => {
|
||||
prismaMock.verificationToken.findFirst.mockResolvedValue(null);
|
||||
await expect(TeamService.acceptInvitationByToken("invalid-token", 1)).rejects.toThrow(TRPCError);
|
||||
});
|
||||
|
||||
it("should throw error if token is not associated with team", async () => {
|
||||
const mockToken = {
|
||||
teamId: null,
|
||||
team: null,
|
||||
identifier: "[email protected]",
|
||||
id: "1",
|
||||
};
|
||||
|
||||
prismaMock.verificationToken.findFirst.mockResolvedValue(
|
||||
mockToken as VerificationToken & { team: Team | null }
|
||||
);
|
||||
|
||||
await expect(TeamService.acceptInvitationByToken("valid-token", 1)).rejects.toThrow(
|
||||
new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Invite token is not associated with any team",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if user not found", async () => {
|
||||
const mockToken = {
|
||||
teamId: 1,
|
||||
team: { name: "Test Team" },
|
||||
identifier: "[email protected]",
|
||||
id: "1",
|
||||
};
|
||||
|
||||
prismaMock.verificationToken.findFirst.mockResolvedValue(
|
||||
mockToken as VerificationToken & { team: Team }
|
||||
);
|
||||
prismaMock.user.findUnique.mockResolvedValue(null);
|
||||
|
||||
await expect(TeamService.acceptInvitationByToken("valid-token", 1)).rejects.toThrow(
|
||||
new TRPCError({ code: "NOT_FOUND", message: "User not found" })
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if user email doesn't match token identifier", async () => {
|
||||
const mockToken = {
|
||||
teamId: 1,
|
||||
team: { name: "Test Team" },
|
||||
identifier: "[email protected]",
|
||||
id: "1",
|
||||
};
|
||||
|
||||
const mockUser = {
|
||||
email: "[email protected]",
|
||||
username: "testuser",
|
||||
};
|
||||
|
||||
prismaMock.verificationToken.findFirst.mockResolvedValue(
|
||||
mockToken as VerificationToken & { team: Team }
|
||||
);
|
||||
prismaMock.user.findUnique.mockResolvedValue(mockUser as User);
|
||||
|
||||
await expect(TeamService.acceptInvitationByToken("valid-token", 1)).rejects.toThrow(
|
||||
new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "This invitation is not for your account",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if user username doesn't match token identifier", async () => {
|
||||
const mockToken = {
|
||||
teamId: 1,
|
||||
team: { name: "Test Team" },
|
||||
identifier: "inviteduser",
|
||||
id: "1",
|
||||
};
|
||||
|
||||
const mockUser = {
|
||||
email: "[email protected]",
|
||||
username: "differentuser",
|
||||
};
|
||||
|
||||
prismaMock.verificationToken.findFirst.mockResolvedValue(
|
||||
mockToken as VerificationToken & { team: Team }
|
||||
);
|
||||
prismaMock.user.findUnique.mockResolvedValue(mockUser as User);
|
||||
|
||||
await expect(TeamService.acceptInvitationByToken("valid-token", 1)).rejects.toThrow(
|
||||
new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "This invitation is not for your account",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should accept invitation when user email matches token identifier", async () => {
|
||||
const mockToken = {
|
||||
teamId: 1,
|
||||
team: { name: "Test Team" },
|
||||
identifier: "[email protected]",
|
||||
id: "1",
|
||||
};
|
||||
|
||||
const mockUser = {
|
||||
email: "[email protected]",
|
||||
username: "testuser",
|
||||
};
|
||||
|
||||
const mockMembership = {
|
||||
team: { id: 1, parentId: null, isOrganization: false },
|
||||
};
|
||||
|
||||
prismaMock.verificationToken.findFirst.mockResolvedValue(
|
||||
mockToken as VerificationToken & { team: Team }
|
||||
);
|
||||
prismaMock.user.findUnique.mockResolvedValue(mockUser as User);
|
||||
prismaMock.membership.update.mockResolvedValue(mockMembership as Membership & { team: Team });
|
||||
vi.mocked(updateNewTeamMemberEventTypes).mockResolvedValue(undefined);
|
||||
|
||||
await TeamService.acceptInvitationByToken("valid-token", 1);
|
||||
|
||||
expect(prismaMock.membership.update).toHaveBeenCalledWith({
|
||||
where: { userId_teamId: { userId: 1, teamId: 1 } },
|
||||
data: { accepted: true },
|
||||
select: { team: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("should accept invitation when user username matches token identifier", async () => {
|
||||
const mockToken = {
|
||||
teamId: 1,
|
||||
team: { name: "Test Team" },
|
||||
identifier: "testuser",
|
||||
id: "1",
|
||||
};
|
||||
|
||||
const mockUser = {
|
||||
email: "[email protected]",
|
||||
username: "testuser",
|
||||
};
|
||||
|
||||
const mockMembership = {
|
||||
team: { id: 1, parentId: null, isOrganization: false },
|
||||
};
|
||||
|
||||
prismaMock.verificationToken.findFirst.mockResolvedValue(
|
||||
mockToken as VerificationToken & { team: Team }
|
||||
);
|
||||
prismaMock.user.findUnique.mockResolvedValue(mockUser as User);
|
||||
prismaMock.membership.update.mockResolvedValue(mockMembership as Membership & { team: Team });
|
||||
vi.mocked(updateNewTeamMemberEventTypes).mockResolvedValue(undefined);
|
||||
|
||||
await TeamService.acceptInvitationByToken("valid-token", 1);
|
||||
|
||||
expect(prismaMock.membership.update).toHaveBeenCalledWith({
|
||||
where: { userId_teamId: { userId: 1, teamId: 1 } },
|
||||
data: { accepted: true },
|
||||
select: { team: true },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("publish", () => {
|
||||
it("should call publish on TeamBilling", async () => {
|
||||
await TeamService.publish(1);
|
||||
|
||||
expect(TeamBilling.findAndInit).toHaveBeenCalledWith(1);
|
||||
expect(mockTeamBilling.publish).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,569 @@
|
||||
import { randomBytes } from "crypto";
|
||||
|
||||
import { TeamBilling } from "@calcom/features/ee/billing/teams";
|
||||
import { deleteWorkfowRemindersOfRemovedMember } from "@calcom/features/ee/teams/lib/deleteWorkflowRemindersOfRemovedMember";
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/features/ee/teams/lib/queries";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { createAProfileForAnExistingUser } from "@calcom/features/profile/lib/createAProfileForAnExistingUser";
|
||||
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 { prisma } from "@calcom/prisma";
|
||||
import { Prisma } from "@calcom/prisma/client";
|
||||
import type { Membership } from "@calcom/prisma/client";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["TeamService"] });
|
||||
|
||||
type MembershipWithRelations = Pick<
|
||||
Membership,
|
||||
"id" | "userId" | "teamId" | "role" | "accepted" | "disableImpersonation"
|
||||
>;
|
||||
|
||||
type TeamWithSettings = {
|
||||
id: number;
|
||||
isOrganization: boolean | null;
|
||||
organizationSettings: unknown;
|
||||
metadata: unknown;
|
||||
activeOrgWorkflows: unknown;
|
||||
parentId: number | null;
|
||||
};
|
||||
|
||||
type UserWithTeams = {
|
||||
id: number;
|
||||
movedToProfileId: number | null;
|
||||
email: string;
|
||||
username: string | null;
|
||||
completedOnboarding: boolean;
|
||||
teams: {
|
||||
team: {
|
||||
id: number;
|
||||
parentId: number | null;
|
||||
};
|
||||
}[];
|
||||
};
|
||||
|
||||
export type RemoveMemberResult = {
|
||||
membership: MembershipWithRelations;
|
||||
};
|
||||
|
||||
export class TeamService {
|
||||
static async createInvite(
|
||||
teamId: number,
|
||||
options?: { token?: string }
|
||||
): Promise<{ token: string; inviteLink: string }> {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { parentId: true, isOrganization: true },
|
||||
});
|
||||
|
||||
if (!team) throw new TRPCError({ code: "NOT_FOUND", message: "Team not found" });
|
||||
|
||||
const isOrganizationOrATeamInOrganization = !!(team.parentId || team.isOrganization);
|
||||
|
||||
if (options?.token) {
|
||||
const existingToken = await prisma.verificationToken.findFirst({
|
||||
where: {
|
||||
token: options.token,
|
||||
identifier: `invite-link-for-teamId-${teamId}`,
|
||||
teamId,
|
||||
},
|
||||
});
|
||||
if (!existingToken) throw new TRPCError({ code: "NOT_FOUND", message: "Invite token not found" });
|
||||
return {
|
||||
token: existingToken.token,
|
||||
inviteLink: TeamService.buildInviteLink(existingToken.token, isOrganizationOrATeamInOrganization),
|
||||
};
|
||||
}
|
||||
|
||||
const token = randomBytes(32).toString("hex");
|
||||
await prisma.verificationToken.create({
|
||||
data: {
|
||||
identifier: `invite-link-for-teamId-${teamId}`,
|
||||
token,
|
||||
expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // +1 week
|
||||
expiresInDays: 7,
|
||||
teamId,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
token,
|
||||
inviteLink: TeamService.buildInviteLink(token, isOrganizationOrATeamInOrganization),
|
||||
};
|
||||
}
|
||||
|
||||
private static buildInviteLink(token: string, isOrgContext: boolean): string {
|
||||
const teamInviteLink = `${WEBAPP_URL}/teams?token=${token}`;
|
||||
const orgInviteLink = `${WEBAPP_URL}/signup?token=${token}&callbackUrl=/getting-started`;
|
||||
return isOrgContext ? orgInviteLink : teamInviteLink;
|
||||
}
|
||||
/**
|
||||
* Deletes a team and all its associated data in a safe, transactional order.
|
||||
* External, critical services like billing are handled first to prevent data inconsistencies.
|
||||
*/
|
||||
static async delete({ id }: { id: number }) {
|
||||
// Step 1: Cancel the external billing subscription first.
|
||||
// If this fails, the entire operation aborts, leaving the team and its data intact.
|
||||
// This prevents a state where the user is billed for a deleted team.
|
||||
const teamBilling = await TeamBilling.findAndInit(id);
|
||||
await teamBilling.cancel();
|
||||
|
||||
// Step 2: Clean up internal, related data like workflow reminders.
|
||||
try {
|
||||
await WorkflowService.deleteWorkflowRemindersOfRemovedTeam(id);
|
||||
} catch (e) {
|
||||
// Log the error, but don't abort the deletion.
|
||||
// It's better to have a deleted team with orphaned reminders than to halt the process
|
||||
// after the subscription has already been canceled.
|
||||
logger.error(`Failed to delete workflow reminders for team ${id}`, e);
|
||||
}
|
||||
|
||||
// Step 3: Delete the team from the database. This is the core "commit" point.
|
||||
const teamRepo = new TeamRepository(prisma);
|
||||
const deletedTeam = await teamRepo.deleteById({ id });
|
||||
|
||||
// Step 4: Clean up any final, non-critical external state.
|
||||
if (deletedTeam && deletedTeam.isOrganization && deletedTeam.slug) {
|
||||
deleteDomain(deletedTeam.slug);
|
||||
}
|
||||
|
||||
return deletedTeam;
|
||||
}
|
||||
|
||||
static async removeMembers({
|
||||
teamIds,
|
||||
userIds,
|
||||
isOrg = false,
|
||||
}: {
|
||||
teamIds: number[];
|
||||
userIds: number[];
|
||||
isOrg?: boolean;
|
||||
}) {
|
||||
const deleteMembershipPromises: Promise<RemoveMemberResult>[] = [];
|
||||
|
||||
for (const userId of userIds) {
|
||||
for (const teamId of teamIds) {
|
||||
deleteMembershipPromises.push(
|
||||
TeamService.removeMember({
|
||||
teamId,
|
||||
userId,
|
||||
isOrg,
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(deleteMembershipPromises);
|
||||
|
||||
const teamsBilling = await TeamBilling.findAndInitMany(teamIds);
|
||||
const teamBillingPromises = teamsBilling.map((teamBilling) => teamBilling.updateQuantity());
|
||||
await Promise.allSettled(teamBillingPromises);
|
||||
}
|
||||
|
||||
// TODO: Move errors away from TRPC error to make it more generic
|
||||
static async inviteMemberByToken(token: string, userId: number) {
|
||||
const verificationToken = await prisma.verificationToken.findFirst({
|
||||
where: {
|
||||
token,
|
||||
OR: [{ expiresInDays: null }, { expires: { gte: new Date() } }],
|
||||
},
|
||||
select: {
|
||||
teamId: true,
|
||||
team: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!verificationToken) throw new TRPCError({ code: "NOT_FOUND", message: "Invite not found" });
|
||||
if (!verificationToken.teamId || !verificationToken.team)
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Invite token is not associated with any team",
|
||||
});
|
||||
|
||||
try {
|
||||
await prisma.membership.create({
|
||||
data: {
|
||||
createdAt: new Date(),
|
||||
teamId: verificationToken.teamId,
|
||||
userId: userId,
|
||||
role: MembershipRole.MEMBER,
|
||||
accepted: false,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
if (e.code === "P2002") {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "This user is a member of this team / has a pending invitation.",
|
||||
});
|
||||
}
|
||||
} else throw e;
|
||||
}
|
||||
|
||||
const teamBilling = await TeamBilling.findAndInit(verificationToken.teamId);
|
||||
await teamBilling.updateQuantity();
|
||||
|
||||
return verificationToken.team.name;
|
||||
}
|
||||
|
||||
static async acceptTeamMembership({
|
||||
userId,
|
||||
teamId,
|
||||
userEmail,
|
||||
username,
|
||||
}: {
|
||||
userId: number;
|
||||
teamId: number;
|
||||
userEmail: string;
|
||||
username: string | null;
|
||||
}) {
|
||||
const teamMembership = await prisma.membership.update({
|
||||
where: {
|
||||
userId_teamId: { userId, teamId },
|
||||
},
|
||||
data: {
|
||||
accepted: true,
|
||||
},
|
||||
select: {
|
||||
team: true,
|
||||
},
|
||||
});
|
||||
|
||||
const team = teamMembership.team;
|
||||
|
||||
if (team.parentId) {
|
||||
await prisma.membership.update({
|
||||
where: {
|
||||
userId_teamId: { userId, teamId: team.parentId },
|
||||
},
|
||||
data: {
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const isASubteam = team.parentId !== null;
|
||||
const idOfOrganizationInContext = team.isOrganization ? team.id : isASubteam ? team.parentId : null;
|
||||
const needProfileUpdate = !!idOfOrganizationInContext;
|
||||
|
||||
if (needProfileUpdate) {
|
||||
await createAProfileForAnExistingUser({
|
||||
user: {
|
||||
id: userId,
|
||||
email: userEmail,
|
||||
currentUsername: username,
|
||||
},
|
||||
organizationId: idOfOrganizationInContext,
|
||||
});
|
||||
}
|
||||
|
||||
await updateNewTeamMemberEventTypes(userId, teamId);
|
||||
}
|
||||
static async leaveTeamMembership({
|
||||
userId,
|
||||
teamId,
|
||||
}: {
|
||||
userId: number;
|
||||
teamId: number;
|
||||
}) {
|
||||
try {
|
||||
const membership = await prisma.membership.delete({
|
||||
where: {
|
||||
userId_teamId: { userId, teamId },
|
||||
},
|
||||
select: {
|
||||
team: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (membership.team.parentId) {
|
||||
await prisma.membership.delete({
|
||||
where: {
|
||||
userId_teamId: { userId, teamId: membership.team.parentId },
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
}
|
||||
|
||||
static async acceptInvitationByToken(acceptanceToken: string, userId: number) {
|
||||
const verificationToken = await prisma.verificationToken.findFirst({
|
||||
where: {
|
||||
token: acceptanceToken,
|
||||
expires: { gte: new Date() },
|
||||
},
|
||||
select: {
|
||||
identifier: true,
|
||||
teamId: true,
|
||||
team: { select: { name: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!verificationToken) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Invite not found" });
|
||||
}
|
||||
|
||||
if (!verificationToken.teamId || !verificationToken.team) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Invite token is not associated with any team",
|
||||
});
|
||||
}
|
||||
|
||||
const currentUser = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { email: true, username: true },
|
||||
});
|
||||
|
||||
if (!currentUser) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
|
||||
}
|
||||
|
||||
if (
|
||||
currentUser.email !== verificationToken.identifier &&
|
||||
currentUser.username !== verificationToken.identifier
|
||||
) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "This invitation is not for your account",
|
||||
});
|
||||
}
|
||||
|
||||
await TeamService.acceptTeamMembership({
|
||||
userId,
|
||||
teamId: verificationToken.teamId,
|
||||
userEmail: currentUser.email,
|
||||
username: currentUser.username,
|
||||
});
|
||||
}
|
||||
|
||||
static async publish(teamId: number) {
|
||||
const teamBilling = await TeamBilling.findAndInit(teamId);
|
||||
return teamBilling.publish();
|
||||
}
|
||||
|
||||
private static async removeMember({
|
||||
userId,
|
||||
teamId,
|
||||
isOrg,
|
||||
}: {
|
||||
userId: number;
|
||||
teamId: number;
|
||||
isOrg: boolean;
|
||||
}) {
|
||||
const membership = await TeamService.fetchMembershipOrThrow(userId, teamId);
|
||||
const team = await TeamService.fetchTeamOrThrow(teamId);
|
||||
const user = await TeamService.fetchUserOrThrow(userId);
|
||||
|
||||
if (isOrg) {
|
||||
log.debug("Removing a member from the organization");
|
||||
await TeamService.removeFromOrganization(membership, team, user);
|
||||
} else {
|
||||
log.debug("Removing a member from a team");
|
||||
await TeamService.removeFromTeam(membership, teamId);
|
||||
}
|
||||
|
||||
await deleteWorkfowRemindersOfRemovedMember(team, userId, isOrg);
|
||||
|
||||
return { membership };
|
||||
}
|
||||
|
||||
// TODO: Needs to be moved to repository
|
||||
private static async fetchMembershipOrThrow(
|
||||
userId: number,
|
||||
teamId: number
|
||||
): Promise<MembershipWithRelations> {
|
||||
const membership = await prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_teamId: { userId: userId, teamId: teamId },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
teamId: true,
|
||||
role: true,
|
||||
accepted: true,
|
||||
disableImpersonation: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Membership not found" });
|
||||
}
|
||||
|
||||
return membership;
|
||||
}
|
||||
|
||||
// TODO: Needs to be moved to repository
|
||||
static async fetchTeamOrThrow(teamId: number): Promise<TeamWithSettings> {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: {
|
||||
isOrganization: true,
|
||||
organizationSettings: true,
|
||||
id: true,
|
||||
metadata: true,
|
||||
activeOrgWorkflows: true,
|
||||
parentId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!team) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Team not found" });
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
// TODO: Needs to be moved to repository
|
||||
private static async fetchUserOrThrow(userId: number): Promise<UserWithTeams> {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
id: true,
|
||||
movedToProfileId: true,
|
||||
email: true,
|
||||
username: true,
|
||||
completedOnboarding: true,
|
||||
teams: {
|
||||
select: {
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
parentId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
// TODO: Needs to be moved to repository
|
||||
private static async cleanupTempOrgRedirect(user: UserWithTeams, team: TeamWithSettings) {
|
||||
const profileToDelete = await ProfileRepository.findByUserIdAndOrgId({
|
||||
userId: user.id,
|
||||
organizationId: team.id,
|
||||
});
|
||||
|
||||
if (user.username && user.movedToProfileId === profileToDelete?.id) {
|
||||
log.debug("Cleaning up tempOrgRedirect for user", user.username);
|
||||
await prisma.tempOrgRedirect.deleteMany({
|
||||
where: {
|
||||
from: user.username,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static async removeFromOrganization(
|
||||
membership: MembershipWithRelations,
|
||||
team: TeamWithSettings,
|
||||
user: UserWithTeams
|
||||
) {
|
||||
await TeamService.cleanupTempOrgRedirect(user, team);
|
||||
const newUsername = generateNewUsername(user);
|
||||
|
||||
await prisma.$transaction([
|
||||
// Remove user from all sub-teams event type hosts
|
||||
prisma.host.deleteMany({
|
||||
where: {
|
||||
userId: membership.userId,
|
||||
eventType: {
|
||||
team: {
|
||||
parentId: team.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
// Delete managed child events in sub-teams
|
||||
prisma.eventType.deleteMany({
|
||||
where: {
|
||||
userId: membership.userId,
|
||||
parent: {
|
||||
team: {
|
||||
parentId: team.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
// Remove organizationId from the user
|
||||
prisma.user.update({
|
||||
where: { id: membership.userId },
|
||||
data: {
|
||||
organizationId: null,
|
||||
username: newUsername,
|
||||
},
|
||||
}),
|
||||
// Delete the profile of the user from the organization
|
||||
ProfileRepository.delete({
|
||||
userId: membership.userId,
|
||||
organizationId: team.id,
|
||||
}),
|
||||
// Delete all sub-team memberships where this team is the organization
|
||||
prisma.membership.deleteMany({
|
||||
where: {
|
||||
team: {
|
||||
parentId: team.id,
|
||||
},
|
||||
userId: membership.userId,
|
||||
},
|
||||
}),
|
||||
// Delete the membership of the user from the organization
|
||||
prisma.membership.delete({
|
||||
where: {
|
||||
userId_teamId: { userId: membership.userId, teamId: team.id },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
// Generate new username for user leaving organization
|
||||
function generateNewUsername(user: UserWithTeams): string | null {
|
||||
// We ensure that new username would be unique across all users in the global namespace outside any organization
|
||||
return user.username != null ? `${user.username}-${user.id}` : null;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove member from regular team
|
||||
private static async removeFromTeam(membership: MembershipWithRelations, teamId: number) {
|
||||
await prisma.$transaction([
|
||||
// Remove user from all team event types' hosts
|
||||
prisma.host.deleteMany({
|
||||
where: {
|
||||
userId: membership.userId,
|
||||
eventType: {
|
||||
teamId: teamId,
|
||||
},
|
||||
},
|
||||
}),
|
||||
// Deleted managed event types from this team for this member
|
||||
prisma.eventType.deleteMany({
|
||||
where: { parent: { teamId: teamId }, userId: membership.userId },
|
||||
}),
|
||||
// Delete the membership of the user from the team
|
||||
prisma.membership.delete({
|
||||
where: {
|
||||
userId_teamId: { userId: membership.userId, teamId: teamId },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import { v4 as uuidv4 } from "uuid";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import generateIcsString from "@calcom/emails/lib/generateIcsString";
|
||||
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
|
||||
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
|
||||
import { getBookerBaseUrl } from "@calcom/features/ee/organizations/lib/getBookerUrlServer";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
|
||||
@@ -7,7 +7,7 @@ import { bulkShortenLinks } from "@calcom/ee/workflows/lib/reminders/utils";
|
||||
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
|
||||
import { isAttendeeAction } from "@calcom/features/ee/workflows/lib/actionHelperFunctions";
|
||||
import { scheduleSmsOrFallbackEmail } from "@calcom/features/ee/workflows/lib/reminders/messageDispatcher";
|
||||
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
|
||||
import { getBookerBaseUrl } from "@calcom/features/ee/organizations/lib/getBookerUrlServer";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { CAL_AI_AGENT_PHONE_NUMBER_FIELD } from "@calcom/features/bookings/lib/SystemField";
|
||||
import { CAL_AI_AGENT_PHONE_NUMBER_FIELD } from "@calcom/lib/SystemField";
|
||||
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
|
||||
import tasker from "@calcom/features/tasker";
|
||||
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
|
||||
@@ -10,12 +10,12 @@ import { sendOrScheduleWorkflowEmails } from "@calcom/features/ee/workflows/lib/
|
||||
import * as twilio from "@calcom/features/ee/workflows/lib/reminders/providers/twilioProvider";
|
||||
import type { Workflow, WorkflowStep } from "@calcom/features/ee/workflows/lib/types";
|
||||
import { getSubmitterEmail } from "@calcom/features/tasker/tasks/triggerFormSubmittedNoEvent/triggerFormSubmittedNoEventWebhook";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import { checkSMSRateLimit } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import { SENDER_NAME } from "@calcom/lib/constants";
|
||||
import { formatCalEventExtended } from "@calcom/lib/formatCalendarEvent";
|
||||
import { withReporting } from "@calcom/lib/sentryWrapper";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import { WorkflowActions, WorkflowMethods, WorkflowTriggerEvents } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -10,7 +10,7 @@ import Shell, { ShellMain } from "@calcom/features/shell/Shell";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
|
||||
import type { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
|
||||
import type { WorkflowRepository } from "@calcom/features/ee/workflows/repositories/WorkflowRepository";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
|
||||
@@ -10,7 +10,7 @@ import { Toaster } from "sonner";
|
||||
import { SENDER_ID } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import type { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
|
||||
import type { WorkflowRepository } from "@calcom/features/ee/workflows/repositories/WorkflowRepository";
|
||||
import type { WorkflowPermissions } from "@calcom/lib/server/repository/workflow-permissions";
|
||||
import type { WorkflowStep } from "@calcom/prisma/client";
|
||||
import type { TimeUnit, WorkflowTriggerEvents } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
import prismaMock from "../../../../../tests/libs/__mocks__/prismaMock";
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import { WorkflowRepository } from "./WorkflowRepository";
|
||||
|
||||
describe("WorkflowRepository", () => {
|
||||
describe("getVerifiedEmails", () => {
|
||||
it("should return the email of the user", async () => {
|
||||
prismaMock.secondaryEmail.findMany.mockResolvedValue([]);
|
||||
prismaMock.verifiedEmail.findMany.mockResolvedValue([]);
|
||||
|
||||
const emails = await WorkflowRepository.getVerifiedEmails({
|
||||
userEmail: "[email protected]",
|
||||
userId: 1,
|
||||
});
|
||||
expect(emails).toEqual(["[email protected]"]);
|
||||
});
|
||||
|
||||
it("should return the email of the user and verified secondary emails", async () => {
|
||||
prismaMock.verifiedEmail.findMany.mockResolvedValue([]);
|
||||
prismaMock.secondaryEmail.findMany.mockResolvedValue([
|
||||
{
|
||||
id: 101,
|
||||
email: "[email protected]",
|
||||
emailVerified: new Date(),
|
||||
},
|
||||
]);
|
||||
|
||||
const emails = await WorkflowRepository.getVerifiedEmails({
|
||||
userEmail: "[email protected]",
|
||||
userId: 1,
|
||||
});
|
||||
expect(emails).toEqual(["[email protected]", "[email protected]"]);
|
||||
});
|
||||
|
||||
it("should return the email of the user and verified secondary emails from the team", async () => {
|
||||
prismaMock.verifiedEmail.findMany.mockResolvedValue([]);
|
||||
prismaMock.secondaryEmail.findMany.mockResolvedValue([
|
||||
{
|
||||
id: 101,
|
||||
email: "[email protected]",
|
||||
emailVerified: new Date(),
|
||||
},
|
||||
]);
|
||||
|
||||
prismaMock.user.findMany.mockResolvedValue([
|
||||
{
|
||||
id: 1,
|
||||
email: "[email protected]",
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
email: "[email protected]",
|
||||
secondaryEmails: [],
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
email: "[email protected]",
|
||||
secondaryEmails: [
|
||||
{
|
||||
email: "[email protected]",
|
||||
emailVerified: new Date(),
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
const emails = await WorkflowRepository.getVerifiedEmails({
|
||||
userEmail: "[email protected]",
|
||||
userId: 1,
|
||||
teamId: 1,
|
||||
});
|
||||
expect(emails).toEqual([
|
||||
"[email protected]",
|
||||
"[email protected]",
|
||||
"[email protected]",
|
||||
"[email protected]",
|
||||
"[email protected]",
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,860 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { WorkflowType } from "@calcom/ee/workflows/components/WorkflowListPage";
|
||||
import { FORM_TRIGGER_WORKFLOW_EVENTS } from "@calcom/ee/workflows/lib/constants";
|
||||
import { deleteScheduledAIPhoneCall } from "@calcom/ee/workflows/lib/reminders/aiPhoneCallManager";
|
||||
import { deleteScheduledEmailReminder } from "@calcom/ee/workflows/lib/reminders/emailReminderManager";
|
||||
import { deleteScheduledSMSReminder } from "@calcom/ee/workflows/lib/reminders/smsReminderManager";
|
||||
import type { WorkflowStep } from "@calcom/ee/workflows/lib/types";
|
||||
import { hasFilter } from "@calcom/features/filters/lib/hasFilter";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import {
|
||||
MembershipRole,
|
||||
TimeUnit,
|
||||
WorkflowTriggerEvents,
|
||||
WorkflowType as PrismaWorkflowType,
|
||||
} from "@calcom/prisma/enums";
|
||||
import { WorkflowMethods } from "@calcom/prisma/enums";
|
||||
import type { TFilteredListInputSchema } from "@calcom/trpc/server/routers/viewer/workflows/filteredList.schema";
|
||||
import type { TGetVerifiedEmailsInputSchema } from "@calcom/trpc/server/routers/viewer/workflows/getVerifiedEmails.schema";
|
||||
import type { TGetVerifiedNumbersInputSchema } from "@calcom/trpc/server/routers/viewer/workflows/getVerifiedNumbers.schema";
|
||||
|
||||
export const ZGetInputSchema = z.object({
|
||||
id: z.number(),
|
||||
});
|
||||
|
||||
const excludeFormTriggersWhereClause = {
|
||||
trigger: {
|
||||
not: {
|
||||
in: FORM_TRIGGER_WORKFLOW_EVENTS,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const getWorkflowType = (trigger: WorkflowTriggerEvents): PrismaWorkflowType => {
|
||||
if (FORM_TRIGGER_WORKFLOW_EVENTS.includes(trigger)) {
|
||||
return PrismaWorkflowType.ROUTING_FORM;
|
||||
}
|
||||
return PrismaWorkflowType.EVENT_TYPE;
|
||||
};
|
||||
|
||||
export type TGetInputSchema = z.infer<typeof ZGetInputSchema>;
|
||||
|
||||
const deleteScheduledWhatsappReminder = deleteScheduledSMSReminder;
|
||||
|
||||
const includedFields = {
|
||||
activeOn: {
|
||||
select: {
|
||||
eventType: {
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
parentId: true,
|
||||
_count: {
|
||||
select: {
|
||||
children: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
activeOnTeams: {
|
||||
select: {
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
steps: true,
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
members: true,
|
||||
logoUrl: true,
|
||||
isOrganization: true,
|
||||
},
|
||||
},
|
||||
} satisfies Prisma.WorkflowInclude;
|
||||
|
||||
export class WorkflowRepository {
|
||||
private static log = logger.getSubLogger({ prefix: ["workflow"] });
|
||||
|
||||
static async getById({ id }: TGetInputSchema) {
|
||||
return await prisma.workflow.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
userId: true,
|
||||
teamId: true,
|
||||
isActiveOnAll: true,
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
members: true,
|
||||
name: true,
|
||||
isOrganization: true,
|
||||
},
|
||||
},
|
||||
time: true,
|
||||
timeUnit: true,
|
||||
activeOn: {
|
||||
select: {
|
||||
eventType: true,
|
||||
},
|
||||
},
|
||||
activeOnTeams: {
|
||||
select: {
|
||||
team: true,
|
||||
},
|
||||
},
|
||||
activeOnRoutingForms: {
|
||||
select: {
|
||||
routingForm: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
trigger: true,
|
||||
steps: {
|
||||
orderBy: {
|
||||
stepNumber: "asc",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async getVerifiedNumbers({
|
||||
userId,
|
||||
teamId,
|
||||
}: TGetVerifiedNumbersInputSchema & { userId: number | null }) {
|
||||
if (!userId) {
|
||||
throw new Error("User Id not found");
|
||||
}
|
||||
const verifiedNumbers = await prisma.verifiedNumber.findMany({
|
||||
where: {
|
||||
OR: [{ userId }, { teamId }],
|
||||
},
|
||||
});
|
||||
|
||||
return verifiedNumbers;
|
||||
}
|
||||
|
||||
static async getVerifiedEmails({
|
||||
userEmail,
|
||||
userId,
|
||||
teamId,
|
||||
}: TGetVerifiedEmailsInputSchema & { userEmail: string | null; userId: number | null }) {
|
||||
if (!userId) {
|
||||
throw new Error("User Id not found");
|
||||
}
|
||||
if (!userEmail) {
|
||||
throw new Error("User email not found");
|
||||
}
|
||||
|
||||
let verifiedEmails: string[] = [userEmail];
|
||||
|
||||
const secondaryEmails = await prisma.secondaryEmail.findMany({
|
||||
where: {
|
||||
userId,
|
||||
emailVerified: {
|
||||
not: null,
|
||||
},
|
||||
},
|
||||
});
|
||||
verifiedEmails = verifiedEmails.concat(secondaryEmails.map((secondaryEmail) => secondaryEmail.email));
|
||||
if (teamId) {
|
||||
const teamMembers = await prisma.user.findMany({
|
||||
where: {
|
||||
teams: {
|
||||
some: {
|
||||
teamId,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
secondaryEmails: {
|
||||
where: {
|
||||
emailVerified: {
|
||||
not: null,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!teamMembers.length) {
|
||||
throw new Error("Team not found");
|
||||
}
|
||||
|
||||
const isTeamMember = teamMembers.some((member) => member.id === userId);
|
||||
|
||||
if (!isTeamMember) {
|
||||
throw new Error("You are not a member of this team");
|
||||
}
|
||||
|
||||
teamMembers.forEach((member) => {
|
||||
if (member.id === userId) {
|
||||
return;
|
||||
}
|
||||
verifiedEmails.push(member.email);
|
||||
member.secondaryEmails.forEach((secondaryEmail) => {
|
||||
verifiedEmails.push(secondaryEmail.email);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const emails = (
|
||||
await prisma.verifiedEmail.findMany({
|
||||
where: {
|
||||
OR: [{ userId }, { teamId }],
|
||||
},
|
||||
})
|
||||
).map((verifiedEmail) => verifiedEmail.email);
|
||||
|
||||
verifiedEmails = verifiedEmails.concat(emails);
|
||||
|
||||
return verifiedEmails;
|
||||
}
|
||||
|
||||
static async getFilteredList({ userId, input }: { userId?: number; input: TFilteredListInputSchema }) {
|
||||
const filters = input?.filters;
|
||||
|
||||
const filtered = filters && hasFilter(filters);
|
||||
|
||||
const allWorkflows = await prisma.workflow.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{
|
||||
userId,
|
||||
},
|
||||
{
|
||||
team: {
|
||||
members: {
|
||||
some: {
|
||||
userId,
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
include: includedFields,
|
||||
orderBy: [
|
||||
{
|
||||
position: "desc",
|
||||
},
|
||||
{
|
||||
id: "desc",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if (!filtered) {
|
||||
const workflowsWithReadOnly: WorkflowType[] = allWorkflows.map((workflow) => {
|
||||
const readOnly = !!workflow.team?.members?.find(
|
||||
(member) => member.userId === userId && member.role === MembershipRole.MEMBER
|
||||
);
|
||||
|
||||
return { readOnly, isOrg: workflow.team?.isOrganization ?? false, ...workflow };
|
||||
});
|
||||
|
||||
return {
|
||||
filtered: workflowsWithReadOnly,
|
||||
totalCount: allWorkflows.length,
|
||||
};
|
||||
}
|
||||
|
||||
const where = {
|
||||
OR: [] as Prisma.WorkflowWhereInput[],
|
||||
};
|
||||
|
||||
if (filtered) {
|
||||
if (filters.teamIds) {
|
||||
where.OR.push({
|
||||
team: {
|
||||
id: {
|
||||
in: filters.teamIds ?? [],
|
||||
},
|
||||
members: {
|
||||
some: {
|
||||
userId,
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (filters.userIds) {
|
||||
where.OR.push({
|
||||
userId: {
|
||||
in: filters.userIds,
|
||||
},
|
||||
teamId: null,
|
||||
});
|
||||
}
|
||||
|
||||
const filteredWorkflows = await prisma.workflow.findMany({
|
||||
where,
|
||||
include: includedFields,
|
||||
orderBy: {
|
||||
id: "desc",
|
||||
},
|
||||
});
|
||||
|
||||
const workflowsWithReadOnly: WorkflowType[] = filteredWorkflows.map((workflow) => {
|
||||
const readOnly = !!workflow.team?.members?.find(
|
||||
(member) => member.userId === userId && member.role === MembershipRole.MEMBER
|
||||
);
|
||||
|
||||
return { readOnly, isOrg: workflow.team?.isOrganization ?? false, ...workflow };
|
||||
});
|
||||
|
||||
return {
|
||||
filtered: workflowsWithReadOnly,
|
||||
totalCount: allWorkflows.length,
|
||||
};
|
||||
}
|
||||
}
|
||||
static async getRemindersFromRemovedTeams(
|
||||
removedTeams: number[],
|
||||
workflowSteps: WorkflowStep[],
|
||||
activeOn?: number[]
|
||||
) {
|
||||
const remindersToDeletePromise: Prisma.PrismaPromise<
|
||||
{
|
||||
id: number;
|
||||
referenceId: string | null;
|
||||
method: string;
|
||||
}[]
|
||||
>[] = [];
|
||||
|
||||
removedTeams.forEach((teamId) => {
|
||||
const reminderToDelete = prisma.workflowReminder.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{
|
||||
//team event types + children managed event types
|
||||
booking: {
|
||||
eventType: {
|
||||
OR: [{ teamId }, { teamId: null, parent: { teamId } }],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
// user bookings
|
||||
booking: {
|
||||
user: {
|
||||
AND: [
|
||||
// user is part of team that got removed
|
||||
{
|
||||
teams: {
|
||||
some: {
|
||||
teamId: teamId,
|
||||
},
|
||||
},
|
||||
},
|
||||
// and user is not part of any team were the workflow is still active on
|
||||
{
|
||||
teams: {
|
||||
none: {
|
||||
teamId: {
|
||||
in: activeOn,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
eventType: {
|
||||
teamId: null,
|
||||
parentId: null, // children managed event types are handled above with team event types
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
workflowStepId: {
|
||||
in: workflowSteps.map((step) => {
|
||||
return step.id;
|
||||
}),
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
referenceId: true,
|
||||
method: true,
|
||||
},
|
||||
});
|
||||
|
||||
remindersToDeletePromise.push(reminderToDelete);
|
||||
});
|
||||
const remindersToDelete = (await Promise.all(remindersToDeletePromise)).flat();
|
||||
return remindersToDelete;
|
||||
}
|
||||
|
||||
static async getActiveOnEventTypeIds({
|
||||
workflowId,
|
||||
userId,
|
||||
teamId,
|
||||
}: {
|
||||
workflowId: number;
|
||||
userId: number;
|
||||
teamId?: number | null;
|
||||
}) {
|
||||
const workflow = await prisma.workflow.findFirst({
|
||||
where: {
|
||||
id: workflowId,
|
||||
userId,
|
||||
teamId: teamId ?? undefined,
|
||||
},
|
||||
select: {
|
||||
activeOn: {
|
||||
select: {
|
||||
eventTypeId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!workflow) {
|
||||
throw new HttpError({
|
||||
statusCode: 404,
|
||||
message: "Workflow not found",
|
||||
});
|
||||
}
|
||||
|
||||
return workflow.activeOn.map((active) => active.eventTypeId);
|
||||
}
|
||||
|
||||
static async deleteAllWorkflowReminders(
|
||||
remindersToDelete:
|
||||
| {
|
||||
id: number;
|
||||
referenceId: string | null;
|
||||
method: string;
|
||||
}[]
|
||||
| null
|
||||
) {
|
||||
const reminderMethods: {
|
||||
[x: string]: (id: number, referenceId: string | null) => void;
|
||||
} = {
|
||||
[WorkflowMethods.EMAIL]: (id) => deleteScheduledEmailReminder(id),
|
||||
[WorkflowMethods.SMS]: (id, referenceId) => deleteScheduledSMSReminder(id, referenceId),
|
||||
[WorkflowMethods.WHATSAPP]: (id, referenceId) => deleteScheduledWhatsappReminder(id, referenceId),
|
||||
[WorkflowMethods.AI_PHONE_CALL]: (id, referenceId) => deleteScheduledAIPhoneCall(id, referenceId),
|
||||
};
|
||||
|
||||
if (!remindersToDelete) return Promise.resolve();
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
remindersToDelete.map((reminder) => {
|
||||
return reminderMethods[reminder.method](reminder.id, reminder.referenceId);
|
||||
})
|
||||
);
|
||||
|
||||
results.forEach((result, index) => {
|
||||
if (result.status !== "fulfilled") {
|
||||
this.log.error(
|
||||
`An error occurred when deleting reminder ${remindersToDelete[index].id}, method: ${remindersToDelete[index].method}`,
|
||||
result.reason
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static async findUniqueForUpdate(id: number) {
|
||||
return await prisma.workflow.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
isActiveOnAll: true,
|
||||
trigger: true,
|
||||
time: true,
|
||||
timeUnit: true,
|
||||
team: {
|
||||
select: {
|
||||
isOrganization: true,
|
||||
},
|
||||
},
|
||||
teamId: true,
|
||||
user: {
|
||||
select: {
|
||||
teams: true,
|
||||
},
|
||||
},
|
||||
steps: true,
|
||||
activeOn: true,
|
||||
activeOnTeams: true,
|
||||
activeOnRoutingForms: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async updateWorkflow(
|
||||
id: number,
|
||||
data: {
|
||||
name: string;
|
||||
trigger: WorkflowTriggerEvents;
|
||||
time: number | null;
|
||||
timeUnit: TimeUnit | null;
|
||||
isActiveOnAll?: boolean;
|
||||
}
|
||||
) {
|
||||
const type = getWorkflowType(data.trigger);
|
||||
return await prisma.workflow.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...data,
|
||||
type,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findUniqueWithRelations(id: number) {
|
||||
return await prisma.workflow.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
activeOn: {
|
||||
select: {
|
||||
eventType: true,
|
||||
},
|
||||
},
|
||||
activeOnTeams: {
|
||||
select: {
|
||||
team: true,
|
||||
},
|
||||
},
|
||||
activeOnRoutingForms: {
|
||||
select: {
|
||||
routingForm: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
members: true,
|
||||
name: true,
|
||||
isOrganization: true,
|
||||
},
|
||||
},
|
||||
steps: {
|
||||
orderBy: {
|
||||
stepNumber: "asc",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findActiveOrgWorkflows({
|
||||
orgId,
|
||||
userId,
|
||||
teamId,
|
||||
excludeFormTriggers,
|
||||
}: {
|
||||
orgId: number;
|
||||
userId: number;
|
||||
teamId: number;
|
||||
excludeFormTriggers: boolean;
|
||||
}) {
|
||||
return await prisma.workflow.findMany({
|
||||
where: {
|
||||
...(excludeFormTriggers ? excludeFormTriggersWhereClause : {}),
|
||||
team: {
|
||||
id: orgId,
|
||||
members: {
|
||||
some: {
|
||||
userId,
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
OR: [
|
||||
{
|
||||
isActiveOnAll: true,
|
||||
},
|
||||
{
|
||||
activeOnTeams: {
|
||||
some: {
|
||||
team: {
|
||||
OR: [
|
||||
{ id: teamId },
|
||||
{
|
||||
members: {
|
||||
some: {
|
||||
userId,
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
include: {
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
members: true,
|
||||
},
|
||||
},
|
||||
activeOnTeams: {
|
||||
select: {
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
steps: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findTeamWorkflows({
|
||||
teamId,
|
||||
userId,
|
||||
excludeFormTriggers,
|
||||
}: {
|
||||
teamId: number;
|
||||
userId: number;
|
||||
excludeFormTriggers: boolean;
|
||||
}) {
|
||||
return await prisma.workflow.findMany({
|
||||
where: {
|
||||
...(excludeFormTriggers ? excludeFormTriggersWhereClause : {}),
|
||||
team: {
|
||||
id: teamId,
|
||||
members: {
|
||||
some: {
|
||||
userId,
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
include: {
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
members: true,
|
||||
},
|
||||
},
|
||||
activeOn: {
|
||||
select: {
|
||||
eventType: {
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
parentId: true,
|
||||
_count: {
|
||||
select: {
|
||||
children: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
steps: true,
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findUserWorkflows({
|
||||
userId,
|
||||
excludeFormTriggers,
|
||||
}: {
|
||||
userId: number;
|
||||
excludeFormTriggers: boolean;
|
||||
}) {
|
||||
return await prisma.workflow.findMany({
|
||||
where: {
|
||||
...(excludeFormTriggers ? excludeFormTriggersWhereClause : {}),
|
||||
userId,
|
||||
},
|
||||
include: {
|
||||
activeOn: {
|
||||
select: {
|
||||
eventType: {
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
parentId: true,
|
||||
_count: {
|
||||
select: {
|
||||
children: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
steps: true,
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
members: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findAllWorkflows({
|
||||
userId,
|
||||
excludeFormTriggers,
|
||||
}: {
|
||||
userId: number;
|
||||
excludeFormTriggers: boolean;
|
||||
}) {
|
||||
return await prisma.workflow.findMany({
|
||||
where: {
|
||||
...(excludeFormTriggers ? excludeFormTriggersWhereClause : {}),
|
||||
OR: [
|
||||
{ userId },
|
||||
{
|
||||
team: {
|
||||
members: {
|
||||
some: {
|
||||
userId,
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
include: {
|
||||
activeOn: {
|
||||
select: {
|
||||
eventType: {
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
parentId: true,
|
||||
_count: {
|
||||
select: {
|
||||
children: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
steps: true,
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
members: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findWorkflowsActiveOnRoutingForm({ routingFormId }: { routingFormId: string }) {
|
||||
return await prisma.workflow.findMany({
|
||||
where: {
|
||||
activeOnRoutingForms: {
|
||||
some: {
|
||||
routingFormId,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
trigger: true,
|
||||
time: true,
|
||||
timeUnit: true,
|
||||
userId: true,
|
||||
teamId: true,
|
||||
steps: true,
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findActiveWorkflowsOnTeam({ parentTeamId, teamId }: { parentTeamId: number; teamId: number }) {
|
||||
return await prisma.workflow.findMany({
|
||||
where: {
|
||||
teamId: parentTeamId,
|
||||
OR: [
|
||||
{
|
||||
activeOnTeams: {
|
||||
some: {
|
||||
teamId: teamId,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
isActiveOnAll: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
select: {
|
||||
steps: true,
|
||||
activeOnTeams: true,
|
||||
isActiveOnAll: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user