Files
cal.diy/packages/lib/server/repository/credits.ts
T
d4bff9d6b1 feat: Cal.ai Self Serve #2 (#22995)
* feat: Cal.ai Self Serve #2

* chore: fix import and remove logs

* fix: update checkout session

* fix: type errors and test

* fix: imports

* fix: type err

* fix: type error

* fix: tests

* chore: save progress

* fix: workflow flow

* fix: workflow update bug

* tests: add unit tests for retell ai webhoo

* fix: status code

* fix: test and delete bug

* fix: add dynamic variables

* fix: type err

* chore: update unit test

* fix: type error

* chore: update default prompt

* fix: type errors

* fix: workflow permissions

* fix: workflow page

* fix: translations

* feat: add call duration

* chore: add booking uid

* fix: button positioning

* chore: update tests

* chore: improvements

* chore: some more improvements

* refactor: improvements

* refactor: code feedback

* refactor: improvements

* feat: enable credits for orgs (#23077)

* Show credits UI for orgs

* fix stripe callback url when buying credits

* give orgs 20% credits

* add test for calulating credits

---------

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>

* fix: types

* fix: types

* chore: error

* fix: type error

* fix: type error

* chore: mock env

* feat: add idempotency key to prevent double charging

* chore: add userId and teamId

* fix: skip inbound calls

* chore: update tests

* feat: add feature flag for voice agent

* feat: finish test call and other improvements

* chore: add alert

* chore: update .env.example

* chore: improvements

* fix: update tests

* refactor: remove un necessary

* feat: add setup badge

* chore: improvements

* fix: use referene id

* chore: improvements

* fix: type error

* fix: type

* refactor: change pricing logic

* refactor: update tests

* fix: conflicts

* fix: billing link for orgs

* fix: types

* refactor: move feature flag up

* fix: alert and test call credit check

* fix: update unit tests

* fix: feedback

* refactor: improvements

* refactor: move handlers to separate files

* fix: types

* fix: missing import

* fix: type

* refactor: change general tools functions handling

* refactor: use repository

* refactor: improvements

* fix: types

* fix: type errorr

* fix: auth check

* feat: add creditFor

* fix: update defualt prompt

* fix: throw error on frontend

* fix: update unit tests

* fix: use deleteAllWorkflowReminders

* refactor: add connect phone number

* refactor: improvements

* chore: translation

* chore: update message

* chore: translation

* design improvements buy number dialog

* add translation for error message

* use translation key in error message

* refactor: improve connect phone number tab

* feat: support un saved workflow to tests

* chore: remove un used

* fix: remove un used

* fix: remove un used

* refactor: similify billing

---------

Co-authored-by: Carina Wollendorfer <[email protected]>
Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
2025-08-29 05:04:05 +01:00

241 lines
5.3 KiB
TypeScript

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,
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,
},
});
}
}