Files
descrybe/apps/web/src/routes/billing/+page.svelte
T

795 lines
26 KiB
Svelte
Raw Normal View History

<script lang="ts">
import { onMount } from "svelte";
import { goto } from "$app/navigation";
import { page } from "$app/state";
import { CreditCard, FileText, ExternalLink, Wallet } from "@lucide/svelte";
import { api, ApiError, failureMessage } from "$lib/api";
import {
claimPurchaseTracking,
resolveCheckoutEcommerceFromParams,
trackEcommerceEvent
} from "$lib/analytics";
import { formatCredits, formatDate } from "$lib/utils";
import {
CREDIT_USAGE_ITEMS,
billingRecovery,
canUseAIFromCredits,
formatCreditsRemaining,
formatMonthlyCredits,
formatSkuUsage,
hasActivePlan,
isEnterprisePlan,
isFreePlan,
isLegacyPlan,
isPayAsYouGoPlan,
planDisplayName,
remainingCreditsOf,
upgradeCtaForRole,
withUpgradeHint,
nextSelfServeUpgradePlan,
planCheckoutDisplayName,
type PlanLike
} from "$lib/billing-display";
import { isCompanyAdmin } from "$lib/company-admin";
import {
fetchStripeStatus,
openBillingPortal,
startCheckout,
startCreditPackCheckout,
redirectToCheckout,
type StripeStatus
} from "$lib/stripe-billing";
import { CREDIT_PACKS } from "$lib/components/pricing/credit-packs";
import type { CreditBalance, MeResponse } from "$lib/types";
import { i18n } from "$lib/i18n";
import Alert from "$lib/components/Alert.svelte";
import Spinner from "$lib/components/Spinner.svelte";
import UpgradeBanner from "$lib/components/UpgradeBanner.svelte";
import AdminSeriesChart from "$lib/components/AdminSeriesChart.svelte";
import {
Badge,
Button,
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
Dialog,
Input,
Label,
Select,
buttonClasses
} from "$lib/components/ui";
type DateRangeOption = "7d" | "30d" | "cycle" | "all";
type UsageDayPoint = {
date: string;
products?: number;
tokens?: number;
};
type UsageSummary = {
company_id?: string;
range?: string;
credits_used?: number;
credits_total?: number;
credits_remaining?: number;
products_processed?: number;
products_total?: number;
tokens?: number;
feeds_input?: number;
feeds_export?: number;
jobs_total?: number;
cycle_start?: string | null;
cycle_end?: string | null;
series?: UsageDayPoint[];
notes?: string[];
};
let credits = $state<CreditBalance | null>(null);
let usage = $state<UsageSummary | null>(null);
let stripe = $state<StripeStatus | null>(null);
let companyId = $state("");
let isPlatformAdmin = $state(false);
let canManageBilling = $state(false);
let error = $state("");
let success = $state("");
let loading = $state(true);
let dateRangeOption = $state<DateRangeOption>("30d");
let addCreditsOpen = $state(false);
let creditAmount = $state("1000");
let addingCredits = $state(false);
let checkoutBusy = $state(false);
let packCheckoutBusy = $state<string | null>(null);
let portalBusy = $state(false);
let usageLoading = $state(false);
onMount(async () => {
try {
const me = await api<MeResponse>("/api/auth/me");
companyId = me.company?.id ?? me.active_company_id ?? "";
isPlatformAdmin = Boolean(me.user?.is_platform_admin);
canManageBilling = isCompanyAdmin(me);
const [creditsRes, usageRes, stripeRes] = await Promise.all([
me.credits
? Promise.resolve(me.credits)
: api<CreditBalance>("/api/billing/credits").catch(() => null),
api<UsageSummary>(`/api/billing/usage?range=${dateRangeOption}`).catch(() => null),
fetchStripeStatus().catch(() => null)
]);
credits = creditsRes;
usage = usageRes;
stripe = stripeRes;
const checkout = page.url.searchParams.get("checkout");
const portal = page.url.searchParams.get("portal");
const mockPlan = page.url.searchParams.get("plan");
const mockPack = page.url.searchParams.get("pack");
const mockCredits = page.url.searchParams.get("credits");
const checkoutEcommerce = resolveCheckoutEcommerceFromParams(page.url.searchParams);
if (checkout === "success") {
if (mockPack || mockCredits) {
success = i18n.t("billing.checkoutCompletePack", {
credits: mockCredits || "…"
});
} else {
success = mockPlan
? i18n.t("billing.checkoutCompletePlan", { plan: mockPlan })
: i18n.t("billing.checkoutComplete");
}
const purchaseId = checkoutEcommerce?.ecommerce.transaction_id;
const storage =
typeof sessionStorage !== "undefined" ? sessionStorage : null;
if (checkoutEcommerce && claimPurchaseTracking(purchaseId, storage)) {
trackEcommerceEvent(
"purchase",
checkoutEcommerce.ecommerce,
checkoutEcommerce.extra
);
}
credits = await api<CreditBalance>("/api/billing/credits").catch(() => credits);
stripe = await fetchStripeStatus().catch(() => stripe);
} else if (checkout === "cancel") {
error = i18n.t("flash.billing.checkoutCanceled");
if (checkoutEcommerce) {
const { ecommerce, extra } = checkoutEcommerce;
trackEcommerceEvent(
"checkout_canceled",
{
currency: ecommerce.currency,
value: ecommerce.value,
items: ecommerce.items
},
extra
);
}
} else if (portal === "mock") {
success = i18n.t("flash.billing.portalReturn");
}
} catch (err) {
if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {
await goto("/login");
return;
}
error = failureMessage(err, i18n.t("billing.loadFailed"));
} finally {
loading = false;
}
});
const remaining = $derived.by(() => {
if (typeof usage?.credits_remaining === "number") {
return Math.max(0, usage.credits_remaining);
}
return remainingCreditsOf(credits);
});
const walletUsed = $derived(
typeof usage?.credits_used === "number" ? usage.credits_used : (credits?.used_credits ?? 0)
);
const plan = $derived.by((): PlanLike | null => {
if (!credits?.plan || typeof credits.plan !== "object") return null;
return credits.plan as PlanLike;
});
const planAssigned = $derived(hasActivePlan(credits, plan));
const planName = $derived(planDisplayName(plan, credits));
const enterprise = $derived(planAssigned && isEnterprisePlan(plan));
const freePlan = $derived(isFreePlan(plan, credits ?? undefined));
const payg = $derived(isPayAsYouGoPlan(plan, credits));
const canUseAI = $derived(canUseAIFromCredits(credits));
const upgradeCta = $derived(upgradeCtaForRole(canManageBilling));
const recovery = $derived(
billingRecovery({
credits,
plan,
subscriptionStatus: stripe?.subscription_status,
canManageBilling
})
);
const isContractExpiringSoon = $derived.by(() => {
const end = usage?.cycle_end ?? plan?.next_billing_date;
if (!end) return false;
const endDate = new Date(end);
if (Number.isNaN(endDate.getTime())) return false;
const days = Math.ceil((endDate.getTime() - Date.now()) / (1000 * 60 * 60 * 24));
return days <= 30 && days >= 0;
});
const rangeLabel = $derived.by(() => {
switch (dateRangeOption) {
case "7d":
return i18n.t("billing.range.7d");
case "30d":
return i18n.t("billing.range.30d");
case "cycle":
return i18n.t("billing.range.cycle");
default:
return i18n.t("billing.range.all");
}
});
const chartPoints = $derived(
(usage?.series ?? []).map((p) => ({
label: p.date.slice(5),
value: Number(p.products ?? 0),
secondary: Number(p.tokens ?? 0)
}))
);
const hasSeries = $derived(chartPoints.some((p) => p.value > 0 || (p.secondary ?? 0) > 0));
const catalogProductCount = $derived(
typeof credits?.product_count === "number"
? credits.product_count
: (usage?.products_total ?? 0)
);
const hasCatalogActivity = $derived(
catalogProductCount > 0 || (usage?.feeds_input ?? 0) > 0 || walletUsed > 0
);
const outOfCredits = $derived(!freePlan && !enterprise && remaining !== null && remaining <= 0);
const lowCredits = $derived(
Boolean(credits?.low_credits) && !outOfCredits && !freePlan && !enterprise && !payg
);
const atProductLimit = $derived(Boolean(credits?.at_product_limit) && !enterprise);
const nextUpgradePlan = $derived(nextSelfServeUpgradePlan(planName));
const showQuickUpgrade = $derived(
canManageBilling &&
!enterprise &&
!payg &&
!isLegacyPlan(plan) &&
!plan?.is_custom &&
nextUpgradePlan !== null &&
(freePlan || Boolean(plan))
);
const remainingLabel = $derived(formatCreditsRemaining(remaining, plan, credits));
const planBillingLabel = $derived.by(() => {
if (!planAssigned) return i18n.t("billing.noPlanAssigned");
if (enterprise) return i18n.t("billing.unlimited");
if (payg) return i18n.t("billing.payAsYouGo");
if (freePlan) return i18n.t("billing.noMonthlyAiCredits");
return formatMonthlyCredits(plan);
});
const headerPlanBlurb = $derived.by(() => {
if (!planAssigned || !plan) {
return i18n.t("billing.header.noPlan");
}
if (freePlan) return i18n.t("billing.header.free");
if (enterprise) return i18n.t("billing.header.enterprise");
if (payg) return i18n.t("billing.header.payg");
return i18n.t("billing.header.remaining", { remaining: remainingLabel });
});
const maxProducts = $derived(
typeof credits?.max_products === "number"
? credits.max_products
: typeof plan?.max_products === "number"
? plan.max_products
: plan?.max_products === null
? null
: undefined
);
const showPortal =
$derived(
Boolean(stripe && (stripe.has_customer || stripe.has_subscription || stripe.mock))
);
function formatContractDate(value: string | Date | null | undefined): string {
if (!value) return i18n.t("billing.na");
const d = value instanceof Date ? value : new Date(value);
if (Number.isNaN(d.getTime())) return i18n.t("billing.na");
return formatDate(d);
}
async function loadUsage(range: DateRangeOption) {
usageLoading = true;
dateRangeOption = range;
try {
usage = await api<UsageSummary>(`/api/billing/usage?range=${range}`);
} catch (err) {
error = failureMessage(err, i18n.t("billing.usageLoadFailed"));
} finally {
usageLoading = false;
}
}
async function submitAddCredits() {
const amount = Number(creditAmount);
if (!amount || amount <= 0) {
error = i18n.t("flash.billing.invalidAmount");
return;
}
if (!companyId) {
error = i18n.t("flash.billing.companyNotFound");
return;
}
addingCredits = true;
error = "";
success = "";
try {
await api("/api/admin/credits", {
method: "POST",
body: { company_id: companyId, amount }
});
success = i18n.t("flash.billing.creditsAdded", { amount: formatCredits(amount) });
addCreditsOpen = false;
credits = await api<CreditBalance>("/api/billing/credits");
await loadUsage(dateRangeOption);
} catch (err) {
error =
err instanceof ApiError
? err.message
: i18n.t("billing.addCreditsFailed");
} finally {
addingCredits = false;
}
}
function openAddCredits() {
error = "";
success = "";
creditAmount = "1000";
addCreditsOpen = true;
}
async function upgradeTo(planKey: string) {
checkoutBusy = true;
error = "";
try {
const result = await startCheckout(planKey, "monthly");
if (result.mock && result.applied) {
success = result.message ?? i18n.t("billing.planApplied");
credits = await api<CreditBalance>("/api/billing/credits");
stripe = await fetchStripeStatus().catch(() => stripe);
}
redirectToCheckout(result);
} catch (err) {
error = failureMessage(err, i18n.t("billing.checkoutFailed"));
} finally {
checkoutBusy = false;
}
}
async function buyCreditPack(packId: string) {
packCheckoutBusy = packId;
error = "";
try {
const result = await startCreditPackCheckout(packId);
if (result.mock && result.applied) {
success = result.message ?? i18n.t("billing.checkoutComplete");
credits = await api<CreditBalance>("/api/billing/credits");
stripe = await fetchStripeStatus().catch(() => stripe);
}
redirectToCheckout(result);
} catch (err) {
error = failureMessage(err, i18n.t("billing.packCheckoutFailed"));
} finally {
packCheckoutBusy = null;
}
}
async function manageSubscription() {
portalBusy = true;
error = "";
try {
const result = await openBillingPortal();
if (result.url) window.location.assign(result.url);
} catch (err) {
error = failureMessage(err, i18n.t("billing.portalFailed"));
} finally {
portalBusy = false;
}
}
</script>
{#if loading}
<div class="flex justify-center py-16">
<Spinner label={i18n.t("common.loading")} />
</div>
{:else}
<div class="mx-auto max-w-5xl space-y-6" data-tour="billing-page">
<div class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div class="min-w-0">
<h1 class="text-2xl font-bold tracking-tight sm:text-3xl">{i18n.t("billing.title")}</h1>
<p class="mt-1 text-sm text-muted-foreground">
{#if planAssigned && plan}
<span class="font-medium text-foreground">{planName}</span>
· {headerPlanBlurb}
{:else}
{headerPlanBlurb}
{/if}
</p>
</div>
<div class="flex flex-wrap gap-2">
{#if canManageBilling}
<a href="/plans" class={buttonClasses("outline", "default", "")}>{i18n.t("billing.comparePlans")}</a>
{#if showPortal}
<Button variant="outline" loading={portalBusy} onclick={() => void manageSubscription()}>
{i18n.t("billing.managePayment")}
</Button>
{/if}
{:else}
<a href={upgradeCta.primaryHref} class={buttonClasses("outline", "default", "")}>
{upgradeCta.primaryLabel}
</a>
{/if}
{#if isPlatformAdmin}
<Button onclick={openAddCredits}>
<Wallet class="mr-2 h-4 w-4" />
{i18n.t("billing.addCredits")}
</Button>
{/if}
</div>
</div>
<Alert message={error} />
<Alert tone="success" message={success} />
{#if recovery}
<UpgradeBanner
tone={recovery.tone}
title={recovery.title}
message={recovery.message}
primaryHref={recovery.primaryHref}
primaryLabel={recovery.primaryLabel}
showSales={recovery.showSales}
primaryOnClick={
recovery.openPortal && canManageBilling
? () => void manageSubscription()
: undefined
}
/>
{:else if freePlan}
<UpgradeBanner
tone="info"
title={i18n.t("billing.freeBannerTitle")}
message={withUpgradeHint(
i18n.t("billing.freeBannerMessage"),
upgradeCta
)}
primaryHref={upgradeCta.primaryHref}
primaryLabel={canManageBilling ? i18n.t("billing.comparePlans") : upgradeCta.primaryLabel}
showSales={upgradeCta.showSales}
/>
{:else if outOfCredits || atProductLimit}
<UpgradeBanner
tone="danger"
title={outOfCredits ? i18n.t("billing.outOfCreditsTitle") : i18n.t("billing.productLimitTitle")}
message={withUpgradeHint(
outOfCredits
? i18n.t("billing.outOfCreditsMessage")
: i18n.t("billing.productLimitMessage"),
upgradeCta
)}
primaryHref={upgradeCta.primaryHref}
primaryLabel={upgradeCta.primaryLabel}
showSales={upgradeCta.showSales}
/>
{:else if lowCredits}
<UpgradeBanner
tone="warning"
title={i18n.t("billing.lowCreditsTitle")}
message={withUpgradeHint(
i18n.t("billing.lowCreditsMessage", { remaining: remainingLabel, plan: planName }),
upgradeCta
)}
primaryHref={upgradeCta.primaryHref}
primaryLabel={canManageBilling ? i18n.t("billing.comparePlans") : upgradeCta.primaryLabel}
showSales={upgradeCta.showSales}
/>
{/if}
{#if credits}
<div class="grid gap-4 md:grid-cols-2">
<Card>
<CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle class="text-sm font-medium">{i18n.t("billing.currentPlan")}</CardTitle>
<FileText class="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent class="space-y-1">
<div class="text-2xl font-bold">{planName}</div>
<p class="text-xs text-muted-foreground">{planBillingLabel}</p>
<p class="text-xs text-muted-foreground">
{formatSkuUsage(credits?.product_count, maxProducts ?? plan?.max_products, plan)}
</p>
{#if isContractExpiringSoon && !enterprise && !payg}
<p class="text-xs font-medium text-amber-600">
{i18n.t("billing.periodEnds", { date: formatContractDate(usage?.cycle_end ?? plan?.next_billing_date) })}
</p>
{:else if payg}
<p class="text-xs text-muted-foreground">{i18n.t("billing.openEndedContract")}</p>
{/if}
</CardContent>
</Card>
<Card>
<CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle class="text-sm font-medium">
{payg ? i18n.t("billing.creditWallet") : i18n.t("billing.creditsRemaining")}
</CardTitle>
<CreditCard class="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent class="space-y-1">
{#if enterprise}
<div class="text-2xl font-bold">{remainingLabel}</div>
<p class="text-xs text-muted-foreground">{i18n.t("billing.enterpriseCapacity")}</p>
{:else if payg}
<div class="text-2xl font-bold">{i18n.t("billing.payAsYouGo")}</div>
<p class="text-xs text-muted-foreground">
{i18n.t("billing.paygWallet", {
remaining: formatCredits(remaining ?? 0)
})}
</p>
{:else if freePlan}
<div class="text-2xl font-bold">{remainingLabel}</div>
<p class="text-xs text-muted-foreground">
{canUseAI ? i18n.t("billing.trialLeftover") : i18n.t("billing.aiLockedFree")}
</p>
{:else}
<div class="text-2xl font-bold">{remainingLabel}</div>
<p class="text-xs text-muted-foreground">
{i18n.t("billing.usedOf", {
used: formatCredits(walletUsed),
total: formatCredits(usage?.credits_total ?? credits.total_credits)
})}
</p>
{/if}
</CardContent>
</Card>
</div>
{:else}
<div class="rounded-lg border border-dashed border-border bg-card px-4 py-8 text-center">
<p class="text-sm font-medium text-foreground">{i18n.t("billing.noBalanceTitle")}</p>
<p class="mt-1 text-sm text-muted-foreground">
{i18n.t("billing.noBalanceBody")}
</p>
<div class="mt-4 flex flex-wrap justify-center gap-2">
{#if canManageBilling}
<a href="/plans" class={buttonClasses("default", "sm", "")}>{i18n.t("billing.comparePlans")}</a>
{:else}
<a href={upgradeCta.primaryHref} class={buttonClasses("outline", "sm", "")}>
{upgradeCta.primaryLabel}
</a>
{/if}
</div>
</div>
{/if}
{#if showQuickUpgrade}
<section class="rounded-lg border border-border bg-card px-4 py-4">
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<p class="text-sm font-medium text-foreground">{i18n.t("billing.needCapacity")}</p>
<p class="text-xs text-muted-foreground">
{i18n.t("billing.selfServeUpgrade")}
{#if stripe?.configured && !stripe?.mock}
{i18n.t("billing.viaStripe")}
{/if}.
</p>
</div>
<div class="flex flex-wrap gap-2">
{#if nextUpgradePlan}
<Button size="sm" loading={checkoutBusy} onclick={() => void upgradeTo(nextUpgradePlan)}>
{i18n.t("plans.cta.upgradeTo", { name: planCheckoutDisplayName(nextUpgradePlan) })}
</Button>
{/if}
<a href="/plans" class={buttonClasses("outline", "sm", "")}>{i18n.t("billing.comparePlans")}</a>
</div>
</div>
</section>
{:else if !canManageBilling && (freePlan || outOfCredits || atProductLimit || lowCredits)}
<section class="rounded-lg border border-border bg-muted/30 px-4 py-4">
<p class="text-sm font-medium text-foreground">{i18n.t("billing.needCapacity")}</p>
<p class="mt-1 text-sm text-muted-foreground">
{upgradeCta.memberHint ?? i18n.t("billing.askAdminPlan")}
</p>
<div class="mt-3">
<a href={upgradeCta.primaryHref} class={buttonClasses("outline", "sm", "")}>
{upgradeCta.primaryLabel}
</a>
</div>
</section>
{/if}
{#if canManageBilling && !enterprise && planAssigned}
<section class="space-y-3 rounded-lg border border-border bg-card px-4 py-4">
<div>
<h2 class="text-base font-semibold tracking-tight">{i18n.t("billing.buyCreditPacks")}</h2>
<p class="mt-1 text-xs text-muted-foreground">{i18n.t("billing.buyCreditPacksHint")}</p>
</div>
<div class="grid gap-3 sm:grid-cols-2">
{#each CREDIT_PACKS as pack (pack.id)}
<div class="flex flex-col gap-2 rounded-md border border-border px-3 py-3">
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<p class="text-sm font-medium text-foreground">{i18n.t(pack.nameKey)}</p>
<p class="text-xs text-muted-foreground">{i18n.t(pack.descriptionKey)}</p>
</div>
<p class="shrink-0 text-sm font-semibold tabular-nums">${pack.priceUSD}</p>
</div>
<p class="text-xs text-muted-foreground">
{i18n.t("billing.packCredits", { credits: pack.credits.toLocaleString() })}
· {i18n.t("billing.packApproxProducts", { count: pack.aiProducts.toLocaleString() })}
</p>
<Button
size="sm"
variant="outline"
class="w-full"
loading={packCheckoutBusy === pack.id}
disabled={packCheckoutBusy !== null}
onclick={() => void buyCreditPack(pack.id)}
>
{i18n.t("billing.buyPack")}
</Button>
</div>
{/each}
</div>
</section>
{/if}
<section class="space-y-3">
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<h2 class="text-base font-semibold tracking-tight">{i18n.t("billing.usage")}</h2>
<p class="text-xs text-muted-foreground">
{i18n.t("billing.productsProcessed", { count: (usage?.products_processed ?? 0).toLocaleString(), range: rangeLabel })}
{#if usageLoading}
· {i18n.t("billing.updating")}
{/if}
</p>
</div>
<Select
class="w-[180px]"
bind:value={dateRangeOption}
onchange={(e) => {
const next = (e.currentTarget as HTMLSelectElement).value as DateRangeOption;
void loadUsage(next);
}}
>
<option value="7d">{i18n.t("billing.rangeOpt.7d")}</option>
<option value="30d">{i18n.t("billing.rangeOpt.30d")}</option>
{#if usage?.cycle_start || plan?.next_billing_date}
<option value="cycle">{i18n.t("billing.rangeOpt.cycle")}</option>
{/if}
<option value="all">{i18n.t("billing.rangeOpt.all")}</option>
</Select>
</div>
<Card>
<CardHeader class="pb-2">
<CardTitle class="text-sm font-medium">{i18n.t("billing.productsByDay")}</CardTitle>
<CardDescription>
{#if isPlatformAdmin}
{i18n.t("billing.chartAmber", { range: rangeLabel })}
{:else}
{i18n.t("billing.chartRange", { range: rangeLabel })}
{/if}
</CardDescription>
</CardHeader>
<CardContent>
{#if !hasCatalogActivity}
<div class="py-8 text-center">
<p class="text-sm font-medium text-foreground">{i18n.t("billing.nothingToChartTitle")}</p>
<p class="mt-1 text-sm text-muted-foreground">
{i18n.t("billing.nothingToChartBody")}
</p>
</div>
{:else if dateRangeOption === "all"}
<div class="py-6 text-center text-sm text-muted-foreground">
{i18n.t("billing.dailyChartsHint")}
</div>
{:else if !hasSeries}
<div class="py-8 text-center">
<p class="text-sm font-medium text-foreground">{i18n.t("billing.noNewProducts", { range: rangeLabel })}</p>
<p class="mt-1 text-sm text-muted-foreground">
{i18n.t("billing.catalogOverall", { count: catalogProductCount.toLocaleString() })}
</p>
</div>
{:else}
<AdminSeriesChart
points={chartPoints}
primaryLabel={i18n.t("billing.chartProducts")}
secondaryLabel={isPlatformAdmin ? i18n.t("billing.chartTokens") : undefined}
emptyMessage={i18n.t("billing.chartEmpty")}
/>
{/if}
{#if isPlatformAdmin}
<p class="mt-3 text-xs text-muted-foreground">
{i18n.t("billing.adminStats", {
tokens: (usage?.tokens ?? 0).toLocaleString(),
jobs: (usage?.jobs_total ?? 0).toLocaleString(),
input: (usage?.feeds_input ?? 0).toLocaleString(),
export: (usage?.feeds_export ?? 0).toLocaleString()
})}
</p>
{/if}
</CardContent>
</Card>
</section>
<details class="rounded-lg border border-border bg-card px-4 py-3">
<summary class="cursor-pointer text-sm font-medium text-foreground">
{i18n.t("billing.whatUsesCredits")}
</summary>
<ul class="mt-3 grid gap-2 sm:grid-cols-2">
{#each CREDIT_USAGE_ITEMS as item (item.labelKey)}
<li class="rounded-md border border-border/60 px-3 py-2">
<div class="flex items-center gap-2">
{#if item.burns}
<Badge variant="secondary">{i18n.t("billing.burnsCredits")}</Badge>
{:else}
<Badge variant="outline">{i18n.t("billing.noCreditCost")}</Badge>
{/if}
<span class="text-sm font-medium">{i18n.t(item.labelKey)}</span>
</div>
<p class="mt-1 text-xs text-muted-foreground">{i18n.t(item.detailKey)}</p>
</li>
{/each}
</ul>
</details>
<div class="flex flex-wrap items-center justify-between gap-2 text-sm text-muted-foreground">
<a
href="/pricing"
class="inline-flex items-center font-medium text-foreground underline-offset-4 hover:underline"
>
{i18n.t("billing.publicPricing")}
<ExternalLink class="ml-1 h-3.5 w-3.5" />
</a>
{#if canManageBilling}
<a href="/plans" class="font-medium text-foreground underline-offset-4 hover:underline">
{i18n.t("billing.managePlanOnPlans")}
</a>
{/if}
</div>
</div>
{/if}
{#if isPlatformAdmin}
<Dialog
bind:open={addCreditsOpen}
title={i18n.t("billing.addCreditsTitle")}
description={i18n.t("billing.addCreditsDescription")}
class="sm:max-w-md sm:min-w-0"
>
<div class="flex flex-col gap-4 py-4">
<div class="flex flex-col gap-2">
<Label for="credit-amount">{i18n.t("billing.creditAmount")}</Label>
<Input id="credit-amount" type="number" min="100" bind:value={creditAmount} />
</div>
</div>
{#snippet footer()}
<Button variant="outline" disabled={addingCredits} onclick={() => (addCreditsOpen = false)}>
{i18n.t("common.cancel")}
</Button>
<Button loading={addingCredits} onclick={submitAddCredits}>
{addingCredits ? i18n.t("billing.addingCredits") : i18n.t("billing.addCredits")}
</Button>
{/snippet}
</Dialog>
{/if}