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
@@ -22,12 +22,12 @@ import {
|
||||
} from "@calcom/features/data-table";
|
||||
import { useSegments } from "@calcom/features/data-table/hooks/useSegments";
|
||||
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import {
|
||||
downloadAsCsv,
|
||||
generateCsvRawForMembersTable,
|
||||
generateHeaderFromReactTable,
|
||||
} from "@calcom/lib/csvUtils";
|
||||
} from "@calcom/features/users/lib/UserListTableUtils";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { downloadAsCsv } from "@calcom/lib/csvUtils";
|
||||
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc";
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { Table } from "@tanstack/react-table";
|
||||
|
||||
import type { UserTableUser } from "@calcom/features/users/components/UserTable/types";
|
||||
import { sanitizeValue } from "@calcom/lib/csvUtils";
|
||||
|
||||
export const generateHeaderFromReactTable = (table: Table<UserTableUser>): string[] | null => {
|
||||
const headerGroups = table.getHeaderGroups();
|
||||
if (!headerGroups.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { headers } = headerGroups[0];
|
||||
const HEADER_IDS_TO_EXCLUDE = ["select", "actions"]; // these columns only make sense in web page
|
||||
const filteredHeaders = headers.filter((header) => !HEADER_IDS_TO_EXCLUDE.includes(header.id));
|
||||
const headerNames = filteredHeaders.map((header) => {
|
||||
const h = header.column.columnDef.header;
|
||||
if (typeof h === "string") {
|
||||
return sanitizeValue(h);
|
||||
}
|
||||
if (typeof h === "function") {
|
||||
return sanitizeValue(h(header.getContext()));
|
||||
}
|
||||
return "Unknown";
|
||||
});
|
||||
|
||||
// Add "Link" column (member's public page)
|
||||
const MEMBERS_COLUMN = "Members";
|
||||
const LINK_COLUMN = "Link";
|
||||
const memberIndex = headerNames.findIndex((name) => name === MEMBERS_COLUMN);
|
||||
if (memberIndex > -1) {
|
||||
headerNames.splice(memberIndex + 1, 0, LINK_COLUMN);
|
||||
}
|
||||
|
||||
return headerNames;
|
||||
};
|
||||
|
||||
export const generateCsvRawForMembersTable = (
|
||||
headers: string[],
|
||||
rows: UserTableUser[],
|
||||
ATTRIBUTE_IDS: string[],
|
||||
orgDomain: string
|
||||
): string => {
|
||||
if (!headers.length) {
|
||||
throw new Error("The header is empty.");
|
||||
}
|
||||
|
||||
const REQUIRED_HEADERS = ["Members", "Link", "Role", "Teams"] as const;
|
||||
// Validate required headers are present and in correct order
|
||||
const firstFourHeaders = headers.slice(0, REQUIRED_HEADERS.length);
|
||||
if (!REQUIRED_HEADERS.every((header, index) => header === firstFourHeaders[index])) {
|
||||
throw new Error(
|
||||
`Invalid headers structure. Expected headers to start with: ${JSON.stringify(REQUIRED_HEADERS)}`
|
||||
);
|
||||
}
|
||||
|
||||
// Body formation
|
||||
const csvRows = rows.map((row) => {
|
||||
const { email, role, teams, username, attributes } = row;
|
||||
|
||||
// Create a map of attributeId to array of values
|
||||
const attributeMap = (attributes ?? []).reduce((acc, attr) => {
|
||||
if (!acc[attr.attributeId]) {
|
||||
acc[attr.attributeId] = [];
|
||||
}
|
||||
acc[attr.attributeId].push({
|
||||
value: attr.value,
|
||||
weight: attr.weight ?? undefined,
|
||||
});
|
||||
return acc;
|
||||
}, {} as Record<string, { value: string; weight: number | undefined }[]>);
|
||||
|
||||
const requiredColumns = [
|
||||
email, // Members column
|
||||
`${orgDomain}/${username}`, // Link column
|
||||
role, // Role column
|
||||
sanitizeValue(teams.map((team) => team.name).join(",")), // Teams column
|
||||
];
|
||||
|
||||
// Add attribute columns
|
||||
const attributeColumns = ATTRIBUTE_IDS.map((attrId) => {
|
||||
const attributes = attributeMap[attrId];
|
||||
if (!attributes?.length) return "";
|
||||
|
||||
return sanitizeValue(
|
||||
attributes.map((attr) => (attr.weight ? `${attr.value} (${attr.weight}%)` : attr.value)).join(",")
|
||||
);
|
||||
});
|
||||
|
||||
return [...requiredColumns, ...attributeColumns];
|
||||
});
|
||||
|
||||
return [headers.join(","), ...csvRows.map((row) => row.join(","))].join("\n");
|
||||
};
|
||||
File renamed without changes.
@@ -0,0 +1,112 @@
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
import prismock from "../../../../tests/libs/__mocks__/prisma";
|
||||
|
||||
import { describe, test, vi, expect, beforeEach } from "vitest";
|
||||
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import { CreationSource } from "@calcom/prisma/enums";
|
||||
|
||||
vi.mock("@calcom/lib/server/i18n", () => {
|
||||
return {
|
||||
getTranslation: async (locale: string, namespace: string) => {
|
||||
const t = (key: string) => key;
|
||||
t.locale = locale;
|
||||
t.namespace = namespace;
|
||||
return t;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
describe("UserRepository", () => {
|
||||
beforeEach(() => {
|
||||
prismock;
|
||||
});
|
||||
|
||||
describe("create", () => {
|
||||
test("Should create a user without a password", async () => {
|
||||
const user = await new UserRepository(prismock).create({
|
||||
username: "test",
|
||||
email: "[email protected]",
|
||||
organizationId: null,
|
||||
creationSource: CreationSource.WEBAPP,
|
||||
locked: false,
|
||||
});
|
||||
|
||||
expect(user).toEqual(
|
||||
expect.objectContaining({
|
||||
username: "test",
|
||||
email: "[email protected]",
|
||||
organizationId: null,
|
||||
creationSource: CreationSource.WEBAPP,
|
||||
locked: false,
|
||||
})
|
||||
);
|
||||
|
||||
const password = await prismock.userPassword.findUnique({
|
||||
where: {
|
||||
userId: user.id,
|
||||
},
|
||||
});
|
||||
|
||||
expect(password).toBeNull();
|
||||
});
|
||||
|
||||
test("If locked param is passed, user should be locked", async () => {
|
||||
const user = await new UserRepository(prismock).create({
|
||||
username: "test",
|
||||
email: "[email protected]",
|
||||
organizationId: null,
|
||||
creationSource: CreationSource.WEBAPP,
|
||||
locked: true,
|
||||
});
|
||||
|
||||
const userQuery = await prismock.user.findUnique({
|
||||
where: {
|
||||
email: "[email protected]",
|
||||
},
|
||||
select: {
|
||||
locked: true,
|
||||
},
|
||||
});
|
||||
|
||||
expect(userQuery).toEqual(
|
||||
expect.objectContaining({
|
||||
locked: true,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test("If organizationId is passed, user should be associated with the organization", async () => {
|
||||
const organizationId = 123;
|
||||
const username = "test";
|
||||
|
||||
const user = await new UserRepository(prismock).create({
|
||||
username,
|
||||
email: "[email protected]",
|
||||
organizationId,
|
||||
creationSource: CreationSource.WEBAPP,
|
||||
locked: true,
|
||||
});
|
||||
|
||||
expect(user).toEqual(
|
||||
expect.objectContaining({
|
||||
organizationId,
|
||||
})
|
||||
);
|
||||
|
||||
const profile = await prismock.profile.findFirst({
|
||||
where: {
|
||||
organizationId,
|
||||
username,
|
||||
},
|
||||
});
|
||||
|
||||
expect(profile).toEqual(
|
||||
expect.objectContaining({
|
||||
organizationId,
|
||||
username,
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,146 @@
|
||||
import prismock from "../../../../tests/libs/__mocks__/prisma";
|
||||
|
||||
import { describe, test, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import { checkIfEmailIsBlockedInWatchlistController } from "@calcom/features/watchlist/operations/check-if-email-in-watchlist.controller";
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import { CreationSource } from "@calcom/prisma/enums";
|
||||
|
||||
import { UserCreationService } from "./userCreationService";
|
||||
|
||||
vi.mock("@calcom/lib/server/i18n", () => {
|
||||
return {
|
||||
getTranslation: async (locale: string, namespace: string) => {
|
||||
const t = (key: string) => key;
|
||||
t.locale = locale;
|
||||
t.namespace = namespace;
|
||||
return t;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@calcom/lib/auth/hashPassword", () => ({
|
||||
hashPassword: vi.fn().mockResolvedValue("hashed-password"),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/users/repositories/UserRepository", () => {
|
||||
return {
|
||||
UserRepository: vi.fn().mockImplementation(() => ({
|
||||
create: vi.fn(),
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@calcom/features/watchlist/operations/check-if-email-in-watchlist.controller", (async) => ({
|
||||
checkIfEmailIsBlockedInWatchlistController: vi.fn(() => false),
|
||||
}));
|
||||
|
||||
const mockUserData = {
|
||||
email: "[email protected]",
|
||||
username: "test",
|
||||
creationSource: CreationSource.WEBAPP,
|
||||
};
|
||||
|
||||
vi.stubEnv("CALCOM_LICENSE_KEY", undefined);
|
||||
|
||||
describe("UserCreationService", () => {
|
||||
beforeEach(() => {
|
||||
prismock;
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("should create user", async () => {
|
||||
const mockCreate = vi.fn().mockResolvedValue({
|
||||
username: "test",
|
||||
locked: false,
|
||||
organizationId: null,
|
||||
} as any);
|
||||
|
||||
const mockUserRepository = vi.mocked(UserRepository);
|
||||
if (mockUserRepository && typeof mockUserRepository.mockImplementation === "function") {
|
||||
mockUserRepository.mockImplementation(
|
||||
() =>
|
||||
({
|
||||
create: mockCreate,
|
||||
} as any)
|
||||
);
|
||||
}
|
||||
|
||||
const user = await UserCreationService.createUser({ data: mockUserData });
|
||||
|
||||
expect(mockCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
username: "test",
|
||||
locked: false,
|
||||
organizationId: null,
|
||||
})
|
||||
);
|
||||
|
||||
expect(user).not.toHaveProperty("locked");
|
||||
});
|
||||
|
||||
test("should lock user when email is in watchlist", async () => {
|
||||
vi.mocked(checkIfEmailIsBlockedInWatchlistController).mockResolvedValue(true);
|
||||
|
||||
const mockCreate = vi.fn().mockResolvedValue({
|
||||
username: "test",
|
||||
locked: true,
|
||||
organizationId: null,
|
||||
} as any);
|
||||
|
||||
const mockUserRepository = vi.mocked(UserRepository);
|
||||
if (mockUserRepository && typeof mockUserRepository.mockImplementation === "function") {
|
||||
mockUserRepository.mockImplementation(
|
||||
() =>
|
||||
({
|
||||
create: mockCreate,
|
||||
} as any)
|
||||
);
|
||||
}
|
||||
|
||||
const user = await UserCreationService.createUser({ data: mockUserData });
|
||||
|
||||
expect(mockCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
locked: true,
|
||||
})
|
||||
);
|
||||
|
||||
expect(user).not.toHaveProperty("locked");
|
||||
});
|
||||
|
||||
test("should hash password when provided", async () => {
|
||||
const mockPassword = "password";
|
||||
vi.mocked(hashPassword).mockResolvedValue("hashed_password");
|
||||
|
||||
const mockCreate = vi.fn().mockResolvedValue({
|
||||
username: "test",
|
||||
locked: false,
|
||||
organizationId: null,
|
||||
} as any);
|
||||
|
||||
const mockUserRepository = vi.mocked(UserRepository);
|
||||
if (mockUserRepository && typeof mockUserRepository.mockImplementation === "function") {
|
||||
mockUserRepository.mockImplementation(
|
||||
() =>
|
||||
({
|
||||
create: mockCreate,
|
||||
} as any)
|
||||
);
|
||||
}
|
||||
|
||||
const user = await UserCreationService.createUser({
|
||||
data: { ...mockUserData, password: mockPassword },
|
||||
});
|
||||
|
||||
expect(hashPassword).toHaveBeenCalledWith(mockPassword);
|
||||
expect(mockCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
hashedPassword: "hashed_password",
|
||||
})
|
||||
);
|
||||
|
||||
expect(user).not.toHaveProperty("locked");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { checkIfEmailIsBlockedInWatchlistController } from "@calcom/features/watchlist/operations/check-if-email-in-watchlist.controller";
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { CreationSource, UserPermissionRole, IdentityProvider } from "@calcom/prisma/enums";
|
||||
|
||||
interface CreateUserInput {
|
||||
email: string;
|
||||
username: string;
|
||||
name?: string | null;
|
||||
password?: string;
|
||||
brandColor?: string;
|
||||
darkBrandColor?: string;
|
||||
hideBranding?: boolean;
|
||||
weekStart?: string;
|
||||
timeZone?: string;
|
||||
theme?: string | null;
|
||||
timeFormat?: number;
|
||||
locale?: string;
|
||||
avatar?: string;
|
||||
organizationId?: number | null;
|
||||
creationSource: CreationSource;
|
||||
role?: UserPermissionRole;
|
||||
emailVerified?: Date;
|
||||
identityProvider?: IdentityProvider;
|
||||
}
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["[userCreationService]"] });
|
||||
|
||||
export class UserCreationService {
|
||||
static async createUser({ data }: { data: CreateUserInput }) {
|
||||
const { email, password, username } = data;
|
||||
|
||||
const shouldLockByDefault = await checkIfEmailIsBlockedInWatchlistController(email);
|
||||
|
||||
const hashedPassword = password ? await hashPassword(password) : null;
|
||||
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const user = await userRepo.create({
|
||||
...data,
|
||||
username: slugify(username),
|
||||
...(hashedPassword && { hashedPassword }),
|
||||
organizationId: data?.organizationId ?? null,
|
||||
locked: shouldLockByDefault,
|
||||
});
|
||||
|
||||
log.info(`Created user: ${user.id} with locked status of ${user.locked}`);
|
||||
|
||||
const { locked, ...restUser } = user;
|
||||
|
||||
return restUser;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user