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

@@ -24,15 +24,28 @@ export const buyCreditsHandler = async ({ ctx, input }: BuyCreditsOptions) => {
const { quantity, teamId } = input;
const adminMembership = await MembershipRepository.getAdminMembership(ctx.user.id, teamId);
if (teamId) {
const adminMembership = await MembershipRepository.getAdminOrOwnerMembership(ctx.user.id, teamId);
if (!adminMembership) {
throw new TRPCError({
code: "UNAUTHORIZED",
});
if (!adminMembership) {
throw new TRPCError({
code: "UNAUTHORIZED",
});
}
} else {
// if user id is part of a team, user can't buy credits for themselves
const membership = await MembershipRepository.findAllAcceptedMemberships(ctx.user.id);
if (membership.length > 0) {
throw new TRPCError({
code: "UNAUTHORIZED",
});
}
}
const redirect_uri = `${WEBAPP_URL}/settings/teams/${teamId}/billing`;
const redirect_uri = teamId
? `${WEBAPP_URL}/settings/teams/${teamId}/billing`
: `${WEBAPP_URL}/settings/billing`;
const billingService = new StripeBillingService();
@@ -41,7 +54,10 @@ export const buyCreditsHandler = async ({ ctx, input }: BuyCreditsOptions) => {
quantity,
successUrl: redirect_uri,
cancelUrl: redirect_uri,
metadata: { teamId: teamId.toString() },
metadata: {
...(teamId && { teamId: teamId.toString() }),
userId: ctx.user.id.toString(),
},
});
return { sessionUrl: checkoutUrl };
@@ -2,7 +2,7 @@ import { z } from "zod";
export const ZBuyCreditsSchema = z.object({
quantity: z.number(),
teamId: z.number(),
teamId: z.number().optional(),
});
export type TBuyCreditsSchema = z.infer<typeof ZBuyCreditsSchema>;
@@ -15,17 +15,26 @@ type GetAllCreditsOptions = {
export const getAllCreditsHandler = async ({ ctx, input }: GetAllCreditsOptions) => {
const { teamId } = input;
const adminMembership = await MembershipRepository.getAdminMembership(ctx.user.id, teamId);
if (teamId) {
const adminMembership = await MembershipRepository.getAdminOrOwnerMembership(ctx.user.id, teamId);
if (!adminMembership) {
throw new TRPCError({
code: "UNAUTHORIZED",
});
if (!adminMembership) {
throw new TRPCError({
code: "UNAUTHORIZED",
});
}
} else {
//if user is part of team, don't return any credits if teamId is not given
const membership = await MembershipRepository.findAllAcceptedMemberships(ctx.user.id);
if (membership.length > 0) {
return null;
}
}
const { CreditService } = await import("@calcom/features/ee/billing/credit-service");
const creditService = new CreditService();
const teamCredits = await creditService.getAllCreditsForTeam(teamId);
return { teamCredits };
const credits = await creditService.getAllCredits({ userId: ctx.user.id, teamId });
return { credits };
};
@@ -1,7 +1,7 @@
import { z } from "zod";
export const ZGetAllCreditsSchema = z.object({
teamId: z.number(),
teamId: z.number().optional(),
});
export type TGetAllCreditsSchema = z.infer<typeof ZGetAllCreditsSchema>;
@@ -46,8 +46,13 @@ export const activateEventTypeHandler = async ({ ctx, input }: ActivateEventType
},
],
},
include: {
children: true,
select: {
teamId: true,
children: {
select: {
id: true,
},
},
},
});
@@ -67,8 +72,26 @@ export const activateEventTypeHandler = async ({ ctx, input }: ActivateEventType
},
],
},
include: {
steps: true,
select: {
steps: {
select: {
id: true,
action: true,
sendTo: true,
numberRequired: true,
template: true,
sender: true,
emailSubject: true,
reminderBody: true,
verifiedAt: true,
},
},
trigger: true,
time: true,
timeUnit: true,
isActiveOnAll: true,
teamId: true,
userId: true,
team: {
select: {
isOrganization: true,
@@ -206,8 +229,23 @@ export const activateEventTypeHandler = async ({ ctx, input }: ActivateEventType
gte: new Date(),
},
},
include: {
attendees: true,
select: {
metadata: true,
userId: true,
smsReminderNumber: true,
userPrimaryEmail: true,
startTime: true,
endTime: true,
title: true,
uid: true,
attendees: {
select: {
name: true,
email: true,
timeZone: true,
locale: true,
},
},
eventType: {
select: {
schedulingType: true,
@@ -230,7 +268,15 @@ export const activateEventTypeHandler = async ({ ctx, input }: ActivateEventType
hideOrganizerEmail: true,
},
},
user: true,
user: {
select: {
name: true,
email: true,
timeZone: true,
locale: true,
timeFormat: true,
},
},
},
});
@@ -1,11 +1,7 @@
import { getWorkflowActionOptions } from "@calcom/features/ee/workflows/lib/getOptions";
import { IS_SELF_HOSTED } from "@calcom/lib/constants";
import hasKeyInMetadata from "@calcom/lib/hasKeyInMetadata";
import { getTranslation } from "@calcom/lib/server/i18n";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import hasActiveTeamPlanHandler from "../teams/hasActiveTeamPlan.handler";
type GetWorkflowActionOptionsOptions = {
ctx: {
user: NonNullable<TrpcSessionUser> & {
@@ -17,20 +13,7 @@ type GetWorkflowActionOptionsOptions = {
export const getWorkflowActionOptionsHandler = async ({ ctx }: GetWorkflowActionOptionsOptions) => {
const { user } = ctx;
const isCurrentUsernamePremium =
user && hasKeyInMetadata(user, "isPremium") ? !!user.metadata.isPremium : false;
let teamsPlan = { isActive: false, isTrial: false };
if (!isCurrentUsernamePremium) {
teamsPlan = await hasActiveTeamPlanHandler({ ctx });
}
const hasOrgsPlan = !!user.profile?.organizationId;
const t = await getTranslation(ctx.user.locale, "common");
return getWorkflowActionOptions(
t,
IS_SELF_HOSTED || isCurrentUsernamePremium || teamsPlan.isActive,
IS_SELF_HOSTED || hasOrgsPlan
);
return getWorkflowActionOptions(t, !!user.profile?.organizationId);
};
@@ -1,7 +1,4 @@
import {
isEmailAction,
isSMSOrWhatsappAction,
} from "@calcom/features/ee/workflows/lib/actionHelperFunctions";
import { isEmailAction } from "@calcom/features/ee/workflows/lib/actionHelperFunctions";
import tasker from "@calcom/features/tasker";
import { IS_SELF_HOSTED, SCANNING_WORKFLOW_STEPS } from "@calcom/lib/constants";
import hasKeyInMetadata from "@calcom/lib/hasKeyInMetadata";
@@ -337,12 +334,10 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
} else if (isStepEdited(oldStep, { ...newStep, verifiedAt: oldStep.verifiedAt })) {
// check if step that require team plan already existed before
if (!hasPaidPlan) {
const isChangingToSMSOrWhatsapp =
!isSMSOrWhatsappAction(oldStep.action) && isSMSOrWhatsappAction(newStep.action);
const isChangingToCustomTemplate =
newStep.template === WorkflowTemplates.CUSTOM && oldStep.template !== WorkflowTemplates.CUSTOM;
if (isChangingToSMSOrWhatsapp || isChangingToCustomTemplate) {
if (isChangingToCustomTemplate) {
throw new TRPCError({ code: "UNAUTHORIZED", message: "Not available on free plan" });
}
@@ -425,10 +420,9 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
.filter((step) => step.id <= 0)
.map(async (newStep) => {
if (!hasPaidPlan) {
if (isSMSOrWhatsappAction(newStep.action) || newStep.template === WorkflowTemplates.CUSTOM) {
if (newStep.template === WorkflowTemplates.CUSTOM) {
throw new TRPCError({ code: "UNAUTHORIZED", message: "Not available on free plan" });
}
// on free plans always use predefined templates
const { emailBody, emailSubject } = await getEmailTemplateText(newStep.template, {
locale: ctx.user.locale,