const express = require('express'); const router = express.Router(); // Get key metrics trends (revenue, inventory value, GMROI) router.get('/trends', async (req, res) => { const pool = req.app.locals.pool; try { const [rows] = await pool.query(` WITH MonthlyMetrics AS ( SELECT DATE(CONCAT(pta.year, '-', LPAD(pta.month, 2, '0'), '-01')) as date, CAST(COALESCE(SUM(pta.total_revenue), 0) AS DECIMAL(15,3)) as revenue, CAST(COALESCE(SUM(pta.total_cost), 0) AS DECIMAL(15,3)) as cost, CAST(COALESCE(SUM(pm.inventory_value), 0) AS DECIMAL(15,3)) as inventory_value, CASE WHEN SUM(pm.inventory_value) > 0 THEN CAST((SUM(pta.total_revenue - pta.total_cost) / SUM(pm.inventory_value)) * 100 AS DECIMAL(15,3)) ELSE 0 END as gmroi FROM product_time_aggregates pta JOIN product_metrics pm ON pta.pid = pm.pid WHERE (pta.year * 100 + pta.month) >= DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 12 MONTH), '%Y%m') GROUP BY pta.year, pta.month ORDER BY date ASC ) SELECT DATE_FORMAT(date, '%b %y') as date, revenue, inventory_value, gmroi FROM MonthlyMetrics `); console.log('Raw metrics trends data:', rows); // Transform the data into the format expected by the frontend const transformedData = { revenue: rows.map(row => ({ date: row.date, value: parseFloat(row.revenue) })), inventory_value: rows.map(row => ({ date: row.date, value: parseFloat(row.inventory_value) })), gmroi: rows.map(row => ({ date: row.date, value: parseFloat(row.gmroi) })) }; console.log('Transformed metrics data:', transformedData); res.json(transformedData); } catch (error) { console.error('Error fetching metrics trends:', error); res.status(500).json({ error: 'Failed to fetch metrics trends' }); } }); module.exports = router;