feat: show invoices on team/org (#27120)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
29ec2b9cb6
commit
4f0a1d0f9b
9 files changed
+544
-4
No files matched your search
@@ -1,5 +1,4 @@
|
||||
import type Stripe from "stripe";
|
||||
|
||||
import type { SubscriptionStatus } from "../../repository/billing/IBillingRepository";
|
||||
|
||||
export interface IBillingProviderService {
|
||||
@@ -123,4 +122,41 @@ export interface IBillingProviderService {
|
||||
current_period_end: number;
|
||||
trial_end: number | null;
|
||||
} | null>;
|
||||
|
||||
// Invoice listing
|
||||
listInvoices(args: {
|
||||
customerId: string;
|
||||
subscriptionId?: string;
|
||||
limit: number;
|
||||
startingAfter?: string;
|
||||
createdGte?: number;
|
||||
createdLte?: number;
|
||||
}): Promise<{
|
||||
invoices: Array<{
|
||||
id: string;
|
||||
number: string | null;
|
||||
created: number;
|
||||
amountDue: number;
|
||||
amountPaid: number;
|
||||
currency: string;
|
||||
status: string | null;
|
||||
hostedInvoiceUrl: string | null;
|
||||
invoicePdf: string | null;
|
||||
lineItems: Array<{
|
||||
id: string;
|
||||
description: string | null;
|
||||
amount: number;
|
||||
quantity: number | null;
|
||||
}>;
|
||||
description: string | null;
|
||||
paymentMethod: {
|
||||
type: string;
|
||||
card?: {
|
||||
last4: string;
|
||||
brand: string;
|
||||
};
|
||||
} | null;
|
||||
}>;
|
||||
hasMore: boolean;
|
||||
}>;
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import logger from "@calcom/lib/logger";
|
||||
import type Stripe from "stripe";
|
||||
|
||||
import { SubscriptionStatus } from "../../repository/billing/IBillingRepository";
|
||||
import type { IBillingProviderService } from "./IBillingProviderService";
|
||||
|
||||
@@ -404,4 +403,67 @@ export class StripeBillingService implements IBillingProviderService {
|
||||
trial_end: subscription.trial_end,
|
||||
};
|
||||
}
|
||||
|
||||
async listInvoices(args: {
|
||||
customerId: string;
|
||||
subscriptionId?: string;
|
||||
limit: number;
|
||||
startingAfter?: string;
|
||||
createdGte?: number;
|
||||
createdLte?: number;
|
||||
}) {
|
||||
const { customerId, subscriptionId, limit, startingAfter, createdGte, createdLte } = args;
|
||||
|
||||
const invoicesResponse = await this.stripe.invoices.list({
|
||||
customer: customerId,
|
||||
subscription: subscriptionId,
|
||||
limit,
|
||||
starting_after: startingAfter,
|
||||
expand: ["data.default_payment_method"],
|
||||
...(createdGte || createdLte
|
||||
? {
|
||||
created: {
|
||||
...(createdGte ? { gte: createdGte } : {}),
|
||||
...(createdLte ? { lte: createdLte } : {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
|
||||
return {
|
||||
invoices: invoicesResponse.data.map((invoice) => ({
|
||||
id: invoice.id,
|
||||
number: invoice.number,
|
||||
created: invoice.created,
|
||||
amountDue: invoice.amount_due,
|
||||
amountPaid: invoice.amount_paid,
|
||||
currency: invoice.currency,
|
||||
status: invoice.status,
|
||||
hostedInvoiceUrl: invoice.hosted_invoice_url ?? null,
|
||||
invoicePdf: invoice.invoice_pdf ?? null,
|
||||
lineItems: invoice.lines.data.map((line) => ({
|
||||
id: line.id,
|
||||
description: line.description,
|
||||
amount: line.amount,
|
||||
quantity: line.quantity,
|
||||
})),
|
||||
description: invoice.description,
|
||||
paymentMethod: this.extractPaymentMethod(
|
||||
invoice.default_payment_method as Stripe.PaymentMethod | null
|
||||
),
|
||||
})),
|
||||
hasMore: invoicesResponse.has_more,
|
||||
};
|
||||
}
|
||||
|
||||
private extractPaymentMethod(pm: Stripe.PaymentMethod | string | null): {
|
||||
type: string;
|
||||
card?: { last4: string; brand: string };
|
||||
} | null {
|
||||
if (!pm || typeof pm === "string") return null;
|
||||
return {
|
||||
type: pm.type,
|
||||
card: pm.card ? { last4: pm.card.last4, brand: pm.card.brand } : undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { ZAcceptOrLeaveInputSchema } from "./acceptOrLeave.schema";
|
||||
@@ -22,6 +21,7 @@ import { ZInviteMemberInputSchema } from "./inviteMember/inviteMember.schema";
|
||||
import { ZInviteMemberByTokenSchemaInputSchema } from "./inviteMemberByToken.schema";
|
||||
import { ZLegacyListMembersInputSchema } from "./legacyListMembers.schema";
|
||||
import { ZGetListSchema } from "./list.schema";
|
||||
import { ZListInvoicesInputSchema } from "./listInvoices.schema";
|
||||
import { ZListMembersInputSchema } from "./listMembers.schema";
|
||||
import { ZGetManagedEventUsersToReassignInputSchema } from "./managedEvents/getManagedEventUsersToReassign.schema";
|
||||
import { ZManagedEventManualReassignInputSchema } from "./managedEvents/managedEventManualReassign.schema";
|
||||
@@ -229,4 +229,8 @@ export const viewerTeamsRouter = router({
|
||||
const { default: handler } = await import("./getSubscriptionStatus.handler");
|
||||
return handler(opts);
|
||||
}),
|
||||
listInvoices: authedProcedure.input(ZListInvoicesInputSchema).query(async (opts) => {
|
||||
const { default: handler } = await import("./listInvoices.handler");
|
||||
return handler(opts);
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
import { getBillingProviderService } from "@calcom/ee/billing/di/containers/Billing";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
|
||||
import { IS_TEAM_BILLING_ENABLED } from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import type { TListInvoicesInputSchema } from "./listInvoices.schema";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["listInvoices"] });
|
||||
|
||||
type ListInvoicesOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: TListInvoicesInputSchema;
|
||||
};
|
||||
|
||||
export interface InvoiceLineItem {
|
||||
id: string;
|
||||
description: string | null;
|
||||
amount: number;
|
||||
quantity: number | null;
|
||||
}
|
||||
|
||||
export interface InvoicePaymentMethod {
|
||||
type: string;
|
||||
card?: {
|
||||
last4: string;
|
||||
brand: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Invoice {
|
||||
id: string;
|
||||
number: string | null;
|
||||
created: number;
|
||||
amountDue: number;
|
||||
amountPaid: number;
|
||||
currency: string;
|
||||
status: string | null;
|
||||
hostedInvoiceUrl: string | null;
|
||||
invoicePdf: string | null;
|
||||
lineItems: InvoiceLineItem[];
|
||||
description: string | null;
|
||||
paymentMethod: InvoicePaymentMethod | null;
|
||||
}
|
||||
|
||||
export const listInvoicesHandler = async ({ ctx, input }: ListInvoicesOptions) => {
|
||||
if (!IS_TEAM_BILLING_ENABLED) {
|
||||
return { invoices: [] as Invoice[], hasMore: false, nextCursor: null };
|
||||
}
|
||||
|
||||
const { teamId, limit, cursor, startDate, endDate } = input;
|
||||
|
||||
// Get team
|
||||
const teamRepository = new TeamRepository(prisma);
|
||||
const team = await teamRepository.findByIdIncludePlatformBilling({ id: teamId });
|
||||
|
||||
if (!team) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Team not found" });
|
||||
}
|
||||
|
||||
// Permission check
|
||||
const permissionService = new PermissionCheckService();
|
||||
const hasPermission = await permissionService.checkPermission({
|
||||
userId: ctx.user.id,
|
||||
teamId,
|
||||
permission: team.isOrganization ? "organization.manageBilling" : "team.manageBilling",
|
||||
fallbackRoles: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
});
|
||||
|
||||
if (!hasPermission) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You don't have permission to view invoices",
|
||||
});
|
||||
}
|
||||
|
||||
// Get subscription ID from team metadata or platformBilling
|
||||
let subscriptionId: string | null = null;
|
||||
|
||||
if (team.isPlatform) {
|
||||
subscriptionId = team.platformBilling?.subscriptionId || null;
|
||||
} else {
|
||||
const metadata = teamMetadataSchema.safeParse(team.metadata);
|
||||
subscriptionId = metadata.success ? metadata.data?.subscriptionId || null : null;
|
||||
}
|
||||
|
||||
if (!subscriptionId) {
|
||||
return { invoices: [] as Invoice[], hasMore: false, nextCursor: null };
|
||||
}
|
||||
|
||||
try {
|
||||
const billingService = getBillingProviderService();
|
||||
|
||||
// Get customer ID from subscription
|
||||
const subscription = await billingService.getSubscription(subscriptionId);
|
||||
const customerId = subscription?.customer;
|
||||
|
||||
if (!customerId) {
|
||||
return { invoices: [] as Invoice[], hasMore: false, nextCursor: null };
|
||||
}
|
||||
|
||||
// Fetch invoices using the billing service, filtered by subscription and date range
|
||||
const invoicesResponse = await billingService.listInvoices({
|
||||
customerId,
|
||||
subscriptionId,
|
||||
limit: limit + 1, // Fetch one extra to check if there are more
|
||||
startingAfter: cursor || undefined,
|
||||
createdGte: startDate ? Math.floor(startDate.getTime() / 1000) : undefined,
|
||||
createdLte: endDate ? Math.floor(endDate.getTime() / 1000) : undefined,
|
||||
});
|
||||
|
||||
const hasMore = invoicesResponse.invoices.length > limit;
|
||||
const invoices = invoicesResponse.invoices.slice(0, limit);
|
||||
const nextCursor = hasMore && invoices.length > 0 ? invoices[invoices.length - 1]?.id : null;
|
||||
|
||||
return {
|
||||
invoices: invoices as Invoice[],
|
||||
hasMore,
|
||||
nextCursor,
|
||||
};
|
||||
} catch (error) {
|
||||
log.error("Failed to fetch invoices", { teamId, error });
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to fetch invoices",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default listInvoicesHandler;
|
||||
@@ -0,0 +1,11 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZListInvoicesInputSchema = z.object({
|
||||
teamId: z.number(),
|
||||
limit: z.number().min(1).max(100).default(10),
|
||||
cursor: z.string().optional().nullable(),
|
||||
startDate: z.date().optional(),
|
||||
endDate: z.date().optional(),
|
||||
});
|
||||
|
||||
export type TListInvoicesInputSchema = z.infer<typeof ZListInvoicesInputSchema>;
|
||||
Reference in new issue
Block a user