feat: add seat tracking infrastructure for monthly proration (#27001)
Part 1 of monthly proration feature. Adds seat change tracking infrastructure with operationId for idempotency. **Dependency chain:** - This PR (seat tracking) - PR #27002 depends on this
This commit is contained in:
1 parent
9690a0111d
commit
e0c637b8ec
12 files changed
+319
-52
No files matched your search
@@ -10,6 +10,7 @@ export interface CreateSeatChangeLogData {
|
||||
userId?: number;
|
||||
triggeredBy?: number;
|
||||
monthKey: string;
|
||||
operationId?: string;
|
||||
metadata?: Prisma.InputJsonValue;
|
||||
teamBillingId: string | null;
|
||||
organizationBillingId: string | null;
|
||||
@@ -28,6 +29,20 @@ export class SeatChangeLogRepository {
|
||||
}
|
||||
|
||||
async create(data: CreateSeatChangeLogData): Promise<SeatChangeLog> {
|
||||
// If operationId is provided, use upsert to prevent duplicates
|
||||
if (data.operationId) {
|
||||
return await this.prisma.seatChangeLog.upsert({
|
||||
where: {
|
||||
teamId_operationId: {
|
||||
teamId: data.teamId,
|
||||
operationId: data.operationId,
|
||||
},
|
||||
},
|
||||
create: data,
|
||||
update: {}, // No update needed - if it exists, we skip
|
||||
});
|
||||
}
|
||||
|
||||
return await this.prisma.seatChangeLog.create({
|
||||
data,
|
||||
});
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { Logger } from "tslog";
|
||||
|
||||
import { formatMonthKey } from "@calcom/features/ee/billing/lib/month-key";
|
||||
import { SeatChangeLogRepository } from "@calcom/features/ee/billing/repository/seatChangeLogs/SeatChangeLogRepository";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import type { SeatChangeType } from "@calcom/prisma/enums";
|
||||
import type { Logger } from "tslog";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["SeatChangeTrackingService"] });
|
||||
|
||||
@@ -14,6 +14,9 @@ export interface SeatChangeLogParams {
|
||||
seatCount?: number;
|
||||
metadata?: Prisma.InputJsonValue;
|
||||
monthKey?: string;
|
||||
// Idempotency key to prevent duplicate seat change logs from race conditions
|
||||
// Format: "{source}-{uniqueId}" e.g., "membership-123" or "invite-abc"
|
||||
operationId?: string;
|
||||
}
|
||||
|
||||
export interface MonthlyChanges {
|
||||
@@ -32,8 +35,16 @@ export class SeatChangeTrackingService {
|
||||
}
|
||||
|
||||
async logSeatAddition(params: SeatChangeLogParams): Promise<void> {
|
||||
const { teamId, userId, triggeredBy, seatCount = 1, metadata, monthKey: providedMonthKey } = params;
|
||||
const monthKey = providedMonthKey || this.calculateMonthKey(new Date());
|
||||
const {
|
||||
teamId,
|
||||
userId,
|
||||
triggeredBy,
|
||||
seatCount = 1,
|
||||
metadata,
|
||||
monthKey: providedMonthKey,
|
||||
operationId,
|
||||
} = params;
|
||||
const monthKey = providedMonthKey || formatMonthKey(new Date());
|
||||
|
||||
const { teamBillingId, organizationBillingId } = await this.repository.getTeamBillingIds(teamId);
|
||||
|
||||
@@ -44,6 +55,7 @@ export class SeatChangeTrackingService {
|
||||
userId,
|
||||
triggeredBy,
|
||||
monthKey,
|
||||
operationId,
|
||||
metadata: (metadata || {}) as Prisma.InputJsonValue,
|
||||
teamBillingId,
|
||||
organizationBillingId,
|
||||
@@ -51,8 +63,16 @@ export class SeatChangeTrackingService {
|
||||
}
|
||||
|
||||
async logSeatRemoval(params: SeatChangeLogParams): Promise<void> {
|
||||
const { teamId, userId, triggeredBy, seatCount = 1, metadata, monthKey: providedMonthKey } = params;
|
||||
const monthKey = providedMonthKey || this.calculateMonthKey(new Date());
|
||||
const {
|
||||
teamId,
|
||||
userId,
|
||||
triggeredBy,
|
||||
seatCount = 1,
|
||||
metadata,
|
||||
monthKey: providedMonthKey,
|
||||
operationId,
|
||||
} = params;
|
||||
const monthKey = providedMonthKey || formatMonthKey(new Date());
|
||||
|
||||
const { teamBillingId, organizationBillingId } = await this.repository.getTeamBillingIds(teamId);
|
||||
|
||||
@@ -63,6 +83,7 @@ export class SeatChangeTrackingService {
|
||||
userId,
|
||||
triggeredBy,
|
||||
monthKey,
|
||||
operationId,
|
||||
metadata: (metadata || {}) as Prisma.InputJsonValue,
|
||||
teamBillingId,
|
||||
organizationBillingId,
|
||||
@@ -94,10 +115,4 @@ export class SeatChangeTrackingService {
|
||||
|
||||
return await this.repository.markAsProcessed({ teamId, monthKey, prorationId });
|
||||
}
|
||||
|
||||
private calculateMonthKey(date: Date): string {
|
||||
const year = date.getUTCFullYear();
|
||||
const month = String(date.getUTCMonth() + 1).padStart(2, "0");
|
||||
return `${year}-${month}`;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
|
||||
import { SeatChangeTrackingService } from "@calcom/features/ee/billing/service/seatTracking/SeatChangeTrackingService";
|
||||
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { IdentityProvider } from "@calcom/prisma/enums";
|
||||
@@ -69,7 +70,7 @@ export const createUsersAndConnectToOrg = async ({
|
||||
});
|
||||
|
||||
// Create memberships for new members
|
||||
await MembershipRepository.createMany(
|
||||
const membershipResult = await MembershipRepository.createMany(
|
||||
users.map((user) => ({
|
||||
userId: user.id,
|
||||
teamId: org.id,
|
||||
@@ -78,6 +79,14 @@ export const createUsersAndConnectToOrg = async ({
|
||||
}))
|
||||
);
|
||||
|
||||
if (membershipResult.count > 0) {
|
||||
const seatTracker = new SeatChangeTrackingService();
|
||||
await seatTracker.logSeatAddition({
|
||||
teamId: org.id,
|
||||
seatCount: membershipResult.count,
|
||||
});
|
||||
}
|
||||
|
||||
return users;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock";
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/features/ee/teams/lib/queries";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import { WorkflowService } from "@calcom/features/ee/workflows/lib/service/WorkflowService";
|
||||
@@ -9,11 +5,21 @@ import { createAProfileForAnExistingUser } from "@calcom/features/profile/lib/cr
|
||||
import { deleteDomain } from "@calcom/lib/domainManager/organization";
|
||||
import { ErrorCode } from "@calcom/lib/errorCodes";
|
||||
import { ErrorWithCode } from "@calcom/lib/errors";
|
||||
import type { Membership, Team, User, VerificationToken, Profile } from "@calcom/prisma/client";
|
||||
import type { Membership, Profile, Team, User, VerificationToken } from "@calcom/prisma/client";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { TeamService } from "./teamService";
|
||||
|
||||
const { MockSeatChangeTrackingService } = vi.hoisted(() => {
|
||||
class MockSeatChangeTrackingService {
|
||||
logSeatAddition = vi.fn().mockResolvedValue(undefined);
|
||||
logSeatRemoval = vi.fn().mockResolvedValue(undefined);
|
||||
}
|
||||
return { MockSeatChangeTrackingService };
|
||||
});
|
||||
|
||||
vi.mock("@calcom/ee/billing/di/containers/Billing");
|
||||
vi.mock("@calcom/features/ee/teams/repositories/TeamRepository");
|
||||
vi.mock("@calcom/features/ee/workflows/lib/service/WorkflowService");
|
||||
@@ -21,6 +27,9 @@ 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");
|
||||
vi.mock("@calcom/features/ee/billing/service/seatTracking/SeatChangeTrackingService", () => ({
|
||||
SeatChangeTrackingService: MockSeatChangeTrackingService,
|
||||
}));
|
||||
|
||||
const mockTeamBilling = {
|
||||
cancel: vi.fn(),
|
||||
@@ -39,7 +48,7 @@ describe("TeamService", () => {
|
||||
vi.resetAllMocks();
|
||||
mockTeamBillingFactory.findAndInit.mockResolvedValue(mockTeamBilling);
|
||||
mockTeamBillingFactory.findAndInitMany.mockResolvedValue([mockTeamBilling]);
|
||||
|
||||
|
||||
const { getTeamBillingServiceFactory } = await import("@calcom/ee/billing/di/containers/Billing");
|
||||
vi.mocked(getTeamBillingServiceFactory).mockReturnValue(mockTeamBillingFactory);
|
||||
});
|
||||
@@ -57,11 +66,13 @@ describe("TeamService", () => {
|
||||
slug: "deleted-team",
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
// @ts-expect-error
|
||||
const mockTeamRepo = {
|
||||
deleteById: vi.fn().mockResolvedValue(mockDeletedTeam),
|
||||
} as Pick<TeamRepository, "deleteById">;
|
||||
vi.mocked(TeamRepository).mockImplementation(function() { return mockTeamRepo; });
|
||||
vi.mocked(TeamRepository).mockImplementation(function () {
|
||||
return mockTeamRepo;
|
||||
});
|
||||
|
||||
const result = await TeamService.delete({ id: 1 });
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
|
||||
import { getTeamBillingServiceFactory } from "@calcom/ee/billing/di/containers/Billing";
|
||||
import { SeatChangeTrackingService } from "@calcom/features/ee/billing/service/seatTracking/SeatChangeTrackingService";
|
||||
import { deleteWorkfowRemindersOfRemovedMember } from "@calcom/features/ee/teams/lib/deleteWorkflowRemindersOfRemovedMember";
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/features/ee/teams/lib/queries";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
@@ -188,6 +189,7 @@ export class TeamService {
|
||||
team: {
|
||||
select: {
|
||||
name: true,
|
||||
parentId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -218,6 +220,15 @@ export class TeamService {
|
||||
} else throw e;
|
||||
}
|
||||
|
||||
if (!verificationToken.team.parentId) {
|
||||
const seatTracker = new SeatChangeTrackingService();
|
||||
await seatTracker.logSeatAddition({
|
||||
teamId: verificationToken.teamId,
|
||||
userId,
|
||||
triggeredBy: userId,
|
||||
});
|
||||
}
|
||||
|
||||
const teamBillingServiceFactory = getTeamBillingServiceFactory();
|
||||
const teamBillingService = await teamBillingServiceFactory.findAndInit(verificationToken.teamId);
|
||||
await teamBillingService.updateQuantity();
|
||||
@@ -296,6 +307,15 @@ export class TeamService {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (!membership.team.parentId) {
|
||||
const seatTracker = new SeatChangeTrackingService();
|
||||
await seatTracker.logSeatRemoval({
|
||||
teamId,
|
||||
userId,
|
||||
triggeredBy: userId,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
@@ -375,6 +395,14 @@ export class TeamService {
|
||||
|
||||
await deleteWorkfowRemindersOfRemovedMember(team, userId, isOrg);
|
||||
|
||||
if (!team.parentId) {
|
||||
const seatTracker = new SeatChangeTrackingService();
|
||||
await seatTracker.logSeatRemoval({
|
||||
teamId,
|
||||
userId,
|
||||
});
|
||||
}
|
||||
|
||||
return { membership };
|
||||
}
|
||||
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- A unique constraint covering the columns `[teamId,operationId]` on the table `SeatChangeLog` will be added. If there are existing duplicate values, this will fail.
|
||||
|
||||
*/
|
||||
-- AlterTable
|
||||
ALTER TABLE "public"."SeatChangeLog" ADD COLUMN "operationId" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "SeatChangeLog_teamId_operationId_key" ON "public"."SeatChangeLog"("teamId", "operationId");
|
||||
@@ -2989,6 +2989,9 @@ model SeatChangeLog {
|
||||
changeDate DateTime @default(now())
|
||||
monthKey String
|
||||
|
||||
// Idempotency key to prevent duplicate seat change logs from race conditions
|
||||
operationId String?
|
||||
|
||||
processedInProrationId String?
|
||||
proration MonthlyProration? @relation(fields: [processedInProrationId], references: [id])
|
||||
|
||||
@@ -3000,6 +3003,7 @@ model SeatChangeLog {
|
||||
organizationBillingId String?
|
||||
organizationBilling OrganizationBilling? @relation(fields: [organizationBillingId], references: [id])
|
||||
|
||||
@@unique([teamId, operationId])
|
||||
@@index([teamId, monthKey])
|
||||
@@index([teamId, processedInProrationId])
|
||||
@@index([monthKey])
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { getTeamBillingServiceFactory } from "@calcom/ee/billing/di/containers/Billing";
|
||||
import { SeatChangeTrackingService } from "@calcom/features/ee/billing/service/seatTracking/SeatChangeTrackingService";
|
||||
import { Resource, CustomAction } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { getSpecificPermissions } from "@calcom/features/pbac/lib/resource-permissions";
|
||||
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
|
||||
@@ -56,19 +57,22 @@ export async function bulkDeleteUsersHandler({ ctx, input }: BulkDeleteUsersHand
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
// Loop over all users in input.userIds and remove all memberships for the organization including child teams
|
||||
const deleteMany = prisma.membership.deleteMany({
|
||||
const deleteOrganizationMemberships = prisma.membership.deleteMany({
|
||||
where: {
|
||||
teamId: currentUserOrgId,
|
||||
userId: {
|
||||
in: input.userIds,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const deleteSubteamMemberships = prisma.membership.deleteMany({
|
||||
where: {
|
||||
userId: {
|
||||
in: input.userIds,
|
||||
},
|
||||
team: {
|
||||
OR: [
|
||||
{
|
||||
parentId: currentUserOrgId,
|
||||
},
|
||||
{ id: currentUserOrgId },
|
||||
],
|
||||
parentId: currentUserOrgId,
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -130,14 +134,24 @@ export async function bulkDeleteUsersHandler({ ctx, input }: BulkDeleteUsersHand
|
||||
|
||||
// We do this in a transaction to make sure that all memberships are removed before we remove the organization relation from the user
|
||||
// We also do this to make sure that if one of the queries fail, the whole transaction fails
|
||||
await prisma.$transaction([
|
||||
const [, { count: orgMembershipRemovalCount }] = await prisma.$transaction([
|
||||
removeProfiles,
|
||||
deleteMany,
|
||||
deleteOrganizationMemberships,
|
||||
deleteSubteamMemberships,
|
||||
removeOrgrelation,
|
||||
removeManagedEventTypes,
|
||||
removeHostAssignment,
|
||||
]);
|
||||
|
||||
if (orgMembershipRemovalCount > 0) {
|
||||
const seatTracker = new SeatChangeTrackingService();
|
||||
await seatTracker.logSeatRemoval({
|
||||
teamId: currentUserOrgId,
|
||||
seatCount: orgMembershipRemovalCount,
|
||||
triggeredBy: currentUser.id,
|
||||
});
|
||||
}
|
||||
|
||||
const teamBillingServiceFactory = getTeamBillingServiceFactory();
|
||||
const teamBillingService = await teamBillingServiceFactory.findAndInit(currentUserOrgId);
|
||||
await teamBillingService.updateQuantity();
|
||||
|
||||
@@ -55,6 +55,7 @@ describe("addMembersToTeams", () => {
|
||||
mockCheckPermission.mockResolvedValue(true);
|
||||
mockUpdateNewTeamMemberEventTypes.mockResolvedValue(undefined);
|
||||
|
||||
prisma.team.findMany.mockResolvedValue([]);
|
||||
prisma.membership.findMany.mockResolvedValue([]);
|
||||
prisma.membership.createMany.mockResolvedValue({ count: 0 });
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { TeamRepository } from "@calcom/ee/teams/repositories/TeamRepository";
|
||||
import { SeatChangeTrackingService } from "@calcom/features/ee/billing/service/seatTracking/SeatChangeTrackingService";
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/features/ee/teams/lib/queries";
|
||||
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
@@ -33,6 +34,22 @@ export const addMembersToTeams = async ({ user, input }: AddBulkToTeamProps) =>
|
||||
});
|
||||
}
|
||||
|
||||
const teamsForSeatTracking = await prisma.team.findMany({
|
||||
where: {
|
||||
id: {
|
||||
in: input.teamIds,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
parentId: true,
|
||||
},
|
||||
});
|
||||
|
||||
const topLevelTeamIds = new Set(
|
||||
teamsForSeatTracking.filter((team) => !team.parentId).map((team) => team.id)
|
||||
);
|
||||
|
||||
// Check if user has permission to invite team members in the organization
|
||||
const permissionCheckService = new PermissionCheckService();
|
||||
const hasPermission = await permissionCheckService.checkPermission({
|
||||
@@ -91,7 +108,7 @@ export const addMembersToTeams = async ({ user, input }: AddBulkToTeamProps) =>
|
||||
const membershipData = filteredUserIds.flatMap((userId) =>
|
||||
input.teamIds.map((teamId) => {
|
||||
const userMembership = usersInOrganization.find((membership) => membership.userId === userId);
|
||||
const accepted = userMembership && userMembership.accepted;
|
||||
const accepted = userMembership?.accepted;
|
||||
return {
|
||||
createdAt: new Date(),
|
||||
userId,
|
||||
@@ -106,6 +123,26 @@ export const addMembersToTeams = async ({ user, input }: AddBulkToTeamProps) =>
|
||||
data: membershipData,
|
||||
});
|
||||
|
||||
if (topLevelTeamIds.size > 0 && membershipData.length > 0) {
|
||||
const seatTracker = new SeatChangeTrackingService();
|
||||
const additionsByTeam = Array.from(topLevelTeamIds)
|
||||
.map((teamId) => ({
|
||||
teamId,
|
||||
seatCount: membershipData.filter((entry) => entry.teamId === teamId).length,
|
||||
}))
|
||||
.filter((entry) => entry.seatCount > 0);
|
||||
|
||||
await Promise.all(
|
||||
additionsByTeam.map(({ teamId, seatCount }) =>
|
||||
seatTracker.logSeatAddition({
|
||||
teamId,
|
||||
seatCount,
|
||||
triggeredBy: user.id,
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
membershipData.map(({ userId, teamId }) => updateNewTeamMemberEventTypes(userId, teamId))
|
||||
);
|
||||
|
||||
@@ -1,27 +1,44 @@
|
||||
import { describe, it, vi, expect, beforeEach } from "vitest";
|
||||
|
||||
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { CreationSource, MembershipRole } from "@calcom/prisma/enums";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { TeamWithParent } from "./types";
|
||||
import type { UserWithMembership } from "./utils";
|
||||
import { INVITE_STATUS } from "./utils";
|
||||
import {
|
||||
ensureAtleastAdminPermissions,
|
||||
getUniqueInvitationsOrThrowIfEmpty,
|
||||
getOrgState,
|
||||
getOrgConnectionInfo,
|
||||
canBeInvited,
|
||||
getAutoJoinStatus,
|
||||
checkInputEmailIsValid,
|
||||
createMemberships,
|
||||
createNewUsersConnectToOrgIfExists,
|
||||
ensureAtleastAdminPermissions,
|
||||
getAutoJoinStatus,
|
||||
getOrgConnectionInfo,
|
||||
getOrgState,
|
||||
getUniqueInvitationsOrThrowIfEmpty,
|
||||
INVITE_STATUS,
|
||||
} from "./utils";
|
||||
|
||||
const { mockCreateMany } = vi.hoisted(() => {
|
||||
const { mockCreateMany, mockUserCreate, mockMembershipCreate, mockTransaction } = vi.hoisted(() => {
|
||||
const mockCreateManyFn = vi.fn();
|
||||
return { mockCreateMany: mockCreateManyFn };
|
||||
const mockUserCreateFn = vi.fn();
|
||||
const mockMembershipCreateFn = vi.fn();
|
||||
const mockTransactionFn = vi.fn(async (callback: (tx: any) => Promise<unknown>) => {
|
||||
return callback({
|
||||
user: {
|
||||
create: mockUserCreateFn,
|
||||
},
|
||||
membership: {
|
||||
create: mockMembershipCreateFn,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
mockCreateMany: mockCreateManyFn,
|
||||
mockUserCreate: mockUserCreateFn,
|
||||
mockMembershipCreate: mockMembershipCreateFn,
|
||||
mockTransaction: mockTransactionFn,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@calcom/prisma", () => {
|
||||
@@ -30,6 +47,10 @@ vi.mock("@calcom/prisma", () => {
|
||||
membership: {
|
||||
createMany: mockCreateMany,
|
||||
},
|
||||
user: {
|
||||
create: mockUserCreate,
|
||||
},
|
||||
$transaction: mockTransaction,
|
||||
},
|
||||
};
|
||||
});
|
||||
@@ -47,6 +68,20 @@ vi.mock("@calcom/features/pbac/services/permission-check.service", () => {
|
||||
};
|
||||
});
|
||||
|
||||
const { mockLogSeatAddition } = vi.hoisted(() => {
|
||||
return { mockLogSeatAddition: vi.fn() };
|
||||
});
|
||||
|
||||
vi.mock("@calcom/features/ee/billing/service/seatTracking/SeatChangeTrackingService", () => ({
|
||||
SeatChangeTrackingService: class {
|
||||
logSeatAddition = mockLogSeatAddition;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/server/i18n", () => ({
|
||||
getTranslation: vi.fn().mockResolvedValue((key: string) => key),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/logger", () => {
|
||||
const mockSubLogger = {
|
||||
debug: vi.fn(),
|
||||
@@ -639,6 +674,50 @@ describe("Invite Member Utils", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("createNewUsersConnectToOrgIfExists", () => {
|
||||
beforeEach(() => {
|
||||
mockUserCreate.mockReset();
|
||||
mockMembershipCreate.mockReset();
|
||||
mockTransaction.mockClear();
|
||||
mockLogSeatAddition.mockClear();
|
||||
});
|
||||
|
||||
it("logs seat changes for new users on regular teams", async () => {
|
||||
let nextId = 100;
|
||||
mockUserCreate.mockImplementation(async ({ data }) => ({
|
||||
id: nextId++,
|
||||
email: data.email,
|
||||
}));
|
||||
mockMembershipCreate.mockResolvedValue({});
|
||||
|
||||
const invitations = [
|
||||
{ usernameOrEmail: "[email protected]", role: MembershipRole.MEMBER },
|
||||
{ usernameOrEmail: "[email protected]", role: MembershipRole.MEMBER },
|
||||
];
|
||||
const orgConnectInfoByUsernameOrEmail = {
|
||||
"[email protected]": { orgId: undefined, autoAccept: false },
|
||||
"[email protected]": { orgId: undefined, autoAccept: false },
|
||||
};
|
||||
|
||||
const result = await createNewUsersConnectToOrgIfExists({
|
||||
invitations,
|
||||
isOrg: false,
|
||||
teamId: mockedRegularTeam.id,
|
||||
parentId: null,
|
||||
autoAcceptEmailDomain: null,
|
||||
orgConnectInfoByUsernameOrEmail,
|
||||
language: "en",
|
||||
creationSource: CreationSource.WEBAPP,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(mockLogSeatAddition).toHaveBeenCalledWith({
|
||||
teamId: mockedRegularTeam.id,
|
||||
seatCount: 2,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("createMemberships - Privilege Escalation Prevention", () => {
|
||||
beforeEach(() => {
|
||||
mockCreateMany.mockClear();
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import { getOrgFullOrigin } from "@calcom/ee/organizations/lib/orgDomains";
|
||||
import { sendTeamInviteEmail } from "@calcom/emails/organization-email-service";
|
||||
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
|
||||
import { SeatChangeTrackingService } from "@calcom/features/ee/billing/service/seatTracking/SeatChangeTrackingService";
|
||||
import { getParsedTeam } from "@calcom/features/ee/teams/lib/getParsedTeam";
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/features/ee/teams/lib/queries";
|
||||
import { OnboardingPathService } from "@calcom/features/onboarding/lib/onboarding-path.service";
|
||||
@@ -18,14 +17,13 @@ import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Membership, OrganizationSettings, Team } from "@calcom/prisma/client";
|
||||
import { type User as UserType, type UserPassword, Prisma } from "@calcom/prisma/client";
|
||||
import type { Profile as ProfileType } from "@calcom/prisma/client";
|
||||
import type { Membership, OrganizationSettings, Profile as ProfileType, Team } from "@calcom/prisma/client";
|
||||
import { Prisma, type UserPassword, type User as UserType } from "@calcom/prisma/client";
|
||||
import type { CreationSource } from "@calcom/prisma/enums";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import { isEmail } from "../util";
|
||||
import type { TeamWithParent } from "./types";
|
||||
@@ -137,7 +135,7 @@ export async function getUniqueInvitationsOrThrowIfEmpty(invitations: Invitation
|
||||
return uniqueInvitations;
|
||||
}
|
||||
|
||||
export const enum INVITE_STATUS {
|
||||
export enum INVITE_STATUS {
|
||||
USER_PENDING_MEMBER_OF_THE_ORG = "USER_PENDING_MEMBER_OF_THE_ORG",
|
||||
USER_ALREADY_INVITED_OR_MEMBER = "USER_ALREADY_INVITED_OR_MEMBER",
|
||||
USER_MEMBER_OF_OTHER_ORGANIZATION = "USER_MEMBER_OF_OTHER_ORGANIZATION",
|
||||
@@ -270,7 +268,7 @@ export function getOrgConnectionInfo({
|
||||
team: Pick<TeamWithParent, "parentId" | "id">;
|
||||
isOrg: boolean;
|
||||
}) {
|
||||
let orgId: number | undefined = undefined;
|
||||
let orgId: number | undefined;
|
||||
let autoAccept = false;
|
||||
|
||||
if (team.parentId || isOrg) {
|
||||
@@ -415,6 +413,16 @@ export async function createNewUsersConnectToOrgIfExists({
|
||||
},
|
||||
{ timeout: 10000 }
|
||||
);
|
||||
|
||||
if (createdUsers.length > 0) {
|
||||
const seatTracker = new SeatChangeTrackingService();
|
||||
const trackingTeamId = parentId ?? teamId;
|
||||
await seatTracker.logSeatAddition({
|
||||
teamId: trackingTeamId,
|
||||
seatCount: createdUsers.length,
|
||||
});
|
||||
}
|
||||
|
||||
return createdUsers;
|
||||
}
|
||||
|
||||
@@ -464,6 +472,33 @@ export async function createMemberships({
|
||||
return data;
|
||||
}),
|
||||
});
|
||||
|
||||
const seatTracker = new SeatChangeTrackingService();
|
||||
const teamSeatAdditions = parentId ? 0 : invitees.length;
|
||||
const organizationSeatAdditions = parentId
|
||||
? invitees.filter((invitee) => invitee.needToCreateOrgMembership).length
|
||||
: 0;
|
||||
|
||||
const trackingPromises: Promise<void>[] = [];
|
||||
if (teamSeatAdditions > 0) {
|
||||
trackingPromises.push(
|
||||
seatTracker.logSeatAddition({
|
||||
teamId,
|
||||
seatCount: teamSeatAdditions,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (parentId && organizationSeatAdditions > 0) {
|
||||
trackingPromises.push(
|
||||
seatTracker.logSeatAddition({
|
||||
teamId: parentId,
|
||||
seatCount: organizationSeatAdditions,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
await Promise.all(trackingPromises);
|
||||
} catch (e) {
|
||||
if (e instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
logger.error("Failed to create memberships", teamId);
|
||||
@@ -928,6 +963,14 @@ export async function handleExistingUsersInvites({
|
||||
})
|
||||
);
|
||||
|
||||
if (!team.parentId && existingUsersWithMembershipsNew.length > 0) {
|
||||
const seatTracker = new SeatChangeTrackingService();
|
||||
await seatTracker.logSeatAddition({
|
||||
teamId: team.id,
|
||||
seatCount: existingUsersWithMembershipsNew.length,
|
||||
});
|
||||
}
|
||||
|
||||
const autoJoinUsers = existingUsersWithMembershipsNew.filter(
|
||||
(user) => orgConnectInfoByUsernameOrEmail[user.email].autoAccept
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user