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:
+26
-3
@@ -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 });
|
||||
|
||||
Reference in New Issue
Block a user