feat: download credit expense log button (#21771)

* add smsSegments to creditExpenseLog

* add download button

* download only data from selected month

* improvements

* improve design

* use repository function

* add tests for credit repository

* fix type error

* fix unit test

* fix type error

* fix unit test

* code clean up

* fix skeleton loader

* remove empty mt

* code clean up

* move csv headers out of function

---------

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: Benny Joo <[email protected]>
This commit is contained in:
authored and GitHub committed 2025-06-23 03:57:32 -04:00
1 parent 7a2060fe08
commit 4edb39616d
16 files changed
+411 -25

No files matched your search

@@ -46,13 +46,13 @@ async function postHandler(req: NextRequest) {
if (!log.smsSid) return;
try {
const price = await twilio.getPriceForSMS(log.smsSid);
const { price, numSegments } = await twilio.getMessageInfo(log.smsSid);
const credits = price ? creditService.calculateCreditsFromPrice(price) : null;
if (!credits) return;
const updatedLog = await prisma.creditExpenseLog.update({
where: { id: log.id },
data: { credits },
data: { credits, smsSegments: numSegments },
select: {
creditBalance: {
select: {
@@ -3,22 +3,60 @@
import { ProgressBar } from "@tremor/react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, useMemo } from "react";
import { useForm } from "react-hook-form";
import dayjs from "@calcom/dayjs";
import ServerTrans from "@calcom/lib/components/ServerTrans";
import { IS_SMS_CREDITS_ENABLED } from "@calcom/lib/constants";
import { downloadAsCsv } from "@calcom/lib/csvUtils";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { Select } from "@calcom/ui/components/form";
import { TextField, Label, InputError } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/toast";
import { BillingCreditsSkeleton } from "./BillingCreditsSkeleton";
type MonthOption = {
value: string;
label: string;
startDate: string;
endDate: string;
};
// returns the last 12 months starting from May 2025 (when credits were introduced)
const getMonthOptions = (): MonthOption[] => {
const options: MonthOption[] = [];
const minDate = dayjs.utc("2025-05-01");
let date = dayjs.utc();
let count = 0;
while ((date.isAfter(minDate) || date.isSame(minDate, "month")) && count < 12) {
const startDate = date.startOf("month");
const endDate = date.endOf("month");
options.push({
value: date.format("MMMM YYYY"),
label: date.format("MMMM YYYY"),
startDate: startDate.toISOString(),
endDate: endDate.toISOString(),
});
date = date.subtract(1, "month");
count++;
}
return options;
};
export default function BillingCredits() {
const { t } = useLocale();
const router = useRouter();
const monthOptions = useMemo(() => getMonthOptions(), []);
const [selectedMonth, setSelectedMonth] = useState<MonthOption>(monthOptions[0]);
const [isDownloading, setIsDownloading] = useState(false);
const utils = trpc.useUtils();
const {
register,
@@ -28,8 +66,8 @@ export default function BillingCredits() {
} = useForm<{ quantity: number }>({ defaultValues: { quantity: 50 } });
const params = useParamsWithFallback();
const teamId = params.id ? Number(params.id) : undefined;
const { data: creditsData, isLoading } = trpc.viewer.credits.getAllCredits.useQuery({ teamId });
const buyCreditsMutation = trpc.viewer.credits.buyCredits.useMutation({
@@ -43,6 +81,27 @@ export default function BillingCredits() {
},
});
const handleDownload = async () => {
setIsDownloading(true);
try {
const result = await utils.viewer.credits.downloadExpenseLog.fetch({
teamId,
startDate: selectedMonth.startDate,
endDate: selectedMonth.endDate,
});
if (result?.csvData) {
const filename = `credit-expense-log-${selectedMonth.value.toLowerCase().replace(" ", "-")}.csv`;
downloadAsCsv(result.csvData, filename);
} else {
showToast(t("error_downloading_expense_log"), "error");
}
} catch (error) {
showToast(t("error_downloading_expense_log"), "error");
} finally {
setIsDownloading(false);
}
};
if (!IS_SMS_CREDITS_ENABLED) {
return null;
}
@@ -112,8 +171,8 @@ export default function BillingCredits() {
<hr className="border-subtle mb-3 mt-3" />
</div>
<form onSubmit={handleSubmit(onSubmit)} className="flex">
<div className="mr-auto">
<div className="mb-2 font-semibold">{t("buy_additional_credits")}</div>
<div className="-mb-1 mr-auto">
<Label>{t("buy_additional_credits")}</Label>
<div className="flex flex-col">
<TextField
required
@@ -132,12 +191,32 @@ export default function BillingCredits() {
{errors.quantity && <InputError message={errors.quantity.message ?? t("invalid_input")} />}
</div>
</div>
<div className="mb-1 mt-auto">
<div className="mt-auto">
<Button color="primary" target="_blank" EndIcon="external-link" type="submit">
{t("buy_credits")}
</Button>
</div>
</form>
<div className="-mx-6 mb-6 mt-6">
<hr className="border-subtle mb-3 mt-3" />
</div>
<div className="flex">
<div className="mr-auto ">
<Label className="mb-4">{t("download_expense_log")}</Label>
<div className="mt-2 flex flex-col">
<Select
options={monthOptions}
value={selectedMonth}
onChange={(option) => option && setSelectedMonth(option)}
/>
</div>
</div>
<div className="mt-auto">
<Button onClick={handleDownload} loading={isDownloading} StartIcon="file-down">
{t("download")}
</Button>
</div>
</div>
</div>
</div>
</div>
@@ -45,7 +45,7 @@ export function BillingCreditsSkeleton() {
<div className="flex">
<div className="mr-auto">
<div>
<SkeletonText className="mb-2 mt-1 h-5 w-[268px]" /> {/* Buy credits label */}
<SkeletonText className="mb-2 h-4 w-[268px]" /> {/* Buy credits label */}
</div>
<div>
<SkeletonText className="mt-2 h-8 w-[240px] rounded-md" /> {/* Input field */}
@@ -56,6 +56,24 @@ export function BillingCreditsSkeleton() {
<SkeletonButton className="h-9 w-[120px] rounded-md" /> {/* Buy button */}
</div>
</div>
<div className="-mx-6 mb-6 mt-6">
<hr className="border-subtle mb-3 mt-3" />
</div>
{/* Download expense log */}
<div className="flex">
<div className="mr-auto mt-1">
<div>
<SkeletonText className="mb-2 h-4 w-[156px]" /> {/* Label */}
</div>
<div>
<SkeletonText className="mt-2 h-8 w-[156px] rounded-md" /> {/* Select */}
</div>
</div>
<div className="mt-auto ">
<SkeletonButton className="h-9 w-[109px] rounded-md" /> {/* Download button */}
</div>
</div>
</div>
</div>
</SkeletonContainer>
+2 -1
View File
@@ -137,7 +137,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
return res.status(200).send(`SMS are free for organizations. Credits set to 0`);
}
const price = await twilio.getPriceForSMS(smsSid);
const { price, numSegments } = await twilio.getMessageInfo(smsSid);
const credits = price ? creditService.calculateCreditsFromPrice(price) : null;
@@ -147,6 +147,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
userId: parsedUserId,
smsSid,
bookingUid: parsedBookingUid,
smsSegments: numSegments ?? undefined,
});
if (chargedUserOrTeamId) {
@@ -3256,6 +3256,8 @@
"meeting_start_time": "Meeting Start Time",
"members_affected_by_disabling_delegation_credential": "Affected members",
"no_members_affected_by_disabling_delegation_credential": "No members affected by disabling delegation credential",
"download_expense_log": "Download Expense Log",
"error_downloading_expense_log": "Error downloading expense log",
"offer_to_reschedule_last_booking": "Offer to reschedule last active booking to chosen time slot",
"booker_limit_exceeded_error": "Booker maximum active booking limit exceeded",
"booker_limit_exceeded_error_reschedule": "You already have a booking for this event on {{date}}. Would you like to reschedule to the new selected time?",
+10 -2
View File
@@ -58,12 +58,14 @@ export class CreditService {
credits,
bookingUid,
smsSid,
smsSegments,
}: {
userId?: number;
teamId?: number;
credits: number | null;
bookingUid?: string;
smsSid?: string;
smsSegments?: number;
}) {
return await prisma
.$transaction(async (tx) => {
@@ -96,6 +98,7 @@ export class CreditService {
userId: userIdToCharge,
credits,
creditType,
smsSegments,
tx,
});
@@ -289,9 +292,10 @@ export class CreditService {
userId?: number;
credits: number | null;
creditType: CreditType;
smsSegments?: number;
tx: PrismaTransaction;
}) {
const { credits, creditType, bookingUid, smsSid, teamId, userId, tx } = props;
const { credits, creditType, bookingUid, smsSid, teamId, userId, smsSegments, tx } = props;
let creditBalance: { id: string; additionalCredits: number } | null | undefined =
await CreditsRepository.findCreditBalance({ teamId, userId }, tx);
@@ -331,6 +335,7 @@ export class CreditService {
date: new Date(),
bookingUid,
smsSid,
smsSegments,
},
tx
);
@@ -592,7 +597,10 @@ export class CreditService {
}
protected async _getAllCreditsForTeam({ teamId, tx }: { teamId: number; tx: PrismaTransaction }) {
const creditBalance = await CreditsRepository.findCreditBalanceWithExpenseLogs({ teamId }, tx);
const creditBalance = await CreditsRepository.findCreditBalanceWithExpenseLogs(
{ teamId, creditType: CreditType.MONTHLY },
tx
);
const totalMonthlyCredits = await this.getMonthlyCredits(teamId);
const totalMonthlyCreditsUsed =
@@ -284,11 +284,14 @@ export async function getCountryCodeForNumber(phoneNumber: string) {
return countryCode;
}
export async function getPriceForSMS(smsSid: string) {
export async function getMessageInfo(smsSid: string) {
const twilio = createTwilioClient();
const message = await twilio.messages(smsSid).fetch();
if (message.price == null || message.price === "null") return null;
return Math.abs(parseFloat(message.price));
const price = message.price ? Math.abs(parseFloat(message.price)) : null;
const numSegments = message.numSegments ? parseInt(message.numSegments) : null;
return { price, numSegments };
}
export async function validateWebhookRequest({
@@ -11,6 +11,7 @@ vi.mock("@calcom/lib/constants", async () => {
vi.mock("../reminders/providers/twilioProvider", () => ({
validateWebhookRequest: vi.fn().mockResolvedValue(true),
getCountryCodeForNumber: vi.fn().mockResolvedValue("US"),
getMessageInfo: vi.fn().mockResolvedValue({ price: null, numSegments: null }),
}));
const mockChargeCredits = vi.fn().mockResolvedValue({ teamId: 1 });
@@ -120,12 +121,6 @@ describe("Twilio Webhook Handler", () => {
default: vi.fn().mockResolvedValue(null),
}));
vi.mock("../reminders/providers/twilioProvider", () => ({
validateWebhookRequest: vi.fn().mockResolvedValue(true),
getCountryCodeForNumber: vi.fn().mockResolvedValue("US"),
getPriceForSMS: vi.fn().mockResolvedValue(null),
}));
const mockRequest = {
method: "POST",
headers: {
@@ -0,0 +1,176 @@
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 "./credits";
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,
},
},
},
});
});
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,
},
},
},
});
});
});
});
+24 -5
View File
@@ -1,7 +1,7 @@
import dayjs from "@calcom/dayjs";
import prisma, { type PrismaTransaction } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { CreditType } from "@calcom/prisma/enums";
import type { CreditType } from "@calcom/prisma/enums";
export class CreditsRepository {
static async findCreditBalance(
@@ -95,26 +95,45 @@ export class CreditsRepository {
}
}
static async findCreditBalanceWithExpenseLogs({ teamId }: { teamId: number }, tx?: PrismaTransaction) {
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: dayjs().startOf("month").toDate(),
lte: new Date(),
gte: startDate,
lte: endDate,
},
creditType: CreditType.MONTHLY,
...(creditType ? { creditType } : {}),
},
orderBy: {
date: "desc",
},
select: {
date: true,
credits: true,
creditType: true,
bookingUid: true,
smsSid: true,
smsSegments: true,
},
},
},
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "CreditExpenseLog" ADD COLUMN "smsSegments" INTEGER;
+1
View File
@@ -580,6 +580,7 @@ model CreditExpenseLog {
creditType CreditType
date DateTime
smsSid String?
smsSegments Int?
}
enum CreditType {
@@ -2,11 +2,13 @@ import authedProcedure from "@calcom/trpc/server/procedures/authedProcedure";
import { router } from "../../../trpc";
import { ZBuyCreditsSchema } from "./buyCredits.schema";
import { ZDownloadExpenseLogSchema } from "./downloadExpenseLog.schema";
import { ZGetAllCreditsSchema } from "./getAllCredits.schema";
type CreditsCache = {
getAllCredits?: typeof import("./getAllCredits.handler").getAllCreditsHandler;
buyCredits?: typeof import("./buyCredits.handler").buyCreditsHandler;
downloadExpenseLog?: typeof import("./downloadExpenseLog.handler").downloadExpenseLogHandler;
};
const UNSTABLE_HANDLER_CACHE: CreditsCache = {};
@@ -46,4 +48,21 @@ export const creditsRouter = router({
input,
});
}),
downloadExpenseLog: authedProcedure.input(ZDownloadExpenseLogSchema).query(async ({ input, ctx }) => {
if (!UNSTABLE_HANDLER_CACHE.downloadExpenseLog) {
UNSTABLE_HANDLER_CACHE.downloadExpenseLog = await import("./downloadExpenseLog.handler").then(
(mod) => mod.downloadExpenseLogHandler
);
}
// Unreachable code but required for type safety
if (!UNSTABLE_HANDLER_CACHE.downloadExpenseLog) {
throw new Error("Failed to load handler");
}
return UNSTABLE_HANDLER_CACHE.downloadExpenseLog({
ctx,
input,
});
}),
});
@@ -0,0 +1,52 @@
import { CreditsRepository } from "@calcom/lib/server/repository/credits";
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
import { TRPCError } from "@trpc/server";
import type { TDownloadExpenseLogSchema } from "./downloadExpenseLog.schema";
type DownloadExpenseLogOptions = {
ctx: {
user: { id: number };
};
input: TDownloadExpenseLogSchema;
};
const headers = ["Date", "Credits", "Type", "Booking UID", "Number of Segments"];
export const downloadExpenseLogHandler = async ({ ctx, input }: DownloadExpenseLogOptions) => {
const { teamId, startDate, endDate } = input;
if (teamId) {
const adminMembership = await MembershipRepository.getAdminOrOwnerMembership(ctx.user.id, teamId);
if (!adminMembership) {
throw new TRPCError({
code: "UNAUTHORIZED",
});
}
}
const creditBalance = await CreditsRepository.findCreditBalanceWithExpenseLogs({
teamId,
userId: ctx.user.id,
startDate: new Date(startDate),
endDate: new Date(endDate),
});
if (!creditBalance) {
return { csvData: headers.join(",") };
}
const rows = creditBalance.expenseLogs.map((log) => [
log.date.toISOString(),
log.credits?.toString() ?? "",
log.creditType,
log.bookingUid ?? "",
log.smsSegments?.toString() ?? "-",
]);
const csvData = [headers, ...rows].map((row) => row.join(",")).join("\n");
return { csvData };
};
@@ -0,0 +1,9 @@
import { z } from "zod";
export const ZDownloadExpenseLogSchema = z.object({
teamId: z.number().optional(),
startDate: z.string(),
endDate: z.string(),
});
export type TDownloadExpenseLogSchema = z.infer<typeof ZDownloadExpenseLogSchema>;
@@ -11,7 +11,9 @@ export const CreditsBadge = function CreditsBadge({ teamId }: { teamId?: number
return (
<Tooltip content={t("requires_credits_tooltip")}>
<Link href={teamId ? `/settings/teams/${teamId}/billing` : "/settings/billing"}>
<Badge variant="gray">{t("requires_credits")}</Badge>
<Badge variant="gray" className="whitespace-nowrap">
{t("requires_credits")}
</Badge>
</Link>
</Tooltip>
);