Skip to content

Open source alternative to Semrush and Ahrefs

Port the billing page to shadcn, with one usage source and errors next to the action (EVE-304) (#747)

Carter Smith709f2e5faf13
diff --git a/src/client/features/billing/BillingFeatureBreakdown.test.ts b/src/client/features/billing/BillingFeatureBreakdown.test.ts
index 6e4d9d0d..3a9f039d 100644
--- a/src/client/features/billing/BillingFeatureBreakdown.test.ts
+++ b/src/client/features/billing/BillingFeatureBreakdown.test.ts
@@ -10,6 +10,7 @@ describe("getBillingFeatureBreakdownRows", () => {
it("prefers an explicit creditFeature (or its raw alias) over the path", () => {
const rows = getBillingFeatureBreakdownRows([
{
+ timestamp: 0,
value: 250,
properties: {
creditFeature: "rank_tracking",
@@ -17,6 +18,7 @@ describe("getBillingFeatureBreakdownRows", () => {
},
},
{
+ timestamp: 0,
value: 200,
properties: {
credit_feature: "local_seo",
@@ -34,22 +36,26 @@ describe("getBillingFeatureBreakdownRows", () => {
it("infers legacy events from DataForSEO paths", () => {
const rows = getBillingFeatureBreakdownRows([
{
+ timestamp: 0,
value: 500,
properties: { paths: ["v3/backlinks/summary/live"] },
},
{
+ timestamp: 0,
value: 250,
properties: {
paths: ["v3/dataforseo_labs/google/domain_rank_overview/live"],
},
},
{
+ timestamp: 0,
value: 125,
properties: {
paths: ["v3/ai_optimization/llm_mentions/search/live"],
},
},
{
+ timestamp: 0,
value: 100,
properties: { paths: ["backlinks/summary"] },
},
@@ -65,12 +71,14 @@ describe("getBillingFeatureBreakdownRows", () => {
it("supports legacy JSON-encoded path groups", () => {
const rows = getBillingFeatureBreakdownRows([
{
+ timestamp: 0,
value: 300,
properties: {
paths: '["v3/ai_optimization/chat_gpt/llm_responses/live"]',
},
},
{
+ timestamp: 0,
value: 200,
properties: {
paths: '["v3","ai_optimization","perplexity","llm_responses","live"]',
diff --git a/src/client/features/billing/BillingFeatureBreakdown.tsx b/src/client/features/billing/BillingFeatureBreakdown.tsx
index 17826bd6..b84847ca 100644
--- a/src/client/features/billing/BillingFeatureBreakdown.tsx
+++ b/src/client/features/billing/BillingFeatureBreakdown.tsx
@@ -1,27 +1,14 @@
-import { useQuery } from "@tanstack/react-query";
import { sort } from "remeda";
-import {
- AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
- AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
- autumnSeoDataCreditsToUsd,
-} from "@/shared/billing";
+import { autumnSeoDataCreditsToUsd } from "@/shared/billing";
import {
creditFeatureLabel,
mapDataforseoPathToCreditFeature,
} from "@/shared/billing-credit-features";
-import {
- getBillingUsageEvents,
- type BillingUsageEvent,
-} from "@/serverFunctions/billing";
+import type { BillingUsageEvent } from "@/serverFunctions/billing";
import { QueryState } from "@/client/components/QueryState";
import { Skeleton } from "@/client/components/ui/skeleton";
-
-const BILLING_USAGE_FEATURE_IDS: string[] = [
- AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
- AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
-];
-
-const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;
+import { BillingUsageCard } from "@/client/features/billing/BillingUsageCard";
+import { useBillingUsageEvents } from "@/client/features/billing/useBillingUsageEvents";
type BillingUsageEventProperties = {
creditFeature?: unknown;
@@ -35,19 +22,6 @@ type BillingFeatureBreakdownRow = {
usd: number;
};
-type BillingUsageRange = {
- start: number;
- end: number;
-};
-
-function getLast30DayUsageRange(): BillingUsageRange {
- const end = Date.now();
- return {
- start: end - THIRTY_DAYS_MS,
- end,
- };
-}
-
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
@@ -139,19 +113,10 @@ export function getBillingFeatureBreakdownRows(
}
export function BillingFeatureBreakdown() {
- const eventsQuery = useQuery({
- queryKey: ["billing", "usage-events", BILLING_USAGE_FEATURE_IDS, "30d"],
- queryFn: () => getBillingUsageEvents({ data: getLast30DayUsageRange() }),
- staleTime: 60_000,
- });
+ const eventsQuery = useBillingUsageEvents();
return (
- <div className="rounded-lg border border-base-300 bg-base-100 p-4 space-y-3">
- <div className="flex items-baseline justify-between gap-4">
- <span className="font-semibold">Usage by feature</span>
- <span className="text-xs text-base-content/50">Last 30 days</span>
- </div>
-
+ <BillingUsageCard title="Usage by feature">
<QueryState
query={eventsQuery}
errorFallback="Failed to load usage"
@@ -165,7 +130,7 @@ export function BillingFeatureBreakdown() {
>
{(events) => <BreakdownRows events={events} />}
</QueryState>
- </div>
+ </BillingUsageCard>
);
}
@@ -175,7 +140,7 @@ function BreakdownRows({ events }: { events: BillingUsageEvent[] }) {
if (rows.length === 0) {
return (
- <div className="text-sm text-base-content/40">No usage recorded yet</div>
+ <div className="text-sm text-muted-foreground">No usage recorded yet</div>
);
}
@@ -185,11 +150,11 @@ function BreakdownRows({ events }: { events: BillingUsageEvent[] }) {
<li key={row.label} className="space-y-1">
<div className="flex items-baseline justify-between gap-4 text-sm">
<span>{row.label}</span>
- <span className="tabular-nums text-base-content/70">
+ <span className="tabular-nums text-muted-foreground">
${row.usd.toFixed(2)}
</span>
</div>
- <div className="h-1.5 w-full overflow-hidden rounded-full bg-base-200">
+ <div className="h-1.5 w-full overflow-hidden rounded-full bg-muted">
<div
className="h-full rounded-full bg-[#7c3aed]"
style={{ width: `${(row.usd / total) * 100}%` }}
diff --git a/src/client/features/billing/BillingUsageCard.tsx b/src/client/features/billing/BillingUsageCard.tsx
new file mode 100644
index 00000000..dd4fdaf3
--- /dev/null
+++ b/src/client/features/billing/BillingUsageCard.tsx
@@ -0,0 +1,29 @@
+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.test.ts b/src/client/features/billing/BillingUsageChart.test.ts
new file mode 100644
index 00000000..b2892d57
--- /dev/null
+++ b/src/client/features/billing/BillingUsageChart.test.ts
@@ -0,0 +1,31 @@
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it, vi } from "vitest";
+import { BillingUsageChart } from "./BillingUsageChart";
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+vi.mock("@/client/features/billing/useBillingUsageEvents", () => ({
+ BILLING_USAGE_DAYS: 30,
+ useBillingUsageEvents: () => ({
+ isPending: false,
+ isError: false,
+ data: [
+ { timestamp: Date.now(), value: 20, properties: {} },
+ // Older than the first bar: cached events after local midnight.
+ {
+ timestamp: Date.now() - 31 * DAY_MS - 60_000,
+ value: 30,
+ properties: {},
+ },
+ ],
+ }),
+}));
+
+describe("BillingUsageChart", () => {
+ it("counts every fetched event in the total, as the breakdown does", () => {
+ const markup = renderToStaticMarkup(createElement(BillingUsageChart));
+
+ expect(markup).toContain("$0.05");
+ });
+});
diff --git a/src/client/features/billing/BillingUsageChart.tsx b/src/client/features/billing/BillingUsageChart.tsx
index 8afe3d20..9982d1a4 100644
--- a/src/client/features/billing/BillingUsageChart.tsx
+++ b/src/client/features/billing/BillingUsageChart.tsx
@@ -1,74 +1,60 @@
-import { useAggregateEvents } from "autumn-js/react";
import { Bar, BarChart } from "recharts";
-import {
- AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
- AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
- autumnSeoDataCreditsToUsd,
-} from "@/shared/billing";
-import { QueryError } from "@/client/components/QueryState";
+import { sort } from "remeda";
+import { autumnSeoDataCreditsToUsd } from "@/shared/billing";
+import type { BillingUsageEvent } from "@/serverFunctions/billing";
+import { QueryState } from "@/client/components/QueryState";
import {
ChartGrid,
ChartXAxis,
ChartYAxis,
} from "@/client/components/ChartAxes";
+import { Skeleton } from "@/client/components/ui/skeleton";
import {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
type ChartConfig,
} from "@/client/components/ui/chart";
-
-const BILLING_USAGE_FEATURE_IDS: string[] = [
- AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
- AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
-];
+import { BillingUsageCard } from "@/client/features/billing/BillingUsageCard";
+import {
+ BILLING_USAGE_DAYS,
+ useBillingUsageEvents,
+} from "@/client/features/billing/useBillingUsageEvents";
const chartConfig = {
credits: { label: "Usage", color: "#7c3aed" },
} satisfies ChartConfig;
export function BillingUsageChart() {
- const eventsQuery = useAggregateEvents({
- featureId: BILLING_USAGE_FEATURE_IDS,
- range: "30d",
- binSize: "day",
- });
+ const eventsQuery = useBillingUsageEvents();
- const chartData = (eventsQuery.list ?? []).map((row) => ({
- date: row.period,
- credits: autumnSeoDataCreditsToUsd(
- BILLING_USAGE_FEATURE_IDS.reduce(
- (sum, featureId) => sum + (row.values?.[featureId] ?? 0),
- 0,
- ),
- ),
- }));
+ return (
+ <BillingUsageCard title="Usage">
+ <QueryState
+ query={eventsQuery}
+ errorFallback="Failed to load usage"
+ loading={<Skeleton className="h-40 w-full" />}
+ >
+ {(events) => <UsageChart events={events} />}
+ </QueryState>
+ </BillingUsageCard>
+ );
+}
+function UsageChart({ events }: { events: BillingUsageEvent[] }) {
+ const chartData = binEventsByDay(events);
const totalSpend = chartData.reduce((sum, d) => sum + d.credits, 0);
return (
- <div className="rounded-lg border border-base-300 bg-base-100 p-4 space-y-3">
- <div className="flex items-baseline justify-between gap-4">
- <span className="font-semibold">Usage</span>
- <span className="text-xs text-base-content/50">Last 30 days</span>
- </div>
-
+ <div className="space-y-3">
<div className="text-2xl font-semibold tabular-nums">
${totalSpend.toFixed(2)}
</div>
- <div className="w-full h-32 min-w-0">
- {eventsQuery.isLoading ? null : eventsQuery.list === undefined &&
- eventsQuery.isError ? (
- <QueryError
- error={eventsQuery.error}
- fallback="Failed to load usage"
- onRetry={() => void eventsQuery.refetch()}
- isRetrying={eventsQuery.isFetching}
- />
- ) : chartData.length === 0 ? (
+ <div className="h-32 w-full min-w-0">
+ {totalSpend === 0 ? (
<div className="flex h-full items-center justify-center">
- <span className="text-sm text-base-content/40">
+ <span className="text-sm text-muted-foreground">
No usage recorded yet
</span>
</div>
@@ -109,6 +95,34 @@ export function BillingUsageChart() {
);
}
+/**
+ * One bar for each local day, from 30 days ago to today, in USD. An event
+ * older than that (cached data after midnight) gets its own bar, so the
+ * total still matches the per-feature breakdown.
+ */
+function binEventsByDay(events: BillingUsageEvent[]) {
+ const creditsByDay = new Map<number, number>();
+ const day = new Date();
+ day.setHours(0, 0, 0, 0);
+ day.setDate(day.getDate() - BILLING_USAGE_DAYS);
+ for (let i = 0; i <= BILLING_USAGE_DAYS; i++) {
+ creditsByDay.set(day.getTime(), 0);
+ day.setDate(day.getDate() + 1);
+ }
+
+ for (const event of events) {
+ const eventDay = new Date(event.timestamp).setHours(0, 0, 0, 0);
+ creditsByDay.set(eventDay, (creditsByDay.get(eventDay) ?? 0) + event.value);
+ }
+
+ return sort([...creditsByDay], ([a], [b]) => a - b).map(
+ ([date, credits]) => ({
+ date,
+ credits: autumnSeoDataCreditsToUsd(credits),
+ }),
+ );
+}
+
function formatShortDate(timestamp: number) {
return new Date(timestamp).toLocaleDateString("en-US", {
month: "short",
diff --git a/src/client/features/billing/FreePlanBanner.tsx b/src/client/features/billing/FreePlanBanner.tsx
index 00c68f07..749fb865 100644
--- a/src/client/features/billing/FreePlanBanner.tsx
+++ b/src/client/features/billing/FreePlanBanner.tsx
@@ -1,46 +1,16 @@
import { Link } from "@tanstack/react-router";
-import { useCustomer } from "autumn-js/react";
import { AppBanner } from "@/client/layout/AppBanner";
-import { useSession } from "@/lib/auth-client";
-import { getCustomerPlanStatus } from "@/client/features/billing/plan-detection";
-import {
- AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
- AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
- BILLING_ROUTE,
- LOW_CREDITS_THRESHOLD_USD,
- SUBSCRIBE_ROUTE,
- autumnSeoDataCreditsToUsd,
-} from "@/shared/billing";
+import { useCreditBalance } from "@/client/features/billing/useCreditBalance";
+import { BILLING_ROUTE, SUBSCRIBE_ROUTE } from "@/shared/billing";
export function FreePlanBanner() {
- const { data: session } = useSession();
- const customerQuery = useCustomer({
- queryOptions: {
- enabled: Boolean(session?.user?.id),
- },
- });
+ const { customerQuery, isFreePlan, isOutOfCredits, isLowCredits } =
+ useCreditBalance();
if (customerQuery.isLoading || !customerQuery.data) {
return null;
}
- const planStatus = getCustomerPlanStatus(customerQuery.data);
- const isFreePlan = planStatus === "free";
-
- const monthlyRemaining = autumnSeoDataCreditsToUsd(
- customerQuery.data.balances?.[AUTUMN_SEO_DATA_BALANCE_FEATURE_ID]
- ?.remaining ?? 0,
- );
- const topUpRemaining = autumnSeoDataCreditsToUsd(
- customerQuery.data.balances?.[AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID]
- ?.remaining ?? 0,
- );
- const totalRemaining = monthlyRemaining + topUpRemaining;
-
- const isOutOfCredits = totalRemaining <= 0;
- const isLowCredits =
- !isOutOfCredits && totalRemaining < LOW_CREDITS_THRESHOLD_USD;
-
const creditsActionLink = isFreePlan ? (
<Link
to={SUBSCRIBE_ROUTE}
diff --git a/src/client/features/billing/useBillingUsageEvents.ts b/src/client/features/billing/useBillingUsageEvents.ts
new file mode 100644
index 00000000..7ee78a4e
--- /dev/null
+++ b/src/client/features/billing/useBillingUsageEvents.ts
@@ -0,0 +1,19 @@
+import { useQuery } from "@tanstack/react-query";
+import { getBillingUsageEvents } from "@/serverFunctions/billing";
+
+export const BILLING_USAGE_DAYS = 30;
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+/** The usage events of the last 30 days, for the usage chart and the per-feature breakdown. */
+export function useBillingUsageEvents() {
+ return useQuery({
+ queryKey: ["billing", "usage-events", `${BILLING_USAGE_DAYS}d`],
+ queryFn: () => {
+ const end = Date.now();
+ return getBillingUsageEvents({
+ data: { start: end - BILLING_USAGE_DAYS * DAY_MS, end },
+ });
+ },
+ staleTime: 60_000,
+ });
+}
diff --git a/src/client/features/billing/useCreditBalance.ts b/src/client/features/billing/useCreditBalance.ts
new file mode 100644
index 00000000..c17143b9
--- /dev/null
+++ b/src/client/features/billing/useCreditBalance.ts
@@ -0,0 +1,45 @@
+import { useCustomer } from "autumn-js/react";
+import { useSession } from "@/lib/auth-client";
+import { getCustomerPlanStatus } from "@/client/features/billing/plan-detection";
+import {
+ AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
+ LOW_CREDITS_THRESHOLD_USD,
+ autumnSeoDataCreditsToUsd,
+} from "@/shared/billing";
+
+type CustomerParams = NonNullable<Parameters<typeof useCustomer>[0]>;
+
+/** The signed-in organization's Autumn customer, plan, and remaining credits in USD. */
+export function useCreditBalance({
+ expand,
+}: { expand?: CustomerParams["expand"] } = {}) {
+ const session = useSession();
+ const customerQuery = useCustomer({
+ expand,
+ queryOptions: {
+ enabled: Boolean(session.data?.user?.id),
+ },
+ });
+
+ const balances = customerQuery.data?.balances;
+ const monthlyRemaining = autumnSeoDataCreditsToUsd(
+ balances?.[AUTUMN_SEO_DATA_BALANCE_FEATURE_ID]?.remaining ?? 0,
+ );
+ const topUpRemaining = autumnSeoDataCreditsToUsd(
+ balances?.[AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID]?.remaining ?? 0,
+ );
+ const totalRemaining = monthlyRemaining + topUpRemaining;
+ const isOutOfCredits = totalRemaining <= 0;
+
+ return {
+ session,
+ customerQuery,
+ isFreePlan: getCustomerPlanStatus(customerQuery.data) === "free",
+ monthlyRemaining,
+ topUpRemaining,
+ totalRemaining,
+ isOutOfCredits,
+ isLowCredits: !isOutOfCredits && totalRemaining < LOW_CREDITS_THRESHOLD_USD,
+ };
+}
diff --git a/src/routes/_app/billing.tsx b/src/routes/_app/billing.tsx
index 74fae1fa..dfe24a1e 100644
--- a/src/routes/_app/billing.tsx
+++ b/src/routes/_app/billing.tsx
@@ -1,9 +1,23 @@
import { createFileRoute, notFound } from "@tanstack/react-router";
-import { useCustomer } from "autumn-js/react";
import { useState } from "react";
+import { ErrorState } from "@/client/components/ErrorState";
+import { PageHeader } from "@/client/components/PageHeader";
import { QueryError } from "@/client/components/QueryState";
import { PageLoading } from "@/client/components/Spinner";
-import { useSession } from "@/lib/auth-client";
+import { Button } from "@/client/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ CardDescription,
+} from "@/client/components/ui/card";
+import { Field, FieldError } from "@/client/components/ui/field";
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+} from "@/client/components/ui/input-group";
import { isHostedClientAuthMode } from "@/lib/auth-mode";
import { useCanManageBilling } from "@/client/features/team/organizationQueries";
import { captureClientEvent } from "@/client/lib/posthog";
@@ -13,10 +27,8 @@ import { BillingUsageChart } from "@/client/features/billing/BillingUsageChart";
import { BillingFeatureBreakdown } from "@/client/features/billing/BillingFeatureBreakdown";
import { parseTopUpAmount } from "@/client/features/billing/HostedBillingContentUtils";
import { getBillingRouteState } from "@/client/features/billing/route-state";
-import {
- getCustomerPaidPlan,
- getCustomerPlanStatus,
-} from "@/client/features/billing/plan-detection";
+import { getCustomerPaidPlan } from "@/client/features/billing/plan-detection";
+import { useCreditBalance } from "@/client/features/billing/useCreditBalance";
import {
BASE_PLAN_OFFER,
monthlyCreditsFeature,
@@ -24,12 +36,9 @@ import {
import {
AUTUMN_CHECKOUT_SESSION_PARAMS,
BILLING_ROUTE,
- AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
- LOW_CREDITS_THRESHOLD_USD,
AUTUMN_SEO_DATA_CREDITS_PER_USD,
AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,
AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
- autumnSeoDataCreditsToUsd,
} from "@/shared/billing";
export const Route = createFileRoute("/_app/billing")({
@@ -41,26 +50,34 @@ export const Route = createFileRoute("/_app/billing")({
component: BillingPage,
});
+type BillingAction = "plan" | "topUp";
+
function BillingPage() {
- const { data: session, isPending: isSessionPending } = useSession();
const [topUpAmount, setTopUpAmount] = useState("20");
const [isPending, setIsPending] = useState(false);
- const [error, setError] = useState<string | null>(null);
+ const [error, setError] = useState<{
+ action: BillingAction;
+ message: string;
+ } | null>(null);
- const customerQuery = useCustomer({
+ const {
+ session: { data: session, isPending: isSessionPending },
+ customerQuery,
+ isFreePlan,
+ monthlyRemaining,
+ topUpRemaining,
+ totalRemaining,
+ isOutOfCredits,
+ isLowCredits,
+ } = useCreditBalance({
// Expanded so the plan card can show the subscribed plan's name.
expand: ["subscriptions.plan"],
- queryOptions: {
- enabled: Boolean(session?.user?.id),
- },
});
// Subscription changes are owner-only; other members see balances but are
// pointed at the owner instead of checkout (the server enforces this too).
const canManageBilling = useCanManageBilling();
- const planStatus = getCustomerPlanStatus(customerQuery.data);
- const isFreePlan = planStatus === "free";
const paidPlan = getCustomerPaidPlan(customerQuery.data);
const billingRouteState = getBillingRouteState({
hasSession: Boolean(session?.user?.id),
@@ -70,18 +87,9 @@ function BillingPage() {
hasCustomerData: customerQuery.data != null,
});
- const monthlyRemaining = autumnSeoDataCreditsToUsd(
- customerQuery.data?.balances?.[AUTUMN_SEO_DATA_BALANCE_FEATURE_ID]
- ?.remaining ?? 0,
- );
- const topUpRemaining = autumnSeoDataCreditsToUsd(
- customerQuery.data?.balances?.[AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID]
- ?.remaining ?? 0,
- );
- const totalRemaining = monthlyRemaining + topUpRemaining;
-
const { isValid: isValidTopUp, parsed: parsedTopUpAmount } =
parseTopUpAmount(topUpAmount);
+ const showTopUpError = topUpAmount.trim() !== "" && !isValidTopUp;
if (billingRouteState === "loading") {
return <PageLoading />;
@@ -90,7 +98,7 @@ function BillingPage() {
if (billingRouteState === "error") {
return (
<div className="mx-auto w-full max-w-2xl space-y-4 p-4 py-10 md:p-6 md:py-12">
- <h1 className="text-xl font-semibold">Billing unavailable</h1>
+ <PageHeader title="Billing unavailable" />
<QueryError
error={customerQuery.error}
fallback="We couldn't load your billing details right now. Please try again."
@@ -112,6 +120,7 @@ function BillingPage() {
}
async function runAction(
+ action: BillingAction,
callback: () => Promise<unknown>,
fallbackMessage: string,
) {
@@ -121,23 +130,34 @@ function BillingPage() {
await callback();
await customerQuery.refetch();
} catch (err) {
- setError(getStandardErrorMessage(err, fallbackMessage));
+ setError({
+ action,
+ message: getStandardErrorMessage(err, fallbackMessage),
+ });
} finally {
setIsPending(false);
}
}
+ function actionError(action: BillingAction) {
+ return error?.action === action ? (
+ <ErrorState message={error.message} />
+ ) : null;
+ }
+
if (isPending) {
return (
<div className="flex h-full items-center justify-center">
- <p className="text-sm text-base-content/50">Redirecting to Stripe...</p>
+ <p className="text-sm text-muted-foreground">
+ Redirecting to Stripe...
+ </p>
</div>
);
}
return (
<div className="mx-auto w-full max-w-2xl space-y-5 p-4 py-10 md:p-6 md:py-12">
- <h1 className="text-xl font-semibold">Billing</h1>
+ <PageHeader title="Billing" />
{customerQuery.isError ? (
<QueryError
@@ -150,188 +170,198 @@ function BillingPage() {
<div className="grid gap-5 md:grid-cols-2">
{/* Subscription card */}
- <div className="flex flex-col justify-between rounded-lg border border-base-300 bg-base-100 p-4 gap-4">
- <div>
- <div className="text-2xl font-semibold tabular-nums">
- ${totalRemaining.toFixed(2)}{" "}
- <span className="text-sm font-normal text-base-content/50">
- remaining
- </span>
- </div>
- {!isFreePlan ? (
- <div className="mt-1 flex gap-3 text-xs text-base-content/50">
- <span className="tabular-nums">
- Monthly ${monthlyRemaining.toFixed(2)}
- </span>
- <span>&middot;</span>
- <span className="tabular-nums">
- Top-ups ${topUpRemaining.toFixed(2)}
+ <Card>
+ <CardContent className="flex h-full flex-col justify-between gap-4">
+ <div>
+ <div className="text-2xl font-semibold tabular-nums">
+ ${totalRemaining.toFixed(2)}{" "}
+ <span className="text-sm font-normal text-muted-foreground">
+ remaining
</span>
</div>
- ) : null}
- {totalRemaining <= 0 ? (
- <p className="mt-2 text-xs text-error">
- You&rsquo;ve used all your credits.{" "}
- {isFreePlan
- ? "Upgrade your plan to continue."
- : "Buy more credits below to continue."}
- </p>
- ) : totalRemaining < LOW_CREDITS_THRESHOLD_USD ? (
- <p className="mt-2 text-xs text-amber-600">
- You&rsquo;re running low on credits.{" "}
- {isFreePlan
- ? `Upgrade to get $${BASE_PLAN_OFFER.monthlyCreditsUsd}/month.`
- : "Buy more credits below."}
- </p>
- ) : null}
- </div>
+ {!isFreePlan ? (
+ <div className="mt-1 flex gap-3 text-xs text-muted-foreground">
+ <span className="tabular-nums">
+ Monthly ${monthlyRemaining.toFixed(2)}
+ </span>
+ <span>&middot;</span>
+ <span className="tabular-nums">
+ Top-ups ${topUpRemaining.toFixed(2)}
+ </span>
+ </div>
+ ) : null}
+ {isOutOfCredits ? (
+ <p className="mt-2 text-xs text-destructive">
+ You&rsquo;ve used all your credits.{" "}
+ {isFreePlan
+ ? "Upgrade your plan to continue."
+ : "Buy more credits below to continue."}
+ </p>
+ ) : isLowCredits ? (
+ <p className="mt-2 text-xs text-amber-600">
+ You&rsquo;re running low on credits.{" "}
+ {isFreePlan
+ ? `Upgrade to get $${BASE_PLAN_OFFER.monthlyCreditsUsd}/month.`
+ : "Buy more credits below."}
+ </p>
+ ) : null}
+ </div>
- <div className="text-sm">
- <span className="font-medium">Plan</span>{" "}
- <span className="text-base-content/50">
- {paidPlan?.name ?? "Free Plan"}
- </span>
- {paidPlan ? (
- <span className="text-base-content/50">
- {" "}
- &middot; ${paidPlan.monthlyCreditsUsd.toFixed(2)} of Usage
- Credits each month
+ <div className="text-sm">
+ <span className="font-medium">Plan</span>{" "}
+ <span className="text-muted-foreground">
+ {paidPlan?.name ?? "Free Plan"}
</span>
- ) : null}
- </div>
-
- {!canManageBilling ? (
- <p className="border-t border-base-300 pt-3 text-sm text-base-content/60">
- Only the organization owner can change the plan or buy credits.
- Ask them if you need more.
- </p>
- ) : isFreePlan ? (
- <div className="space-y-3 border-t border-base-300 pt-3">
- <div className="flex items-baseline justify-between gap-4">
- <span className="text-sm font-medium">
- {BASE_PLAN_OFFER.name}
- </span>
- <span className="text-sm font-medium tabular-nums">
- ${BASE_PLAN_OFFER.priceUsd}/month
+ {paidPlan ? (
+ <span className="text-muted-foreground">
+ {" "}
+ &middot; ${paidPlan.monthlyCreditsUsd.toFixed(2)} of Usage
+ Credits each month
</span>
- </div>
- <ul className="space-y-1.5">
- {[
- "Access to all OpenSEO features",
- monthlyCreditsFeature(BASE_PLAN_OFFER),
- ].map((item) => (
- <li
- key={item}
- className="flex gap-2 text-xs text-base-content/60"
- >
- <span className="text-base-content/30 mt-[1px] shrink-0">
- &mdash;
- </span>
- {item}
- </li>
- ))}
- </ul>
- <button
- className="btn btn-soft btn-sm w-full"
- onClick={() =>
- void runAction(
- startUpgradeCheckout,
- "We couldn't start the checkout. Please try again.",
- )
- }
- >
- Upgrade Plan
- </button>
+ ) : null}
</div>
- ) : (
- <button
- className="btn btn-soft btn-sm w-full"
- onClick={() =>
- void runAction(
- () =>
- customerQuery.openCustomerPortal({
- returnUrl: window.location.href,
- }),
- "We couldn't open the billing portal. Please try again.",
- )
- }
- >
- Manage subscription
- </button>
- )}
- </div>
+
+ {!canManageBilling ? (
+ <p className="border-t border-border pt-3 text-sm text-muted-foreground">
+ Only the organization owner can change the plan or buy credits.
+ Ask them if you need more.
+ </p>
+ ) : isFreePlan ? (
+ <div className="space-y-3 border-t border-border pt-3">
+ <div className="flex items-baseline justify-between gap-4">
+ <span className="text-sm font-medium">
+ {BASE_PLAN_OFFER.name}
+ </span>
+ <span className="text-sm font-medium tabular-nums">
+ ${BASE_PLAN_OFFER.priceUsd}/month
+ </span>
+ </div>
+ <ul className="space-y-1.5">
+ {[
+ "Access to all OpenSEO features",
+ monthlyCreditsFeature(BASE_PLAN_OFFER),
+ ].map((item) => (
+ <li
+ key={item}
+ className="flex gap-2 text-xs text-muted-foreground"
+ >
+ <span className="mt-[1px] shrink-0 text-muted-foreground/60">
+ &mdash;
+ </span>
+ {item}
+ </li>
+ ))}
+ </ul>
+ <Button
+ variant="secondary"
+ className="w-full"
+ onClick={() =>
+ void runAction(
+ "plan",
+ startUpgradeCheckout,
+ "We couldn't start the checkout. Please try again.",
+ )
+ }
+ >
+ Upgrade Plan
+ </Button>
+ {actionError("plan")}
+ </div>
+ ) : (
+ <div className="space-y-3">
+ <Button
+ variant="secondary"
+ className="w-full"
+ onClick={() =>
+ void runAction(
+ "plan",
+ () =>
+ customerQuery.openCustomerPortal({
+ returnUrl: window.location.href,
+ }),
+ "We couldn't open the billing portal. Please try again.",
+ )
+ }
+ >
+ Manage subscription
+ </Button>
+ {actionError("plan")}
+ </div>
+ )}
+ </CardContent>
+ </Card>
{/* Buy credits card — paid plan only, owner-only */}
{!isFreePlan && canManageBilling ? (
- <div className="rounded-lg border border-base-300 bg-base-100 p-4 space-y-3">
- <div>
- <span className="font-semibold">Buy credits</span>
- <p className="mt-1 text-sm text-base-content/60">
+ <Card>
+ <CardHeader>
+ <CardTitle>Buy credits</CardTitle>
+ <CardDescription>
Top-up credits never expire and are used after your monthly
credits.
- </p>
- </div>
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-3">
+ <Field data-invalid={showTopUpError}>
+ <InputGroup>
+ <InputGroupAddon>$</InputGroupAddon>
+ <InputGroupInput
+ type="number"
+ min={10}
+ max={99}
+ step={1}
+ inputMode="numeric"
+ aria-label="Top-up amount in USD"
+ aria-invalid={showTopUpError}
+ value={topUpAmount}
+ onChange={(e) => setTopUpAmount(e.target.value)}
+ />
+ </InputGroup>
+ {showTopUpError ? (
+ <FieldError>Enter between $10–$99.</FieldError>
+ ) : null}
+ </Field>
- <div>
- <div className="flex items-center gap-2">
- <span className="text-sm text-base-content/60">$</span>
- <input
- type="number"
- min={10}
- max={99}
- step={1}
- inputMode="numeric"
- className="input input-bordered input-sm w-full"
- value={topUpAmount}
- onChange={(e) => setTopUpAmount(e.target.value)}
- />
- </div>
- {topUpAmount.trim() !== "" && !isValidTopUp ? (
- <p className="mt-1 text-xs text-error">
- Enter between $10–$99.
- </p>
- ) : null}
- </div>
-
- <button
- className="btn btn-soft btn-sm w-full"
- disabled={!isValidTopUp}
- onClick={() =>
- void runAction(
- () =>
- customerQuery.attach({
- planId: AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,
- redirectMode: "always",
- successUrl: window.location.href,
- checkoutSessionParams: AUTUMN_CHECKOUT_SESSION_PARAMS,
- featureQuantities: [
- {
- featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
- quantity: Math.round(
- parsedTopUpAmount * AUTUMN_SEO_DATA_CREDITS_PER_USD,
- ),
- },
- ],
- }),
- "We couldn't start the checkout. Please try again.",
- )
- }
- >
- Buy credits
- </button>
- </div>
+ <Button
+ variant="secondary"
+ className="w-full"
+ disabled={!isValidTopUp}
+ onClick={() =>
+ void runAction(
+ "topUp",
+ () =>
+ customerQuery.attach({
+ planId: AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,
+ redirectMode: "always",
+ successUrl: window.location.href,
+ checkoutSessionParams: AUTUMN_CHECKOUT_SESSION_PARAMS,
+ featureQuantities: [
+ {
+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
+ quantity: Math.round(
+ parsedTopUpAmount *
+ AUTUMN_SEO_DATA_CREDITS_PER_USD,
+ ),
+ },
+ ],
+ }),
+ "We couldn't start the checkout. Please try again.",
+ )
+ }
+ >
+ Buy credits
+ </Button>
+ {actionError("topUp")}
+ </CardContent>
+ </Card>
) : null}
</div>
- {/* Usage chart */}
<BillingUsageChart />
- {/* Per-feature usage breakdown */}
<BillingFeatureBreakdown />
- {error ? <p className="text-sm text-error">{error}</p> : null}
-
- <p className="text-xs text-base-content/40">
+ <p className="text-xs text-muted-foreground">
Billing is powered by Stripe.
</p>
</div>
diff --git a/src/serverFunctions/billing.ts b/src/serverFunctions/billing.ts
index 1b5b2120..51ccd38e 100644
--- a/src/serverFunctions/billing.ts
+++ b/src/serverFunctions/billing.ts
@@ -32,6 +32,7 @@ const billingUsagePropertySchema = z.json();
const autumnEventSchema = z
.object({
+ timestamp: z.number(),
value: z.number(),
properties: z
.record(z.string(), billingUsagePropertySchema)
@@ -49,6 +50,7 @@ const autumnEventsListResponseSchema = z
.passthrough();
export type BillingUsageEvent = {
+ timestamp: number;
value: number;
properties: Record<string, z.infer<typeof billingUsagePropertySchema>>;
};
@@ -134,6 +136,7 @@ async function fetchAutumnEventsPage(args: {
return {
hasMore: parsed.has_more ?? parsed.hasMore ?? false,
list: parsed.list.map((event) => ({
+ timestamp: event.timestamp,
value: event.value,
properties: event.properties,
})),