Files
sts-avto-v2/modules/leads/index.js
kalugin66 11fb813a09
All checks were successful
Deploy sts / deploy-sber (push) Successful in 42s
модификация
2026-07-20 00:27:48 +05:00

46 lines
1.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
let db;
function init(database) { db = database; }
function setupRoutes(app, auth) {
const { authenticateToken, requireAdmin } = auth;
app.get('/api/admin/leads', authenticateToken, requireAdmin, (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = 20;
const offset = (page - 1) * limit;
const search = req.query.search || '';
let where = '';
const params = [];
if (search) {
where = `WHERE name LIKE ? OR phone LIKE ? OR message LIKE ?`;
params.push(`%${search}%`, `%${search}%`, `%${search}%`);
}
db.get(`SELECT COUNT(*) as total FROM leads ${where}`, params, (err, countRow) => {
if (err) return res.status(500).json({ error: 'Ошибка БД' });
const total = countRow.total;
db.all(`SELECT * FROM leads ${where} ORDER BY created_at DESC LIMIT ? OFFSET ?`,
[...params, limit, offset], (err2, rows) => {
if (err2) return res.status(500).json({ error: 'Ошибка БД' });
res.json({ data: rows, total, page, totalPages: Math.ceil(total / limit) });
});
});
});
app.delete('/api/admin/leads/:id', authenticateToken, requireAdmin, (req, res) => {
const id = parseInt(req.params.id);
if (isNaN(id)) return res.status(400).json({ error: 'Неверный ID' });
const stmt = db.prepare(`DELETE FROM leads WHERE id = ?`);
stmt.run(id, function(err) {
if (err) return res.status(500).json({ error: 'Ошибка удаления' });
if (this.changes === 0) return res.status(404).json({ error: 'Не найдено' });
res.json({ message: 'Заявка удалена' });
});
stmt.finalize();
});
}
module.exports = { init, setupRoutes };