/** * routes/activity.js * GET /api/attivita — Paginates and filters the local SQLite activity log. */ const express = require('express'); const router = express.Router(); const { db } = require('../activityDb'); router.get('/', (req, res) => { try { const { page = 1, per_page = 50, agente_id, esito, da, a, } = req.query; const pageNum = Math.max(1, parseInt(page, 10)); const perPageNum = Math.min(200, Math.max(1, parseInt(per_page, 10))); const offset = (pageNum - 1) * perPageNum; const conditions = []; const params = []; if (agente_id) { conditions.push('agente_id = ?'); params.push(parseInt(agente_id, 10)); } if (esito) { conditions.push('esito = ?'); params.push(esito); } if (da) { conditions.push('creato_il >= ?'); params.push(da); } if (a) { conditions.push('creato_il <= ?'); params.push(a); } const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''; const totalRow = db.prepare(`SELECT COUNT(*) AS cnt FROM attivita ${whereClause}`).get(...params); const total = totalRow ? totalRow.cnt : 0; const rows = db .prepare(`SELECT * FROM attivita ${whereClause} ORDER BY creato_il DESC LIMIT ? OFFSET ?`) .all(...params, perPageNum, offset); res.json({ rows, total, page: pageNum, per_page: perPageNum, total_pages: Math.ceil(total / perPageNum), }); } catch (err) { console.error('[activity] Error fetching activities:', err); res.status(500).json({ error: err.message }); } }); module.exports = router;