forked from admin/zeropost-tool
feat: billing complete — plans page, admin billing, credit cost hints
/plans: страница тарифов с карточками, стоимостью операций, FAQ /system → Биллинг: таблица пользователей с кредитами, ручное начисление ChannelView: badge стоимости (2кр текст + 5кр картинка) под кнопкой генерации Ошибка INSUFFICIENT_CREDITS → понятное сообщение После генерации — event credits-updated → обновление badge в header Header: подписка на credits-updated event API роуты: /api/billing/plans, /api/billing/admin/users, /api/billing/admin/credit
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { requireUser } from '@/lib/session';
|
||||
import { engine } from '@/lib/engine';
|
||||
|
||||
export async function POST(req) {
|
||||
const user = await requireUser();
|
||||
if (!user?.isAdmin) return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
try {
|
||||
const body = await req.json();
|
||||
const data = await engine.adminCreditUser(body);
|
||||
return NextResponse.json(data);
|
||||
} catch (err) { return NextResponse.json({ error: err.message }, { status: 500 }); }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { requireUser } from '@/lib/session';
|
||||
import { engine } from '@/lib/engine';
|
||||
|
||||
export async function GET() {
|
||||
const user = await requireUser();
|
||||
if (!user?.isAdmin) return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
try {
|
||||
const data = await engine.adminGetBalances();
|
||||
return NextResponse.json(data);
|
||||
} catch (err) { return NextResponse.json({ error: err.message }, { status: 500 }); }
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
const ENGINE_URL = process.env.ENGINE_URL || 'http://localhost:3030';
|
||||
const ENGINE_SECRET = process.env.ENGINE_SECRET || '';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const res = await fetch(`${ENGINE_URL}/api/billing/plans`, {
|
||||
headers: { 'x-internal-secret': ENGINE_SECRET },
|
||||
cache: 'no-store',
|
||||
});
|
||||
const data = await res.json();
|
||||
return NextResponse.json(data);
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: err.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
'use client';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Check, Zap, Loader2 } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
|
||||
const PLAN_STYLE = {
|
||||
free: { color: 'border-border', badge: null, btnClass: 'btn-ghost' },
|
||||
starter: { color: 'border-blue-500/50', badge: null, btnClass: 'btn-primary' },
|
||||
pro: { color: 'border-purple-500/60', badge: 'Популярный', btnClass: 'bg-purple-600 hover:bg-purple-500 text-white px-4 py-2 rounded-lg font-medium transition-colors' },
|
||||
business: { color: 'border-yellow-500/40', badge: 'Для агентств', btnClass: 'bg-yellow-600 hover:bg-yellow-500 text-white px-4 py-2 rounded-lg font-medium transition-colors' },
|
||||
};
|
||||
|
||||
const FEATURES = {
|
||||
free: ['1 канал', '50 кредитов/мес', 'TG и VK публикация', 'Ручная генерация'],
|
||||
starter: ['2 канала', '500 кредитов/мес', 'Автогенерация постов', 'Календарь публикаций', 'Аналитика канала'],
|
||||
pro: ['5 каналов', '2000 кредитов/мес', 'Всё из Starter', 'Приоритетная генерация', 'История контента'],
|
||||
business: ['Без ограничений', 'Безлимит кредитов', 'Всё из Pro', 'Поддержка 24/7', 'API доступ'],
|
||||
};
|
||||
|
||||
export default function PlansPage() {
|
||||
const [plans, setPlans] = useState([]);
|
||||
const [costs, setCosts] = useState({});
|
||||
const [balance, setBalance] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([
|
||||
fetch('/api/billing/plans').then(r => r.json()),
|
||||
fetch('/api/billing/balance').then(r => r.json()).catch(() => null),
|
||||
]).then(([pd, bd]) => {
|
||||
setPlans(pd.plans || []);
|
||||
setCosts(Object.fromEntries((pd.costs || []).map(c => [c.operation, c.credits])));
|
||||
setBalance(bd);
|
||||
setLoading(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
if (loading) return (
|
||||
<main className="max-w-5xl mx-auto p-6 text-center py-20">
|
||||
<Loader2 className="w-6 h-6 animate-spin mx-auto text-accent" />
|
||||
</main>
|
||||
);
|
||||
|
||||
return (
|
||||
<main className="max-w-5xl mx-auto p-4 sm:p-6">
|
||||
<div className="text-center mb-10">
|
||||
<h1 className="text-3xl font-bold mb-2">Тарифы</h1>
|
||||
<p className="text-gray-400">Выберите план под ваши задачи. Все планы включают публикацию в TG и VK.</p>
|
||||
{balance && (
|
||||
<p className="text-sm text-accent mt-2">
|
||||
Сейчас у вас: <strong>{balance.planName}</strong> · {balance.isUnlimited ? '∞' : balance.credits} кредитов
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Карточки планов */}
|
||||
<div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-10">
|
||||
{plans.map(plan => {
|
||||
const style = PLAN_STYLE[plan.code] || PLAN_STYLE.free;
|
||||
const features = FEATURES[plan.code] || [];
|
||||
const isCurrent = balance?.plan === plan.code;
|
||||
const isUnlimited = plan.credits_month === -1;
|
||||
|
||||
return (
|
||||
<div key={plan.code} className={`card p-5 flex flex-col border-2 ${style.color} ${plan.code === 'pro' ? 'relative' : ''}`}>
|
||||
{style.badge && (
|
||||
<div className="absolute -top-3 left-1/2 -translate-x-1/2 text-xs px-3 py-1 rounded-full bg-purple-600 text-white font-medium whitespace-nowrap">
|
||||
{style.badge}
|
||||
</div>
|
||||
)}
|
||||
<div className="mb-4">
|
||||
<div className="text-lg font-bold">{plan.name}</div>
|
||||
<div className="mt-1">
|
||||
{plan.price_rub === 0
|
||||
? <span className="text-2xl font-bold">Бесплатно</span>
|
||||
: <><span className="text-2xl font-bold">₽{plan.price_rub}</span><span className="text-gray-400 text-sm">/мес</span></>
|
||||
}
|
||||
</div>
|
||||
<div className="text-sm text-accent mt-1 font-medium">
|
||||
{isUnlimited ? '∞ кредитов' : `${plan.credits_month} кредитов/мес`}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul className="space-y-2 flex-1 mb-5">
|
||||
{features.map(f => (
|
||||
<li key={f} className="flex items-start gap-2 text-sm text-gray-300">
|
||||
<Check className="w-4 h-4 text-green-400 mt-0.5 shrink-0" />
|
||||
{f}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{isCurrent ? (
|
||||
<div className="w-full text-center py-2 rounded-lg bg-surface2 text-gray-400 text-sm">Текущий план</div>
|
||||
) : plan.price_rub === 0 ? (
|
||||
<Link href="/register" className={`w-full text-center py-2 rounded-lg text-sm ${style.btnClass}`}>Начать бесплатно</Link>
|
||||
) : (
|
||||
<button className={`w-full text-center py-2 text-sm ${style.btnClass}`}
|
||||
onClick={() => alert('ЮKassa — скоро')}>
|
||||
Подключить
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Стоимость операций */}
|
||||
<div className="card p-5 mb-6">
|
||||
<h2 className="font-semibold mb-4 flex items-center gap-2">
|
||||
<Zap className="w-4 h-4 text-accent" /> Стоимость генерации
|
||||
</h2>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-sm">
|
||||
{[
|
||||
{ label: 'Картинка', op: 'image', icon: '🖼', note: 'gpt-5-image-mini' },
|
||||
{ label: 'Пост', op: 'text_post', icon: '✍️', note: 'aiprimetech' },
|
||||
{ label: 'Статья', op: 'article', icon: '📝', note: 'Claude Sonnet' },
|
||||
{ label: 'Публикация', op: 'autopublish',icon: '📤', note: 'TG / VK / MAX' },
|
||||
].map(op => (
|
||||
<div key={op.op} className="p-3 rounded-lg bg-surface2 text-center">
|
||||
<div className="text-2xl mb-1">{op.icon}</div>
|
||||
<div className="font-medium">{op.label}</div>
|
||||
<div className="text-accent font-bold mt-1">
|
||||
{(costs[op.op] || 0) === 0 ? 'бесплатно' : `${costs[op.op]} кр`}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 mt-0.5">{op.note}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* FAQ */}
|
||||
<div className="card p-5">
|
||||
<h2 className="font-semibold mb-4">Часто спрашивают</h2>
|
||||
<div className="space-y-3 text-sm text-gray-400">
|
||||
{[
|
||||
['Что такое кредиты?', '1 кредит = 1 рубль. Кредиты списываются при каждой AI-генерации. Публикация постов — всегда бесплатна.'],
|
||||
['Что будет если кредиты закончатся?', 'Генерация будет заблокирована до пополнения. Уже опубликованные посты и автопостинг продолжают работать.'],
|
||||
['Переносятся ли кредиты на следующий месяц?', 'Нет, кредиты по тарифу сбрасываются раз в 30 дней. Дополнительно купленные кредиты не сгорают.'],
|
||||
['Можно ли купить кредиты отдельно?', 'Скоро. Сейчас кредиты начисляются только по тарифному плану.'],
|
||||
].map(([q, a]) => (
|
||||
<details key={q} className="group">
|
||||
<summary className="cursor-pointer font-medium text-gray-200 hover:text-white list-none flex items-center justify-between">
|
||||
{q} <span className="text-gray-500 group-open:rotate-180 transition-transform">▾</span>
|
||||
</summary>
|
||||
<p className="mt-2 pl-1">{a}</p>
|
||||
</details>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -231,7 +231,14 @@ export default function ChannelView({ channel }) {
|
||||
}),
|
||||
});
|
||||
const job = await createRes.json();
|
||||
if (!createRes.ok) throw new Error(job.error || 'Ошибка');
|
||||
if (!createRes.ok) {
|
||||
if (job.code === 'INSUFFICIENT_CREDITS') {
|
||||
throw new Error(`Недостаточно кредитов: нужно ${job.cost}, есть ${job.credits}. Пополните баланс на странице тарифов.`);
|
||||
}
|
||||
throw new Error(job.error || 'Ошибка');
|
||||
}
|
||||
// Триггер обновления баланса в header
|
||||
if (job.credits_after !== null) window.dispatchEvent(new Event('credits-updated'));
|
||||
|
||||
let final;
|
||||
for (let i = 0; i < 60; i++) {
|
||||
@@ -447,8 +454,12 @@ export default function ChannelView({ channel }) {
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="text-xs text-gray-500">
|
||||
ИИ напишет пост в стиле твоего канала с учётом примеров
|
||||
<div className="text-xs text-gray-500 space-y-0.5">
|
||||
<div>ИИ напишет пост в стиле твоего канала с учётом примеров</div>
|
||||
<div className="flex items-center gap-1.5 text-gray-600">
|
||||
<span className="px-1.5 py-0.5 rounded bg-surface2 text-[11px]">2 кр — текст</span>
|
||||
{channel.image_enabled && <span className="px-1.5 py-0.5 rounded bg-surface2 text-[11px]">+ 5 кр — картинка</span>}
|
||||
</div>
|
||||
</div>
|
||||
<button onClick={() => generate(false)} disabled={generating || !topic.trim()} className="btn-primary">
|
||||
{generating ? (
|
||||
|
||||
@@ -11,10 +11,11 @@ export default function Header({ user }) {
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
fetch('/api/billing/balance')
|
||||
.then(r => r.json())
|
||||
.then(d => setCredits(d.isUnlimited ? '∞' : d.credits))
|
||||
.catch(() => {});
|
||||
const refresh = () => fetch('/api/billing/balance').then(r => r.json())
|
||||
.then(d => setCredits(d.isUnlimited ? '∞' : d.credits)).catch(() => {});
|
||||
refresh();
|
||||
window.addEventListener('credits-updated', refresh);
|
||||
return () => window.removeEventListener('credits-updated', refresh);
|
||||
}, [user?.id]);
|
||||
|
||||
async function logout() {
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
'use client';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Loader2, Save, Eye, EyeOff, RefreshCw, Check, AlertCircle, BarChart3 } from 'lucide-react';
|
||||
import { Loader2, Save, Eye, EyeOff, RefreshCw, Check, AlertCircle, BarChart3, Coins } from 'lucide-react';
|
||||
import AdminBilling from './admin/AdminBilling';
|
||||
|
||||
const TABS_SYS = [
|
||||
{ id: 'settings', label: 'Настройки API' },
|
||||
{ id: 'billing', label: 'Биллинг' },
|
||||
];
|
||||
|
||||
// Категории, которые управляются здесь (в админке tool, а не в админке блога).
|
||||
// Категория `engine` (TELEGRAM_API_BASE и т.п.) намеренно живёт в zeropost.ru/admin.
|
||||
const CATEGORIES = [
|
||||
{ slug: 'ai_providers', title: 'AI провайдеры',
|
||||
hint: 'Ключи, URL и модели для текстовой и картиночной генерации. Меняются на лету — рестарт engine не нужен. Курс USD↔РУБ и наценка реселлера тут же — влияют на расчёт стоимости в блоке «Расход AI» выше.' },
|
||||
@@ -12,6 +16,7 @@ const CATEGORIES = [
|
||||
];
|
||||
|
||||
export default function SystemSettings() {
|
||||
const [sysTab, setSysTab] = useState('settings');
|
||||
const [byCategory, setByCategory] = useState({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
@@ -60,6 +65,21 @@ export default function SystemSettings() {
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Вкладки системной страницы */}
|
||||
<div className="flex gap-1 border-b border-border pb-0">
|
||||
{TABS_SYS.map(t => (
|
||||
<button key={t.id} onClick={() => setSysTab(t.id)}
|
||||
className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors -mb-px ${
|
||||
sysTab === t.id ? 'border-accent text-accent' : 'border-transparent text-gray-400 hover:text-gray-200'
|
||||
}`}>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{sysTab === 'billing' && <AdminBilling />}
|
||||
|
||||
{sysTab === 'settings' && (<>
|
||||
<UsageSummary />
|
||||
{CATEGORIES.map(cat => (
|
||||
<CategoryBlock
|
||||
@@ -69,6 +89,7 @@ export default function SystemSettings() {
|
||||
onSaved={() => load()}
|
||||
/>
|
||||
))}
|
||||
</>)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
'use client';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Loader2, Plus, RefreshCw, Search } from 'lucide-react';
|
||||
|
||||
const PLAN_BADGE = {
|
||||
free: 'bg-gray-600 text-gray-200',
|
||||
starter: 'bg-blue-600 text-white',
|
||||
pro: 'bg-purple-600 text-white',
|
||||
business: 'bg-yellow-600 text-black',
|
||||
};
|
||||
|
||||
export default function AdminBillingPage() {
|
||||
const [users, setUsers] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [search, setSearch] = useState('');
|
||||
const [crediting, setCrediting] = useState(null); // user being credited
|
||||
const [amount, setAmount] = useState('');
|
||||
const [desc, setDesc] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
async function load() {
|
||||
setLoading(true);
|
||||
const res = await fetch('/api/billing/admin/users').then(r => r.json());
|
||||
setUsers(Array.isArray(res) ? res : []);
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
useEffect(() => { load(); }, []);
|
||||
|
||||
async function handleCredit(userId) {
|
||||
if (!amount || isNaN(parseInt(amount))) return;
|
||||
setSaving(true);
|
||||
await fetch('/api/billing/admin/credit', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ user_id: userId, amount: parseInt(amount), description: desc || undefined }),
|
||||
});
|
||||
setCrediting(null);
|
||||
setAmount('');
|
||||
setDesc('');
|
||||
setSaving(false);
|
||||
load();
|
||||
}
|
||||
|
||||
const filtered = users.filter(u =>
|
||||
!search || u.email?.toLowerCase().includes(search.toLowerCase()) || u.name?.toLowerCase().includes(search.toLowerCase())
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="font-semibold">Балансы пользователей</h2>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative">
|
||||
<Search className="w-3.5 h-3.5 absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-400" />
|
||||
<input
|
||||
value={search} onChange={e => setSearch(e.target.value)}
|
||||
placeholder="Поиск по email..."
|
||||
className="input pl-8 py-1.5 text-sm w-48"
|
||||
/>
|
||||
</div>
|
||||
<button onClick={load} className="btn-ghost p-2"><RefreshCw className="w-4 h-4" /></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{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">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-surface2 text-xs text-gray-400">
|
||||
<tr>
|
||||
<th className="px-4 py-2.5 text-left">Пользователь</th>
|
||||
<th className="px-4 py-2.5 text-center">Тариф</th>
|
||||
<th className="px-4 py-2.5 text-right">Кредиты</th>
|
||||
<th className="px-4 py-2.5 text-right">Сброс</th>
|
||||
<th className="px-4 py-2.5 text-center">Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.map(u => (
|
||||
<>
|
||||
<tr key={u.id} className="border-t border-border hover:bg-surface2/50">
|
||||
<td className="px-4 py-2.5">
|
||||
<div className="font-medium">{u.name || u.email}</div>
|
||||
{u.name && <div className="text-xs text-gray-500">{u.email}</div>}
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-center">
|
||||
<span className={`text-xs px-2 py-0.5 rounded font-medium ${PLAN_BADGE[u.plan_code] || PLAN_BADGE.free}`}>
|
||||
{u.plan_name || 'Free'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-right font-bold">{u.credits ?? 0}</td>
|
||||
<td className="px-4 py-2.5 text-right text-xs text-gray-500">
|
||||
{u.reset_at ? new Date(u.reset_at).toLocaleDateString('ru-RU') : '—'}
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-center">
|
||||
<button
|
||||
onClick={() => setCrediting(crediting === u.id ? null : u.id)}
|
||||
className="btn-ghost px-2 py-1 text-xs flex items-center gap-1 mx-auto"
|
||||
>
|
||||
<Plus className="w-3 h-3" /> Начислить
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
{crediting === u.id && (
|
||||
<tr key={`${u.id}-credit`} className="border-t border-accent/20 bg-accent/5">
|
||||
<td colSpan={5} className="px-4 py-3">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<input
|
||||
type="number" value={amount} onChange={e => setAmount(e.target.value)}
|
||||
placeholder="Кол-во кредитов" className="input py-1.5 text-sm w-36"
|
||||
autoFocus
|
||||
/>
|
||||
<input
|
||||
value={desc} onChange={e => setDesc(e.target.value)}
|
||||
placeholder="Комментарий (необязательно)" className="input py-1.5 text-sm flex-1 min-w-40"
|
||||
/>
|
||||
<button
|
||||
onClick={() => handleCredit(u.id)}
|
||||
disabled={saving || !amount}
|
||||
className="btn-primary py-1.5 px-3 text-sm"
|
||||
>
|
||||
{saving ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : 'Начислить'}
|
||||
</button>
|
||||
<button onClick={() => setCrediting(null)} className="btn-ghost py-1.5 px-3 text-sm">Отмена</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</>
|
||||
))}
|
||||
{!filtered.length && (
|
||||
<tr><td colSpan={5} className="px-4 py-6 text-center text-gray-500">Пользователи не найдены</td></tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user