29ec2b9cb6
* 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>
254 lines
7.0 KiB
TypeScript
254 lines
7.0 KiB
TypeScript
import { captureException } from "@sentry/nextjs";
|
|
|
|
import type { TeamFeaturesDto } from "@calcom/lib/dto/TeamFeaturesDto";
|
|
import type { PrismaClient } from "@calcom/prisma/client";
|
|
import { Prisma } from "@calcom/prisma/client";
|
|
|
|
import type { FeatureId, TeamFeatures } from "../config";
|
|
|
|
export interface ITeamFeatureRepository {
|
|
findByTeamIdAndFeatureId(teamId: number, featureId: FeatureId): Promise<TeamFeaturesDto | null>;
|
|
findByTeamIdsAndFeatureIds(
|
|
teamIds: number[],
|
|
featureIds: FeatureId[]
|
|
): Promise<Partial<Record<FeatureId, Record<number, TeamFeaturesDto>>>>;
|
|
upsert(
|
|
teamId: number,
|
|
featureId: FeatureId,
|
|
enabled: boolean,
|
|
assignedBy: string
|
|
): Promise<TeamFeaturesDto>;
|
|
delete(teamId: number, featureId: FeatureId): Promise<void>;
|
|
findAutoOptInByTeamId(teamId: number): Promise<boolean>;
|
|
findAutoOptInByTeamIds(teamIds: number[]): Promise<Record<number, boolean>>;
|
|
setAutoOptIn(teamId: number, enabled: boolean): Promise<void>;
|
|
checkIfTeamHasFeature(teamId: number, featureId: FeatureId): Promise<boolean>;
|
|
getEnabledFeatures(teamId: number): Promise<TeamFeatures | null>;
|
|
}
|
|
|
|
export class PrismaTeamFeatureRepository implements ITeamFeatureRepository {
|
|
private prisma: PrismaClient;
|
|
|
|
constructor(prisma: PrismaClient) {
|
|
this.prisma = prisma;
|
|
}
|
|
|
|
async findByTeamIdAndFeatureId(teamId: number, featureId: FeatureId): Promise<TeamFeaturesDto | null> {
|
|
const result = await this.prisma.teamFeatures.findUnique({
|
|
where: {
|
|
teamId_featureId: {
|
|
teamId,
|
|
featureId,
|
|
},
|
|
},
|
|
});
|
|
if (!result) return null;
|
|
return this.toDto(result);
|
|
}
|
|
|
|
async findByTeamIdsAndFeatureIds(
|
|
teamIds: number[],
|
|
featureIds: FeatureId[]
|
|
): Promise<Partial<Record<FeatureId, Record<number, TeamFeaturesDto>>>> {
|
|
if (teamIds.length === 0 || featureIds.length === 0) {
|
|
return {};
|
|
}
|
|
|
|
const results = await Promise.all(
|
|
teamIds.flatMap((teamId) =>
|
|
featureIds.map(async (featureId) => {
|
|
const teamFeature = await this.findByTeamIdAndFeatureId(teamId, featureId);
|
|
return { teamId, featureId, teamFeature };
|
|
})
|
|
)
|
|
);
|
|
|
|
const result: Partial<Record<FeatureId, Record<number, TeamFeaturesDto>>> = {};
|
|
for (const { teamId, featureId, teamFeature } of results) {
|
|
if (teamFeature !== null) {
|
|
if (!result[featureId]) {
|
|
result[featureId] = {};
|
|
}
|
|
const featureRecord = result[featureId];
|
|
if (featureRecord) {
|
|
featureRecord[teamId] = teamFeature;
|
|
}
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
async upsert(
|
|
teamId: number,
|
|
featureId: FeatureId,
|
|
enabled: boolean,
|
|
assignedBy: string
|
|
): Promise<TeamFeaturesDto> {
|
|
const result = await this.prisma.teamFeatures.upsert({
|
|
where: {
|
|
teamId_featureId: {
|
|
teamId,
|
|
featureId,
|
|
},
|
|
},
|
|
create: {
|
|
teamId,
|
|
featureId,
|
|
enabled,
|
|
assignedBy,
|
|
},
|
|
update: {
|
|
enabled,
|
|
assignedBy,
|
|
},
|
|
});
|
|
return this.toDto(result);
|
|
}
|
|
|
|
private toDto(teamFeature: {
|
|
teamId: number;
|
|
featureId: string;
|
|
enabled: boolean;
|
|
assignedBy: string;
|
|
updatedAt: Date;
|
|
}): TeamFeaturesDto {
|
|
return {
|
|
teamId: teamFeature.teamId,
|
|
featureId: teamFeature.featureId,
|
|
enabled: teamFeature.enabled,
|
|
assignedBy: teamFeature.assignedBy,
|
|
updatedAt: teamFeature.updatedAt,
|
|
};
|
|
}
|
|
|
|
async delete(teamId: number, featureId: FeatureId): Promise<void> {
|
|
await this.prisma.teamFeatures.delete({
|
|
where: {
|
|
teamId_featureId: {
|
|
teamId,
|
|
featureId,
|
|
},
|
|
},
|
|
});
|
|
}
|
|
|
|
async findAutoOptInByTeamId(teamId: number): Promise<boolean> {
|
|
const team = await this.prisma.team.findUnique({
|
|
where: { id: teamId },
|
|
select: { autoOptInFeatures: true },
|
|
});
|
|
return team?.autoOptInFeatures ?? false;
|
|
}
|
|
|
|
async findAutoOptInByTeamIds(teamIds: number[]): Promise<Record<number, boolean>> {
|
|
if (teamIds.length === 0) {
|
|
return {};
|
|
}
|
|
|
|
const results = await Promise.all(
|
|
teamIds.map(async (teamId) => {
|
|
const autoOptIn = await this.findAutoOptInByTeamId(teamId);
|
|
return { teamId, autoOptIn };
|
|
})
|
|
);
|
|
|
|
const result: Record<number, boolean> = {};
|
|
for (const { teamId, autoOptIn } of results) {
|
|
result[teamId] = autoOptIn;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
async setAutoOptIn(teamId: number, enabled: boolean): Promise<void> {
|
|
await this.prisma.team.update({
|
|
where: { id: teamId },
|
|
data: { autoOptInFeatures: enabled },
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Checks if a team or any of its ancestors has access to a specific feature.
|
|
* Uses a recursive CTE raw SQL query for performance.
|
|
* Uses tri-state semantics: only treats as enabled if TeamFeatures row exists AND enabled=true.
|
|
*/
|
|
async checkIfTeamHasFeature(teamId: number, featureId: FeatureId): Promise<boolean> {
|
|
try {
|
|
const teamFeature = await this.prisma.teamFeatures.findUnique({
|
|
where: {
|
|
teamId_featureId: {
|
|
teamId,
|
|
featureId,
|
|
},
|
|
},
|
|
select: { enabled: true },
|
|
});
|
|
if (teamFeature) return teamFeature.enabled;
|
|
|
|
const query = Prisma.sql`
|
|
WITH RECURSIVE TeamHierarchy AS (
|
|
SELECT id, "parentId",
|
|
CASE WHEN EXISTS (
|
|
SELECT 1 FROM "TeamFeatures" tf
|
|
WHERE tf."teamId" = id AND tf."featureId" = ${featureId} AND tf."enabled" = true
|
|
) THEN true ELSE false END as has_feature
|
|
FROM "Team"
|
|
WHERE id = ${teamId}
|
|
|
|
UNION ALL
|
|
|
|
SELECT p.id, p."parentId",
|
|
CASE WHEN EXISTS (
|
|
SELECT 1 FROM "TeamFeatures" tf
|
|
WHERE tf."teamId" = p.id AND tf."featureId" = ${featureId} AND tf."enabled" = true
|
|
) THEN true ELSE false END as has_feature
|
|
FROM "Team" p
|
|
INNER JOIN TeamHierarchy c ON p.id = c."parentId"
|
|
WHERE NOT c.has_feature
|
|
)
|
|
SELECT 1
|
|
FROM TeamHierarchy
|
|
WHERE has_feature = true
|
|
LIMIT 1;
|
|
`;
|
|
|
|
const result = await this.prisma.$queryRaw<unknown[]>(query);
|
|
return result.length > 0;
|
|
} catch (err) {
|
|
captureException(err);
|
|
console.error(
|
|
`Recursive feature check failed for team ${teamId}, feature ${featureId}:`,
|
|
err instanceof Error ? err.message : err
|
|
);
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Gets all features enabled for a specific team in a map format.
|
|
*/
|
|
async getEnabledFeatures(teamId: number): Promise<TeamFeatures | null> {
|
|
const result = await this.prisma.teamFeatures.findMany({
|
|
where: {
|
|
teamId,
|
|
enabled: true,
|
|
},
|
|
select: {
|
|
feature: {
|
|
select: {
|
|
slug: true,
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
if (!result.length) return null;
|
|
|
|
const features: TeamFeatures = Object.fromEntries(
|
|
result.map((teamFeature) => [teamFeature.feature.slug, true])
|
|
) as TeamFeatures;
|
|
|
|
return features;
|
|
}
|
|
}
|