Files
cal.diy/packages/features/ee/teams/services/teamService.test.ts
T
7e4d9e26c6 refactor: implement DI in team billing service and team billing data repository factory (#24803)
* Move TeamBillingRepositories

* WIP refactor team internal billing service

* Remove duplicate billing repository files

* Remove logic check in repository for billing is enabled

* Rename repository to `TeamBillingData`

* Use repository factory in main service

* Fix new import paths

* Rename  to

* Ensure `IS_TEAM_BILLING_ENABLED` is of type boolean

* Rename classes to TeamBillingService and TeamBillingServiceFactory

* Implement DI in `BookingServiceFactory`

* `TeamBillingService` use repository in `getOrgIfNeeded`

* DI `isTeamBillingEnabled` to `TeamBillingServiceFactory`

* Rename files for consistency

* Return stub BillingRepository if billing is not enabled

* Move Stripe billing service to service folder

* Rename file

* `StripeBillingService.getSubscriptionStatus` return `SubscriptionStatus`

* Type fices in StripeBillingService

* Type fix in `stubTeamBillingService`

* DI the `BillingProviderService` into the `TeamBillingService`

* Implement DI in `skipTeamTrials.handler`

* Implement DI for team billing in `inviteMember.handler`

* `skipTeamTrials.handler` use `team.isOrganization`

* Implement DI for billing in `hasActiveTeamPlan.handler`

* Type fixes

* Implement DI in `bulkDeleteUsers.handler`

* Implement `BillingProviderServiceFactory` in `updateProfile.handler`

* Implment `BillingProviderServiceFactory` in `buyCredits.handler`

* Fix import in `stripeCustomer.handler`

* Add a constructor to `teamBillingServiceFactory`

* Add DI to `PrismaTeamBillingRepository`

* Add DI to `StripeBillingService`

* Implement singleton in `BillingProviderServiceFactory`

* Add DI folder and contents to billing folder

* Use `getTeamBillingServiceFactory` in `inviteMember.handler`

* Add `saveTeamBilling` method to `ITeamBillingService`

* Implement DI in new team route

* Implement DI in `teamService`

* Implement DI in `OrganizationPaymentService`

* Implement DI in `credit-service`

* In `StripeBillingService` remove `static` from status methods

* Implemnt DI in `_invoice.paid.org`

* Refactor `hasActiveTeamPlan` to use `getTeamBillingFactory`

* Refactor `skipTeamTrials` to use `getTeamBillingFactory`

* Refactor `skipTeamTrials` to use `getTeamBillingServiceFactory`

* `stripeCustomer.handler` to use `getBillingProviderService`

* Remove old factories

* Type fix

* Remove unused factory

* Refactor `updateProfile.handler` to use `getBillingProviderService`

* Change name to `TeamBillingDataRepositoryFactory`

* Type Prisma return in `prisma.module`

* Type fix

* Refactor `buyCredits.handler` to use `getBillingProviderService`

* Refactor `credit-service` to use billing DI containers

* Type fix

* Add `getTeamBillingDataRepository`

* Refactor `_invoice.paid.org` to use DI container

* Refactor `_customer.subscription.deleted.team-plan` to use DI container

* Refactor `calcomHandler` to use DI container

* Refactor `getCustomerAndCheckoutSession` to use DI container

* Refactor `verify-email` to use DI containers

* Refactor `api/create/route` to use DI container

* Refactor downgradeUsers to use DI container

* Type fix

* Clean up console.logs

* Add await to `this.billingRepository.create` in `saveTeamBilling`

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Fix type errors

* Address comments

* fix: update tests to work with new DI pattern

- Update teamBillingService.test.ts to properly inject DI dependencies
- Remove unused billingModule import and mock
- Fix import naming in teamService.integration-test.ts (remove unused rename)
- Fix import path for TeamBillingPublishResponseStatus

All tests now properly mock IBillingProviderService, ITeamBillingDataRepository,
and IBillingRepository instead of using the old BillingRepositoryFactory pattern.

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: add compatibility layer and env setup for unit tests

- Add STRIPE_PRIVATE_KEY dummy value to vitest.config.ts to prevent DI module errors
- Fix import paths in credit-service.test.ts (StripeBillingService, TeamBillingService)
- Create compatibility barrel at packages/features/ee/billing/teams/index.ts for test mocking

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: update unit tests to mock DI container properly

- Update teamService.test.ts to mock getTeamBillingServiceFactory() instead of TeamBilling.findAndInit
- Update teamService.alternative.test.ts to mock DI container
- Update credit-service.test.ts to mock getBillingProviderService() and use SubscriptionStatus enum values
- Update OrganizationPaymentService.test.ts to mock DI container instead of direct StripeBillingService import
- Remove all 'as any' type casting to comply with Cal.com coding standards
- Fix unused variable warnings by prefixing with underscore

All 53 tests now passing (16 + 1 + 30 + 6)

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: update remaining unit tests to use DI pattern

- Fix StripeBillingService.test.ts to inject mock Stripe client directly
- Fix teamBillingFactory.test.ts to mock getTeamBillingServiceFactory() from DI container
- Fix skipTeamTrials.test.ts to mock DI container and use SubscriptionStatus enum

All 11 previously failing tests now pass (5 + 5 + 1)

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Undo changes made to Prisma module

* fix: address test-related PR comments

- Fix OrganizationPaymentService.test.ts mock path from @calcom/ee to @calcom/features/ee
- Refactor teamBillingFactory.test.ts to test real factory logic instead of mocking container
- Remove duplicate teamBillingService.test..ts file with incorrect double-dot filename

All three test files now pass successfully with proper DI patterns.

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Address feedback

* fix: update teamService integration test to mock new DI factory pattern

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* refactor: remove duplicate imports in credit-service.test.ts

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Remove unused index file

* `getBySubscriptionId` to return team or null

* Address feedback

* Merge fix

* Refactor file names

* fix: correct mockStripe variable name to stripeMock in StripeBillingService.test.ts

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* refactor: update internal-team-billing.test.ts to use new DI structure with TeamBillingService

- Replace InternalTeamBilling with TeamBillingService
- Use constructor injection with mock dependencies instead of factory pattern
- Remove BillingRepositoryFactory mock and import
- Update all test cases to use mockBillingProviderService, mockTeamBillingDataRepository, and mockBillingRepository
- Simplify saveTeamBilling tests to focus on repository.create calls
- All 11 tests now pass with the new DI structure

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: update createWithPaymentIntent.handler.test.ts to mock DI container's getBillingProviderService

- OrganizationPaymentService now uses getBillingProviderService() from DI container
- Test was mocking @calcom/features/ee/payments/server/stripe directly, which no longer works
- Added mock for @calcom/features/ee/billing/di/containers/Billing module
- Mock returns fake billing provider that delegates to mockSharedStripe
- Preserves all existing test assertions and helpers
- Fixed lint error by prefixing unused lastCreatedSessionId with underscore
- All 11 tests now pass (1 skipped as expected)

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com>
2025-11-19 10:21:22 -05:00

407 lines
14 KiB
TypeScript

import prismaMock from "../../../../../tests/libs/__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";
import { createAProfileForAnExistingUser } from "@calcom/features/profile/lib/createAProfileForAnExistingUser";
import { deleteDomain } from "@calcom/lib/domainManager/organization";
import type { Membership, Team, User, VerificationToken, Profile } from "@calcom/prisma/client";
import { MembershipRole } from "@calcom/prisma/enums";
import { TRPCError } from "@trpc/server";
import { TeamService } from "./teamService";
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");
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");
const mockTeamBilling = {
cancel: vi.fn(),
updateQuantity: vi.fn(),
publish: vi.fn(),
downgrade: vi.fn(),
};
const mockTeamBillingFactory = {
findAndInit: vi.fn().mockResolvedValue(mockTeamBilling),
findAndInitMany: vi.fn().mockResolvedValue([mockTeamBilling]),
};
describe("TeamService", () => {
beforeEach(async () => {
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);
});
afterEach(() => {
vi.clearAllMocks();
});
describe("delete", () => {
it("should delete team, cancel billing, and clean up", async () => {
const mockDeletedTeam = {
id: 1,
name: "Deleted Team",
isOrganization: true,
slug: "deleted-team",
};
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const mockTeamRepo = {
deleteById: vi.fn().mockResolvedValue(mockDeletedTeam),
} as Pick<TeamRepository, "deleteById">;
vi.mocked(TeamRepository).mockImplementation(() => mockTeamRepo);
const result = await TeamService.delete({ id: 1 });
expect(mockTeamBillingFactory.findAndInit).toHaveBeenCalledWith(1);
expect(mockTeamBilling.cancel).toHaveBeenCalled();
expect(WorkflowService.deleteWorkflowRemindersOfRemovedTeam).toHaveBeenCalledWith(1);
expect(mockTeamRepo.deleteById).toHaveBeenCalledWith({ id: 1 });
expect(deleteDomain).toHaveBeenCalledWith("deleted-team");
expect(result).toEqual(mockDeletedTeam);
});
});
describe("inviteMemberByToken", () => {
it("should throw error if verification token is not found", async () => {
prismaMock.verificationToken.findFirst.mockResolvedValue(null);
await expect(TeamService.inviteMemberByToken("invalid-token", 1)).rejects.toThrow(TRPCError);
});
it("should create provisional membership and update billing", async () => {
const mockToken = {
teamId: 1,
team: { name: "Test Team" },
expiresInDays: null,
expires: new Date(Date.now() + 86400000),
token: "valid-token",
identifier: "test@example.com",
id: "1",
};
prismaMock.verificationToken.findFirst.mockResolvedValue(mockToken);
prismaMock.membership.create.mockResolvedValue({} as Membership);
const result = await TeamService.inviteMemberByToken("valid-token", 1);
expect(prismaMock.membership.create).toHaveBeenCalledWith({
data: {
accepted: false,
createdAt: expect.any(Date),
role: MembershipRole.MEMBER,
teamId: 1,
userId: 1,
},
});
expect(mockTeamBilling.updateQuantity).toHaveBeenCalled();
expect(result).toBe("Test Team");
});
});
describe("acceptTeamMembership", () => {
it("should accept membership and update event types for regular team", async () => {
const mockMembership = {
team: { id: 1, parentId: null, isOrganization: false },
};
prismaMock.membership.update.mockResolvedValue(mockMembership as Membership & { team: Team });
vi.mocked(updateNewTeamMemberEventTypes).mockResolvedValue(undefined);
await TeamService.acceptTeamMembership({
userId: 1,
teamId: 1,
userEmail: "test@example.com",
username: "testuser",
});
expect(prismaMock.membership.update).toHaveBeenCalledWith({
where: { userId_teamId: { userId: 1, teamId: 1 } },
data: { accepted: true },
select: { team: true },
});
expect(updateNewTeamMemberEventTypes).toHaveBeenCalledWith(1, 1);
});
it("should accept membership and create profile for organization", async () => {
const mockMembership = {
team: { id: 1, parentId: null, isOrganization: true },
};
prismaMock.membership.update.mockResolvedValue(mockMembership as Membership & { team: Team });
vi.mocked(createAProfileForAnExistingUser).mockResolvedValue({} as Profile);
vi.mocked(updateNewTeamMemberEventTypes).mockResolvedValue(undefined);
await TeamService.acceptTeamMembership({
userId: 1,
teamId: 1,
userEmail: "test@example.com",
username: "testuser",
});
expect(createAProfileForAnExistingUser).toHaveBeenCalledWith({
user: {
id: 1,
email: "test@example.com",
currentUsername: "testuser",
},
organizationId: 1,
});
});
it("should accept membership and handle parent team for subteam", async () => {
const mockMembership = {
team: { id: 1, parentId: 2, isOrganization: false },
};
prismaMock.membership.update
.mockResolvedValueOnce(mockMembership as Membership & { team: Team })
.mockResolvedValueOnce({} as Membership);
vi.mocked(createAProfileForAnExistingUser).mockResolvedValue({} as Profile);
vi.mocked(updateNewTeamMemberEventTypes).mockResolvedValue(undefined);
await TeamService.acceptTeamMembership({
userId: 1,
teamId: 1,
userEmail: "test@example.com",
username: "testuser",
});
expect(prismaMock.membership.update).toHaveBeenCalledTimes(2);
expect(prismaMock.membership.update).toHaveBeenNthCalledWith(2, {
where: { userId_teamId: { userId: 1, teamId: 2 } },
data: { accepted: true },
});
expect(createAProfileForAnExistingUser).toHaveBeenCalledWith({
user: {
id: 1,
email: "test@example.com",
currentUsername: "testuser",
},
organizationId: 2,
});
});
});
describe("leaveTeamMembership", () => {
it("should delete membership when rejecting invitation", async () => {
const mockMembership = {
team: { id: 1, parentId: null },
};
prismaMock.membership.delete.mockResolvedValue(mockMembership as Membership & { team: Team });
await TeamService.leaveTeamMembership({
userId: 1,
teamId: 1,
});
expect(prismaMock.membership.delete).toHaveBeenCalledWith({
where: { userId_teamId: { userId: 1, teamId: 1 } },
select: { team: true },
});
});
it("should delete parent membership when rejecting subteam invitation", async () => {
const mockMembership = {
team: { id: 1, parentId: 2 },
};
prismaMock.membership.delete
.mockResolvedValueOnce(mockMembership as Membership & { team: Team })
.mockResolvedValueOnce({} as Membership);
await TeamService.leaveTeamMembership({
userId: 1,
teamId: 1,
});
expect(prismaMock.membership.delete).toHaveBeenCalledTimes(2);
expect(prismaMock.membership.delete).toHaveBeenNthCalledWith(2, {
where: { userId_teamId: { userId: 1, teamId: 2 } },
});
});
});
describe("acceptInvitationByToken", () => {
it("should throw error if verification token is not found", async () => {
prismaMock.verificationToken.findFirst.mockResolvedValue(null);
await expect(TeamService.acceptInvitationByToken("invalid-token", 1)).rejects.toThrow(TRPCError);
});
it("should throw error if token is not associated with team", async () => {
const mockToken = {
teamId: null,
team: null,
identifier: "test@example.com",
id: "1",
};
prismaMock.verificationToken.findFirst.mockResolvedValue(
mockToken as VerificationToken & { team: Team | null }
);
await expect(TeamService.acceptInvitationByToken("valid-token", 1)).rejects.toThrow(
new TRPCError({
code: "NOT_FOUND",
message: "Invite token is not associated with any team",
})
);
});
it("should throw error if user not found", async () => {
const mockToken = {
teamId: 1,
team: { name: "Test Team" },
identifier: "test@example.com",
id: "1",
};
prismaMock.verificationToken.findFirst.mockResolvedValue(
mockToken as VerificationToken & { team: Team }
);
prismaMock.user.findUnique.mockResolvedValue(null);
await expect(TeamService.acceptInvitationByToken("valid-token", 1)).rejects.toThrow(
new TRPCError({ code: "NOT_FOUND", message: "User not found" })
);
});
it("should throw error if user email doesn't match token identifier", async () => {
const mockToken = {
teamId: 1,
team: { name: "Test Team" },
identifier: "invited@example.com",
id: "1",
};
const mockUser = {
email: "different@example.com",
username: "testuser",
};
prismaMock.verificationToken.findFirst.mockResolvedValue(
mockToken as VerificationToken & { team: Team }
);
prismaMock.user.findUnique.mockResolvedValue(mockUser as User);
await expect(TeamService.acceptInvitationByToken("valid-token", 1)).rejects.toThrow(
new TRPCError({
code: "FORBIDDEN",
message: "This invitation is not for your account",
})
);
});
it("should throw error if user username doesn't match token identifier", async () => {
const mockToken = {
teamId: 1,
team: { name: "Test Team" },
identifier: "inviteduser",
id: "1",
};
const mockUser = {
email: "test@example.com",
username: "differentuser",
};
prismaMock.verificationToken.findFirst.mockResolvedValue(
mockToken as VerificationToken & { team: Team }
);
prismaMock.user.findUnique.mockResolvedValue(mockUser as User);
await expect(TeamService.acceptInvitationByToken("valid-token", 1)).rejects.toThrow(
new TRPCError({
code: "FORBIDDEN",
message: "This invitation is not for your account",
})
);
});
it("should accept invitation when user email matches token identifier", async () => {
const mockToken = {
teamId: 1,
team: { name: "Test Team" },
identifier: "test@example.com",
id: "1",
};
const mockUser = {
email: "test@example.com",
username: "testuser",
};
const mockMembership = {
team: { id: 1, parentId: null, isOrganization: false },
};
prismaMock.verificationToken.findFirst.mockResolvedValue(
mockToken as VerificationToken & { team: Team }
);
prismaMock.user.findUnique.mockResolvedValue(mockUser as User);
prismaMock.membership.update.mockResolvedValue(mockMembership as Membership & { team: Team });
vi.mocked(updateNewTeamMemberEventTypes).mockResolvedValue(undefined);
await TeamService.acceptInvitationByToken("valid-token", 1);
expect(prismaMock.membership.update).toHaveBeenCalledWith({
where: { userId_teamId: { userId: 1, teamId: 1 } },
data: { accepted: true },
select: { team: true },
});
});
it("should accept invitation when user username matches token identifier", async () => {
const mockToken = {
teamId: 1,
team: { name: "Test Team" },
identifier: "testuser",
id: "1",
};
const mockUser = {
email: "testuser@example.com",
username: "testuser",
};
const mockMembership = {
team: { id: 1, parentId: null, isOrganization: false },
};
prismaMock.verificationToken.findFirst.mockResolvedValue(
mockToken as VerificationToken & { team: Team }
);
prismaMock.user.findUnique.mockResolvedValue(mockUser as User);
prismaMock.membership.update.mockResolvedValue(mockMembership as Membership & { team: Team });
vi.mocked(updateNewTeamMemberEventTypes).mockResolvedValue(undefined);
await TeamService.acceptInvitationByToken("valid-token", 1);
expect(prismaMock.membership.update).toHaveBeenCalledWith({
where: { userId_teamId: { userId: 1, teamId: 1 } },
data: { accepted: true },
select: { team: true },
});
});
});
describe("publish", () => {
it("should call publish on TeamBilling", async () => {
await TeamService.publish(1);
expect(mockTeamBillingFactory.findAndInit).toHaveBeenCalledWith(1);
expect(mockTeamBilling.publish).toHaveBeenCalled();
});
});
});