feat: billing system — credits, plans, transactions

DB:
- plans: free/starter/pro/business с ценами и лимитами
- user_subscriptions: подписка пользователя на план
- user_balance: баланс кредитов + monthly reset
- user_transactions: история всех движений кредитов
- credit_costs: image=5, text_post=2, article=5, autopublish=0

Engine:
- services/billing.js: getBalance, check, spend, credit, getTransactions, processMonthlyResets
- routes/billing.js: GET /balance, /transactions, /plans, POST /admin/credit, GET /admin/users
- routes/generate.js: списание кредитов перед генерацией (text_post, article, image)
- index.js: GET /api/billing/plans публично (без auth)
This commit is contained in:
Ник (Claude)
2026-06-11 18:26:38 +03:00
parent eede50bee7
commit 2e60a6e316
4 changed files with 331 additions and 3 deletions
+82
View File
@@ -0,0 +1,82 @@
const express = require('express');
const router = express.Router();
const billing = require('../services/billing');
const { query } = require('../config/db');
function uid(req) { return req.headers['x-user-id'] ? parseInt(req.headers['x-user-id']) : null; }
// GET /api/billing/balance — баланс + план текущего юзера
router.get('/balance', async (req, res) => {
const userId = uid(req);
if (!userId) return res.status(401).json({ error: 'x-user-id required' });
try {
await billing.ensureBalance(userId);
const bal = await billing.getBalance(userId);
res.json(bal);
} catch (err) { res.status(500).json({ error: err.message }); }
});
// GET /api/billing/transactions — история транзакций
router.get('/transactions', async (req, res) => {
const userId = uid(req);
if (!userId) return res.status(401).json({ error: 'x-user-id required' });
const limit = Math.min(parseInt(req.query.limit || 50), 200);
const offset = parseInt(req.query.offset || 0);
try {
const txs = await billing.getTransactions(userId, { limit, offset });
const { rows: [{ total }] } = await query(
'SELECT count(*)::int as total FROM user_transactions WHERE user_id=$1', [userId]
);
res.json({ transactions: txs, total, limit, offset });
} catch (err) { res.status(500).json({ error: err.message }); }
});
// GET /api/billing/plans — все тарифы (публичный)
router.get('/plans', async (req, res) => {
try {
const { rows } = await query(
'SELECT * FROM plans WHERE is_active=true ORDER BY sort_order'
);
const { rows: costs } = await query('SELECT * FROM credit_costs ORDER BY operation');
res.json({ plans: rows, costs });
} catch (err) { res.status(500).json({ error: err.message }); }
});
// POST /api/billing/admin/credit — начислить кредиты вручную (только admin)
router.post('/admin/credit', async (req, res) => {
const adminId = uid(req);
if (!adminId) return res.status(401).json({ error: 'x-user-id required' });
const { rows: [admin] } = await query('SELECT is_admin FROM users WHERE id=$1', [adminId]);
if (!admin?.is_admin) return res.status(403).json({ error: 'Forbidden' });
const { user_id, amount, description = 'Ручное начисление от администратора' } = req.body;
if (!user_id || !amount) return res.status(400).json({ error: 'user_id и amount обязательны' });
try {
const result = await billing.credit(user_id, amount, 'bonus', description, { by_admin: adminId });
res.json(result);
} catch (err) { res.status(500).json({ error: err.message }); }
});
// GET /api/billing/admin/users — балансы всех пользователей (только admin)
router.get('/admin/users', async (req, res) => {
const adminId = uid(req);
if (!adminId) return res.status(401).json({ error: 'x-user-id required' });
const { rows: [admin] } = await query('SELECT is_admin FROM users WHERE id=$1', [adminId]);
if (!admin?.is_admin) return res.status(403).json({ error: 'Forbidden' });
try {
const { rows } = await query(`
SELECT u.id, u.email, u.name,
ub.credits, ub.reset_at,
p.name as plan_name, p.code as plan_code, p.price_rub
FROM users u
LEFT JOIN user_balance ub ON ub.user_id = u.id
LEFT JOIN user_subscriptions us ON us.user_id = u.id
AND us.status='active' AND (us.expires_at IS NULL OR us.expires_at > NOW())
LEFT JOIN plans p ON p.id = us.plan_id
ORDER BY u.created_at DESC
`);
res.json(rows);
} catch (err) { res.status(500).json({ error: err.message }); }
});
module.exports = router;
+26 -3
View File
@@ -3,18 +3,33 @@ const router = express.Router();
const { query } = require('../config/db');
const channelsSvc = require('../services/channels');
const generationQueue = require('../workers/generation');
const billing = require('../services/billing');
// Маппинг type → billing operation
const BILLING_OP = { post: 'text_post', article: 'article', topics: null };
// POST /api/generate — создать задачу генерации
router.post('/', async (req, res) => {
try {
const { type, topic, channelId, rubric, keywords = [], useCritique = true, customPrompt } = req.body;
const userId = req.headers['x-user-id'] || null;
const userId = req.headers['x-user-id'] ? parseInt(req.headers['x-user-id']) : null;
if (!type) return res.status(400).json({ error: 'type is required' });
if (!['post', 'article', 'topics'].includes(type)) return res.status(400).json({ error: 'Invalid type' });
if (type !== 'topics' && !topic) return res.status(400).json({ error: 'topic is required' });
if (type === 'post' && !channelId) return res.status(400).json({ error: 'channelId is required for posts' });
// Проверка и списание кредитов
const billingOp = BILLING_OP[type];
let billingResult = null;
if (userId && billingOp) {
const ck = await billing.check(userId, billingOp);
if (!ck.allowed) {
return res.status(402).json({ error: ck.reason, code: 'INSUFFICIENT_CREDITS', credits: ck.credits, cost: ck.cost });
}
billingResult = await billing.spend(userId, billingOp, { channel_id: channelId });
}
const { rows } = await query(
`INSERT INTO generation_jobs (user_id, channel_id, type, topic, rubric, status)
VALUES ($1,$2,$3,$4,$5,'pending') RETURNING id`,
@@ -24,7 +39,7 @@ router.post('/', async (req, res) => {
await generationQueue.add({ jobId, type, topic, channelId, rubric, keywords, useCritique, customPrompt });
res.json({ jobId, status: 'pending' });
res.json({ jobId, status: 'pending', credits_after: billingResult?.credits_after ?? null, cost: billingResult?.cost ?? 0 });
} catch (err) {
console.error('[Route] POST /generate', err);
res.status(500).json({ error: err.message });
@@ -72,9 +87,17 @@ router.post('/post-image', async (req, res) => {
const channel = await channelsSvc.getChannel(channelId, userId);
if (!channel) return res.status(404).json({ error: 'Channel not found' });
// Списываем кредиты за картинку
let imgBilling = null;
if (userId) {
const ck = await billing.check(userId, 'image');
if (!ck.allowed) return res.status(402).json({ error: ck.reason, code: 'INSUFFICIENT_CREDITS', credits: ck.credits, cost: ck.cost });
imgBilling = await billing.spend(userId, 'image', { channel_id: channelId });
}
const { generatePostImage } = require('../services/postImages');
const result = await generatePostImage({ post, channel, style: channel.style || {} });
res.json(result);
res.json({ ...result, credits_after: imgBilling?.credits_after ?? null, cost: imgBilling?.cost ?? 0 });
} catch (err) {
console.error('[Route] POST /post-image', err);
res.status(500).json({ error: err.message });