Files
zeropost-tool/app/billing/page.js
T
Ник (Claude) b620927c25 feat: promo codes UI + apply on /billing
AdminPromos.js: создание/список/toggle/удаление промокодов
  auto-generated code, type (credits/%), max_uses, expires, description
AdminPanel: раздел Промокоды между Тарифами и Пользователями
/billing page: кнопка '🎁 Есть промокод?' → форма ввода → apply-promo API
API routes: /api/admin/promos, /api/admin/promos/[id], /api/billing/apply-promo
2026-06-13 09:37:19 +03:00

217 lines
9.3 KiB
JavaScript

'use client';
import { useState, useEffect } from 'react';
import { Coins, RefreshCw, TrendingDown, TrendingUp, Loader2, ArrowRight } from 'lucide-react';
import Link from 'next/link';
import BackButton from '@/components/BackButton';
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">
<BackButton />
<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>
)}
{/* Промокод */}
<PromoForm onApplied={() => load(0)} />
{/* Стоимость операций */}
<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>
);
}
function PromoForm({ onApplied }) {
const [code, setCode] = useState('');
const [msg, setMsg] = useState('');
const [busy, setBusy] = useState(false);
const [show, setShow] = useState(false);
async function apply() {
if (!code.trim()) return;
setBusy(true);
const res = await fetch('/api/billing/apply-promo', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code: code.trim().toUpperCase() }),
}).then(r => r.json());
setBusy(false);
if (res.ok) {
setMsg(res.message);
setCode('');
setShow(false);
onApplied?.();
} else {
setMsg('Ошибка: ' + (res.error || 'неизвестно'));
}
setTimeout(() => setMsg(''), 4000);
}
return (
<div className="mb-6">
{!show ? (
<button onClick={() => setShow(true)} className="text-sm text-gray-500 hover:text-accent transition-colors">
🎁 Есть промокод?
</button>
) : (
<div className="card p-4">
<div className="flex gap-2">
<input
value={code}
onChange={e => setCode(e.target.value.toUpperCase())}
onKeyDown={e => e.key === 'Enter' && apply()}
placeholder="ВВЕДИТЕ КОД"
className="input flex-1 font-mono text-sm py-1.5 tracking-widest"
autoFocus
maxLength={32}
/>
<button onClick={apply} disabled={busy || !code.trim()} className="btn-primary px-4 text-sm">
{busy ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Применить'}
</button>
<button onClick={() => { setShow(false); setCode(''); }} className="btn-ghost px-3 text-sm"></button>
</div>
{msg && <p className={`text-xs mt-2 ${msg.startsWith('Ошибка') ? 'text-red-400' : 'text-green-400'}`}>{msg}</p>}
</div>
)}
</div>
);
}