Files
cal.diy/packages/features/ee/organizations/lib/OrganizationPaymentService.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: [email protected] <[email protected]>

* 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: [email protected] <[email protected]>

* 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: [email protected] <[email protected]>

* 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: [email protected] <[email protected]>

* 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: [email protected] <[email protected]>

* Address feedback

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

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

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

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

* 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: [email protected] <[email protected]>

* 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: [email protected] <[email protected]>

* 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: [email protected] <[email protected]>

---------

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 <[email protected]>
2025-11-19 10:21:22 -05:00

325 lines
10 KiB
TypeScript

import { describe, expect, it, vi, beforeEach } from "vitest";
import { ORGANIZATION_SELF_SERVE_MIN_SEATS } from "@calcom/lib/constants";
import { prisma } from "@calcom/prisma";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
import { OrganizationPaymentService } from "./OrganizationPaymentService";
import type { IOrganizationPermissionService } from "./OrganizationPermissionService";
vi.stubEnv("STRIPE_ORG_PRODUCT_ID", "STRIPE_ORG_PRODUCT_ID");
vi.stubEnv("STRIPE_ORG_MONTHLY_PRICE_ID", "STRIPE_ORG_MONTHLY_PRICE_ID");
const defaultOrgOnboarding = {
id: "onboard-id-1",
name: "Test Org",
slug: "test-org",
orgOwnerEmail: "[email protected]",
billingPeriod: "MONTHLY",
seats: 5,
pricePerSeat: 20,
isComplete: false,
stripeCustomerId: "mock_stripe_customer_id",
};
vi.mock("@calcom/prisma", () => {
const prismaMock = {
organizationOnboarding: {
findFirst: vi.fn(),
create: vi.fn(),
update: vi.fn(),
},
membership: {
findMany: vi.fn(),
},
user: {
findUnique: vi.fn(),
update: vi.fn(),
},
};
return {
prisma: prismaMock,
default: prismaMock,
};
});
const mockBillingService = {
createCustomer: vi.fn().mockResolvedValue({ id: "mock_customer_id" }),
createPrice: vi.fn().mockResolvedValue({ id: "mock_price_id", isCustom: false }),
createSubscription: vi.fn().mockResolvedValue({ id: "mock_subscription_id" }),
createSubscriptionCheckout: vi.fn().mockResolvedValue({
checkoutUrl: "https://checkout.stripe.com/mock-checkout-url",
}),
};
vi.mock("@calcom/features/ee/billing/di/containers/Billing", () => ({
getBillingProviderService: vi.fn(() => mockBillingService),
getTeamBillingServiceFactory: vi.fn(),
getTeamBillingDataRepository: vi.fn(),
}));
describe("OrganizationPaymentService", () => {
let service: OrganizationPaymentService;
let mockPermissionService: IOrganizationPermissionService;
const mockUser: TrpcSessionUser = {
id: 1,
email: "[email protected]",
role: "USER",
};
beforeEach(() => {
vi.clearAllMocks();
mockPermissionService = {
hasPermissionToCreateForEmail: vi.fn().mockResolvedValue(true),
hasPendingOrganizations: vi.fn().mockResolvedValue(false),
hasPermissionToModifyDefaultPayment: vi.fn().mockReturnValue(false),
hasPermissionToMigrateTeams: vi.fn().mockResolvedValue(true),
hasModifiedDefaultPayment: vi.fn().mockReturnValue(false),
validatePermissions: vi.fn().mockResolvedValue(true),
};
service = new OrganizationPaymentService(mockUser, mockPermissionService);
vi.mocked(prisma.user.findUnique).mockResolvedValue({ metadata: {} });
vi.mocked(prisma.organizationOnboarding.create).mockResolvedValue({
id: 1,
name: "Test Org",
slug: "test-org",
orgOwnerEmail: "[email protected]",
billingPeriod: "MONTHLY",
seats: 5,
pricePerSeat: 20,
stripeCustomerId: "mock_customer_id",
isComplete: false,
});
});
describe("createPaymentIntent", () => {
const baseInput = {
bio: "BIO",
logo: "LOGO",
teams: [{ id: 1, isBeingMigrated: true, name: "Team 1", slug: "team1" }],
};
it("should not allow non-admin to modify payment settings", async () => {
mockPermissionService.validatePermissions.mockRejectedValueOnce(
new Error("You do not have permission to modify the default payment settings")
);
await expect(
service.createPaymentIntent(
{
...baseInput,
pricePerSeat: 1000, // Trying to modify price
},
defaultOrgOnboarding
)
).rejects.toThrow("You do not have permission to modify the default payment settings");
});
it("should use minimum seats when total unique members is less than minimum", async () => {
// Mock 3 unique members (less than minimum of 5)
vi.mocked(prisma.membership.findMany).mockImplementation(async () => [
{ userId: 1, user: { email: "[email protected]" } },
{ userId: 2, user: { email: "[email protected]" } },
{ userId: 3, user: { email: "[email protected]" } },
]);
const result = await service.createPaymentIntent(
{
...baseInput,
invitedMembers: [{ email: "[email protected]" }], // Adding 1 invited member
},
defaultOrgOnboarding
);
expect(result).toBeDefined();
const updateCall = vi.mocked(prisma.organizationOnboarding.update).mock.calls[0][0];
expect(updateCall.where).toEqual({ id: "onboard-id-1" });
const { updatedAt: _updatedAt, ...data } = updateCall.data;
expect(data).toEqual({
bio: "BIO",
logo: "LOGO",
brandColor: null,
bannerUrl: null,
teams: [
{
id: 1,
isBeingMigrated: true,
name: "Team 1",
slug: "team1",
},
],
invitedMembers: [
{
email: "[email protected]",
},
],
stripeCustomerId: "mock_stripe_customer_id",
pricePerSeat: defaultOrgOnboarding.pricePerSeat,
billingPeriod: "MONTHLY",
seats: Number(ORGANIZATION_SELF_SERVE_MIN_SEATS),
});
});
it("should use total unique members when more than minimum", async () => {
// Mock 7 unique team members
vi.mocked(prisma.membership.findMany).mockImplementation(async () =>
Array.from({ length: 7 }, (_, i) => ({
userId: i + 1,
user: { email: `user${i + 1}@example.com` },
}))
);
const result = await service.createPaymentIntent(
{
...baseInput,
invitedMembers: [
{ email: "[email protected]" },
{ email: "[email protected]" },
{ email: "[email protected]" },
], // Adding 3 invited members, total should be 7 as these new invites are pending
},
defaultOrgOnboarding
);
expect(result).toBeDefined();
const updateCall = vi.mocked(prisma.organizationOnboarding.update).mock.calls[0][0];
expect(updateCall.where).toEqual({ id: "onboard-id-1" });
const { updatedAt: _updatedAt, ...data } = updateCall.data;
expect(data).toEqual({
bio: "BIO",
logo: "LOGO",
brandColor: null,
bannerUrl: null,
teams: [
{
id: 1,
isBeingMigrated: true,
name: "Team 1",
slug: "team1",
},
],
invitedMembers: [
{ email: "[email protected]" },
{ email: "[email protected]" },
{ email: "[email protected]" },
],
stripeCustomerId: "mock_stripe_customer_id",
pricePerSeat: defaultOrgOnboarding.pricePerSeat,
billingPeriod: "MONTHLY",
seats: 10,
});
});
describe("admin overrides", () => {
beforeEach(() => {
mockPermissionService.hasPermissionToModifyDefaultPayment.mockReturnValue(true);
mockPermissionService.hasModifiedDefaultPayment.mockReturnValue(true);
mockPermissionService.validatePermissions.mockResolvedValue(true);
// Mock membership count to be 0 for admin override tests
vi.mocked(prisma.membership.findMany).mockResolvedValue([]);
});
it("should allow admin to override minimum seats to a lower value", async () => {
const customSeats = 3;
await service.createPaymentIntent(
{
...baseInput,
seats: customSeats,
},
{
...defaultOrgOnboarding,
seats: customSeats,
}
);
expect(vi.mocked(prisma.organizationOnboarding.update)).toHaveBeenCalled();
const updateCall = vi.mocked(prisma.organizationOnboarding.update).mock.calls[0][0];
expect(updateCall.where).toEqual({ id: "onboard-id-1" });
const { updatedAt: _updatedAt, ...data } = updateCall.data;
expect(data).toEqual({
bio: "BIO",
logo: "LOGO",
brandColor: null,
bannerUrl: null,
invitedMembers: undefined,
teams: [
{
id: 1,
isBeingMigrated: true,
name: "Team 1",
slug: "team1",
},
],
stripeCustomerId: "mock_stripe_customer_id",
pricePerSeat: defaultOrgOnboarding.pricePerSeat,
billingPeriod: "MONTHLY",
seats: customSeats,
});
});
it("should allow admin to override price per seat", async () => {
const customPrice = 1000;
const result = await service.createPaymentIntent(baseInput, {
...defaultOrgOnboarding,
pricePerSeat: customPrice,
});
expect(result).toBeDefined();
const updateCall = vi.mocked(prisma.organizationOnboarding.update).mock.calls[0][0];
expect(updateCall.where).toEqual({ id: "onboard-id-1" });
const { updatedAt: _updatedAt, ...data } = updateCall.data;
expect(data).toEqual({
bio: "BIO",
logo: "LOGO",
brandColor: null,
bannerUrl: null,
invitedMembers: undefined,
teams: [
{
id: 1,
isBeingMigrated: true,
name: "Team 1",
slug: "team1",
},
],
stripeCustomerId: "mock_stripe_customer_id",
pricePerSeat: customPrice,
billingPeriod: "MONTHLY",
seats: 5,
});
});
it("should create custom price in Stripe when admin overrides price", async () => {
const customPrice = 1500;
await service.createPaymentIntent(
{
...baseInput,
pricePerSeat: customPrice,
},
{
...defaultOrgOnboarding,
pricePerSeat: customPrice,
}
);
// Verify a custom price was created in Stripe
expect(vi.mocked(service["billingService"].createPrice)).toHaveBeenCalledWith(
expect.objectContaining({
amount: customPrice * 100, // Convert to cents for Stripe
currency: "usd",
interval: "month",
productId: "STRIPE_ORG_PRODUCT_ID",
nickname: expect.stringContaining("Custom Organization Price"),
metadata: expect.objectContaining({
billingPeriod: "MONTHLY",
organizationOnboardingId: "onboard-id-1",
pricePerSeat: customPrice,
}),
})
);
});
});
});
});