Files
cal.diy/packages/features/ee/teams/repositories/TeamRepository.test.ts
T
29ec2b9cb6 refactor: split flag repositories into Prisma and Cached layers (#27186)
* refactor: split flag repositories into Prisma and Cached layers

- Rename FeatureRepository to PrismaFeatureRepository (raw DB access)
- Rename TeamFeatureRepository to PrismaTeamFeatureRepository (raw DB access)
- Rename UserFeatureRepository to PrismaUserFeatureRepository (raw DB access)
- Create CachedFeatureRepository with @Memoize wrapping PrismaFeatureRepository
- Create CachedTeamFeatureRepository with @Memoize/@Unmemoize wrapping PrismaTeamFeatureRepository
- Create CachedUserFeatureRepository with @Memoize/@Unmemoize wrapping PrismaUserFeatureRepository
- Update DI tokens, modules, and containers for all 6 repositories
- Update imports in FeatureOptInService and related modules
- Update tests to use new repository structure

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

* refactor: simplify @Memoize key patterns and delegate batch methods to Prisma

- Use direct function references for @Memoize key (e.g., KEY.all instead of () => KEY.all())
- Simplify batch methods in Cached repositories to delegate to Prisma repository
- Update tests to reflect the new delegation pattern

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

* fix: add orderBy to TeamRepository.findAllByParentId for deterministic results

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

* test: update TeamRepository test to expect orderBy in findAllByParentId

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

* refactor: cleanup features repository and add specialized repository methods (#27195)

* refactor: cleanup features repository and add findBySlug, update methods

- Remove unused methods from FeaturesRepository (keep getTeamsWithFeatureEnabled)
- Add findAll(), findBySlug(), update() to IFeatureRepository interface
- Add findAll() with caching to CachedFeatureRepository
- Add findBySlug() with caching to CachedFeatureRepository
- Add update() with Unmemoize to CachedFeatureRepository
- Add checkIfFeatureIsEnabledGlobally() to CachedFeatureRepository
- Update toggleFeatureFlag.handler.ts to use repository instead of raw Prisma
- Add comprehensive unit tests for all new methods

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

* fix: update updatedAt timestamp in feature update method

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

* refactor: move feature check methods to specialized repositories

- Replace getUserFeaturesStatus with two checkIfUserHasFeature calls in bookings page
- Move checkIfTeamHasFeature to PrismaTeamFeatureRepository with pass-through in CachedTeamFeatureRepository
- Move checkIfUserHasFeature and checkIfUserHasFeatureNonHierarchical to PrismaUserFeatureRepository with pass-throughs in CachedUserFeatureRepository
- Add getEnabledFeatures to PrismaTeamFeatureRepository with caching in CachedTeamFeatureRepository
- Keep FeaturesRepository methods as pass-throughs for backward compatibility
- Update test to expect updatedAt in feature update

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

* refactor: remove getUserFeaturesStatus and unused methods from FeaturesRepository

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

* restore comment

* fix: invalidate all-features cache on update and enabledFeatures cache on upsert/delete

- CachedFeatureRepository: Add KEY.all() to @Unmemoize keys in update() to prevent stale findAll() results
- CachedTeamFeatureRepository: Add KEY.enabledFeatures(teamId) to @Unmemoize keys in upsert() and delete() to prevent stale getEnabledFeatures() results

Co-Authored-By: unknown <>

---------

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

* test: add CachedUserFeatureRepository tests

Add comprehensive tests for CachedUserFeatureRepository covering:
- findByUserIdAndFeatureId (cache hit, cache miss, not found)
- findByUserIdAndFeatureIds (empty input, multiple features)
- upsert (with cache invalidation)
- delete (with cache invalidation)
- findAutoOptInByUserId (cache hit, cache miss, not found)
- setAutoOptIn (with cache invalidation)

Co-Authored-By: unknown <>

* test: remove tests for methods removed from FeaturesRepository

Remove integration tests for methods that were intentionally removed:
- getUserFeatureStates
- getTeamsFeatureStates
- getUserAutoOptIn
- getTeamsAutoOptIn
- setUserAutoOptIn
- setTeamAutoOptIn

Co-Authored-By: unknown <>

* avoid N+1 query

* refactor: add select clauses to PrismaFeatureRepository queries

- Add explicit select clauses to findAll, findBySlug, and update methods
- Only fetch fields needed for FeatureDto (slug, enabled, description, type, stale, lastUsedAt, createdAt, updatedAt, updatedBy)
- Update tests to expect select clauses
- Fix UserFeatureRepository test to use findMany mock

Co-Authored-By: unknown <>

* fix bad conflict resolved

* use userId

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-02 14:26:23 +01:00

470 lines
11 KiB
TypeScript

import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { Team } from "@calcom/prisma/client";
import { getTeam, getOrg, TeamRepository } from "./TeamRepository";
const sampleTeamProps = {
logo: null,
logoUrl: null,
calVideoLogo: null,
appLogo: null,
appIconLogo: null,
bio: null,
description: null,
hideBranding: false,
isPrivate: false,
hideBookATeamMember: false,
hideTeamProfileLink: false,
createdAt: new Date(),
theme: null,
brandColor: "",
darkBrandColor: "",
timeFormat: null,
timeZone: "",
weekStart: "",
parentId: null,
metadata: null,
isOrganization: false,
organizationSettings: null,
isPlatform: false,
bannerUrl: null,
rrResetInterval: 0,
rrResetOccurrence: 0,
rrResetLimitOn: null,
rrResetLimitOccurrences: null,
rrResetLimitDate: null,
includeManagedEventsInLimits: false,
rrTimestampBasis: null,
pendingPayment: false,
createdByOAuthClientId: null,
smsLockState: null,
smsLockReviewedByAdmin: false,
bookingLimits: null,
};
describe("TeamRepository", () => {
let teamRepository: TeamRepository;
beforeEach(() => {
vi.resetAllMocks();
teamRepository = new TeamRepository(prismaMock);
});
afterEach(() => {
vi.clearAllMocks();
});
describe("findById", () => {
it("should return null if team is not found", async () => {
prismaMock.team.findUnique.mockResolvedValue(null);
const result = await teamRepository.findById({ id: 1 });
expect(result).toBeNull();
});
it("should return parsed team if found", async () => {
const mockTeam = {
id: 1,
name: "Test Team",
slug: "test-team",
logoUrl: "test-logo-url",
parentId: 1,
metadata: {
requestedSlug: null,
},
isOrganization: true,
organizationSettings: {},
isPlatform: true,
requestedSlug: null,
};
prismaMock.team.findUnique.mockResolvedValue(mockTeam as unknown as Team);
const result = await teamRepository.findById({ id: 1 });
expect(result).toEqual(mockTeam);
});
});
describe("deleteById", () => {
it("should delete team and related data", async () => {
const mockDeletedTeam = { id: 1, name: "Deleted Team" };
const deleteManyEventTypeMock = vi.fn();
const deleteManyMembershipMock = vi.fn();
const deleteTeamMock = vi.fn().mockResolvedValue(mockDeletedTeam as unknown as Team);
prismaMock.$transaction.mockImplementation(async (callback) => {
const mockTx = {
...prismaMock,
eventType: {
...prismaMock.eventType,
deleteMany: deleteManyEventTypeMock,
},
membership: {
...prismaMock.membership,
deleteMany: deleteManyMembershipMock,
},
team: {
...prismaMock.team,
delete: deleteTeamMock,
},
};
return callback(mockTx);
});
const result = await teamRepository.deleteById({ id: 1 });
expect(deleteManyEventTypeMock).toHaveBeenCalledWith({
where: {
teamId: 1,
schedulingType: "MANAGED",
},
});
expect(deleteManyMembershipMock).toHaveBeenCalledWith({
where: {
teamId: 1,
},
});
expect(deleteTeamMock).toHaveBeenCalledWith({
where: {
id: 1,
},
});
expect(result).toEqual(mockDeletedTeam);
});
});
describe("findAllByParentId", () => {
it("should return all teams with given parentId", async () => {
const mockTeams = [{ id: 1 }, { id: 2 }];
prismaMock.team.findMany.mockResolvedValue(mockTeams as unknown as Team[]);
const result = await teamRepository.findAllByParentId({ parentId: 1 });
expect(prismaMock.team.findMany).toHaveBeenCalledWith({
where: { parentId: 1 },
select: {
id: true,
name: true,
slug: true,
logoUrl: true,
parentId: true,
metadata: true,
isOrganization: true,
organizationSettings: true,
isPlatform: true,
},
orderBy: { id: "asc" },
});
expect(result).toEqual(mockTeams);
});
});
describe("findTeamWithMembers", () => {
it("should return team with its members", async () => {
const mockTeam = { id: 1, members: [] };
prismaMock.team.findUnique.mockResolvedValue(mockTeam as unknown as Team & { members: [] });
const result = await teamRepository.findTeamWithMembers(1);
expect(prismaMock.team.findUnique).toHaveBeenCalledWith({
where: { id: 1 },
select: {
members: {
select: {
accepted: true,
},
},
id: true,
metadata: true,
parentId: true,
isOrganization: true,
},
});
expect(result).toEqual(mockTeam);
});
});
});
describe("getOrg", () => {
it("should return an Organization correctly by slug even if there is a team with the same slug", async () => {
prismaMock.team.findMany.mockResolvedValue([
{
id: 101,
name: "Test Team",
slug: "test-slug",
isOrganization: true,
} as Team,
]);
const org = await getOrg({
lookupBy: {
slug: "test-slug",
},
forOrgWithSlug: null,
teamSelect: {
id: true,
slug: true,
},
});
const firstFindManyCallArguments = prismaMock.team.findMany.mock.calls[0];
expect(firstFindManyCallArguments[0]).toEqual({
where: {
slug: "test-slug",
isOrganization: true,
},
select: {
id: true,
slug: true,
metadata: true,
isOrganization: true,
},
});
expect(org?.isOrganization).toBe(true);
});
it("should not return an org result if metadata.isOrganization isn't true", async () => {
prismaMock.team.findMany.mockResolvedValue([
{
...sampleTeamProps,
id: 101,
name: "Test Team",
slug: "test-slug",
metadata: {},
} as Team,
]);
const org = await getOrg({
lookupBy: {
slug: "test-slug",
},
forOrgWithSlug: null,
teamSelect: {
id: true,
slug: true,
},
});
const firstFindManyCallArguments = prismaMock.team.findMany.mock.calls[0];
expect(firstFindManyCallArguments[0]).toEqual({
where: {
slug: "test-slug",
isOrganization: true,
},
select: {
id: true,
slug: true,
metadata: true,
isOrganization: true,
},
});
expect(org).toBe(null);
});
it("should error if metadata isn't valid", async () => {
prismaMock.team.findMany.mockResolvedValue([
{
...sampleTeamProps,
id: 101,
name: "Test Team",
slug: "test-slug",
metadata: [],
} as Team,
]);
await expect(() =>
getOrg({
lookupBy: {
slug: "test-slug",
},
forOrgWithSlug: null,
teamSelect: {
id: true,
slug: true,
},
})
).rejects.toThrow("invalid_type");
});
});
describe("getTeam", () => {
it("should query a team correctly", async () => {
prismaMock.team.findMany.mockResolvedValue([
{
...sampleTeamProps,
id: 101,
name: "Test Team",
slug: "test-slug",
metadata: {
anything: "here",
paymentId: "1",
},
} as Team,
]);
const team = await getTeam({
lookupBy: {
slug: "test-slug",
},
forOrgWithSlug: null,
teamSelect: {
id: true,
slug: true,
name: true,
},
});
const firstFindManyCallArguments = prismaMock.team.findMany.mock.calls[0];
expect(firstFindManyCallArguments[0]).toEqual({
where: {
slug: "test-slug",
},
select: {
id: true,
slug: true,
name: true,
metadata: true,
isOrganization: true,
},
});
expect(team).not.toBeNull();
// 'anything' is not in the teamMetadata schema, so it should be stripped out
expect(team?.metadata).toEqual({ paymentId: "1" });
});
it("should not return a team result if the queried result isn't a team", async () => {
prismaMock.team.findMany.mockResolvedValue([
{
...sampleTeamProps,
id: 101,
name: "Test Team",
slug: "test-slug",
isOrganization: true,
} as Team,
]);
const team = await getTeam({
lookupBy: {
slug: "test-slug",
},
forOrgWithSlug: null,
teamSelect: {
id: true,
slug: true,
name: true,
},
});
const firstFindManyCallArguments = prismaMock.team.findMany.mock.calls[0];
expect(firstFindManyCallArguments[0]).toEqual({
where: {
slug: "test-slug",
},
select: {
id: true,
slug: true,
name: true,
metadata: true,
isOrganization: true,
},
});
expect(team).toBe(null);
});
it("should return a team by slug within an org", async () => {
prismaMock.team.findMany.mockResolvedValue([
{
...sampleTeamProps,
id: 101,
name: "Test Team",
slug: "test-slug",
parentId: 100,
metadata: null,
} as Team,
]);
await getTeam({
lookupBy: {
slug: "team-in-test-org",
},
forOrgWithSlug: "test-org",
teamSelect: {
id: true,
slug: true,
name: true,
},
});
const firstFindManyCallArguments = prismaMock.team.findMany.mock.calls[0];
expect(firstFindManyCallArguments[0]).toEqual({
where: {
slug: "team-in-test-org",
parent: {
OR: [
{
slug: "test-org",
},
{
metadata: {
path: ["requestedSlug"],
equals: "test-org",
},
},
],
isOrganization: true,
},
},
select: {
id: true,
name: true,
slug: true,
metadata: true,
isOrganization: true,
},
});
});
it("should return a team by requestedSlug within an org", async () => {
prismaMock.team.findMany.mockResolvedValue([]);
await getTeam({
lookupBy: {
slug: "test-team",
},
forOrgWithSlug: "test-org",
teamSelect: {
id: true,
slug: true,
name: true,
},
});
const firstFindManyCallArguments = prismaMock.team.findMany.mock.calls[0];
expect(firstFindManyCallArguments[0]).toEqual({
where: {
slug: "test-team",
parent: {
isOrganization: true,
OR: [
{
slug: "test-org",
},
{
metadata: {
path: ["requestedSlug"],
equals: "test-org",
},
},
],
},
},
select: {
id: true,
slug: true,
name: true,
metadata: true,
isOrganization: true,
},
});
});
});