Skip to content

Open source alternative to Semrush and Ahrefs

Let customers email and download invoices from the billing page (EVE-326) (#916)

Carter Smith346dcd8a0012
diff --git a/src/client/features/billing/BillingFeatureBreakdown.tsx b/src/client/features/billing/BillingFeatureBreakdown.tsx
index b84847ca..d0a7c8bd 100644
--- a/src/client/features/billing/BillingFeatureBreakdown.tsx
+++ b/src/client/features/billing/BillingFeatureBreakdown.tsx
@@ -7,7 +7,7 @@ import {
import type { BillingUsageEvent } from "@/serverFunctions/billing";
import { QueryState } from "@/client/components/QueryState";
import { Skeleton } from "@/client/components/ui/skeleton";
-import { BillingUsageCard } from "@/client/features/billing/BillingUsageCard";
+import { BillingUsageSection } from "@/client/features/billing/BillingUsageSection";
import { useBillingUsageEvents } from "@/client/features/billing/useBillingUsageEvents";
type BillingUsageEventProperties = {
@@ -116,7 +116,7 @@ export function BillingFeatureBreakdown() {
const eventsQuery = useBillingUsageEvents();
return (
- <BillingUsageCard title="Usage by feature">
+ <BillingUsageSection title="Usage by feature">
<QueryState
query={eventsQuery}
errorFallback="Failed to load usage"
@@ -130,7 +130,7 @@ export function BillingFeatureBreakdown() {
>
{(events) => <BreakdownRows events={events} />}
</QueryState>
- </BillingUsageCard>
+ </BillingUsageSection>
);
}
diff --git a/src/client/features/billing/BillingInvoices.tsx b/src/client/features/billing/BillingInvoices.tsx
new file mode 100644
index 00000000..09b85904
--- /dev/null
+++ b/src/client/features/billing/BillingInvoices.tsx
@@ -0,0 +1,207 @@
+import { queryOptions, useMutation, useQuery } from "@tanstack/react-query";
+import { Download } from "lucide-react";
+import { QueryError } from "@/client/components/QueryState";
+import { buttonVariants } from "@/client/components/ui/button";
+import {
+ Field,
+ FieldDescription,
+ FieldLabel,
+} from "@/client/components/ui/field";
+import { Skeleton } from "@/client/components/ui/skeleton";
+import { Switch } from "@/client/components/ui/switch";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/client/components/ui/table";
+import { billingAccountQueryOptions } from "@/client/features/billing/billingAccountQuery";
+import { getStandardErrorMessage } from "@/client/lib/error-messages";
+import { queryClient } from "@/client/tanstack-db";
+import {
+ listBillingInvoices,
+ setInvoiceEmails,
+} from "@/serverFunctions/billing";
+
+const dateFormat: Intl.DateTimeFormatOptions = {
+ day: "numeric",
+ month: "short",
+ year: "numeric",
+};
+
+function formatDate(epochMs: number) {
+ return new Date(epochMs).toLocaleDateString(undefined, dateFormat);
+}
+
+function formatAmount(total: number, currency: string) {
+ return new Intl.NumberFormat(undefined, {
+ style: "currency",
+ currency: currency.toUpperCase(),
+ }).format(total);
+}
+
+const invoicesQueryOptions = queryOptions({
+ queryKey: ["billing", "invoices"],
+ queryFn: () => listBillingInvoices(),
+});
+
+/** Invoice emails and the newest invoices, the billing Invoices tab.
+ * Owner-only at the call site, as the server enforces: invoices show the
+ * billing address. */
+export function BillingInvoices({
+ invoiceEmailsEnabled,
+}: {
+ invoiceEmailsEnabled: boolean;
+}) {
+ return (
+ <div className="space-y-4">
+ <InvoiceEmailsToggle invoiceEmailsEnabled={invoiceEmailsEnabled} />
+ <InvoiceTable />
+ </div>
+ );
+}
+
+function InvoiceEmailsToggle({
+ invoiceEmailsEnabled,
+}: {
+ invoiceEmailsEnabled: boolean;
+}) {
+ const mutation = useMutation({
+ mutationFn: (enabled: boolean) => setInvoiceEmails({ data: { enabled } }),
+ // The error shows inline under the switch.
+ meta: { errorToast: false },
+ onSuccess: (_, enabled) => {
+ queryClient.setQueryData(billingAccountQueryOptions().queryKey, (prev) =>
+ prev ? { ...prev, invoiceEmailsEnabled: enabled } : prev,
+ );
+ },
+ });
+
+ const checked = mutation.isPending
+ ? mutation.variables
+ : invoiceEmailsEnabled;
+
+ return (
+ <Field>
+ <div className="flex items-center gap-2">
+ <Switch
+ id="billing-invoice-emails"
+ checked={checked}
+ disabled={mutation.isPending}
+ onCheckedChange={(enabled) => mutation.mutate(enabled)}
+ />
+ <FieldLabel htmlFor="billing-invoice-emails">
+ Email me a receipt for each invoice
+ </FieldLabel>
+ </div>
+ <FieldDescription>
+ Stripe sends the receipt to the billing email on your account after each
+ payment.
+ </FieldDescription>
+ {mutation.isError ? (
+ <p role="alert" className="text-sm text-destructive">
+ {getStandardErrorMessage(
+ mutation.error,
+ "We couldn't save this setting. Please try again.",
+ )}
+ </p>
+ ) : null}
+ </Field>
+ );
+}
+
+function InvoiceTable() {
+ const invoicesQuery = useQuery(invoicesQueryOptions);
+
+ if (invoicesQuery.isPending) {
+ return (
+ <div aria-busy className="space-y-2">
+ <Skeleton className="h-8 w-full" />
+ <Skeleton className="h-8 w-full" />
+ <Skeleton className="h-8 w-full" />
+ </div>
+ );
+ }
+
+ if (invoicesQuery.isError) {
+ return (
+ <QueryError
+ error={invoicesQuery.error}
+ fallback="We couldn't load your invoices. Please try again."
+ onRetry={() => void invoicesQuery.refetch()}
+ isRetrying={invoicesQuery.isFetching}
+ />
+ );
+ }
+
+ const { invoices, hasMore } = invoicesQuery.data;
+
+ if (invoices.length === 0) {
+ return <p className="text-sm text-muted-foreground">No invoices yet.</p>;
+ }
+
+ return (
+ <div className="space-y-2">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Invoice</TableHead>
+ <TableHead>Date</TableHead>
+ <TableHead>Billing period</TableHead>
+ <TableHead>Amount</TableHead>
+ <TableHead>Status</TableHead>
+ <TableHead>
+ <span className="sr-only">Download</span>
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {invoices.map((invoice) => (
+ <TableRow key={invoice.id}>
+ <TableCell className="font-medium">
+ {invoice.number ?? "—"}
+ </TableCell>
+ <TableCell className="whitespace-nowrap">
+ {formatDate(invoice.createdAt)}
+ </TableCell>
+ <TableCell className="whitespace-nowrap">
+ {invoice.periodStart !== null && invoice.periodEnd !== null
+ ? `${formatDate(invoice.periodStart)} – ${formatDate(invoice.periodEnd)}`
+ : "—"}
+ </TableCell>
+ <TableCell className="tabular-nums">
+ {formatAmount(invoice.total, invoice.currency)}
+ </TableCell>
+ <TableCell className="capitalize">{invoice.status}</TableCell>
+ <TableCell className="text-right">
+ {invoice.pdfUrl ? (
+ <a
+ href={invoice.pdfUrl}
+ target="_blank"
+ rel="noreferrer"
+ className={buttonVariants({
+ variant: "outline",
+ size: "sm",
+ })}
+ aria-label={`Download ${invoice.number ?? "invoice"} PDF`}
+ >
+ <Download />
+ PDF
+ </a>
+ ) : null}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ {hasMore ? (
+ <p className="text-xs text-muted-foreground">
+ Showing your newest invoices. Find older invoices under Manage
+ subscription.
+ </p>
+ ) : null}
+ </div>
+ );
+}
diff --git a/src/client/features/billing/BillingTabs.tsx b/src/client/features/billing/BillingTabs.tsx
new file mode 100644
index 00000000..3fa21f78
--- /dev/null
+++ b/src/client/features/billing/BillingTabs.tsx
@@ -0,0 +1,59 @@
+import { DataTableTabs } from "@/client/components/table/DataTableToolbar";
+import { TableCard } from "@/client/components/ui/table";
+import { TabsTrigger } from "@/client/components/ui/tabs";
+import { BillingFeatureBreakdown } from "@/client/features/billing/BillingFeatureBreakdown";
+import { BillingInvoices } from "@/client/features/billing/BillingInvoices";
+import { BillingUsageChart } from "@/client/features/billing/BillingUsageChart";
+
+export const BILLING_TABS = [
+ { value: "usage", label: "Usage" },
+ { value: "invoices", label: "Invoices" },
+] as const;
+type BillingTab = (typeof BILLING_TABS)[number]["value"];
+
+/**
+ * Usage and, for owners, invoices in one card with a tab row. Members see
+ * usage alone: invoices follow the billing permission.
+ */
+export function BillingTabs({
+ tab,
+ onTabChange,
+ invoiceEmailsEnabled,
+}: {
+ tab: BillingTab;
+ onTabChange: (tab: BillingTab) => void;
+ /** Null hides the Invoices tab. */
+ invoiceEmailsEnabled: boolean | null;
+}) {
+ const showInvoices = invoiceEmailsEnabled !== null && tab === "invoices";
+
+ return (
+ <TableCard>
+ {invoiceEmailsEnabled !== null ? (
+ <DataTableTabs
+ value={tab}
+ onValueChange={(value) => {
+ const next = BILLING_TABS.find((item) => item.value === value);
+ if (next) onTabChange(next.value);
+ }}
+ >
+ {BILLING_TABS.map((item) => (
+ <TabsTrigger key={item.value} value={item.value}>
+ {item.label}
+ </TabsTrigger>
+ ))}
+ </DataTableTabs>
+ ) : null}
+ <div className="space-y-6 p-4">
+ {showInvoices ? (
+ <BillingInvoices invoiceEmailsEnabled={invoiceEmailsEnabled} />
+ ) : (
+ <>
+ <BillingUsageChart />
+ <BillingFeatureBreakdown />
+ </>
+ )}
+ </div>
+ </TableCard>
+ );
+}
diff --git a/src/client/features/billing/BillingUsageCard.tsx b/src/client/features/billing/BillingUsageCard.tsx
deleted file mode 100644
index dd4fdaf3..00000000
--- a/src/client/features/billing/BillingUsageCard.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import type { ReactNode } from "react";
-import {
- Card,
- CardAction,
- CardContent,
- CardHeader,
- CardTitle,
-} from "@/client/components/ui/card";
-
-/** A billing usage card: a title with "Last 30 days" on the right. */
-export function BillingUsageCard({
- title,
- children,
-}: {
- title: string;
- children: ReactNode;
-}) {
- return (
- <Card>
- <CardHeader>
- <CardTitle>{title}</CardTitle>
- <CardAction className="self-center text-xs text-muted-foreground">
- Last 30 days
- </CardAction>
- </CardHeader>
- <CardContent>{children}</CardContent>
- </Card>
- );
-}
diff --git a/src/client/features/billing/BillingUsageChart.tsx b/src/client/features/billing/BillingUsageChart.tsx
index 9982d1a4..7e84a898 100644
--- a/src/client/features/billing/BillingUsageChart.tsx
+++ b/src/client/features/billing/BillingUsageChart.tsx
@@ -15,7 +15,7 @@ import {
ChartTooltipContent,
type ChartConfig,
} from "@/client/components/ui/chart";
-import { BillingUsageCard } from "@/client/features/billing/BillingUsageCard";
+import { BillingUsageSection } from "@/client/features/billing/BillingUsageSection";
import {
BILLING_USAGE_DAYS,
useBillingUsageEvents,
@@ -29,7 +29,7 @@ export function BillingUsageChart() {
const eventsQuery = useBillingUsageEvents();
return (
- <BillingUsageCard title="Usage">
+ <BillingUsageSection title="Usage">
<QueryState
query={eventsQuery}
errorFallback="Failed to load usage"
@@ -37,7 +37,7 @@ export function BillingUsageChart() {
>
{(events) => <UsageChart events={events} />}
</QueryState>
- </BillingUsageCard>
+ </BillingUsageSection>
);
}
diff --git a/src/client/features/billing/BillingUsageSection.tsx b/src/client/features/billing/BillingUsageSection.tsx
new file mode 100644
index 00000000..cb254a26
--- /dev/null
+++ b/src/client/features/billing/BillingUsageSection.tsx
@@ -0,0 +1,21 @@
+import type { ReactNode } from "react";
+
+/** A section of the billing Usage tab: a title with "Last 30 days" on the
+ * right. */
+export function BillingUsageSection({
+ title,
+ children,
+}: {
+ title: string;
+ children: ReactNode;
+}) {
+ return (
+ <section className="space-y-3">
+ <div className="flex items-baseline justify-between gap-4">
+ <h2 className="font-medium">{title}</h2>
+ <span className="text-xs text-muted-foreground">Last 30 days</span>
+ </div>
+ {children}
+ </section>
+ );
+}
diff --git a/src/routes/_app/billing.tsx b/src/routes/_app/billing.tsx
index 8b3190ad..d6ce43f2 100644
--- a/src/routes/_app/billing.tsx
+++ b/src/routes/_app/billing.tsx
@@ -1,4 +1,5 @@
-import { createFileRoute, notFound } from "@tanstack/react-router";
+import { createFileRoute, notFound, useNavigate } from "@tanstack/react-router";
+import { z } from "zod";
import { useState } from "react";
import { ErrorState } from "@/client/components/ErrorState";
import { PageHeader } from "@/client/components/PageHeader";
@@ -27,8 +28,10 @@ import {
openUpgradeCheckout,
prefetchUpgradeCheckout,
} from "@/client/features/billing/checkout";
-import { BillingUsageChart } from "@/client/features/billing/BillingUsageChart";
-import { BillingFeatureBreakdown } from "@/client/features/billing/BillingFeatureBreakdown";
+import {
+ BILLING_TABS,
+ BillingTabs,
+} from "@/client/features/billing/BillingTabs";
import { parseTopUpAmount } from "@/client/features/billing/HostedBillingContentUtils";
import { billingUsageEventsQueryOptions } from "@/client/features/billing/useBillingUsageEvents";
import { useCreditBalance } from "@/client/features/billing/useCreditBalance";
@@ -44,6 +47,12 @@ import {
import { BILLING_ROUTE } from "@/shared/billing";
export const Route = createFileRoute("/_app/billing")({
+ validateSearch: z.object({
+ tab: z
+ .enum(BILLING_TABS.map((item) => item.value))
+ .optional()
+ .catch(undefined),
+ }),
// The loader fills the module-scoped query client, so keep it out of server
// requests: one worker isolate must not cache another account's billing.
ssr: false,
@@ -65,6 +74,8 @@ export const Route = createFileRoute("/_app/billing")({
type BillingAction = "plan" | "topUp";
function BillingPage() {
+ const { tab } = Route.useSearch();
+ const navigate = useNavigate();
const [topUpAmount, setTopUpAmount] = useState("20");
const [pendingAction, setPendingAction] = useState<BillingAction | null>(
null,
@@ -347,9 +358,20 @@ function BillingPage() {
</>
)}
- <BillingUsageChart />
-
- <BillingFeatureBreakdown />
+ <BillingTabs
+ tab={tab ?? "usage"}
+ onTabChange={(next) =>
+ void navigate({
+ to: BILLING_ROUTE,
+ // Like other tabbed pages, Back leaves the page.
+ replace: true,
+ search: { tab: next === "usage" ? undefined : next },
+ })
+ }
+ invoiceEmailsEnabled={
+ canManageBilling && account ? account.invoiceEmailsEnabled : null
+ }
+ />
<p className="text-xs text-muted-foreground">
Billing is powered by Stripe.
diff --git a/src/server/billing/autumn.ts b/src/server/billing/autumn.ts
index 70241f76..f5eb2391 100644
--- a/src/server/billing/autumn.ts
+++ b/src/server/billing/autumn.ts
@@ -53,6 +53,12 @@ export const autumn = {
loadAutumn().then((client) => client.customers.getOrCreate(...args)),
get: (...args: Parameters<Autumn["customers"]["get"]>) =>
loadAutumn().then((client) => client.customers.get(...args)),
+ update: (...args: Parameters<Autumn["customers"]["update"]>) =>
+ loadAutumn().then((client) => client.customers.update(...args)),
+ },
+ invoices: {
+ list: (...args: Parameters<Autumn["invoices"]["list"]>) =>
+ loadAutumn().then((client) => client.invoices.list(...args)),
},
balances: {
// Confirms or releases a hold taken by `check({ lock })`. Not in the
diff --git a/src/server/billing/billing-account.test.ts b/src/server/billing/billing-account.test.ts
index 2792c638..326297b4 100644
--- a/src/server/billing/billing-account.test.ts
+++ b/src/server/billing/billing-account.test.ts
@@ -37,6 +37,7 @@ describe("getOrganizationBillingAccount", () => {
[AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID]: { remaining: 2500 },
},
subscriptions: [{ planId: "friends_and_family_2", pastDue: true }],
+ sendEmailReceipts: true,
});
await expect(getOrganizationBillingAccount(context)).resolves.toEqual({
@@ -48,6 +49,7 @@ describe("getOrganizationBillingAccount", () => {
hasManagedAccess: true,
isPastDue: true,
monthlyRefillsAt: 1_790_000_000_000,
+ invoiceEmailsEnabled: true,
});
// The organization is the billing identity.
expect(getOrCreateMock).toHaveBeenCalledWith({
diff --git a/src/server/billing/billing-account.ts b/src/server/billing/billing-account.ts
index 798435fb..8f08cc28 100644
--- a/src/server/billing/billing-account.ts
+++ b/src/server/billing/billing-account.ts
@@ -26,6 +26,8 @@ type BillingAccount = {
* one-time credits and for a paid plan canceled at period end, which ends
* then instead of refilling. */
monthlyRefillsAt: number | null;
+ /** Stripe emails a receipt for each paid invoice. */
+ invoiceEmailsEnabled: boolean;
};
export async function getOrganizationBillingAccount(
@@ -70,5 +72,6 @@ export async function getOrganizationBillingAccount(
monthlyRefillsAt: paidSubscription?.canceledAt
? null
: (monthly?.nextResetAt ?? null),
+ invoiceEmailsEnabled: customer.sendEmailReceipts,
};
}
diff --git a/src/server/billing/invoices.test.ts b/src/server/billing/invoices.test.ts
new file mode 100644
index 00000000..5704bd9a
--- /dev/null
+++ b/src/server/billing/invoices.test.ts
@@ -0,0 +1,104 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { listMock, updateMock, fetchMock } = vi.hoisted(() => ({
+ listMock: vi.fn(),
+ updateMock: vi.fn(),
+ fetchMock: vi.fn(),
+}));
+
+vi.mock("@/server/billing/autumn", () => ({
+ autumn: {
+ customers: { update: updateMock },
+ invoices: { list: listMock },
+ },
+}));
+
+vi.mock("@/server/lib/runtime-env", () => ({
+ getRequiredEnvValue: vi.fn(async () => "am_sk_test"),
+}));
+
+import {
+ listOrganizationInvoices,
+ setOrganizationInvoiceEmails,
+} from "./invoices";
+
+const owner = { organizationId: "org_1", role: "owner" };
+const admin = { organizationId: "org_1", role: "admin" };
+
+beforeEach(() => {
+ vi.stubGlobal("fetch", fetchMock);
+ listMock.mockResolvedValue({
+ nextCursor: null,
+ list: [
+ {
+ stripeId: "in_topup",
+ createdAt: 1_000,
+ items: [{ periodStart: 1_000, periodEnd: 1_000 }],
+ },
+ {
+ stripeId: "in_renewal",
+ createdAt: 2_000,
+ items: [
+ { periodStart: 300, periodEnd: 900 },
+ { periodStart: 100, periodEnd: 600 },
+ ],
+ },
+ ],
+ });
+ fetchMock.mockImplementation(async (url: string) =>
+ Response.json({
+ number: `NUM-${url.split("/").at(-2)}`,
+ invoice_pdf: `https://pay.stripe.com/${url.split("/").at(-2)}/pdf`,
+ }),
+ );
+});
+
+describe("listOrganizationInvoices", () => {
+ it("lists the organization's invoices, newest first, with the Stripe number and PDF", async () => {
+ await expect(listOrganizationInvoices(owner)).resolves.toEqual({
+ hasMore: false,
+ invoices: [
+ expect.objectContaining({
+ id: "in_renewal",
+ number: "NUM-in_renewal",
+ pdfUrl: "https://pay.stripe.com/in_renewal/pdf",
+ periodStart: 100,
+ periodEnd: 900,
+ }),
+ expect.objectContaining({
+ id: "in_topup",
+ periodStart: null,
+ periodEnd: null,
+ }),
+ ],
+ });
+ expect(listMock).toHaveBeenCalledWith(
+ expect.objectContaining({ customerId: "org_1" }),
+ );
+ });
+
+ it("refuses a member without the billing permission", async () => {
+ await expect(listOrganizationInvoices(admin)).rejects.toMatchObject({
+ code: "FORBIDDEN",
+ });
+ expect(listMock).not.toHaveBeenCalled();
+ });
+});
+
+describe("setOrganizationInvoiceEmails", () => {
+ it("stores the setting on the organization's Autumn customer", async () => {
+ await setOrganizationInvoiceEmails(owner, false);
+
+ expect(updateMock).toHaveBeenCalledWith({
+ customerId: "org_1",
+ sendEmailReceipts: false,
+ });
+ });
+
+ it("refuses a member without the billing permission", async () => {
+ await expect(
+ setOrganizationInvoiceEmails(admin, true),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ expect(updateMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/billing/invoices.ts b/src/server/billing/invoices.ts
new file mode 100644
index 00000000..b61d1228
--- /dev/null
+++ b/src/server/billing/invoices.ts
@@ -0,0 +1,118 @@
+import { sort } from "remeda";
+import { z } from "zod";
+import type { EnsuredUserContext } from "@/middleware/ensure-user/types";
+import { requireOrgPermission } from "@/server/auth/org-gate";
+import { autumn } from "@/server/billing/autumn";
+import { AppError } from "@/server/lib/errors";
+import { getRequiredEnvValue } from "@/server/lib/runtime-env";
+import { safeHttpUrl } from "@/shared/safe-url";
+
+type BillingCaller = Pick<EnsuredUserContext, "organizationId" | "role">;
+
+/** The newest invoices the billing page lists. Older ones stay in the Stripe
+ * billing portal. Each row costs one Stripe lookup, so keep this small. */
+const INVOICE_PAGE_SIZE = 12;
+
+type BillingInvoice = {
+ id: string;
+ /** Stripe's invoice number, as printed on the PDF. */
+ number: string | null;
+ createdAt: number;
+ /** The billing period of the invoice's lines, in epoch ms. Null on one-off
+ * purchases such as top-ups. */
+ periodStart: number | null;
+ periodEnd: number | null;
+ /** Major units (dollars), as Autumn reports them. */
+ total: number;
+ currency: string;
+ status: string;
+ pdfUrl: string | null;
+};
+
+// The Stripe invoice, as Autumn's `GET /v1/invoices/{id}/stripe` returns it.
+// Only the fields the billing page shows.
+const stripeInvoiceSchema = z.object({
+ number: z.string().nullable(),
+ invoice_pdf: z.string().nullable(),
+});
+
+export async function listOrganizationInvoices(caller: BillingCaller) {
+ // Invoices show the billing address, so they follow the billing permission.
+ requireOrgPermission(caller, { billing: ["manage"] });
+ const { list, nextCursor } = await autumn.invoices.list({
+ customerId: caller.organizationId,
+ // Drafts have no number or PDF yet.
+ status: ["open", "paid", "uncollectible", "void"],
+ limit: INVOICE_PAGE_SIZE,
+ });
+
+ const rows = await Promise.all(
+ list.map(async (invoice) => ({
+ invoice,
+ stripeInvoice: await getStripeInvoice(invoice.stripeId),
+ })),
+ );
+ const invoices = rows.map(({ invoice, stripeInvoice }): BillingInvoice => {
+ // A one-off line, such as a top-up, starts and ends at the purchase.
+ const periods = (invoice.items ?? []).flatMap((item) =>
+ item.periodStart !== null &&
+ item.periodEnd !== null &&
+ item.periodEnd > item.periodStart
+ ? [{ start: item.periodStart, end: item.periodEnd }]
+ : [],
+ );
+ return {
+ id: invoice.stripeId,
+ number: stripeInvoice.number,
+ createdAt: invoice.createdAt,
+ periodStart: periods.length
+ ? Math.min(...periods.map((period) => period.start))
+ : null,
+ periodEnd: periods.length
+ ? Math.max(...periods.map((period) => period.end))
+ : null,
+ total: invoice.total,
+ currency: invoice.currency,
+ status: invoice.status,
+ pdfUrl: safeHttpUrl(stripeInvoice.invoice_pdf),
+ };
+ });
+
+ return {
+ invoices: sort(invoices, (a, b) => b.createdAt - a.createdAt),
+ hasMore: nextCursor !== null,
+ };
+}
+
+/** Stripe emails a receipt for each paid invoice to the billing email. Autumn
+ * stores the setting on the customer and triggers the email. */
+export async function setOrganizationInvoiceEmails(
+ caller: BillingCaller,
+ enabled: boolean,
+) {
+ requireOrgPermission(caller, { billing: ["manage"] });
+ await autumn.customers.update({
+ customerId: caller.organizationId,
+ sendEmailReceipts: enabled,
+ });
+}
+
+// The SDK has no method for this endpoint. Callers pass only Stripe ids from
+// the organization's own invoice list.
+async function getStripeInvoice(stripeInvoiceId: string) {
+ const secretKey = await getRequiredEnvValue("AUTUMN_SECRET_KEY");
+ const response = await fetch(
+ `https://api.useautumn.com/v1/invoices/${encodeURIComponent(stripeInvoiceId)}/stripe`,
+ {
+ headers: { Authorization: `Bearer ${secretKey}` },
+ signal: AbortSignal.timeout(10_000),
+ },
+ );
+ if (!response.ok) {
+ throw new AppError(
+ "UPSTREAM_UNAVAILABLE",
+ `Autumn Stripe invoice lookup failed with status ${response.status}`,
+ );
+ }
+ return stripeInvoiceSchema.parse(await response.json());
+}
diff --git a/src/serverFunctions/billing.ts b/src/serverFunctions/billing.ts
index 6c577513..b71e25b1 100644
--- a/src/serverFunctions/billing.ts
+++ b/src/serverFunctions/billing.ts
@@ -12,6 +12,10 @@ import {
createPlanCheckoutUrl,
createTopUpCheckoutUrl,
} from "@/server/billing/checkout";
+import {
+ listOrganizationInvoices,
+ setOrganizationInvoiceEmails,
+} from "@/server/billing/invoices";
import { AppError } from "@/server/lib/errors";
import {
getRequiredEnvValue,
@@ -62,6 +66,17 @@ export const createBillingPortalSession = createServerFn({ method: "POST" })
}),
);
+export const listBillingInvoices = createServerFn({ method: "POST" })
+ .middleware(requireAuthenticatedContext)
+ .handler(({ context }) => listOrganizationInvoices(context));
+
+export const setInvoiceEmails = createServerFn({ method: "POST" })
+ .middleware(requireAuthenticatedContext)
+ .validator(z.object({ enabled: z.boolean() }))
+ .handler(({ data, context }) =>
+ setOrganizationInvoiceEmails(context, data.enabled),
+ );
+
const AUTUMN_EVENTS_LIST_URL = "https://api.useautumn.com/v1/events.list";
const EVENT_PAGE_LIMIT = 1000;
// Autumn rate-limits events.list; back off on 429 before giving up.