forked from admin/zeropost-engine
05fa7644cc
routes/admin.js: GET /users/:id (profile+channels+balance+transactions) PATCH /users/:id (is_blocked, plan_code, name) plan change: cancels active sub → creates new → credits reset generate.js: check is_blocked before generation → 403 ACCOUNT_BLOCKED DB: users.is_blocked BOOLEAN DEFAULT false
176 lines
8.5 KiB
JavaScript
176 lines
8.5 KiB
JavaScript
/**
|
|
* admin.js — admin-only API routes.
|
|
* Монтируется на /api/admin
|
|
*/
|
|
const express = require('express');
|
|
const router = express.Router();
|
|
const { query } = require('../config/db');
|
|
|
|
function uid(req) { return req.headers['x-user-id'] ? parseInt(req.headers['x-user-id']) : null; }
|
|
|
|
async function requireAdmin(req, res) {
|
|
const adminId = uid(req);
|
|
if (!adminId) { res.status(401).json({ error: 'x-user-id required' }); return null; }
|
|
const { rows: [u] } = await query('SELECT is_admin FROM users WHERE id=$1', [adminId]);
|
|
if (!u?.is_admin) { res.status(403).json({ error: 'Forbidden' }); return null; }
|
|
return adminId;
|
|
}
|
|
|
|
// GET /api/admin/dashboard
|
|
router.get('/dashboard', async (req, res) => {
|
|
if (!await requireAdmin(req, res)) return;
|
|
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'`),
|
|
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'`),
|
|
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'`),
|
|
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 }); }
|
|
});
|
|
|
|
// GET /api/admin/users — балансы всех пользователей
|
|
router.get('/users', async (req, res) => {
|
|
if (!await requireAdmin(req, res)) return;
|
|
try {
|
|
const { rows } = await query(`
|
|
SELECT u.id, u.email, u.name, u.created_at,
|
|
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 }); }
|
|
});
|
|
|
|
// POST /api/admin/credit — начислить кредиты
|
|
router.post('/credit', async (req, res) => {
|
|
if (!await requireAdmin(req, res)) return;
|
|
const { user_id, amount, description = 'Ручное начисление' } = req.body;
|
|
if (!user_id || !amount) return res.status(400).json({ error: 'user_id и amount обязательны' });
|
|
try {
|
|
const billing = require('../services/billing');
|
|
const result = await billing.credit(user_id, amount, 'bonus', description, { by_admin: uid(req) });
|
|
res.json(result);
|
|
} catch (err) { res.status(500).json({ error: err.message }); }
|
|
});
|
|
|
|
// PATCH /api/admin/plans/:id
|
|
router.patch('/plans/:id', async (req, res) => {
|
|
if (!await requireAdmin(req, res)) return;
|
|
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('/credit-costs/:operation', async (req, res) => {
|
|
if (!await requireAdmin(req, res)) return;
|
|
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 }); }
|
|
});
|
|
|
|
module.exports = router;
|
|
|
|
// GET /api/admin/users/:id — детальная информация о пользователе
|
|
router.get('/users/:id', async (req, res) => {
|
|
if (!await requireAdmin(req, res)) return;
|
|
try {
|
|
const [user, channels, balance, txs, sub] = await Promise.all([
|
|
query(`SELECT id, email, name, is_admin, is_blocked, created_at FROM users WHERE id=$1`, [req.params.id]),
|
|
query(`SELECT id, name, platform, is_active, tg_username, created_at FROM channels WHERE user_id=$1 ORDER BY created_at DESC`, [req.params.id]),
|
|
query(`SELECT ub.credits, ub.reset_at, p.name as plan_name, p.code as plan_code, p.price_rub
|
|
FROM user_balance ub
|
|
LEFT JOIN user_subscriptions us ON us.user_id=ub.user_id AND us.status='active'
|
|
LEFT JOIN plans p ON p.id=us.plan_id
|
|
WHERE ub.user_id=$1`, [req.params.id]),
|
|
query(`SELECT * FROM user_transactions WHERE user_id=$1 ORDER BY created_at DESC LIMIT 20`, [req.params.id]),
|
|
query(`SELECT us.*, p.name as plan_name, p.code as plan_code FROM user_subscriptions us
|
|
JOIN plans p ON p.id=us.plan_id WHERE us.user_id=$1 AND us.status='active' LIMIT 1`, [req.params.id]),
|
|
]);
|
|
if (!user.rows.length) return res.status(404).json({ error: 'User not found' });
|
|
res.json({
|
|
user: user.rows[0],
|
|
channels: channels.rows,
|
|
balance: balance.rows[0] || null,
|
|
transactions: txs.rows,
|
|
subscription: sub.rows[0] || null,
|
|
});
|
|
} catch (err) { res.status(500).json({ error: err.message }); }
|
|
});
|
|
|
|
// PATCH /api/admin/users/:id — обновить пользователя (block/unblock, план)
|
|
router.patch('/users/:id', async (req, res) => {
|
|
if (!await requireAdmin(req, res)) return;
|
|
const { is_blocked, plan_code, name } = req.body;
|
|
try {
|
|
if (is_blocked !== undefined) {
|
|
await query('UPDATE users SET is_blocked=$1 WHERE id=$2', [is_blocked, req.params.id]);
|
|
}
|
|
if (name !== undefined) {
|
|
await query('UPDATE users SET name=$1 WHERE id=$2', [name, req.params.id]);
|
|
}
|
|
if (plan_code !== undefined) {
|
|
// Смена плана вручную
|
|
const { rows: [plan] } = await query('SELECT * FROM plans WHERE code=$1', [plan_code]);
|
|
if (!plan) return res.status(400).json({ error: `Plan ${plan_code} not found` });
|
|
await query("UPDATE user_subscriptions SET status='cancelled' WHERE user_id=$1 AND status='active'", [req.params.id]);
|
|
const expires = new Date(Date.now() + 32*24*60*60*1000);
|
|
await query(`INSERT INTO user_subscriptions (user_id, plan_id, status, expires_at)
|
|
VALUES ($1,$2,'active',$3)`, [req.params.id, plan.id, expires]);
|
|
// Начисляем кредиты по новому плану
|
|
if (plan.credits_month > 0) {
|
|
await query('UPDATE user_balance SET credits=$1, reset_at=$2 WHERE user_id=$3',
|
|
[plan.credits_month, expires, req.params.id]);
|
|
await query(`INSERT INTO user_transactions (user_id, type, amount, balance_after, description)
|
|
VALUES ($1,'plan_credit',$2,$2,$3)`,
|
|
[req.params.id, plan.credits_month, `Ручная смена плана на ${plan.name}`]);
|
|
}
|
|
}
|
|
res.json({ ok: true });
|
|
} catch (err) { res.status(500).json({ error: err.message }); }
|
|
});
|