Files
zeropost-engine/src/routes/billing.js
T
Ник (Claude) ce74ac9909 feat: promo codes system
DB: promo_codes, promo_usages tables
routes/admin.js: CRUD /api/admin/promos (GET/POST/PATCH/DELETE)
routes/billing.js: POST /api/billing/apply-promo
  Валидация: exists, active, not expired, not exhausted, not used by this user
  type=credits → начисляет через billing.credit()
2026-06-13 09:36:32 +03:00

257 lines
12 KiB
JavaScript

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 });
}
});
// PATCH /api/admin/plans/:id — обновить план (только admin)
router.patch('/admin/plans/:id', 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 { price_rub, credits_month, channels_max, name } = req.body;
try {
const sets = []; const vals = [];
if (price_rub !== undefined) sets.push(`price_rub=$${vals.push(price_rub)}`);
if (credits_month!== undefined) sets.push(`credits_month=$${vals.push(credits_month)}`);
if (channels_max !== undefined) sets.push(`channels_max=$${vals.push(channels_max)}`);
if (name !== undefined) sets.push(`name=$${vals.push(name)}`);
if (!sets.length) return res.status(400).json({ error: 'nothing to update' });
vals.push(req.params.id);
const { rows: [plan] } = await query(`UPDATE plans SET ${sets.join(',')} WHERE id=$${vals.length} RETURNING *`, vals);
res.json(plan);
} catch (err) { res.status(500).json({ error: err.message }); }
});
// PATCH /api/admin/credit-costs/:operation — обновить стоимость операции
router.patch('/admin/credit-costs/:operation', 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 { credits } = req.body;
try {
await query('UPDATE credit_costs SET credits=$1 WHERE operation=$2', [credits, req.params.operation]);
res.json({ ok: true, operation: req.params.operation, credits });
} catch (err) { res.status(500).json({ error: err.message }); }
});
// GET /api/admin/dashboard — сводная статистика для admin
router.get('/admin/dashboard', 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 [users, channels, posts, drafts, revenue, ai, regs] = await Promise.all([
// Пользователи
query(`SELECT count(*)::int as total,
count(*) FILTER (WHERE created_at > NOW()-INTERVAL '7 days')::int as new_7d,
count(*) FILTER (WHERE created_at > NOW()-INTERVAL '30 days')::int as new_30d
FROM users`),
// Каналы по платформам
query(`SELECT platform, count(*)::int as cnt FROM channels WHERE is_active=true GROUP BY platform`),
// Посты
query(`SELECT count(*)::int as total,
count(*) FILTER (WHERE published_at > NOW()-INTERVAL '24 hours')::int as today,
count(*) FILTER (WHERE published_at > NOW()-INTERVAL '7 days')::int as week
FROM scheduled_posts WHERE status='sent'`),
// Черновики ожидающие
query(`SELECT count(*)::int as pending FROM post_drafts WHERE status='pending'`),
// Выручка ЮKassa
query(`SELECT coalesce(sum(amount_rub),0)::int as total_rub,
count(*) FILTER (WHERE status='succeeded')::int as paid_count,
coalesce(sum(amount_rub) FILTER (WHERE created_at > NOW()-INTERVAL '30 days'),0)::int as month_rub
FROM payment_orders WHERE status='succeeded'`),
// Расходы AI за 30 дней
query(`SELECT coalesce(sum(cost_rub),0)::numeric(10,2) as month_rub,
count(*)::int as calls,
count(*) FILTER (WHERE NOT succeeded)::int as errors
FROM ai_usage WHERE created_at > NOW()-INTERVAL '30 days'`),
// Регистрации по дням (последние 14 дней)
query(`SELECT date_trunc('day', created_at)::date as day, count(*)::int as cnt
FROM users WHERE created_at > NOW()-INTERVAL '14 days'
GROUP BY 1 ORDER BY 1`),
]);
res.json({
users: users.rows[0],
channels: channels.rows,
posts: posts.rows[0],
drafts: drafts.rows[0],
revenue: revenue.rows[0],
ai: { ...ai.rows[0], cost_rub: parseFloat(ai.rows[0].month_rub) },
registrations_14d: regs.rows,
});
} catch (err) { res.status(500).json({ error: err.message }); }
});
// POST /api/billing/apply-promo — применить промокод
router.post('/apply-promo', async (req, res) => {
const userId = uid(req);
if (!userId) return res.status(401).json({ error: 'x-user-id required' });
const { code } = req.body;
if (!code?.trim()) return res.status(400).json({ error: 'code обязателен' });
try {
// Ищем промокод
const { rows: [promo] } = await query(`
SELECT p.*, count(pu.id)::int as uses_real
FROM promo_codes p
LEFT JOIN promo_usages pu ON pu.code_id = p.id
WHERE p.code = $1 AND p.is_active = true
AND (p.expires_at IS NULL OR p.expires_at > NOW())
GROUP BY p.id
`, [code.toUpperCase()]);
if (!promo) return res.status(404).json({ error: 'Промокод не найден или истёк' });
if (promo.max_uses !== -1 && promo.uses_real >= promo.max_uses)
return res.status(410).json({ error: 'Промокод исчерпан' });
// Проверяем что пользователь ещё не использовал
const { rows: [used] } = await query(
'SELECT id FROM promo_usages WHERE code_id=$1 AND user_id=$2',
[promo.id, userId]
);
if (used) return res.status(409).json({ error: 'Вы уже использовали этот промокод' });
// Применяем
const billing = require('../services/billing');
if (promo.type === 'credits') {
await billing.credit(userId, promo.value, 'bonus', `Промокод ${promo.code}`, { promo_id: promo.id });
}
// Записываем использование
await query('INSERT INTO promo_usages (code_id, user_id) VALUES ($1,$2)', [promo.id, userId]);
await query('UPDATE promo_codes SET used_count = used_count + 1 WHERE id=$1', [promo.id]);
res.json({
ok: true,
type: promo.type,
value: promo.value,
message: promo.type === 'credits'
? `+${promo.value} кредитов начислено на ваш баланс`
: `Скидка ${promo.value}% применена`,
});
} catch (err) { res.status(500).json({ error: err.message }); }
});