refactor: create CreditsRepository in /features/credits (#25843)

* mv test

* mv repo

* update imports

* Update packages/features/ee/billing/api/webhook/_checkout.session.completed.ts

Co-authored-by: Volnei Munhoz <[email protected]>

* fix test

---------

Co-authored-by: Volnei Munhoz <[email protected]>
This commit is contained in:
Benny JooandVolnei Munhoz authored and GitHub committed 2025-12-16 10:42:27 -03:00
1 parent 272cf43322
commit c3bcd623f6
7 files changed
+8 -11

No files matched your search

@@ -0,0 +1,184 @@
import prismaMock from "../../../../tests/libs/__mocks__/prismaMock";
import { describe, it, expect, beforeEach, vi, afterEach } from "vitest";
import { CreditType } from "@calcom/prisma/enums";
import { CreditsRepository } from "./CreditsRepository";
describe("CreditsRepository", () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.useRealTimers();
});
describe("findCreditBalance", () => {
it("should use teamId if both userId and teamId are provided", async () => {
await CreditsRepository.findCreditBalance({ teamId: 1, userId: 5 });
expect(prismaMock.creditBalance.findUnique).toHaveBeenCalledWith({
where: { teamId: 1 },
select: {
id: true,
additionalCredits: true,
limitReachedAt: true,
warningSentAt: true,
},
});
});
it("should use userId if teamId is undefined", async () => {
await CreditsRepository.findCreditBalance({ userId: 1 });
expect(prismaMock.creditBalance.findUnique).toHaveBeenCalledWith({
where: { userId: 1 },
select: {
id: true,
additionalCredits: true,
limitReachedAt: true,
warningSentAt: true,
},
});
});
});
describe("findCreditBalanceWithTeamOrUser", () => {
it("should use teamId if both userId and teamId are provided", async () => {
await CreditsRepository.findCreditBalanceWithTeamOrUser({ teamId: 1, userId: 5 });
expect(prismaMock.creditBalance.findUnique).toHaveBeenCalledWith({
where: { teamId: 1 },
select: expect.objectContaining({
id: true,
additionalCredits: true,
team: expect.any(Object),
}),
});
});
it("should use userId if teamId is undefined", async () => {
await CreditsRepository.findCreditBalanceWithTeamOrUser({ userId: 1 });
expect(prismaMock.creditBalance.findUnique).toHaveBeenCalledWith({
where: { userId: 1 },
select: expect.objectContaining({
id: true,
additionalCredits: true,
user: expect.any(Object),
}),
});
});
});
describe("findCreditBalanceWithExpenseLogs", () => {
it("should use teamId if both userId and teamId are provided", async () => {
await CreditsRepository.findCreditBalanceWithExpenseLogs({ teamId: 1, userId: 5 });
expect(prismaMock.creditBalance.findUnique).toHaveBeenCalledWith({
where: { teamId: 1 },
select: expect.objectContaining({
additionalCredits: true,
expenseLogs: expect.any(Object),
}),
});
});
it("should use userId if teamId is undefined", async () => {
await CreditsRepository.findCreditBalanceWithExpenseLogs({ userId: 1 });
expect(prismaMock.creditBalance.findUnique).toHaveBeenCalledWith({
where: { teamId: undefined, userId: 1 },
select: expect.objectContaining({
additionalCredits: true,
expenseLogs: expect.any(Object),
}),
});
});
it("should apply startDate, endDate and creditType to expenseLogs filter", async () => {
const startDate = new Date("2025-05-01");
const endDate = new Date("2025-05-31");
const creditType = CreditType.MONTHLY;
await CreditsRepository.findCreditBalanceWithExpenseLogs({
userId: 1,
startDate,
endDate,
creditType,
});
expect(prismaMock.creditBalance.findUnique).toHaveBeenCalledWith({
where: { userId: 1 },
select: {
additionalCredits: true,
expenseLogs: {
where: {
date: {
gte: startDate,
lte: endDate,
},
creditType,
},
orderBy: {
date: "desc",
},
select: {
date: true,
credits: true,
creditType: true,
bookingUid: true,
smsSid: true,
smsSegments: true,
email: true,
phoneNumber: true,
callDuration: true,
externalRef: true,
},
},
},
});
});
it("should use correct fallbacks for startDate, endDate and creditType if undefined", async () => {
const systemTime = new Date("2025-04-20T10:00:00Z");
vi.setSystemTime(systemTime);
await CreditsRepository.findCreditBalanceWithExpenseLogs({
teamId: 1,
});
expect(prismaMock.creditBalance.findUnique).toHaveBeenCalledWith({
where: { teamId: 1 },
select: {
additionalCredits: true,
expenseLogs: {
where: {
date: {
gte: new Date("2025-04-01T00:00:00Z"),
lte: systemTime,
},
},
orderBy: {
date: "desc",
},
select: {
date: true,
credits: true,
creditType: true,
bookingUid: true,
smsSid: true,
smsSegments: true,
email: true,
phoneNumber: true,
callDuration: true,
externalRef: true,
},
},
},
});
});
});
});
@@ -0,0 +1,242 @@
import dayjs from "@calcom/dayjs";
import prisma, { type PrismaTransaction } from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import type { CreditType } from "@calcom/prisma/enums";
export class CreditsRepository {
static async findCreditBalance(
{ teamId, userId }: { teamId?: number; userId?: number },
tx?: PrismaTransaction
) {
const prismaClient = tx ?? prisma;
const select = {
id: true,
additionalCredits: true,
limitReachedAt: true,
warningSentAt: true,
};
if (teamId) {
return await prismaClient.creditBalance.findUnique({
where: {
teamId,
},
select,
});
}
if (userId) {
return await prismaClient.creditBalance.findUnique({
where: { userId },
select,
});
}
}
static async findCreditExpenseLogByExternalRef(externalRef: string, tx?: PrismaTransaction) {
const prismaClient = tx ?? prisma;
return await prismaClient.creditExpenseLog.findUnique({
where: { externalRef },
select: {
id: true,
credits: true,
creditType: true,
date: true,
bookingUid: true,
},
});
}
static async findCreditBalanceWithTeamOrUser(
{
teamId,
userId,
}: {
teamId?: number | null;
userId?: number | null;
},
tx?: PrismaTransaction
) {
const prismaClient = tx ?? prisma;
const select = {
id: true,
additionalCredits: true,
limitReachedAt: true,
warningSentAt: true,
team: {
select: {
id: true,
name: true,
members: {
select: {
user: {
select: {
id: true,
name: true,
email: true,
locale: true,
},
},
},
},
},
},
user: {
select: {
id: true,
name: true,
email: true,
locale: true,
},
},
};
if (teamId) {
return await prismaClient.creditBalance.findUnique({
where: {
teamId,
},
select,
});
}
if (userId) {
return await prismaClient.creditBalance.findUnique({
where: { userId },
select,
});
}
}
static async findCreditBalanceWithExpenseLogs(
{
teamId,
userId,
startDate = dayjs().startOf("month").toDate(),
endDate = new Date(),
creditType,
}: { teamId?: number; userId?: number; startDate?: Date; endDate?: Date; creditType?: CreditType },
tx?: PrismaTransaction
) {
if (!teamId && !userId) return null;
const prismaClient = tx ?? prisma;
return await prismaClient.creditBalance.findUnique({
where: {
teamId,
...(!teamId ? { userId } : {}),
},
select: {
additionalCredits: true,
expenseLogs: {
where: {
date: {
gte: startDate,
lte: endDate,
},
...(creditType ? { creditType } : {}),
},
orderBy: {
date: "desc",
},
select: {
date: true,
credits: true,
creditType: true,
bookingUid: true,
smsSid: true,
smsSegments: true,
phoneNumber: true,
email: true,
callDuration: true,
externalRef: true,
},
},
},
});
}
static async updateCreditBalance(
{
id,
teamId,
userId,
data,
}: {
id?: string;
teamId?: number | null;
userId?: number | null;
data: Prisma.CreditBalanceUncheckedUpdateInput;
},
tx?: PrismaTransaction
) {
const prismaClient = tx ?? prisma;
if (id) {
return prismaClient.creditBalance.update({
where: { id },
data,
});
}
if (teamId) {
return prismaClient.creditBalance.update({
where: { teamId },
data,
});
}
if (userId) {
return prismaClient.creditBalance.update({
where: { userId },
data,
});
}
return null;
}
static async createCreditBalance(data: Prisma.CreditBalanceUncheckedCreateInput, tx?: PrismaTransaction) {
const { teamId, userId } = data;
if (!teamId && !userId) {
throw new Error("Team or user ID is required");
}
return (tx ?? prisma).creditBalance.create({
data: {
...data,
...(!teamId ? { userId } : {}),
},
});
}
static async createCreditExpenseLog(
data: Prisma.CreditExpenseLogUncheckedCreateInput,
tx?: PrismaTransaction
) {
const prismaClient = tx ?? prisma;
try {
return await prismaClient.creditExpenseLog.create({
data,
});
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
throw new Error(`Duplicate external reference - already processed: ${data?.externalRef}`);
}
throw error;
}
}
static async createCreditPurchaseLog(data: { credits: number; creditBalanceId: string }) {
const { credits, creditBalanceId } = data;
return prisma.creditPurchaseLog.create({
data: {
credits,
creditBalanceId,
},
});
}
}
@@ -1,10 +1,10 @@
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
import { PrismaAgentRepository } from "@calcom/features/calAIPhone/repositories/PrismaAgentRepository";
import { PrismaPhoneNumberRepository } from "@calcom/features/calAIPhone/repositories/PrismaPhoneNumberRepository";
import { CreditsRepository } from "@calcom/features/credits/repositories/CreditsRepository";
import stripe from "@calcom/features/ee/payments/server/stripe";
import logger from "@calcom/lib/logger";
import { CreditsRepository } from "@calcom/lib/server/repository/credits";
import prisma from "@calcom/prisma";
import { prisma } from "@calcom/prisma";
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import { CHECKOUT_SESSION_TYPES } from "../../constants";
@@ -2,10 +2,10 @@ import { describe, it, expect, beforeEach, vi } from "vitest";
import dayjs from "@calcom/dayjs";
import * as EmailManager from "@calcom/emails/billing-email-service";
import { CreditsRepository } from "@calcom/features/credits/repositories/CreditsRepository";
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import { CreditsRepository } from "@calcom/lib/server/repository/credits";
import { CreditType } from "@calcom/prisma/enums";
import { CreditService } from "./credit-service";
@@ -91,6 +91,7 @@ vi.mock("@calcom/prisma/enums", async (importOriginal) => {
vi.mock("@calcom/lib/server/repository/credits");
vi.mock("@calcom/features/membership/repositories/MembershipRepository");
vi.mock("@calcom/features/ee/teams/repositories/TeamRepository");
vi.mock("@calcom/features/credits/repositories/CreditsRepository");
vi.mock("@calcom/emails/billing-email-service", () => ({
sendCreditBalanceLimitReachedEmails: vi.fn().mockResolvedValue(undefined),
sendCreditBalanceLowWarningEmails: vi.fn().mockResolvedValue(undefined),
@@ -125,10 +126,6 @@ vi.spyOn(creditService, "_getAllCredits").mockResolvedValue({
additionalCredits: 1,
});
CreditsRepository.findCreditBalance.mockResolvedValueOnce({
limitReachedAt: null,
});
describe("CreditService", () => {
let creditService: CreditService;
@@ -1,12 +1,12 @@
import type { TFunction } from "i18next";
import dayjs from "@calcom/dayjs";
import { CreditsRepository } from "@calcom/features/credits/repositories/CreditsRepository";
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import { IS_SMS_CREDITS_ENABLED } from "@calcom/lib/constants";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import logger from "@calcom/lib/logger";
import { CreditsRepository } from "@calcom/lib/server/repository/credits";
import { prisma, type PrismaTransaction } from "@calcom/prisma";
import { CreditUsageType, CreditType } from "@calcom/prisma/enums";