Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: add invoices page

Marc Seitze597960fdc19
diff --git a/components/billing/upgrade-plan-container.tsx b/components/billing/upgrade-plan-container.tsx
index 45c3c6dc..5e73763b 100644
--- a/components/billing/upgrade-plan-container.tsx
+++ b/components/billing/upgrade-plan-container.tsx
@@ -272,7 +272,7 @@ export default function UpgradePlanContainer() {
Change billing information
</DropdownMenuItem>
<DropdownMenuItem
- onClick={() => manageSubscription({ type: "invoices" })}
+ onClick={() => router.push("/settings/billing/invoices")}
>
<ReceiptTextIcon className="h-4 w-4" />
View invoices
diff --git a/components/layouts/breadcrumb.tsx b/components/layouts/breadcrumb.tsx
index 3b8b058f..199eac20 100644
--- a/components/layouts/breadcrumb.tsx
+++ b/components/layouts/breadcrumb.tsx
@@ -219,6 +219,8 @@ const SettingsBreadcrumb = () => {
return "Presets";
case "/settings/billing":
return "Billing";
+ case "/settings/billing/invoices":
+ return "Invoices";
case "/settings/tokens":
return "API Tokens";
case "/settings/webhooks":
@@ -234,6 +236,8 @@ const SettingsBreadcrumb = () => {
}
}, [path]);
+ const isInvoicesPage = path === "/settings/billing/invoices";
+
return (
<Breadcrumb>
<BreadcrumbList>
@@ -243,9 +247,23 @@ const SettingsBreadcrumb = () => {
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />
- <BreadcrumbItem>
- <BreadcrumbPage>{settingsTitle}</BreadcrumbPage>
- </BreadcrumbItem>
+ {isInvoicesPage ? (
+ <>
+ <BreadcrumbItem>
+ <BreadcrumbLink asChild>
+ <Link href="/settings/billing">Billing</Link>
+ </BreadcrumbLink>
+ </BreadcrumbItem>
+ <BreadcrumbSeparator />
+ <BreadcrumbItem>
+ <BreadcrumbPage>Invoices</BreadcrumbPage>
+ </BreadcrumbItem>
+ </>
+ ) : (
+ <BreadcrumbItem>
+ <BreadcrumbPage>{settingsTitle}</BreadcrumbPage>
+ </BreadcrumbItem>
+ )}
</BreadcrumbList>
</Breadcrumb>
);
diff --git a/lib/swr/use-invoices.ts b/lib/swr/use-invoices.ts
new file mode 100644
index 00000000..48d255bc
--- /dev/null
+++ b/lib/swr/use-invoices.ts
@@ -0,0 +1,39 @@
+import { useTeam } from "@/context/team-context";
+import useSWR from "swr";
+
+import { fetcher } from "@/lib/utils";
+
+export interface Invoice {
+ id: string;
+ number: string | null;
+ status: string | null;
+ amount: number;
+ currency: string;
+ created: number;
+ invoicePdf: string | null;
+ hostedInvoiceUrl: string | null;
+ periodStart: number;
+ periodEnd: number;
+ description: string;
+}
+
+export function useInvoices() {
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+
+ const { data, error, isLoading } = useSWR<{ invoices: Invoice[] }>(
+ teamId ? `/api/teams/${teamId}/billing/invoices` : null,
+ fetcher,
+ {
+ dedupingInterval: 60000,
+ revalidateOnFocus: false,
+ },
+ );
+
+ return {
+ invoices: data?.invoices || [],
+ loading: isLoading,
+ error,
+ };
+}
+
diff --git a/pages/api/teams/[teamId]/billing/invoices.ts b/pages/api/teams/[teamId]/billing/invoices.ts
new file mode 100644
index 00000000..0f4601a5
--- /dev/null
+++ b/pages/api/teams/[teamId]/billing/invoices.ts
@@ -0,0 +1,84 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { stripeInstance } from "@/ee/stripe";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+
+function isOldAccount(plan: string) {
+ return plan.includes("+old");
+}
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "GET") {
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const userId = (session.user as CustomUser).id;
+ const { teamId } = req.query as { teamId: string };
+
+ try {
+ // Get team with stripeId
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ select: {
+ stripeId: true,
+ plan: true,
+ },
+ });
+
+ if (!team) {
+ return res.status(404).json({ error: "Team not found" });
+ }
+
+ if (!team.stripeId) {
+ return res.status(200).json({ invoices: [] });
+ }
+
+ // Fetch invoices from Stripe
+ const stripe = stripeInstance(isOldAccount(team.plan));
+ const invoices = await stripe.invoices.list({
+ customer: team.stripeId,
+ limit: 100,
+ });
+
+ // Transform invoices to a simpler format
+ const transformedInvoices = invoices.data.map((invoice) => ({
+ id: invoice.id,
+ number: invoice.number,
+ status: invoice.status,
+ amount: invoice.amount_paid,
+ currency: invoice.currency,
+ created: invoice.created,
+ invoicePdf: invoice.invoice_pdf,
+ hostedInvoiceUrl: invoice.hosted_invoice_url,
+ periodStart: invoice.period_start,
+ periodEnd: invoice.period_end,
+ description: invoice.lines.data[0]?.description || "Subscription",
+ }));
+
+ return res.status(200).json({ invoices: transformedInvoices });
+ } catch (error) {
+ console.error("Error fetching invoices:", error);
+ return res.status(500).json({ error: "Failed to fetch invoices" });
+ }
+}
+
diff --git a/pages/settings/billing.tsx b/pages/settings/billing.tsx
index 41742f23..9e5a44a9 100644
--- a/pages/settings/billing.tsx
+++ b/pages/settings/billing.tsx
@@ -13,6 +13,7 @@ import UpgradePlanContainer from "@/components/billing/upgrade-plan-container";
import { GTMComponent } from "@/components/gtm-component";
import AppLayout from "@/components/layouts/app";
import { SettingsHeader } from "@/components/settings/settings-header";
+import { TabMenu } from "@/components/tab-menu";
export default function Billing() {
const router = useRouter();
@@ -55,6 +56,23 @@ export default function Billing() {
<main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
<SettingsHeader />
+ <TabMenu
+ navigation={[
+ {
+ label: "Subscription",
+ href: "/settings/billing",
+ value: "subscription",
+ currentValue: "subscription",
+ },
+ {
+ label: "Invoices",
+ href: "/settings/billing/invoices",
+ value: "invoices",
+ currentValue: "subscription",
+ },
+ ]}
+ />
+
<UpgradePlanContainer />
</main>
</AppLayout>
diff --git a/pages/settings/billing/invoices.tsx b/pages/settings/billing/invoices.tsx
new file mode 100644
index 00000000..38d3a96e
--- /dev/null
+++ b/pages/settings/billing/invoices.tsx
@@ -0,0 +1,174 @@
+import { useRouter } from "next/router";
+
+import { Download, FileText, Loader2 } from "lucide-react";
+
+import { useInvoices } from "@/lib/swr/use-invoices";
+
+import AppLayout from "@/components/layouts/app";
+import { SettingsHeader } from "@/components/settings/settings-header";
+import { TabMenu } from "@/components/tab-menu";
+import { Button } from "@/components/ui/button";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+
+export default function Invoices() {
+ const router = useRouter();
+ const { invoices, loading, error } = useInvoices();
+
+ const formatCurrency = (amount: number, currency: string) => {
+ return new Intl.NumberFormat("en-US", {
+ style: "currency",
+ currency: currency.toUpperCase(),
+ }).format(amount / 100);
+ };
+
+ const formatDate = (timestamp: number) => {
+ return new Date(timestamp * 1000).toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ });
+ };
+
+ const handleDownload = (invoicePdf: string | null) => {
+ if (invoicePdf) {
+ window.open(invoicePdf, "_blank");
+ }
+ };
+
+ const handleViewInvoice = (hostedInvoiceUrl: string | null) => {
+ if (hostedInvoiceUrl) {
+ window.open(hostedInvoiceUrl, "_blank");
+ }
+ };
+
+ return (
+ <AppLayout>
+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
+ <SettingsHeader />
+
+ <TabMenu
+ navigation={[
+ {
+ label: "Subscription",
+ href: "/settings/billing",
+ value: "subscription",
+ currentValue: "invoices",
+ },
+ {
+ label: "Invoices",
+ href: "/settings/billing/invoices",
+ value: "invoices",
+ currentValue: "invoices",
+ },
+ ]}
+ />
+
+ <div className="space-y-4">
+ <div className="space-y-1">
+ <h3 className="text-2xl font-semibold tracking-tight text-foreground">
+ Invoices
+ </h3>
+ <p className="text-sm text-muted-foreground">
+ A history of all your invoices
+ </p>
+ </div>
+
+ <div className="rounded-lg border bg-white">
+ {loading ? (
+ <div className="flex items-center justify-center py-12">
+ <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
+ </div>
+ ) : error ? (
+ <div className="flex flex-col items-center justify-center gap-2 py-12">
+ <p className="text-sm text-muted-foreground">
+ Failed to load invoices
+ </p>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => router.reload()}
+ >
+ Retry
+ </Button>
+ </div>
+ ) : invoices.length === 0 ? (
+ <div className="flex flex-col items-center justify-center gap-4 py-12">
+ <div className="rounded-full border border-white bg-gradient-to-t from-gray-100 p-3">
+ <FileText className="size-6" />
+ </div>
+ <div className="text-center">
+ <p className="text-sm font-medium">No invoices yet</p>
+ <p className="text-sm text-muted-foreground">
+ Your invoices will appear here once you have a subscription
+ </p>
+ </div>
+ </div>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Description</TableHead>
+ <TableHead>Date</TableHead>
+ <TableHead>Total</TableHead>
+ <TableHead className="text-right">Actions</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {invoices.map((invoice) => (
+ <TableRow key={invoice.id}>
+ <TableCell>
+ <div className="flex flex-col">
+ <span className="font-medium">
+ Papermark Subscription
+ </span>
+ {invoice.number && (
+ <span className="text-xs text-muted-foreground">
+ {invoice.number}
+ </span>
+ )}
+ </div>
+ </TableCell>
+ <TableCell>{formatDate(invoice.created)}</TableCell>
+ <TableCell>
+ {formatCurrency(invoice.amount, invoice.currency)}
+ </TableCell>
+ <TableCell className="text-right">
+ <div className="flex justify-end gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ handleViewInvoice(invoice.hostedInvoiceUrl)
+ }
+ disabled={!invoice.hostedInvoiceUrl}
+ >
+ View invoice
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => handleDownload(invoice.invoicePdf)}
+ disabled={!invoice.invoicePdf}
+ >
+ <Download className="h-4 w-4" />
+ </Button>
+ </div>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </div>
+ </div>
+ </main>
+ </AppLayout>
+ );
+}