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:
Benny Joo authored and GitHub committed 2025-10-13 12:01:02 -03:00
1 parent 1dc20e3aec
commit ff38d6c7db
339 files changed
+876 -833

No files matched your search

@@ -0,0 +1,154 @@
import prismock from "../../../../../tests/libs/__mocks__/prisma";
import { describe, expect, it } from "vitest";
import { ColumnFilterType } from "@calcom/features/data-table/lib/types";
import { MembershipRole } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { FilterSegmentRepository } from "../../repositories/filterSegment";
import type { TCreateFilterSegmentInputSchema } from "../../repositories/filterSegment.type";
const repository = new FilterSegmentRepository();
describe("FilterSegmentRepository.create()", () => {
const userId = 1;
const mockUser = {
id: userId,
name: "Test User",
} as NonNullable<TrpcSessionUser>;
const baseInput = {
tableIdentifier: "bookings",
activeFilters: [
{
f: "status",
v: {
type: ColumnFilterType.SINGLE_SELECT,
data: "active",
},
},
],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
searchTerm: "test search",
};
it("should create a user-scoped filter segment", async () => {
const input: TCreateFilterSegmentInputSchema = {
...baseInput,
scope: "USER",
name: "My Bookings",
};
const result = await repository.create({
userId,
input,
});
expect(result).toEqual(
expect.objectContaining({
userId: mockUser.id,
scope: "USER",
tableIdentifier: "bookings",
name: "My Bookings",
searchTerm: "test search",
})
);
});
it("should create a team-scoped filter segment for admin user", async () => {
// Create team membership first
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: 1,
accepted: true,
role: MembershipRole.ADMIN,
},
});
const input: TCreateFilterSegmentInputSchema = {
...baseInput,
scope: "TEAM",
teamId: 1,
name: "Team Bookings",
};
const result = await repository.create({
userId,
input,
});
expect(result).toEqual(
expect.objectContaining({
teamId: 1,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Team Bookings",
searchTerm: "test search",
})
);
});
it("should throw error when creating team segment without admin role", async () => {
// Create team membership with MEMBER role
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: 1,
accepted: true,
role: MembershipRole.MEMBER,
},
});
const input: TCreateFilterSegmentInputSchema = {
...baseInput,
scope: "TEAM",
teamId: 1,
name: "Team Bookings",
};
await expect(
repository.create({
userId,
input,
})
).rejects.toThrow("You must be a team admin or owner to create team segments");
});
it("should throw error when creating team segment without teamId", async () => {
const invalidInput = {
...baseInput,
scope: "TEAM",
name: "Team Bookings",
};
await expect(
repository.create({
userId,
// @ts-expect-error - Testing invalid input where teamId is missing for TEAM scope
input: invalidInput,
})
).rejects.toThrow("Team ID is required for team scope");
});
it("should throw error when creating user segment with teamId", async () => {
const invalidInput = {
...baseInput,
scope: "USER",
name: "My Bookings",
teamId: 1,
};
await expect(
repository.create({
userId,
// @ts-expect-error - Testing invalid input where teamId is present for USER scope
input: invalidInput,
})
).rejects.toThrow("Team ID is not allowed for user scope");
});
});
@@ -0,0 +1,166 @@
import prismock from "../../../../../tests/libs/__mocks__/prisma";
import { describe, expect, it } from "vitest";
import { MembershipRole } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { FilterSegmentRepository } from "../../repositories/filterSegment";
import { type TDeleteFilterSegmentInputSchema } from "../../repositories/filterSegment.type";
const repository = new FilterSegmentRepository();
describe("FilterSegmentRepository.delete()", () => {
const userId = 1;
const mockUser = {
id: userId,
name: "Test User",
} as NonNullable<TrpcSessionUser>;
it("should delete a user-scoped filter segment", async () => {
// Create a user-scoped segment first
const segment = await prismock.filterSegment.create({
data: {
userId: mockUser.id,
scope: "USER",
tableIdentifier: "bookings",
name: "My Bookings",
activeFilters: { f: "status" },
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
},
});
const input: TDeleteFilterSegmentInputSchema = {
id: segment.id,
};
await expect(
repository.delete({
userId,
id: segment.id,
})
).resolves.not.toThrow();
// Verify segment is deleted
const deletedSegment = await prismock.filterSegment.findUnique({
where: { id: segment.id },
});
expect(deletedSegment).toBeNull();
});
it("should delete a team-scoped filter segment for admin user", async () => {
// Create team first
const team = await prismock.team.create({
data: {
name: "Test Team",
slug: "test-team",
},
});
// Create team membership
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: team.id,
accepted: true,
role: MembershipRole.ADMIN,
},
});
// Create a team-scoped segment
const segment = await prismock.filterSegment.create({
data: {
userId: mockUser.id,
teamId: team.id,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Team Bookings",
activeFilters: { f: "status" },
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
},
});
const input: TDeleteFilterSegmentInputSchema = {
id: segment.id,
};
await expect(
repository.delete({
userId,
id: segment.id,
})
).resolves.not.toThrow();
// Verify segment is deleted
const deletedSegment = await prismock.filterSegment.findUnique({
where: { id: segment.id },
});
expect(deletedSegment).toBeNull();
});
it("should throw error when deleting non-existent segment", async () => {
const input: TDeleteFilterSegmentInputSchema = {
id: 999,
};
await expect(
repository.delete({
userId,
id: 999,
})
).rejects.toThrow("Filter segment not found or you don't have permission to delete it");
});
it("should throw error when deleting team segment without admin role", async () => {
// Create team first
const team = await prismock.team.create({
data: {
name: "Test Team",
slug: "test-team",
},
});
// Create team membership with MEMBER role
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: team.id,
accepted: true,
role: MembershipRole.MEMBER,
},
});
// Create a team-scoped segment
const segment = await prismock.filterSegment.create({
data: {
userId: mockUser.id,
teamId: team.id,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Team Bookings",
activeFilters: { f: "status" },
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
},
});
const input: TDeleteFilterSegmentInputSchema = {
id: segment.id,
};
await expect(
repository.delete({
userId,
id: segment.id,
})
).rejects.toThrow("Filter segment not found or you don't have permission to delete it");
});
});
@@ -0,0 +1,337 @@
import prismock from "../../../../../tests/libs/__mocks__/prisma";
import { describe, expect, it } from "vitest";
import { MembershipRole } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { FilterSegmentRepository } from "../../repositories/filterSegment";
import { type TListFilterSegmentsInputSchema } from "../../repositories/filterSegment.type";
const repository = new FilterSegmentRepository();
describe("FilterSegmentRepository.get()", () => {
const userId = 1;
const mockUser = {
id: userId,
name: "Test User",
} as NonNullable<TrpcSessionUser>;
it("should return user-scoped filter segments", async () => {
// Create user-scoped segments
await prismock.filterSegment.create({
data: {
userId: mockUser.id,
scope: "USER",
tableIdentifier: "bookings",
name: "My Bookings",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
},
});
await prismock.filterSegment.create({
data: {
userId: mockUser.id,
scope: "USER",
tableIdentifier: "bookings",
name: "My Other Bookings",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: false }],
columnVisibility: {},
columnSizing: {},
perPage: 20,
},
});
const input: TListFilterSegmentsInputSchema = {
tableIdentifier: "bookings",
};
const result = await repository.get({
userId,
tableIdentifier: input.tableIdentifier,
});
expect(result.segments).toHaveLength(2);
expect(result.segments).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "My Other Bookings",
scope: "USER",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: false }],
columnVisibility: {},
columnSizing: {},
perPage: 20,
}),
expect.objectContaining({
name: "My Bookings",
scope: "USER",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
}),
])
);
});
it("should return team-scoped filter segments for team member", async () => {
// Create team first
const team = await prismock.team.create({
data: {
name: "Test Team",
slug: "test-team",
},
});
// Create team membership
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: team.id,
accepted: true,
role: MembershipRole.MEMBER,
},
});
// Create team-scoped segments
await prismock.filterSegment.create({
data: {
userId: mockUser.id,
teamId: team.id,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Team Bookings",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
},
});
await prismock.filterSegment.create({
data: {
userId: mockUser.id,
teamId: team.id,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Other Team Bookings",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: false }],
columnVisibility: {},
columnSizing: {},
perPage: 15,
},
});
const input: TListFilterSegmentsInputSchema = {
tableIdentifier: "bookings",
};
const result = await repository.get({
userId,
tableIdentifier: input.tableIdentifier,
});
expect(result.segments).toHaveLength(2);
expect(result.segments).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "Other Team Bookings",
scope: "TEAM",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: false }],
columnVisibility: {},
columnSizing: {},
perPage: 15,
}),
expect.objectContaining({
name: "Team Bookings",
scope: "TEAM",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
}),
])
);
});
it("should return both user-scoped and team-scoped segments", async () => {
// Create team first
const team = await prismock.team.create({
data: {
name: "Test Team",
slug: "test-team",
},
});
// Create team membership
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: team.id,
accepted: true,
role: MembershipRole.MEMBER,
},
});
// Create user-scoped segment
await prismock.filterSegment.create({
data: {
userId: mockUser.id,
scope: "USER",
tableIdentifier: "bookings",
name: "My Bookings",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
},
});
// Create team-scoped segment
await prismock.filterSegment.create({
data: {
userId: mockUser.id,
teamId: team.id,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Team Bookings",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: false }],
columnVisibility: {},
columnSizing: {},
perPage: 15,
},
});
const input: TListFilterSegmentsInputSchema = {
tableIdentifier: "bookings",
};
const result = await repository.get({
userId,
tableIdentifier: input.tableIdentifier,
});
expect(result.segments).toHaveLength(2);
expect(result.segments).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "My Bookings",
scope: "USER",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
}),
expect.objectContaining({
name: "Team Bookings",
scope: "TEAM",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: false }],
columnVisibility: {},
columnSizing: {},
perPage: 15,
}),
])
);
});
it("should return empty array when no segments exist", async () => {
const input: TListFilterSegmentsInputSchema = {
tableIdentifier: "bookings",
};
const result = await repository.get({
userId,
tableIdentifier: input.tableIdentifier,
});
expect(result).toEqual({
segments: [],
preferredSegmentId: null,
});
});
it("should return segments with user preferences", async () => {
// Create a filter segment
const segment = await prismock.filterSegment.create({
data: {
userId: mockUser.id,
scope: "USER",
tableIdentifier: "contacts",
name: "Important Contacts",
activeFilters: [{ f: "priority" }],
sorting: [{ id: "lastContact", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 50,
},
});
// Create a user preference for this segment
await prismock.userFilterSegmentPreference.create({
data: {
userId: mockUser.id,
tableIdentifier: "contacts",
segmentId: segment.id,
},
});
const result = await repository.get({
userId: mockUser.id,
tableIdentifier: "contacts",
});
expect(result.segments).toHaveLength(1);
expect(result.preferredSegmentId).toEqual({ id: segment.id, type: "user" });
expect(result.segments[0].name).toBe("Important Contacts");
});
it("should handle segments with null JSON fields gracefully", async () => {
// Create segment with minimal data (some fields will be null/undefined)
await prismock.filterSegment.create({
data: {
userId: mockUser.id,
scope: "USER",
tableIdentifier: "reports",
name: "Basic Report",
activeFilters: undefined, // This should be parsed to []
sorting: undefined, // This should be parsed to []
columnVisibility: undefined, // This should be parsed to {}
columnSizing: undefined, // This should be parsed to {}
perPage: 10,
searchTerm: null,
},
});
const result = await repository.get({
userId: mockUser.id,
tableIdentifier: "reports",
});
expect(result.segments).toHaveLength(1);
expect(result.segments[0]).toEqual(
expect.objectContaining({
name: "Basic Report",
activeFilters: [], // Should default to empty array
sorting: [], // Should default to empty array
columnVisibility: {}, // Should default to empty object
columnSizing: {}, // Should default to empty object
perPage: 10,
})
);
});
});
@@ -0,0 +1,248 @@
import prismock from "../../../../../tests/libs/__mocks__/prisma";
import { describe, expect, it } from "vitest";
import { ColumnFilterType } from "@calcom/features/data-table/lib/types";
import { MembershipRole } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { FilterSegmentRepository } from "../../repositories/filterSegment";
import { type TUpdateFilterSegmentInputSchema } from "../../repositories/filterSegment.type";
const repository = new FilterSegmentRepository();
describe("FilterSegmentRepository.update()", () => {
const userId = 1;
const mockUser = {
id: userId,
name: "Test User",
} as NonNullable<TrpcSessionUser>;
const baseInput = {
tableIdentifier: "bookings",
activeFilters: [
{
f: "status",
v: {
type: ColumnFilterType.SINGLE_SELECT,
data: "active",
},
},
],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
searchTerm: "test search",
};
it("should update a user-scoped filter segment", async () => {
// Create a user-scoped segment first
const segment = await prismock.filterSegment.create({
data: {
...baseInput,
userId: mockUser.id,
scope: "USER",
name: "My Bookings",
},
});
const input: TUpdateFilterSegmentInputSchema = {
...baseInput,
id: segment.id,
scope: "USER",
name: "Updated Bookings",
searchTerm: "updated search",
activeFilters: [
{
f: "status",
v: {
type: ColumnFilterType.SINGLE_SELECT,
data: "inactive",
},
},
],
};
const result = await repository.update({
userId,
input,
});
expect(result).toEqual(
expect.objectContaining({
userId: mockUser.id,
scope: "USER",
tableIdentifier: "bookings",
name: "Updated Bookings",
searchTerm: "updated search",
activeFilters: [
{
f: "status",
v: { type: ColumnFilterType.SINGLE_SELECT, data: "inactive" },
},
],
})
);
});
it("should update a team-scoped filter segment for admin user", async () => {
// Create team first
const team = await prismock.team.create({
data: {
name: "Test Team",
slug: "test-team",
},
});
// Create team membership first
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: team.id,
accepted: true,
role: MembershipRole.ADMIN,
},
});
// Create a team-scoped segment
const segment = await prismock.filterSegment.create({
data: {
...baseInput,
userId: mockUser.id,
teamId: team.id,
scope: "TEAM",
name: "Team Bookings",
},
});
const input: TUpdateFilterSegmentInputSchema = {
id: segment.id,
scope: "TEAM",
teamId: team.id,
name: "Updated Team Bookings",
searchTerm: "updated search",
activeFilters: [
{
f: "status",
v: {
type: ColumnFilterType.SINGLE_SELECT,
data: "inactive",
},
},
],
};
const result = await repository.update({
userId,
input,
});
expect(result).toEqual(
expect.objectContaining({
id: segment.id,
teamId: team.id,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Updated Team Bookings",
searchTerm: "updated search",
activeFilters: [
{
f: "status",
v: { type: ColumnFilterType.SINGLE_SELECT, data: "inactive" },
},
],
})
);
});
it("should throw error when updating non-existent segment", async () => {
const input: TUpdateFilterSegmentInputSchema = {
id: 999,
scope: "USER",
name: "Updated Bookings",
activeFilters: [
{
f: "status",
v: { type: ColumnFilterType.SINGLE_SELECT, data: "inactive" },
},
],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
};
await expect(
repository.update({
userId,
input,
})
).rejects.toThrow("Filter segment not found or you don't have permission to update it");
});
it("should throw error when updating team segment without admin role", async () => {
// Create team first
const team = await prismock.team.create({
data: {
name: "Test Team",
slug: "test-team",
},
});
// Create team membership with MEMBER role
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: team.id,
accepted: true,
role: MembershipRole.MEMBER,
},
});
// Create a team-scoped segment
const segment = await prismock.filterSegment.create({
data: {
userId: mockUser.id,
teamId: team.id,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Team Bookings",
activeFilters: [
{
f: "status",
v: { type: ColumnFilterType.SINGLE_SELECT, data: "active" },
},
],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
},
});
const input: TUpdateFilterSegmentInputSchema = {
id: segment.id,
scope: "TEAM",
teamId: team.id,
name: "Updated Team Bookings",
activeFilters: [
{
f: "status",
v: { type: ColumnFilterType.SINGLE_SELECT, data: "inactive" },
},
],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
};
await expect(
repository.update({
userId,
input,
})
).rejects.toThrow("Filter segment not found or you don't have permission to update it");
});
});
@@ -0,0 +1,395 @@
import type { FilterSegmentOutput, SegmentIdentifier } from "@calcom/features/data-table/lib/types";
import {
ZActiveFilters,
ZSortingState,
ZColumnSizing,
ZColumnVisibility,
} from "@calcom/features/data-table/lib/types";
import { prisma } from "@calcom/prisma";
import type { UserFilterSegmentPreference } from "@calcom/prisma/client";
import type { TCreateFilterSegmentInputSchema, TUpdateFilterSegmentInputSchema } from "./filterSegment.type";
export interface IFilterSegmentRepository {
get({ userId, tableIdentifier }: { userId: number; tableIdentifier: string }): Promise<{
segments: FilterSegmentOutput[];
preferredSegmentId: SegmentIdentifier | null;
}>;
create({
userId,
input,
}: {
userId: number;
input: TCreateFilterSegmentInputSchema;
}): Promise<FilterSegmentOutput>;
update({
userId,
input,
}: {
userId: number;
input: TUpdateFilterSegmentInputSchema;
}): Promise<FilterSegmentOutput>;
delete({ userId, id }: { userId: number; id: number }): Promise<void>;
setPreference({
userId,
tableIdentifier,
segmentId,
}: {
userId: number;
tableIdentifier: string;
segmentId: SegmentIdentifier | null;
}): Promise<UserFilterSegmentPreference | null>;
}
export class FilterSegmentRepository implements IFilterSegmentRepository {
async get({ userId, tableIdentifier }: { userId: number; tableIdentifier: string }) {
// Get all teams that the user is a member of
const userTeamIds = await prisma.membership
.findMany({
where: {
userId,
accepted: true,
},
select: {
teamId: true,
},
})
.then((memberships) => memberships.map((m) => m.teamId));
// Fetch both user-scoped and team-scoped segments
const segments = await prisma.filterSegment.findMany({
where: {
tableIdentifier,
OR: [
// User-scoped segments created by the current user
{
scope: "USER",
userId,
},
// Team-scoped segments for teams the user belongs to
{
scope: "TEAM",
teamId: {
in: userTeamIds,
},
},
],
},
select: {
id: true,
name: true,
tableIdentifier: true,
scope: true,
activeFilters: true,
sorting: true,
columnVisibility: true,
columnSizing: true,
perPage: true,
searchTerm: true,
createdAt: true,
updatedAt: true,
userId: true,
teamId: true,
team: {
select: {
id: true,
name: true,
},
},
},
orderBy: [
{ scope: "desc" }, // USER segments first, then TEAM segments
{ createdAt: "desc" }, // Newest first within each scope
],
});
const parsedSegments: FilterSegmentOutput[] = segments.map((segment) => ({
...segment,
activeFilters: ZActiveFilters.catch([]).parse(segment.activeFilters),
sorting: ZSortingState.catch([]).parse(segment.sorting),
columnVisibility: ZColumnVisibility.catch({}).parse(segment.columnVisibility),
columnSizing: ZColumnSizing.catch({}).parse(segment.columnSizing),
}));
const preference = await prisma.userFilterSegmentPreference.findUnique({
where: {
userId_tableIdentifier: {
userId,
tableIdentifier,
},
},
select: {
segmentId: true,
systemSegmentId: true,
},
});
const preferredSegmentId = preference?.segmentId
? { id: preference.segmentId, type: "user" as const }
: preference?.systemSegmentId
? { id: preference.systemSegmentId, type: "system" as const }
: null;
return {
segments: parsedSegments,
preferredSegmentId,
};
}
async create({ userId, input }: { userId: number; input: TCreateFilterSegmentInputSchema }) {
const { scope, teamId, ...filterData } = input;
// If scope is TEAM, verify user has admin/owner permissions
if (scope === "TEAM") {
if (!teamId) {
throw new Error("Team ID is required for team scope");
}
const membership = await prisma.membership.findFirst({
select: {
id: true,
},
where: {
userId,
teamId,
accepted: true,
role: {
in: ["ADMIN", "OWNER"],
},
},
});
if (!membership) {
throw new Error("You must be a team admin or owner to create team segments");
}
}
// For USER scope, ensure no teamId is provided
if (scope === "USER" && teamId) {
throw new Error("Team ID is not allowed for user scope");
}
// Create the filter segment
const filterSegment = await prisma.filterSegment.create({
data: {
...filterData,
scope,
...(scope === "TEAM" ? { teamId } : {}),
userId,
},
select: {
id: true,
name: true,
tableIdentifier: true,
scope: true,
activeFilters: true,
sorting: true,
columnVisibility: true,
columnSizing: true,
perPage: true,
searchTerm: true,
createdAt: true,
updatedAt: true,
userId: true,
teamId: true,
team: {
select: {
id: true,
name: true,
},
},
},
});
// Parse the segment with Zod schemas
const parsedSegment: FilterSegmentOutput = {
...filterSegment,
activeFilters: ZActiveFilters.catch([]).parse(filterSegment.activeFilters),
sorting: ZSortingState.catch([]).parse(filterSegment.sorting),
columnVisibility: ZColumnVisibility.catch({}).parse(filterSegment.columnVisibility),
columnSizing: ZColumnSizing.catch({}).parse(filterSegment.columnSizing),
};
return parsedSegment;
}
async update({ userId, input }: { userId: number; input: TUpdateFilterSegmentInputSchema }) {
const { id, name, activeFilters, sorting, columnVisibility, columnSizing, perPage, searchTerm } = input;
// First, fetch the existing segment to check permissions
const existingSegment = await prisma.filterSegment.findFirst({
where: {
id,
...(input.scope === "TEAM"
? {
scope: "TEAM",
teamId: input.teamId,
team: {
members: {
some: {
userId,
accepted: true,
role: {
in: ["ADMIN", "OWNER"],
},
},
},
},
}
: {
scope: "USER",
userId,
}),
},
select: {
id: true,
},
});
if (!existingSegment) {
throw new Error("Filter segment not found or you don't have permission to update it");
}
// Update the filter segment with only the allowed fields
const updatedSegment = await prisma.filterSegment.update({
where: { id },
data: {
name,
activeFilters,
sorting,
columnVisibility,
columnSizing,
perPage,
searchTerm,
},
select: {
id: true,
name: true,
tableIdentifier: true,
scope: true,
activeFilters: true,
sorting: true,
columnVisibility: true,
columnSizing: true,
perPage: true,
searchTerm: true,
createdAt: true,
updatedAt: true,
userId: true,
teamId: true,
team: {
select: {
id: true,
name: true,
},
},
},
});
// Parse the segment with Zod schemas
const parsedSegment: FilterSegmentOutput = {
...updatedSegment,
activeFilters: ZActiveFilters.catch([]).parse(updatedSegment.activeFilters),
sorting: ZSortingState.catch([]).parse(updatedSegment.sorting),
columnVisibility: ZColumnVisibility.catch({}).parse(updatedSegment.columnVisibility),
columnSizing: ZColumnSizing.catch({}).parse(updatedSegment.columnSizing),
};
return parsedSegment;
}
async delete({ userId, id }: { userId: number; id: number }) {
// First, fetch the existing segment to check permissions
const existingSegment = await prisma.filterSegment.findFirst({
where: {
id,
OR: [
{
scope: "TEAM",
teamId: { not: null },
team: {
members: {
some: {
userId,
accepted: true,
role: {
in: ["ADMIN", "OWNER"],
},
},
},
},
},
{
scope: "USER",
userId,
},
],
},
select: {
id: true,
},
});
if (!existingSegment) {
throw new Error("Filter segment not found or you don't have permission to delete it");
}
// Delete the filter segment
await prisma.filterSegment.delete({
where: { id },
});
}
async setPreference({
userId,
tableIdentifier,
segmentId,
}: {
userId: number;
tableIdentifier: string;
segmentId: SegmentIdentifier | null;
}) {
if (segmentId === null) {
await prisma.userFilterSegmentPreference.deleteMany({
where: {
userId,
tableIdentifier,
},
});
return null;
}
const isSystemSegment = segmentId.type === "system";
const updateData = isSystemSegment
? {
segmentId: null,
systemSegmentId: segmentId.id,
}
: {
segmentId: segmentId.id,
systemSegmentId: null,
};
const preference = await prisma.userFilterSegmentPreference.upsert({
where: {
userId_tableIdentifier: {
userId,
tableIdentifier,
},
},
update: updateData,
create: {
userId,
tableIdentifier,
...updateData,
},
});
return preference;
}
}
@@ -0,0 +1,99 @@
import { z } from "zod";
import {
ZActiveFilters,
ZSortingState,
ZColumnSizing,
ZColumnVisibility,
} from "@calcom/features/data-table/lib/types";
export const ZListFilterSegmentsInputSchema = z.object({
tableIdentifier: z.string(),
});
export type TListFilterSegmentsInputSchema = z.infer<typeof ZListFilterSegmentsInputSchema>;
export const ZDeleteFilterSegmentInputSchema = z.object({
id: z.number().int().positive(),
});
export type TDeleteFilterSegmentInputSchema = z.infer<typeof ZDeleteFilterSegmentInputSchema>;
// Base schema for common fields
const baseCreateSchema = {
name: z.string().min(1),
tableIdentifier: z.string().min(1),
activeFilters: ZActiveFilters.optional(),
sorting: ZSortingState.optional(),
columnVisibility: ZColumnVisibility.optional(),
columnSizing: ZColumnSizing.optional(),
searchTerm: z.string().nullable().optional(),
perPage: z.number().int().min(1),
};
// Schema for team scope - requires teamId
const teamCreateSchema = z.object({
scope: z.literal("TEAM"),
teamId: z.number().int().positive(),
...baseCreateSchema,
});
// Schema for user scope - no teamId allowed
const userCreateSchema = z.object({
scope: z.literal("USER"),
teamId: z.undefined().optional(),
...baseCreateSchema,
});
export const ZCreateFilterSegmentInputSchema = z.discriminatedUnion("scope", [
teamCreateSchema,
userCreateSchema,
]);
export type TCreateFilterSegmentInputSchema = z.infer<typeof ZCreateFilterSegmentInputSchema>;
const ZSegmentIdentifier = z.discriminatedUnion("type", [
z.object({ id: z.string(), type: z.literal("system") }),
z.object({ id: z.number(), type: z.literal("user") }),
]);
export const ZSetFilterSegmentPreferenceInputSchema = z.object({
tableIdentifier: z.string(),
segmentId: ZSegmentIdentifier.nullable(),
});
export type TSetFilterSegmentPreferenceInputSchema = z.infer<typeof ZSetFilterSegmentPreferenceInputSchema>;
// Base schema for common fields that can be updated
const baseUpdateSchema = {
name: z.string().min(1).optional(),
tableIdentifier: z.string().min(1).optional(),
activeFilters: ZActiveFilters.optional(),
sorting: ZSortingState.optional(),
columnVisibility: ZColumnVisibility.optional(),
columnSizing: ZColumnSizing.optional(),
searchTerm: z.string().nullable().optional(),
perPage: z.number().int().min(1).optional(),
};
// Schema for team scope updates
const teamUpdateSchema = z.object({
id: z.number().int().positive(),
scope: z.literal("TEAM"),
teamId: z.number().int().positive(),
...baseUpdateSchema,
});
// Schema for user scope updates
const userUpdateSchema = z.object({
id: z.number().int().positive(),
scope: z.literal("USER"),
...baseUpdateSchema,
});
export const ZUpdateFilterSegmentInputSchema = z.discriminatedUnion("scope", [
teamUpdateSchema,
userUpdateSchema,
]);
export type TUpdateFilterSegmentInputSchema = z.infer<typeof ZUpdateFilterSegmentInputSchema>;