feat: SMS credits for free users (#21245)

* Add credits section to billing

* create seperate router for credits

* add stripe checkout session

* schema changes + code improvements

* rename to creditBalance

* custom quantify input with error message

* add checkout session completed webhook endpoint

* fix typo

* UI fixes

* add payCredits handler

* add error toast message

* allow scheduling sms up as close to 15 minutes in the future

* schedule at most 2 hours in advance

* webhook to pay for sent sms

* continued work on twilio callback

* code clean up

* further implementation for credit handling

* add migration

* object as param for scheduleSMS

* object as param for sendSMS

* fix TrpcSessionUser imports

* fix imports

* add db changes

* add cron job for price setting

* twilio status callback to create expense log

* remove unused code

* set up low credit balance email

* fixes for buying credits

* fixes in api/twilio/webhook

* add test to save credits to credits balance

* fix typos

* add new helper function chargeCredits

* expand twilioProvider

* fix type errors

* adjust tests

* type errors

* clean up

* clean up

* fix subscription active check

* remove some user/org related code

* more changes to remove user/org support

* send emails seperatly to admins

* fixes for team billing page

* fix stripe success url

* fixes to creating expense log

* email imrovements and more

* get monthly team price from stripe

* fix import

* fix monthly credits calculation

* finsih low credit balance warning email

* credit balance limit reached email

* create CreditService

* cancel SMS and send as email instead

* add messageDispatcher

* fix type error

* fix type error

* fix type error

* fix import

* fix unit test

* clean up twilioProvider

* clean up chckSmsPrices/route

* add missing translations

* add skeleton loader

* add admin check to get handler

* code clean up + fixes

* improve scheduling with fallback

* fix type error

* add bookingUid to handleSendingSMS

* add unit tests for creditService

* add more tests to credit-service.test.ts

* add test for cancelScheduledMessagesAndScheduleEmails

* fix test and type error

* add back resolve

* fix empty resolve

* adjust limitReachedAt logic

* address mrge comment on styling

* add getAdminMembership to repository

* twilio/webhook clean up (feedback)

* feedback - clean up

* remove todo comment

* clean up twilio/webhook

* code clean up

* add use client

* add createOneTimeCheckout to stripe service

* refactor repository pattern

* small fixes + clean up

* fix type error

* add missing import

* fix hasAvailableCredits for user

* force-dynamic

* rename credits to creditBalance

* fix stripe import

* remove not needed code

* fix e2e tests

* improve low balance warning email

* dynamic-import CreditService

* index.ts

* add user logic checkSmsPrices endpoint

* fix e2e tests

* remove dynamic import CreditService

* Revert "remove dynamic import CreditService"

This reverts commit e272978a7ff3fc5a04139e656c9f8d2c84a40dda.

* no need to dynamic-import credit service

* Revert "no need to dynamic-import credit service"

This reverts commit ba5ae488d08979a65fb47b5d0722cda9f45d6ea0.

* fix twilio webhook

* add userId support in checkout.session.completed

* clean up code

* only select id in getAdminMembership

* revert billing/package.json

* fix type checks

* fix type checks

* adjust hasAvailableCredits function

* fixes for checkout sessioned completed

* add UI for user

* fix type errors

* adds requires credits badge

* remove team check from update.handler

* clean up inlcude statements

* fix credit-service tests

* add tests

* fix type errors

* fix type errors

* fix and add tests

* imrove badge

* code clean up

* add reminderScheduler test

* add additional credits as title

* fixes for warningSentAt and limitReachedAt

* mock stripe

---------

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: hbjORbj <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
This commit is contained in:
authored and GitHub committed 2025-05-13 15:55:19 +02:00
1 parent e669996442
commit ead42c1a9c
30 files changed
+1173 -514

No files matched your search

@@ -10,10 +10,11 @@ const handler = async (data: SWHMap["checkout.session.completed"]["data"]) => {
throw new HttpCode(400, "Missing required payment details");
}
const teamId = session.metadata?.teamId ? Number(session.metadata.teamId) : null;
const teamId = session.metadata?.teamId ? Number(session.metadata.teamId) : undefined;
const userId = session.metadata?.userId ? Number(session.metadata.userId) : undefined;
if (!teamId) {
throw new HttpCode(400, "Team id missing but required");
if (!teamId && !userId) {
throw new HttpCode(400, "Team id and user id, but at least one is required");
}
const lineItems = await stripe.checkout.sessions.listLineItems(session.id);
@@ -24,15 +25,24 @@ const handler = async (data: SWHMap["checkout.session.completed"]["data"]) => {
throw new HttpCode(400, "Invalid price ID");
}
await saveToCreditBalance({ teamId, nrOfCredits });
await saveToCreditBalance({ userId, teamId, nrOfCredits });
return { success: true };
};
async function saveToCreditBalance({ teamId, nrOfCredits }: { teamId: number; nrOfCredits: number }) {
async function saveToCreditBalance({
userId,
teamId,
nrOfCredits,
}: {
userId?: number;
teamId?: number;
nrOfCredits: number;
}) {
const creditBalance = await prisma.creditBalance.findUnique({
where: {
teamId,
userId: !teamId ? userId : undefined,
},
select: {
id: true,
@@ -51,6 +61,7 @@ async function saveToCreditBalance({ teamId, nrOfCredits }: { teamId: number; nr
await prisma.creditBalance.create({
data: {
teamId: teamId,
userId: !teamId ? userId : undefined,
additionalCredits: nrOfCredits,
},
});
@@ -1,3 +1,4 @@
import Stripe from "stripe";
import { describe, it, expect, beforeEach, vi } from "vitest";
import dayjs from "@calcom/dayjs";
@@ -8,6 +9,10 @@ import { TeamRepository } from "@calcom/lib/server/repository/team";
import { CreditType } from "@calcom/prisma/enums";
import { CreditService } from "./credit-service";
import { StripeBillingService } from "./stripe-billling-service";
import { InternalTeamBilling } from "./teams/internal-team-billing";
vi.mock("stripe");
vi.mock("@calcom/lib/constants", async () => {
const actual = (await vi.importActual("@calcom/lib/constants")) as typeof import("@calcom/lib/constants");
@@ -27,279 +32,549 @@ vi.mock("../workflows/lib/reminders/reminderScheduler", () => ({
describe("CreditService", () => {
let creditService: CreditService;
let stripeMock: any;
beforeEach(() => {
vi.restoreAllMocks();
stripeMock = {
prices: {
list: vi.fn().mockResolvedValue({ data: [] }),
retrieve: vi.fn().mockResolvedValue({ id: "price_123", unit_amount: 1000 }),
},
};
(Stripe as any).mockImplementation(() => stripeMock);
creditService = new CreditService();
vi.clearAllMocks();
});
describe("hasAvailableCredits", () => {
it("should return true if team has not yet reached limit", async () => {
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: null,
warningSentAt: null,
describe("Team credits", () => {
describe("hasAvailableCredits", () => {
it("should return true if team has not yet reached limit", async () => {
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: null,
warningSentAt: null,
});
const noLimitReached = await creditService.hasAvailableCredits({ teamId: 1 });
expect(noLimitReached).toBe(true);
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: dayjs().subtract(1, "month").toDate(),
warningSentAt: null,
});
const limitReachedLastMonth = await creditService.hasAvailableCredits({ teamId: 1 });
expect(limitReachedLastMonth).toBe(true);
});
const noLimitReached = await creditService.hasAvailableCredits({ teamId: 1 });
expect(noLimitReached).toBe(true);
it("should return false if team limit reached this month", async () => {
vi.setSystemTime(new Date("2024-06-20T11:59:59Z"));
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: dayjs().subtract(1, "month").toDate(),
warningSentAt: null,
});
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: dayjs().subtract(1, "week").toDate(),
warningSentAt: null,
});
const limitReachedLastMonth = await creditService.hasAvailableCredits({ teamId: 1 });
expect(limitReachedLastMonth).toBe(true);
});
it("should return false if team limit reached this month", async () => {
vi.setSystemTime(new Date("2024-06-20T11:59:59Z"));
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: dayjs().subtract(1, "week").toDate(),
warningSentAt: null,
});
const result = await creditService.hasAvailableCredits({ teamId: 1 });
expect(result).toBe(false);
});
});
describe("getTeamWithAvailableCredits", () => {
it("should return team with available credits", async () => {
vi.mocked(MembershipRepository.findAllAcceptedMemberships).mockResolvedValue([
{
id: 1,
teamId: 1,
userId: 1,
role: "MEMBER",
accepted: true,
},
]);
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: null,
warningSentAt: null,
});
const result = await creditService.getTeamWithAvailableCredits(1);
expect(result).toEqual({
teamId: 1,
availableCredits: 0,
creditType: CreditType.ADDITIONAL,
const result = await creditService.hasAvailableCredits({ teamId: 1 });
expect(result).toBe(false);
});
});
it("should return first team if no team has available credits", async () => {
vi.mocked(MembershipRepository.findAllAcceptedMemberships).mockResolvedValue([
{
id: 1,
teamId: 1,
userId: 1,
role: "MEMBER",
accepted: true,
},
]);
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: new Date(),
warningSentAt: null,
});
const result = await creditService.getTeamWithAvailableCredits(1);
expect(result).toEqual({
teamId: 1,
availableCredits: 0,
creditType: CreditType.ADDITIONAL,
});
});
});
describe("chargeCredits", () => {
it("should create expense log and send low balance warning email", async () => {
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 10,
limitReachedAt: null,
warningSentAt: null,
});
vi.mocked(TeamRepository.findTeamWithAdmins).mockResolvedValue({
id: 1,
name: "team-name",
members: [
describe("getTeamWithAvailableCredits", () => {
it("should return team with available credits", async () => {
vi.mocked(MembershipRepository.findAllAcceptedMemberships).mockResolvedValue([
{
user: {
name: "admin",
email: "[email protected]",
locale: "en",
},
id: 1,
teamId: 1,
userId: 1,
role: "MEMBER",
accepted: true,
},
],
});
]);
vi.spyOn(EmailManager, "sendCreditBalanceLowWarningEmails").mockResolvedValue();
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: null,
warningSentAt: null,
});
vi.spyOn(CreditService.prototype, "getAllCreditsForTeam").mockResolvedValue({
totalMonthlyCredits: 500,
totalRemainingMonthlyCredits: 20,
additionalCredits: 60,
});
await creditService.chargeCredits({
teamId: 1,
credits: 5,
bookingUid: "booking-123",
smsSid: "sms-123",
});
expect(CreditsRepository.createCreditExpenseLog).toHaveBeenCalledWith(
expect.objectContaining({
bookingUid: "booking-123",
creditBalanceId: "1",
creditType: CreditType.MONTHLY,
credits: 5,
smsSid: "sms-123",
})
);
expect(EmailManager.sendCreditBalanceLowWarningEmails).toHaveBeenCalled();
});
it("should create expense log and send limit reached email", async () => {
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: null,
warningSentAt: null,
});
vi.mocked(TeamRepository.findTeamWithAdmins).mockResolvedValue({
id: 1,
name: "team-name",
members: [
{
user: {
name: "admin",
email: "[email protected]",
locale: "en",
},
},
],
});
vi.spyOn(EmailManager, "sendCreditBalanceLimitReachedEmails").mockResolvedValue();
vi.spyOn(CreditService.prototype, "getAllCreditsForTeam").mockResolvedValue({
totalMonthlyCredits: 500,
totalRemainingMonthlyCredits: -1,
additionalCredits: 0,
});
await creditService.chargeCredits({
teamId: 1,
credits: 5,
bookingUid: "booking-123",
smsSid: "sms-123",
});
expect(CreditsRepository.createCreditExpenseLog).toHaveBeenCalledWith(
expect.objectContaining({
bookingUid: "booking-123",
creditBalanceId: "1",
const result = await creditService.getTeamWithAvailableCredits(1);
expect(result).toEqual({
teamId: 1,
availableCredits: 0,
creditType: CreditType.ADDITIONAL,
credits: 5,
smsSid: "sms-123",
})
);
});
});
expect(EmailManager.sendCreditBalanceLimitReachedEmails).toHaveBeenCalled();
it("should return first team if no team has available credits", async () => {
vi.mocked(MembershipRepository.findAllAcceptedMemberships).mockResolvedValue([
{
id: 1,
teamId: 1,
userId: 1,
role: "MEMBER",
accepted: true,
},
]);
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: new Date(),
warningSentAt: null,
});
const result = await creditService.getTeamWithAvailableCredits(1);
expect(result).toEqual({
teamId: 1,
availableCredits: 0,
creditType: CreditType.ADDITIONAL,
});
});
});
describe("chargeCredits", () => {
it("should create expense log and send low balance warning email", async () => {
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 10,
limitReachedAt: null,
warningSentAt: null,
});
vi.mocked(CreditsRepository.findCreditBalanceWithTeamOrUser).mockResolvedValue({
id: "1",
additionalCredits: 10,
limitReachedAt: null,
warningSentAt: null,
team: {
id: 1,
name: "team-name",
members: [
{
user: {
id: 1,
name: "admin",
email: "[email protected]",
locale: "en",
},
},
],
},
user: null,
});
vi.spyOn(CreditService.prototype, "getTeamWithAvailableCredits").mockResolvedValue(null);
vi.spyOn(EmailManager, "sendCreditBalanceLowWarningEmails").mockResolvedValue();
vi.spyOn(CreditService.prototype, "getAllCreditsForTeam").mockResolvedValue({
totalMonthlyCredits: 500,
totalRemainingMonthlyCredits: 20,
additionalCredits: 60,
});
await creditService.chargeCredits({
teamId: 1,
credits: 5,
bookingUid: "booking-123",
smsSid: "sms-123",
});
expect(CreditsRepository.createCreditExpenseLog).toHaveBeenCalledWith(
expect.objectContaining({
bookingUid: "booking-123",
creditBalanceId: "1",
creditType: CreditType.MONTHLY,
credits: 5,
smsSid: "sms-123",
})
);
expect(EmailManager.sendCreditBalanceLowWarningEmails).toHaveBeenCalled();
});
it("should create expense log and send limit reached email", async () => {
vi.mocked(CreditsRepository.findCreditBalanceWithTeamOrUser).mockResolvedValue({
id: "1",
additionalCredits: 10,
limitReachedAt: null,
warningSentAt: null,
team: {
id: 1,
name: "team-name",
members: [
{
user: {
id: 1,
name: "admin",
email: "[email protected]",
locale: "en",
},
},
],
},
user: null,
});
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: null,
warningSentAt: null,
});
vi.spyOn(EmailManager, "sendCreditBalanceLimitReachedEmails").mockResolvedValue();
vi.spyOn(CreditService.prototype, "getAllCreditsForTeam").mockResolvedValue({
totalMonthlyCredits: 500,
totalRemainingMonthlyCredits: -1,
additionalCredits: 0,
});
await creditService.chargeCredits({
teamId: 1,
credits: 5,
bookingUid: "booking-123",
smsSid: "sms-123",
});
expect(CreditsRepository.createCreditExpenseLog).toHaveBeenCalledWith(
expect.objectContaining({
bookingUid: "booking-123",
creditBalanceId: "1",
creditType: CreditType.ADDITIONAL,
credits: 5,
smsSid: "sms-123",
})
);
expect(EmailManager.sendCreditBalanceLimitReachedEmails).toHaveBeenCalled();
});
});
describe("getUserOrTeamToCharge", () => {
it("should return team with remaining credits when teamId is provided", async () => {
vi.spyOn(CreditService.prototype, "getAllCreditsForTeam").mockResolvedValue({
totalMonthlyCredits: 500,
totalRemainingMonthlyCredits: 100,
additionalCredits: 50,
});
const result = await creditService.getUserOrTeamToCharge({
credits: 50,
teamId: 1,
});
expect(result).toEqual({
teamId: 1,
remainingCredits: 100,
creditType: CreditType.MONTHLY,
});
});
it("should use additional credits when monthly credits are out", async () => {
vi.spyOn(CreditService.prototype, "getAllCreditsForTeam").mockResolvedValue({
totalMonthlyCredits: 500,
totalRemainingMonthlyCredits: 0,
additionalCredits: 50,
});
const result = await creditService.getUserOrTeamToCharge({
credits: 30,
teamId: 1,
});
expect(result).toEqual({
teamId: 1,
remainingCredits: 20,
creditType: CreditType.ADDITIONAL,
});
});
it("should return team with available credits when userId is provided", async () => {
vi.mocked(MembershipRepository.findAllAcceptedMemberships).mockResolvedValue([{ teamId: 1 }]);
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: null,
warningSentAt: null,
});
vi.spyOn(CreditService.prototype, "getTeamWithAvailableCredits").mockResolvedValue({
teamId: 1,
availableCredits: 150,
creditType: CreditType.MONTHLY,
});
const result = await creditService.getUserOrTeamToCharge({
credits: 50,
userId: 1,
});
expect(result).toEqual({
teamId: 1,
availableCredits: 150,
creditType: CreditType.MONTHLY,
remainingCredits: 100,
});
});
});
describe("getMonthlyCredits", () => {
it("should return 0 if subscription is not active", async () => {
vi.mocked(TeamRepository.findTeamWithMembers).mockResolvedValue({
id: 1,
members: [{ accepted: true }],
} as any);
const mockTeamBillingService = {
getSubscriptionStatus: vi.fn().mockResolvedValue("trialing"),
};
vi.spyOn(InternalTeamBilling.prototype, "getSubscriptionStatus").mockImplementation(
mockTeamBillingService.getSubscriptionStatus
);
const result = await creditService.getMonthlyCredits(1);
expect(result).toBe(0);
});
it("should calculate credits based on active members and price", async () => {
vi.mocked(TeamRepository.findTeamWithMembers).mockResolvedValue({
id: 1,
members: [{ accepted: true }, { accepted: true }, { accepted: true }],
} as any);
const mockTeamBillingService = {
getSubscriptionStatus: vi.fn().mockResolvedValue("active"),
};
vi.spyOn(InternalTeamBilling.prototype, "getSubscriptionStatus").mockImplementation(
mockTeamBillingService.getSubscriptionStatus
);
const mockStripeBillingService = {
getPrice: vi.fn().mockResolvedValue({ unit_amount: 1000 }),
};
vi.spyOn(StripeBillingService.prototype, "getPrice").mockImplementation(
mockStripeBillingService.getPrice
);
const result = await creditService.getMonthlyCredits(1);
expect(result).toBe(1500); // (3 members * 1000 price) / 2
});
});
describe("getAllCreditsForTeam", () => {
it("should calculate total and remaining credits correctly", async () => {
vi.mocked(CreditsRepository.findCreditBalanceWithExpenseLogs).mockResolvedValue({
additionalCredits: 100,
expenseLogs: [
{ credits: 50, date: new Date() },
{ credits: 30, date: new Date() },
],
});
vi.spyOn(CreditService.prototype, "getMonthlyCredits").mockResolvedValue(500);
const result = await creditService.getAllCreditsForTeam(1);
console.log(`tesult ${JSON.stringify(result)}`);
expect(result).toEqual({
totalMonthlyCredits: 500,
totalRemainingMonthlyCredits: 420, // 500 - (50 + 30)
additionalCredits: 100,
});
});
it("should handle no expense logs", async () => {
vi.mocked(CreditsRepository.findCreditBalanceWithExpenseLogs).mockResolvedValue({
additionalCredits: 100,
expenseLogs: [],
});
vi.spyOn(CreditService.prototype, "getMonthlyCredits").mockResolvedValue(500);
const result = await creditService.getAllCreditsForTeam(1);
expect(result).toEqual({
totalMonthlyCredits: 500,
totalRemainingMonthlyCredits: 500,
additionalCredits: 100,
});
});
});
});
describe("getTeamToCharge", () => {
it("should return team with remaining credits when teamId is provided", async () => {
vi.spyOn(CreditService.prototype, "getAllCreditsForTeam").mockResolvedValue({
totalMonthlyCredits: 500,
totalRemainingMonthlyCredits: 100,
additionalCredits: 50,
describe("User credits", () => {
describe("hasAvailableCredits", () => {
it("should return true if user has not yet reached limit", async () => {
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 10,
limitReachedAt: null,
warningSentAt: null,
});
vi.spyOn(CreditService.prototype, "getTeamWithAvailableCredits").mockResolvedValue(null);
const hasAvailableCredits = await creditService.hasAvailableCredits({ userId: 1 });
expect(hasAvailableCredits).toBe(true);
});
const result = await creditService.getTeamToCharge({
credits: 50,
teamId: 1,
});
it("should return false if user limit reached this month", async () => {
vi.setSystemTime(new Date("2024-06-20T11:59:59Z"));
expect(result).toEqual({
teamId: 1,
remainingCredits: 100,
creditType: CreditType.MONTHLY,
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: dayjs().subtract(1, "week").toDate(),
warningSentAt: null,
});
vi.spyOn(CreditService.prototype, "getTeamWithAvailableCredits").mockResolvedValue(null);
const result = await creditService.hasAvailableCredits({ userId: 1 });
expect(result).toBe(false);
});
});
it("should use additional credits when monthly credits are out", async () => {
vi.spyOn(CreditService.prototype, "getAllCreditsForTeam").mockResolvedValue({
totalMonthlyCredits: 500,
totalRemainingMonthlyCredits: 0,
additionalCredits: 50,
});
describe("chargeCredits", () => {
it("should create expense log and send low balance warning email for user", async () => {
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 10,
limitReachedAt: null,
warningSentAt: null,
});
const result = await creditService.getTeamToCharge({
credits: 30,
teamId: 1,
});
vi.mocked(CreditsRepository.findCreditBalanceWithTeamOrUser).mockResolvedValue({
id: "1",
additionalCredits: 10,
limitReachedAt: null,
warningSentAt: null,
user: {
id: 1,
name: "user-name",
email: "[email protected]",
locale: "en",
},
team: null,
});
expect(result).toEqual({
teamId: 1,
remainingCredits: 20,
creditType: CreditType.ADDITIONAL,
});
});
vi.spyOn(CreditService.prototype, "getTeamWithAvailableCredits").mockResolvedValue(null);
it("should return team with available credits when userId is provided", async () => {
vi.mocked(MembershipRepository.findAllAcceptedMemberships).mockResolvedValue([
{
id: 1,
teamId: 1,
vi.spyOn(EmailManager, "sendCreditBalanceLowWarningEmails").mockResolvedValue();
vi.spyOn(CreditService.prototype, "getAllCredits").mockResolvedValue({
totalMonthlyCredits: 0,
totalRemainingMonthlyCredits: 0,
additionalCredits: 10,
});
await creditService.chargeCredits({
userId: 1,
role: "MEMBER",
accepted: true,
},
]);
credits: 5,
bookingUid: "booking-123",
smsSid: "sms-123",
});
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: null,
warningSentAt: null,
expect(CreditsRepository.createCreditExpenseLog).toHaveBeenCalledWith(
expect.objectContaining({
bookingUid: "booking-123",
creditBalanceId: "1",
creditType: CreditType.ADDITIONAL,
credits: 5,
smsSid: "sms-123",
})
);
expect(EmailManager.sendCreditBalanceLowWarningEmails).toHaveBeenCalled();
});
vi.spyOn(CreditService.prototype, "getAllCreditsForTeam").mockResolvedValue({
totalMonthlyCredits: 500,
totalRemainingMonthlyCredits: 100,
additionalCredits: 50,
});
it("should create expense log and send limit reached email for user", async () => {
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: null,
warningSentAt: null,
});
const result = await creditService.getTeamToCharge({
credits: 50,
userId: 1,
});
vi.mocked(CreditsRepository.findCreditBalanceWithTeamOrUser).mockResolvedValue({
id: "1",
additionalCredits: 0,
limitReachedAt: null,
warningSentAt: null,
team: {
id: 1,
name: "team-name",
members: [
{
user: {
id: 1,
name: "admin",
email: "[email protected]",
locale: "en",
},
},
],
},
user: null,
});
expect(result).toEqual({
teamId: 1,
availableCredits: 150,
creditType: CreditType.MONTHLY,
remainingCredits: 100,
vi.spyOn(EmailManager, "sendCreditBalanceLimitReachedEmails").mockResolvedValue();
vi.spyOn(CreditService.prototype, "getTeamWithAvailableCredits").mockResolvedValue(null);
vi.spyOn(CreditService.prototype, "getAllCredits").mockResolvedValue({
totalMonthlyCredits: 0,
totalRemainingMonthlyCredits: 0,
additionalCredits: 2,
});
await creditService.chargeCredits({
userId: 1,
credits: 5,
bookingUid: "booking-123",
smsSid: "sms-123",
});
expect(CreditsRepository.createCreditExpenseLog).toHaveBeenCalledWith(
expect.objectContaining({
bookingUid: "booking-123",
creditBalanceId: "1",
creditType: CreditType.ADDITIONAL,
credits: 5,
smsSid: "sms-123",
})
);
expect(EmailManager.sendCreditBalanceLimitReachedEmails).toHaveBeenCalled();
});
});
describe("getUserOrTeamToCharge", () => {
it("should return user with remaining credits when userId is provided", async () => {
vi.spyOn(CreditService.prototype, "getTeamWithAvailableCredits").mockResolvedValue(null);
vi.spyOn(CreditService.prototype, "getAllCredits").mockResolvedValue({
totalMonthlyCredits: 0,
totalRemainingMonthlyCredits: 0,
additionalCredits: 10,
});
const result = await creditService.getUserOrTeamToCharge({
credits: 2,
userId: 1,
});
expect(result).toEqual({
userId: 1,
remainingCredits: 8,
creditType: CreditType.ADDITIONAL,
});
});
});
});
+116 -54
View File
@@ -30,21 +30,23 @@ export class CreditService {
bookingUid?: string;
smsSid?: string;
}) {
let teamToCharge = credits === 0 && teamId ? teamId : null;
let teamIdToCharge = credits === 0 && teamId ? teamId : undefined;
let creditType: CreditType = CreditType.ADDITIONAL;
let remainingCredits;
if (credits !== 0) {
const result = await this.getTeamToCharge({
let userIdToCharge;
if (!teamIdToCharge) {
const result = await this.getUserOrTeamToCharge({
credits: credits ?? 1, // if we don't have exact credits, we check for at east 1 credit available
userId,
teamId,
});
teamToCharge = result?.teamId ?? null;
teamIdToCharge = result?.teamId;
userIdToCharge = result?.userId;
creditType = result?.creditType ?? creditType;
remainingCredits = result?.remainingCredits;
}
if (!teamToCharge) {
if (!teamIdToCharge && !userIdToCharge) {
log.error("No team or user found to charge. No credit expense log created");
return null;
}
@@ -52,19 +54,21 @@ export class CreditService {
await this.createExpenseLog({
bookingUid,
smsSid,
teamId: teamToCharge,
teamId: teamIdToCharge,
userId: userIdToCharge,
credits,
creditType,
});
if (credits) {
await this.handleLowCreditBalance({
teamId: teamToCharge,
remainingCredits,
teamId: teamIdToCharge,
userId: userIdToCharge,
remainingCredits: remainingCredits ?? 0,
});
}
return teamToCharge;
return { teamId: teamIdToCharge, userId: userIdToCharge };
}
async hasAvailableCredits({ userId, teamId }: { userId?: number | null; teamId?: number | null }) {
@@ -96,8 +100,13 @@ export class CreditService {
}
if (userId) {
const team = await this.getTeamWithAvailableCredits(userId);
return team.availableCredits > 0;
const teamWithAvailableCredits = await this.getTeamWithAvailableCredits(userId);
if (teamWithAvailableCredits && teamWithAvailableCredits?.availableCredits > 0) return true;
const userCredits = await this.getAllCredits({ userId });
return userCredits.additionalCredits > 0;
}
return false;
@@ -106,6 +115,10 @@ export class CreditService {
async getTeamWithAvailableCredits(userId: number) {
const memberships = await MembershipRepository.findAllAcceptedMemberships(userId);
if (memberships.length === 0) {
return null;
}
//check if user is member of team that has available credits
for (const membership of memberships) {
const creditBalance = await CreditsRepository.findCreditBalance({ teamId: membership.teamId });
@@ -146,7 +159,7 @@ export class CreditService {
/*
always returns a team, even if all teams are out of credits
*/
async getTeamToCharge({
async getUserOrTeamToCharge({
credits,
userId,
teamId,
@@ -168,7 +181,17 @@ export class CreditService {
if (userId) {
const team = await this.getTeamWithAvailableCredits(userId);
return { ...team, remainingCredits: team.availableCredits - credits };
if (team) {
return { ...team, remainingCredits: team.availableCredits - credits };
}
const userCredits = await this.getAllCredits({ userId });
return {
userId,
remainingCredits: userCredits.additionalCredits - credits,
creditType: CreditType.ADDITIONAL,
};
}
return null;
}
@@ -176,17 +199,19 @@ export class CreditService {
private async createExpenseLog(props: {
bookingUid?: string;
smsSid?: string;
teamId: number;
teamId?: number;
userId?: number;
credits: number | null;
creditType: CreditType;
}) {
const { credits, creditType, bookingUid, smsSid, teamId } = props;
let creditBalance: { id: string; additionalCredits: number } | null =
await CreditsRepository.findCreditBalance({ teamId });
const { credits, creditType, bookingUid, smsSid, teamId, userId } = props;
let creditBalance: { id: string; additionalCredits: number } | null | undefined =
await CreditsRepository.findCreditBalance({ teamId, userId });
if (!creditBalance) {
creditBalance = await CreditsRepository.createCreditBalance({
teamId,
userId,
});
}
@@ -225,80 +250,94 @@ export class CreditService {
*/
async handleLowCreditBalance({
teamId,
remainingCredits = 0,
userId,
remainingCredits,
}: {
teamId: number;
remainingCredits?: number;
teamId?: number | null;
userId?: number | null;
remainingCredits: number;
}) {
const { totalMonthlyCredits } = await this.getAllCreditsForTeam(teamId);
const warningLimit = totalMonthlyCredits * 0.2;
let warningLimit = 0;
if (teamId) {
const { totalMonthlyCredits } = await this.getAllCreditsForTeam(teamId);
warningLimit = totalMonthlyCredits * 0.2;
} else if (userId) {
const billingService = new StripeBillingService();
const teamMonthlyPrice = await billingService.getPrice(process.env.STRIPE_TEAM_MONTHLY_PRICE_ID || "");
const pricePerSeat = teamMonthlyPrice.unit_amount ?? 0;
warningLimit = (pricePerSeat / 2) * 0.2;
}
if (remainingCredits < warningLimit) {
const creditBalance = await CreditsRepository.findCreditBalance({ teamId });
const creditBalance = await CreditsRepository.findCreditBalanceWithTeamOrUser({ teamId, userId });
if (
creditBalance?.limitReachedAt &&
dayjs(creditBalance?.limitReachedAt).isAfter(dayjs().startOf("month"))
(!teamId || dayjs(creditBalance?.limitReachedAt).isAfter(dayjs().startOf("month")))
) {
return; // team has already reached limit this month
return; // user has limit already reached or team has already reached limit this month
}
const team = await TeamRepository.findTeamWithAdmins(teamId);
const teamWithAdmins = creditBalance?.team
? {
...creditBalance.team,
adminAndOwners: await Promise.all(
creditBalance.team.members.map(async (member) => ({
id: member.user.id,
name: member.user.name,
email: member.user.email,
t: await getTranslation(member.user.locale ?? "en", "common"),
}))
),
}
: undefined;
if (!team) {
log.error("Team not found to send warning email");
const user = creditBalance?.user
? {
...creditBalance.user,
t: await getTranslation(creditBalance.user.locale ?? "en", "common"),
}
: undefined;
if ((!teamWithAdmins || !teamWithAdmins.adminAndOwners?.length) && !user) {
log.error("Team or user not found to send warning email");
return;
}
if (remainingCredits <= 0) {
await sendCreditBalanceLimitReachedEmails({
team: {
id: teamId,
name: team.name,
adminAndOwners: await Promise.all(
team.members.map(async (member) => ({
name: member.user.name ?? "",
email: member.user.email,
t: await getTranslation(member.user.locale ?? "en", "common"),
}))
),
},
team: teamWithAdmins,
user,
});
await CreditsRepository.updateCreditBalance({
teamId,
userId,
data: {
limitReachedAt: new Date(),
warningSentAt: null,
},
});
await cancelScheduledMessagesAndScheduleEmails(teamId);
await cancelScheduledMessagesAndScheduleEmails({ teamId, userId });
return;
}
if (
creditBalance?.warningSentAt &&
dayjs(creditBalance?.warningSentAt).isAfter(dayjs().startOf("month"))
(!teamId || dayjs(creditBalance?.warningSentAt).isAfter(dayjs().startOf("month")))
) {
return; // team has already sent warning email this month
return; // user has already received a warning or team has already sent warning email this month
}
// team balance below 20% of total monthly credits
await sendCreditBalanceLowWarningEmails({
balance: remainingCredits,
team: {
id: teamId,
name: team.name,
adminAndOwners: await Promise.all(
team.members.map(async (member) => ({
name: member.user.name ?? "",
email: member.user.email,
t: await getTranslation(member.user.locale ?? "en", "common"),
}))
),
},
team: teamWithAdmins,
user,
});
await CreditsRepository.updateCreditBalance({
teamId,
userId,
data: {
warningSentAt: new Date(),
},
@@ -308,6 +347,7 @@ export class CreditService {
await CreditsRepository.updateCreditBalance({
teamId,
userId,
data: {
warningSentAt: null,
limitReachedAt: null,
@@ -347,6 +387,28 @@ export class CreditService {
return credits || null;
}
async getAllCredits({ userId, teamId }: { userId?: number | null; teamId?: number | null }) {
if (teamId) {
return this.getAllCreditsForTeam(teamId);
}
if (userId) {
const creditBalance = await CreditsRepository.findCreditBalance({ userId });
return {
totalMonthlyCredits: 0,
totalRemainingMonthlyCredits: 0,
additionalCredits: creditBalance?.additionalCredits ?? 0,
};
}
return {
totalMonthlyCredits: 0,
totalRemainingMonthlyCredits: 0,
additionalCredits: 0,
};
}
async getAllCreditsForTeam(teamId: number) {
const creditBalance = await CreditsRepository.findCreditBalanceWithExpenseLogs({ teamId });
@@ -171,8 +171,8 @@ export const AddActionDialog = (props: IAddActionDialog) => {
isOptionDisabled={(option: {
label: string;
value: WorkflowActions;
needsTeamsUpgrade: boolean;
}) => option.needsTeamsUpgrade}
needsCredits: boolean;
}) => option.needsCredits}
/>
);
}}
@@ -13,7 +13,13 @@ import { useHasActiveTeamPlan } from "@calcom/lib/hooks/useHasPaidPlan";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import { TimeUnit, WorkflowActions, WorkflowTemplates, WorkflowTriggerEvents } from "@calcom/prisma/enums";
import {
MembershipRole,
TimeUnit,
WorkflowActions,
WorkflowTemplates,
WorkflowTriggerEvents,
} from "@calcom/prisma/enums";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import classNames from "@calcom/ui/classNames";
@@ -45,6 +51,7 @@ import {
isWhatsappAction,
getTemplateBodyForAction,
shouldScheduleEmailReminder,
isSMSOrWhatsappAction,
} from "../lib/actionHelperFunctions";
import { DYNAMIC_TEXT_VARIABLES } from "../lib/constants";
import { getWorkflowTemplateOptions, getWorkflowTriggerOptions } from "../lib/getOptions";
@@ -86,6 +93,12 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
{ enabled: !!teamId }
);
const { data: userTeams } = trpc.viewer.teams.list.useQuery({}, { enabled: !teamId });
const creditsTeamId = userTeams?.find(
(team) => team.accepted && (team.role === MembershipRole.ADMIN || team.role === MembershipRole.OWNER)
)?.id;
const { hasActiveTeamPlan } = useHasActiveTeamPlan();
const { data: _verifiedEmails } = trpc.viewer.workflows.getVerifiedEmails.useQuery({ teamId });
@@ -355,7 +368,8 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
const selectedAction = {
label: actionString.charAt(0).toUpperCase() + actionString.slice(1),
value: step.action,
needsTeamsUpgrade: false,
needsCredits: isSMSOrWhatsappAction(step.action),
creditsTeamId: teamId ?? creditsTeamId,
};
const selectedTemplate = {
@@ -494,12 +508,8 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
defaultValue={selectedAction}
options={actionOptions?.map((option) => ({
...option,
creditsTeamId: teamId ?? creditsTeamId,
}))}
isOptionDisabled={(option: {
label: string;
value: WorkflowActions;
needsTeamsUpgrade: boolean;
}) => option.needsTeamsUpgrade}
/>
);
}}
@@ -12,14 +12,14 @@ import {
ATTENDEE_WORKFLOW_TEMPLATES,
} from "./constants";
export function getWorkflowActionOptions(t: TFunction, isTeamsPlan?: boolean, isOrgsPlan?: boolean) {
export function getWorkflowActionOptions(t: TFunction, isOrgsPlan?: boolean) {
return WORKFLOW_ACTIONS.map((action) => {
const actionString = t(`${action.toLowerCase()}_action`);
return {
label: actionString.charAt(0).toUpperCase() + actionString.slice(1),
value: action,
needsTeamsUpgrade: isSMSOrWhatsappAction(action) && !isTeamsPlan,
needsCredits: !isOrgsPlan && isSMSOrWhatsappAction(action),
};
});
}
@@ -53,7 +53,7 @@ describe("reminderScheduler", () => {
prismaMock.workflowReminder.updateMany.mockResolvedValue({ count: 1 });
await cancelScheduledMessagesAndScheduleEmails(1);
await cancelScheduledMessagesAndScheduleEmails({ teamId: 10 });
expect(twilioProvider.cancelSMS).toHaveBeenCalledWith("sms-123");
@@ -65,6 +65,55 @@ describe("reminderScheduler", () => {
})
);
const callArgs = prismaMock.workflowReminder.findMany.mock.calls[0][0];
expect(callArgs.where.workflowStep.workflow.OR).toEqual([{ userId: { in: [] } }, { teamId: 10 }]);
});
it("should cancel SMS messages and schedule emails for user", async () => {
prismaMock.membership.findMany.mockResolvedValue([]);
const mockScheduledMessages = [
{
id: 1,
referenceId: "sms-456",
workflowStep: {
action: "SMS_ATTENDEE",
},
scheduledDate: new Date(),
uuid: "uuid-456",
booking: {
attendees: [
{
email: "[email protected]",
locale: "en",
},
],
user: {
email: "[email protected]",
},
},
},
];
prismaMock.workflowReminder.findMany.mockResolvedValue(mockScheduledMessages);
prismaMock.workflowReminder.updateMany.mockResolvedValue({ count: 1 });
await cancelScheduledMessagesAndScheduleEmails({ userId: 11 });
const callArgs = prismaMock.workflowReminder.findMany.mock.calls[0][0];
expect(callArgs.where.workflowStep.workflow.OR).toEqual([{ userId: { in: [11] } }]);
expect(twilioProvider.cancelSMS).toHaveBeenCalledWith("sms-456");
expect(sendOrScheduleWorkflowEmails).toHaveBeenCalledWith(
expect.objectContaining({
to: ["[email protected]"],
replyTo: "[email protected]",
referenceUid: "uuid-456",
})
);
expect(prismaMock.workflowReminder.updateMany).toHaveBeenCalledWith({
where: {
id: {
@@ -256,27 +256,38 @@ const _sendCancelledReminders = async (args: SendCancelledRemindersArgs) => {
}
};
const _cancelScheduledMessagesAndScheduleEmails = async (teamId: number) => {
const teamMembers = await prisma.membership.findMany({
where: {
teamId,
accepted: true,
},
});
const _cancelScheduledMessagesAndScheduleEmails = async ({
teamId,
userId,
}: {
teamId?: number | null;
userId?: number | null;
}) => {
const { CreditService } = await import("@calcom/features/ee/billing/credit-service");
const creditService = new CreditService();
let userIdsWithNoCredits: number[] = userId ? [userId] : [];
const membersWithNoCredits = (
await Promise.all(
teamMembers.map(async (member) => {
const hasCredits = await creditService.hasAvailableCredits({ userId: member.userId });
return { member, hasCredits };
})
if (teamId) {
const teamMembers = await prisma.membership.findMany({
where: {
teamId,
accepted: true,
},
});
const creditService = new CreditService();
userIdsWithNoCredits = (
await Promise.all(
teamMembers.map(async (member) => {
const hasCredits = await creditService.hasAvailableCredits({ userId: member.userId });
return { userId: member.userId, hasCredits };
})
)
)
)
.filter(({ hasCredits }) => !hasCredits)
.map(({ member }) => member);
.filter(({ hasCredits }) => !hasCredits)
.map(({ userId }) => userId);
}
const scheduledMessages = await prisma.workflowReminder.findMany({
where: {
@@ -285,12 +296,10 @@ const _cancelScheduledMessagesAndScheduleEmails = async (teamId: number) => {
OR: [
{
userId: {
in: membersWithNoCredits.map((member) => member.userId),
in: userIdsWithNoCredits,
},
},
{
teamId,
},
...(teamId ? [{ teamId }] : []),
],
},
},