feat: billing UI — balance in header + /billing transactions page
- Header: Coins badge с кредитами, ссылка на /billing - app/billing/page.js: баланс, план, стоимость операций, история транзакций - app/api/billing/balance/route.js, transactions/route.js — прокси к engine - lib/engine.js: getBillingBalance, getTransactions, getBillingPlans, adminCreditUser
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { requireUser } from '@/lib/session';
|
||||
import { engine } from '@/lib/engine';
|
||||
|
||||
export async function GET(req) {
|
||||
const user = await requireUser();
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
try {
|
||||
const data = await engine.getBillingBalance(user.id);
|
||||
return NextResponse.json(data);
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { requireUser } from '@/lib/session';
|
||||
import { engine } from '@/lib/engine';
|
||||
|
||||
export async function GET(req) {
|
||||
const user = await requireUser();
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
const { searchParams } = new URL(req.url);
|
||||
try {
|
||||
const data = await engine.getTransactions(Object.fromEntries(searchParams));
|
||||
return NextResponse.json(data);
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
'use client';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Coins, RefreshCw, TrendingDown, TrendingUp, Loader2, ArrowRight } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
|
||||
const TYPE_LABELS = {
|
||||
spend_image: { label: 'Генерация картинки', sign: '-', color: 'text-red-400' },
|
||||
spend_text_post: { label: 'Генерация поста', sign: '-', color: 'text-red-400' },
|
||||
spend_article: { label: 'Генерация статьи', sign: '-', color: 'text-red-400' },
|
||||
spend_autopublish:{ label: 'Публикация', sign: '-', color: 'text-gray-400' },
|
||||
plan_credit: { label: 'Начисление по тарифу',sign: '+', color: 'text-green-400' },
|
||||
topup: { label: 'Пополнение', sign: '+', color: 'text-green-400' },
|
||||
bonus: { label: 'Бонус', sign: '+', color: 'text-blue-400' },
|
||||
refund: { label: 'Возврат', sign: '+', color: 'text-blue-400' },
|
||||
};
|
||||
|
||||
function fmtDate(s) {
|
||||
const d = new Date(s);
|
||||
return d.toLocaleString('ru-RU', { day:'2-digit', month:'2-digit', hour:'2-digit', minute:'2-digit' });
|
||||
}
|
||||
|
||||
export default function BillingPage() {
|
||||
const [balance, setBalance] = useState(null);
|
||||
const [txs, setTxs] = useState([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [page, setPage] = useState(0);
|
||||
const PER_PAGE = 30;
|
||||
|
||||
async function load(p = 0) {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [balRes, txRes] = await Promise.all([
|
||||
fetch('/api/billing/balance').then(r => r.json()),
|
||||
fetch(`/api/billing/transactions?limit=${PER_PAGE}&offset=${p * PER_PAGE}`).then(r => r.json()),
|
||||
]);
|
||||
setBalance(balRes);
|
||||
setTxs(txRes.transactions || []);
|
||||
setTotal(txRes.total || 0);
|
||||
} catch {}
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
useEffect(() => { load(0); }, []);
|
||||
|
||||
const PLAN_COLORS = { free: 'text-gray-400', starter: 'text-blue-400', pro: 'text-purple-400', business: 'text-yellow-400' };
|
||||
|
||||
return (
|
||||
<main className="max-w-3xl mx-auto p-4 sm:p-6">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-xl font-bold flex items-center gap-2">
|
||||
<Coins className="w-5 h-5 text-accent" /> Баланс и кредиты
|
||||
</h1>
|
||||
<button onClick={() => load(page)} className="btn-ghost p-2">
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Баланс */}
|
||||
{balance && (
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 mb-6">
|
||||
<div className="card p-4 col-span-2 sm:col-span-1 border-accent/40 bg-accent/5">
|
||||
<div className="text-3xl font-bold text-accent">
|
||||
{balance.isUnlimited ? '∞' : balance.credits}
|
||||
</div>
|
||||
<div className="text-xs text-gray-400 mt-1">кредитов осталось</div>
|
||||
</div>
|
||||
<div className="card p-4">
|
||||
<div className={`text-lg font-bold ${PLAN_COLORS[balance.plan] || 'text-gray-300'}`}>
|
||||
{balance.planName}
|
||||
</div>
|
||||
<div className="text-xs text-gray-400 mt-1">текущий тариф</div>
|
||||
</div>
|
||||
<div className="card p-4">
|
||||
<div className="text-sm font-medium text-gray-300">
|
||||
{balance.resetAt ? new Date(balance.resetAt).toLocaleDateString('ru-RU') : '—'}
|
||||
</div>
|
||||
<div className="text-xs text-gray-400 mt-1">сброс кредитов</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* CTA апгрейд */}
|
||||
{balance?.plan === 'free' && (
|
||||
<div className="card p-4 mb-6 border-accent/30 bg-accent/5 flex items-center justify-between">
|
||||
<div>
|
||||
<div className="font-medium text-sm">Хотите больше кредитов?</div>
|
||||
<div className="text-xs text-gray-400 mt-0.5">Starter — 500 кредитов за ₽490/мес</div>
|
||||
</div>
|
||||
<Link href="/plans" className="btn-primary text-sm px-4 py-1.5 flex items-center gap-1">
|
||||
Тарифы <ArrowRight className="w-3.5 h-3.5" />
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Стоимость операций */}
|
||||
<div className="card p-4 mb-6">
|
||||
<div className="text-xs text-gray-400 uppercase tracking-wide mb-3">Стоимость операций</div>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
|
||||
{[
|
||||
{ label: 'Картинка', credits: 5, icon: '🖼' },
|
||||
{ label: 'Пост', credits: 2, icon: '✍️' },
|
||||
{ label: 'Статья', credits: 5, icon: '📝' },
|
||||
{ label: 'Публикация', credits: 0, icon: '📤' },
|
||||
].map(op => (
|
||||
<div key={op.label} className="text-center p-2 rounded-lg bg-surface2">
|
||||
<div className="text-lg">{op.icon}</div>
|
||||
<div className="text-xs text-gray-300 mt-1">{op.label}</div>
|
||||
<div className="text-sm font-bold text-accent mt-0.5">
|
||||
{op.credits === 0 ? 'бесплатно' : `${op.credits} кр`}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* История транзакций */}
|
||||
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wide mb-3">История</h2>
|
||||
{loading && <div className="py-8 text-center"><Loader2 className="w-5 h-5 animate-spin mx-auto text-accent" /></div>}
|
||||
{!loading && (
|
||||
<div className="card overflow-hidden">
|
||||
{txs.length === 0 && (
|
||||
<div className="py-8 text-center text-gray-500 text-sm">Транзакций пока нет</div>
|
||||
)}
|
||||
{txs.map(tx => {
|
||||
const meta = TYPE_LABELS[tx.type] || { label: tx.type, sign: tx.amount > 0 ? '+' : '-', color: 'text-gray-400' };
|
||||
return (
|
||||
<div key={tx.id} className="flex items-center justify-between px-4 py-3 border-b border-border last:border-0 hover:bg-surface2/50">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm truncate">{tx.description || meta.label}</div>
|
||||
<div className="text-xs text-gray-500 mt-0.5">{fmtDate(tx.created_at)}</div>
|
||||
</div>
|
||||
<div className="text-right ml-4">
|
||||
<div className={`font-bold text-sm ${meta.color}`}>
|
||||
{meta.sign}{Math.abs(tx.amount)} кр
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">= {tx.balance_after === -1 ? '∞' : tx.balance_after} кр</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Пагинация */}
|
||||
{total > PER_PAGE && (
|
||||
<div className="flex justify-center gap-2 mt-4">
|
||||
<button disabled={page === 0} onClick={() => { setPage(p => p-1); load(page-1); }} className="btn-ghost px-3 py-1.5 text-sm disabled:opacity-40">← Назад</button>
|
||||
<span className="text-sm text-gray-500 self-center">{page+1} / {Math.ceil(total/PER_PAGE)}</span>
|
||||
<button disabled={(page+1)*PER_PAGE >= total} onClick={() => { setPage(p => p+1); load(page+1); }} className="btn-ghost px-3 py-1.5 text-sm disabled:opacity-40">Вперёд →</button>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user