feat: enhance billing and credits management with new components and improved layout

This commit is contained in:
javayhu 2025-07-12 19:29:21 +08:00
parent b4e8585929
commit ee341522f5
7 changed files with 397 additions and 307 deletions

View File

@ -587,9 +587,12 @@
"description": "Manage your credits",
"balance": {
"title": "Credit Balance",
"description": "Your credit balance",
"credits": "Credits",
"creditsDescription": "You have {credits} credits",
"creditsExpired": "Credits expired"
"creditsExpired": "Credits expired",
"creditsAdded": "Credits have been added to your account",
"viewTransactions": "View Transactions"
},
"packages": {
"balance": "Credit Balance",

View File

@ -90,10 +90,10 @@ export const createCreditCheckoutSession = actionClient
// Create checkout session with credit-specific URLs
const successUrl = getUrlWithLocale(
`${Routes.SettingsCredits}?session_id={CHECKOUT_SESSION_ID}`,
`${Routes.SettingsBilling}?session_id={CHECKOUT_SESSION_ID}`,
locale
);
const cancelUrl = getUrlWithLocale(Routes.SettingsCredits, locale);
const cancelUrl = getUrlWithLocale(Routes.SettingsBilling, locale);
const params: CreateCreditCheckoutParams = {
packageId,

View File

@ -1,5 +1,23 @@
import BillingCard from '@/components/settings/billing/billing-card';
import CreditsBalanceCard from '@/components/settings/billing/credits-balance-card';
import { CreditPackages } from '@/components/settings/credits/credit-packages';
import { websiteConfig } from '@/config/website';
export default function BillingPage() {
return <BillingCard />;
return (
<div className="space-y-8">
{/* Billing and Credits Balance Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
<BillingCard />
{websiteConfig.credits.enableCredits && <CreditsBalanceCard />}
</div>
{/* Credit Packages */}
{websiteConfig.credits.enableCredits && (
<div className="w-full">
<CreditPackages />
</div>
)}
</div>
);
}

View File

@ -1,29 +1,16 @@
import { CreditPackages } from '@/components/settings/credits/credit-packages';
import { CreditTransactionsPageClient } from '@/components/settings/credits/credit-transactions-page';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useTranslations } from 'next-intl';
import { websiteConfig } from '@/config/website';
import { Routes } from '@/routes';
import { redirect } from 'next/navigation';
/**
* Credits page, show credit transactions
*/
export default function CreditsPage() {
const t = useTranslations('Dashboard.settings.credits');
// If credits are disabled, redirect to billing page
if (!websiteConfig.credits.enableCredits) {
redirect(Routes.SettingsBilling);
}
return (
<Tabs defaultValue="balance" className="">
<TabsList className="">
<TabsTrigger value="balance" className="flex items-center gap-2 cursor-pointer">
{t('tabs.balance')}
</TabsTrigger>
<TabsTrigger value="transactions" className="flex items-center gap-2 cursor-pointer">
{t('tabs.transactions')}
</TabsTrigger>
</TabsList>
<TabsContent value="balance" className="space-y-6 py-4">
<CreditPackages />
</TabsContent>
<TabsContent value="transactions" className="space-y-6 py-4">
<CreditTransactionsPageClient />
</TabsContent>
</Tabs>
);
return <CreditTransactionsPageClient />;
}

View File

@ -90,87 +90,81 @@ export default function BillingCard() {
// Render loading skeleton
if (isPageLoading) {
return (
<div className="grid md:grid-cols-2 gap-8">
<Card
className={cn(
'w-full max-w-lg md:max-w-xl overflow-hidden pt-6 pb-0 flex flex-col'
)}
>
<CardHeader>
<CardTitle>{t('currentPlan.title')}</CardTitle>
<CardDescription>{t('currentPlan.description')}</CardDescription>
</CardHeader>
<CardContent className="space-y-4 flex-1">
<div className="space-y-3">
<Skeleton className="h-6 w-1/2" />
<Skeleton className="h-6 w-4/5" />
<Skeleton className="h-6 w-4/5" />
</div>
</CardContent>
<CardFooter className="mt-2 px-6 py-4 flex justify-end items-center bg-background rounded-none">
<Skeleton className="h-10 w-4/5" />
</CardFooter>
</Card>
</div>
<Card
className={cn(
'w-full max-w-lg md:max-w-xl overflow-hidden pt-6 pb-0 flex flex-col'
)}
>
<CardHeader>
<CardTitle>{t('currentPlan.title')}</CardTitle>
<CardDescription>{t('currentPlan.description')}</CardDescription>
</CardHeader>
<CardContent className="space-y-4 flex-1">
<div className="space-y-3">
<Skeleton className="h-6 w-1/2" />
<Skeleton className="h-6 w-4/5" />
<Skeleton className="h-6 w-4/5" />
</div>
</CardContent>
<CardFooter className="mt-2 px-6 py-4 flex justify-end items-center bg-background rounded-none">
<Skeleton className="h-10 w-4/5" />
</CardFooter>
</Card>
);
}
// Render error state
if (loadPaymentError) {
return (
<div className="grid md:grid-cols-2 gap-8">
<Card
className={cn(
'w-full max-w-lg md:max-w-xl overflow-hidden pt-6 pb-0 flex flex-col'
)}
>
<CardHeader>
<CardTitle>{t('currentPlan.title')}</CardTitle>
<CardDescription>{t('currentPlan.description')}</CardDescription>
</CardHeader>
<CardContent className="space-y-4 flex-1">
<div className="text-destructive text-sm">{loadPaymentError}</div>
</CardContent>
<CardFooter className="mt-2 px-6 py-4 flex justify-end items-center bg-background rounded-none">
<Button
variant="outline"
className="cursor-pointer"
onClick={() => refetch()}
>
<RefreshCwIcon className="size-4 mr-1" />
{t('retry')}
</Button>
</CardFooter>
</Card>
</div>
<Card
className={cn(
'w-full max-w-lg md:max-w-xl overflow-hidden pt-6 pb-0 flex flex-col'
)}
>
<CardHeader>
<CardTitle>{t('currentPlan.title')}</CardTitle>
<CardDescription>{t('currentPlan.description')}</CardDescription>
</CardHeader>
<CardContent className="space-y-4 flex-1">
<div className="text-destructive text-sm">{loadPaymentError}</div>
</CardContent>
<CardFooter className="mt-2 px-6 py-4 flex justify-end items-center bg-background rounded-none">
<Button
variant="outline"
className="cursor-pointer"
onClick={() => refetch()}
>
<RefreshCwIcon className="size-4 mr-1" />
{t('retry')}
</Button>
</CardFooter>
</Card>
);
}
// currentPlanFromStore maybe null, so we need to check if it is null
if (!currentPlanFromStore) {
return (
<div className="grid md:grid-cols-2 gap-8">
<Card
className={cn(
'w-full max-w-lg md:max-w-xl overflow-hidden pt-6 pb-0 flex flex-col'
)}
>
<CardHeader>
<CardTitle>{t('currentPlan.title')}</CardTitle>
<CardDescription>{t('currentPlan.description')}</CardDescription>
</CardHeader>
<CardContent>
<div className="text-sm text-muted-foreground">
{t('currentPlan.noPlan')}
</div>
</CardContent>
<CardFooter className="mt-2 px-6 py-4 flex justify-end items-center bg-muted rounded-none">
<Button variant="default" className="cursor-pointer" asChild>
<LocaleLink href={Routes.Pricing}>{t('upgradePlan')}</LocaleLink>
</Button>
</CardFooter>
</Card>
</div>
<Card
className={cn(
'w-full max-w-lg md:max-w-xl overflow-hidden pt-6 pb-0 flex flex-col'
)}
>
<CardHeader>
<CardTitle>{t('currentPlan.title')}</CardTitle>
<CardDescription>{t('currentPlan.description')}</CardDescription>
</CardHeader>
<CardContent>
<div className="text-sm text-muted-foreground">
{t('currentPlan.noPlan')}
</div>
</CardContent>
<CardFooter className="mt-2 px-6 py-4 flex justify-end items-center bg-muted rounded-none">
<Button variant="default" className="cursor-pointer" asChild>
<LocaleLink href={Routes.Pricing}>{t('upgradePlan')}</LocaleLink>
</Button>
</CardFooter>
</Card>
);
}
@ -179,98 +173,96 @@ export default function BillingCard() {
// console.log('billing card, currentUser', currentUser);
return (
<div className="grid md:grid-cols-2 gap-8">
<Card
className={cn(
'w-full max-w-lg md:max-w-xl overflow-hidden pt-6 pb-0 flex flex-col'
)}
>
<CardHeader>
<CardTitle className="text-lg font-semibold">
{t('currentPlan.title')}
</CardTitle>
<CardDescription>{t('currentPlan.description')}</CardDescription>
</CardHeader>
<CardContent className="space-y-4 flex-1">
{/* Plan name and status */}
<div className="flex items-center justify-between">
<div className="text-3xl font-medium">{currentPlan?.name}</div>
{subscription && (
<Badge variant="outline">
{subscription?.status === 'trialing'
? t('status.trial')
: subscription?.status === 'active'
? t('status.active')
: ''}
</Badge>
)}
<Card
className={cn(
'w-full max-w-lg md:max-w-xl overflow-hidden pt-6 pb-0 flex flex-col'
)}
>
<CardHeader>
<CardTitle className="text-lg font-semibold">
{t('currentPlan.title')}
</CardTitle>
<CardDescription>{t('currentPlan.description')}</CardDescription>
</CardHeader>
<CardContent className="space-y-4 flex-1">
{/* Plan name and status */}
<div className="flex items-center justify-between">
<div className="text-3xl font-medium">{currentPlan?.name}</div>
{subscription && (
<Badge variant="outline">
{subscription?.status === 'trialing'
? t('status.trial')
: subscription?.status === 'active'
? t('status.active')
: ''}
</Badge>
)}
</div>
{/* Free plan message */}
{isFreePlan && (
<div className="text-sm text-muted-foreground">
{t('freePlanMessage')}
</div>
)}
{/* Free plan message */}
{isFreePlan && (
<div className="text-sm text-muted-foreground">
{t('freePlanMessage')}
{/* Lifetime plan message */}
{isLifetimeMember && (
<div className="text-sm text-muted-foreground">
{t('lifetimeMessage')}
</div>
)}
{/* Subscription plan message */}
{subscription && currentPrice && (
<div className="text-sm text-muted-foreground space-y-2">
<div>
{t('price')}{' '}
{formatPrice(currentPrice.amount, currentPrice.currency)} /{' '}
{currentPrice.interval === PlanIntervals.MONTH
? t('interval.month')
: currentPrice.interval === PlanIntervals.YEAR
? t('interval.year')
: t('interval.oneTime')}
</div>
)}
{/* Lifetime plan message */}
{isLifetimeMember && (
<div className="text-sm text-muted-foreground">
{t('lifetimeMessage')}
</div>
)}
{/* Subscription plan message */}
{subscription && currentPrice && (
<div className="text-sm text-muted-foreground space-y-2">
{nextBillingDate && (
<div>
{t('price')}{' '}
{formatPrice(currentPrice.amount, currentPrice.currency)} /{' '}
{currentPrice.interval === PlanIntervals.MONTH
? t('interval.month')
: currentPrice.interval === PlanIntervals.YEAR
? t('interval.year')
: t('interval.oneTime')}
{t('nextBillingDate')} {nextBillingDate}
</div>
)}
{nextBillingDate && (
<div>
{t('nextBillingDate')} {nextBillingDate}
{subscription.status === 'trialing' &&
subscription.currentPeriodEnd && (
<div className="text-amber-500">
{t('trialEnds')} {formatDate(subscription.currentPeriodEnd)}
</div>
)}
</div>
)}
</CardContent>
<CardFooter className="mt-2 px-6 py-4 flex justify-end items-center bg-background rounded-none">
{/* user is on free plan, show upgrade plan button */}
{isFreePlan && (
<Button variant="default" className="cursor-pointer" asChild>
<LocaleLink href={Routes.Pricing}>{t('upgradePlan')}</LocaleLink>
</Button>
)}
{subscription.status === 'trialing' &&
subscription.currentPeriodEnd && (
<div className="text-amber-500">
{t('trialEnds')} {formatDate(subscription.currentPeriodEnd)}
</div>
)}
</div>
)}
</CardContent>
<CardFooter className="mt-2 px-6 py-4 flex justify-end items-center bg-background rounded-none">
{/* user is on free plan, show upgrade plan button */}
{isFreePlan && (
<Button variant="default" className="cursor-pointer" asChild>
<LocaleLink href={Routes.Pricing}>{t('upgradePlan')}</LocaleLink>
</Button>
)}
{/* user is lifetime member, show manage billing button */}
{isLifetimeMember && currentUser && (
<CustomerPortalButton userId={currentUser.id} className="">
{t('manageBilling')}
</CustomerPortalButton>
)}
{/* user is lifetime member, show manage billing button */}
{isLifetimeMember && currentUser && (
<CustomerPortalButton userId={currentUser.id} className="">
{t('manageBilling')}
</CustomerPortalButton>
)}
{/* user has subscription, show manage subscription button */}
{subscription && currentUser && (
<CustomerPortalButton userId={currentUser.id} className="">
{t('manageSubscription')}
</CustomerPortalButton>
)}
</CardFooter>
</Card>
</div>
{/* user has subscription, show manage subscription button */}
{subscription && currentUser && (
<CustomerPortalButton userId={currentUser.id} className="">
{t('manageSubscription')}
</CustomerPortalButton>
)}
</CardFooter>
</Card>
);
}

View File

@ -0,0 +1,143 @@
'use client';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { websiteConfig } from '@/config/website';
import { useCredits } from '@/hooks/use-credits';
import { LocaleLink, useLocaleRouter } from '@/i18n/navigation';
import { cn } from '@/lib/utils';
import { Routes } from '@/routes';
import { CoinsIcon } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
import { useEffect, useRef } from 'react';
import { toast } from 'sonner';
export default function CreditsBalanceCard() {
const t = useTranslations('Dashboard.settings.credits.balance');
const searchParams = useSearchParams();
const localeRouter = useLocaleRouter();
const hasHandledSession = useRef(false);
// Use the credits hook to get balance
const { balance, isLoading, error, refresh } = useCredits();
// Don't render if credits are disabled
if (!websiteConfig.credits.enableCredits) {
return null;
}
// Check for payment success and show success message
useEffect(() => {
const sessionId = searchParams.get('session_id');
if (sessionId && !hasHandledSession.current) {
hasHandledSession.current = true;
// Show success toast (delayed to avoid React lifecycle conflicts)
setTimeout(() => {
toast.success(t('creditsAdded'));
}, 0);
// Refresh credits data to show updated balance
refresh();
// Clean up URL parameters
const url = new URL(window.location.href);
url.searchParams.delete('session_id');
localeRouter.replace(Routes.SettingsBilling + url.search);
}
}, [searchParams, localeRouter, refresh]);
// Render loading skeleton
if (isLoading) {
return (
<Card
className={cn(
'w-full max-w-lg md:max-w-xl overflow-hidden pt-6 pb-0 flex flex-col'
)}
>
<CardHeader>
<CardTitle>{t('title')}</CardTitle>
<CardDescription>{t('description')}</CardDescription>
</CardHeader>
<CardContent className="space-y-4 flex-1">
<div className="space-y-3">
<Skeleton className="h-6 w-1/2" />
<Skeleton className="h-6 w-4/5" />
</div>
</CardContent>
<CardFooter className="mt-2 px-6 py-4 flex justify-end items-center bg-background rounded-none">
<Skeleton className="h-10 w-4/5" />
</CardFooter>
</Card>
);
}
// Render error state
if (error) {
return (
<Card
className={cn(
'w-full max-w-lg md:max-w-xl overflow-hidden pt-6 pb-0 flex flex-col'
)}
>
<CardHeader>
<CardTitle>{t('title')}</CardTitle>
<CardDescription>{t('description')}</CardDescription>
</CardHeader>
<CardContent className="space-y-4 flex-1">
<div className="text-destructive text-sm">{error}</div>
</CardContent>
<CardFooter className="mt-2 px-6 py-4 flex justify-end items-center bg-background rounded-none">
<Button variant="outline" className="cursor-pointer" asChild>
<LocaleLink href={Routes.SettingsCredits}>
{t('viewTransactions')}
</LocaleLink>
</Button>
</CardFooter>
</Card>
);
}
return (
<Card
className={cn(
'w-full max-w-lg md:max-w-xl overflow-hidden pt-6 pb-0 flex flex-col'
)}
>
<CardHeader>
<CardTitle className="text-lg font-semibold">{t('title')}</CardTitle>
<CardDescription>{t('description')}</CardDescription>
</CardHeader>
<CardContent className="space-y-4 flex-1">
{/* Credits balance display */}
<div className="flex items-center justify-between">
<div className="flex items-center space-x-2">
<CoinsIcon className="h-6 w-6 text-muted-foreground" />
<div className="text-3xl font-medium">
{balance.toLocaleString()}
</div>
</div>
{/* <Badge variant="outline">{t('available')}</Badge> */}
</div>
{/* Balance information */}
{/* <div className="text-sm text-muted-foreground">{t('message')}</div> */}
</CardContent>
<CardFooter className="mt-2 px-6 py-4 flex justify-end items-center bg-background rounded-none">
<Button variant="default" className="cursor-pointer" asChild>
<LocaleLink href={Routes.SettingsCredits}>
{t('viewTransactions')}
</LocaleLink>
</Button>
</CardFooter>
</Card>
);
}

View File

@ -9,17 +9,12 @@ import {
CardTitle,
} from '@/components/ui/card';
import { getCreditPackages } from '@/config/credits-config';
import { useCredits } from '@/hooks/use-credits';
import { websiteConfig } from '@/config/website';
import { useCurrentUser } from '@/hooks/use-current-user';
import { useLocaleRouter } from '@/i18n/navigation';
import { formatPrice } from '@/lib/formatter';
import { cn } from '@/lib/utils';
import { Routes } from '@/routes';
import { CircleCheckBigIcon, CoinsIcon, Loader2Icon } from 'lucide-react';
import { CircleCheckBigIcon, CoinsIcon } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
import { useEffect, useRef } from 'react';
import { toast } from 'sonner';
import { CreditCheckoutButton } from './credit-checkout-button';
/**
@ -28,137 +23,89 @@ import { CreditCheckoutButton } from './credit-checkout-button';
*/
export function CreditPackages() {
const t = useTranslations('Dashboard.settings.credits.packages');
const searchParams = useSearchParams();
const localeRouter = useLocaleRouter();
const hasHandledSession = useRef(false);
// Use the new useCredits hook
const { balance, isLoading, refresh } = useCredits();
// Get current user
const currentUser = useCurrentUser();
// Don't render if credits are disabled
if (!websiteConfig.credits.enableCredits) {
return null;
}
// show only enabled packages
const creditPackages = Object.values(getCreditPackages()).filter(
(pkg) => !pkg.disabled && pkg.price.priceId
);
// Check for payment success and show success message
useEffect(() => {
const sessionId = searchParams.get('session_id');
if (sessionId && !hasHandledSession.current) {
hasHandledSession.current = true;
// Show success toast (delayed to avoid React lifecycle conflicts)
setTimeout(() => {
toast.success(t('creditsAdded'));
}, 0);
// Refresh credits data to show updated balance
refresh();
// Clean up URL parameters
const url = new URL(window.location.href);
url.searchParams.delete('session_id');
// Use Routes.SettingsCredits + url.search to properly handle locale routing
localeRouter.replace(Routes.SettingsCredits + url.search);
}
}, [searchParams, localeRouter, refresh]);
return (
<div className="space-y-6">
<Card className="w-full">
<CardHeader className="flex flex-row items-center justify-between space-y-0">
<CardTitle className="text-lg font-semibold">
{t('balance')}
</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-col gap-4">
<div className="flex items-center space-x-2">
{/* <CoinsIcon className="h-4 w-4 text-muted-foreground" /> */}
<div>
{isLoading ? (
<Loader2Icon className="h-8 w-8 animate-spin" />
) : (
<div className="text-2xl font-bold">
{balance.toLocaleString()}
</div>
)}
</div>
</div>
</div>
</CardContent>
</Card>
<Card className="w-full">
<CardHeader>
<CardTitle className="text-lg font-semibold">{t('title')}</CardTitle>
<CardDescription className="text-sm text-muted-foreground">
{t('description')}
</CardDescription>
</CardHeader>
<CardContent>
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
{creditPackages.map((creditPackage) => (
<Card
key={creditPackage.id}
className={cn(
`relative ${creditPackage.popular ? 'border-primary' : ''}`,
'shadow-none border-1 border-border'
)}
>
{creditPackage.popular && (
<div className="absolute -top-3.5 left-1/2 transform -translate-x-1/2">
<Badge
variant="default"
className="bg-primary text-primary-foreground"
>
{t('popular')}
</Badge>
</div>
)}
<CardContent className="space-y-4">
{/* Price and Credits - Left/Right Layout */}
<div className="flex items-center justify-between py-2">
<div className="text-left">
<div className="text-2xl font-semibold flex items-center gap-2">
<CoinsIcon className="h-4 w-4 text-muted-foreground" />
{creditPackage.credits.toLocaleString()}
</div>
</div>
<div className="text-right">
<div className="text-3xl font-bold text-primary">
{formatPrice(
creditPackage.price.amount,
creditPackage.price.currency
)}
</div>
</div>
</div>
<div className="text-sm text-muted-foreground text-left py-2 flex items-center gap-2">
<CircleCheckBigIcon className="h-4 w-4 text-green-500" />
{creditPackage.description}
</div>
{/* purchase button using checkout */}
<CreditCheckoutButton
userId={currentUser?.id ?? ''}
packageId={creditPackage.id}
priceId={creditPackage.price.priceId}
className="w-full cursor-pointer mt-2"
variant={creditPackage.popular ? 'default' : 'outline'}
disabled={!creditPackage.price.priceId}
<Card className="w-full">
<CardHeader>
<CardTitle className="text-lg font-semibold">{t('title')}</CardTitle>
<CardDescription className="text-sm text-muted-foreground">
{t('description')}
</CardDescription>
</CardHeader>
<CardContent>
<div className="grid gap-6 md:grid-cols-2 xl:grid-cols-4">
{creditPackages.map((creditPackage) => (
<Card
key={creditPackage.id}
className={cn(
`relative ${creditPackage.popular ? 'border-primary' : ''}`,
'shadow-none border-1 border-border'
)}
>
{creditPackage.popular && (
<div className="absolute -top-3.5 left-1/2 transform -translate-x-1/2">
<Badge
variant="default"
className="bg-primary text-primary-foreground"
>
{t('purchase')}
</CreditCheckoutButton>
</CardContent>
</Card>
))}
</div>
</CardContent>
</Card>
</div>
{t('popular')}
</Badge>
</div>
)}
<CardContent className="space-y-4">
{/* Price and Credits - Left/Right Layout */}
<div className="flex items-center justify-between py-2">
<div className="text-left">
<div className="text-2xl font-semibold flex items-center gap-2">
<CoinsIcon className="h-4 w-4 text-muted-foreground" />
{creditPackage.credits.toLocaleString()}
</div>
</div>
<div className="text-right">
<div className="text-3xl font-bold text-primary">
{formatPrice(
creditPackage.price.amount,
creditPackage.price.currency
)}
</div>
</div>
</div>
<div className="text-sm text-muted-foreground text-left py-2 flex items-center gap-2">
<CircleCheckBigIcon className="h-4 w-4 text-green-500" />
{creditPackage.description}
</div>
{/* purchase button using checkout */}
<CreditCheckoutButton
userId={currentUser?.id ?? ''}
packageId={creditPackage.id}
priceId={creditPackage.price.priceId}
className="w-full cursor-pointer mt-2"
variant={creditPackage.popular ? 'default' : 'outline'}
disabled={!creditPackage.price.priceId}
>
{t('purchase')}
</CreditCheckoutButton>
</CardContent>
</Card>
))}
</div>
</CardContent>
</Card>
);
}