const express = require('express'); const router = express.Router(); const billing = require('../services/billing'); const yukassa = require('../services/yukassa'); 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; // POST /api/billing/checkout — создать платёж ЮKassa router.post('/checkout', async (req, res) => { const userId = uid(req); if (!userId) return res.status(401).json({ error: 'x-user-id required' }); const { plan_code } = req.body; if (!plan_code) return res.status(400).json({ error: 'plan_code required' }); try { const { rows: [user] } = await query('SELECT email FROM users WHERE id=$1', [userId]); const result = await yukassa.createPayment({ userId, planCode: plan_code, userEmail: user?.email }); res.json(result); } catch (err) { console.error('[billing] checkout:', err.message); res.status(500).json({ error: err.message }); } }); // POST /api/billing/webhook — вебхук ЮKassa (без auth, проверка по IP/подписи) router.post('/webhook', express.json({ type: '*/*' }), async (req, res) => { try { const result = await yukassa.handleWebhook(req.body); res.json({ ok: true, ...result }); } catch (err) { console.error('[billing] webhook error:', err.message); res.status(500).json({ error: err.message }); } }); // POST /api/billing/monthly-reset — ежемесячный сброс кредитов (вызывается cron) router.post('/monthly-reset', async (req, res) => { try { const processed = await billing.processMonthlyResets(); console.log(`[Billing] monthly reset: ${processed} users processed`); res.json({ ok: true, processed }); } catch (err) { console.error('[Billing] monthly-reset error:', err.message); res.status(500).json({ error: err.message }); } });