Add new dashboard backend

This commit is contained in:
2025-01-13 00:14:15 -05:00
parent 024155d054
commit 88c51059bb
14 changed files with 1085 additions and 727 deletions

View File

@@ -0,0 +1,60 @@
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,
SUM(pta.total_revenue) as revenue,
SUM(pta.total_cost) as cost,
SUM(pm.inventory_value) as inventory_value,
CASE
WHEN SUM(pm.inventory_value) > 0
THEN (SUM(pta.total_revenue - pta.total_cost) / SUM(pm.inventory_value)) * 100
ELSE 0
END as gmroi
FROM product_time_aggregates pta
JOIN product_metrics pm ON pta.product_id = pm.product_id
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,
ROUND(revenue, 2) as revenue,
ROUND(inventory_value, 2) as inventory_value,
ROUND(gmroi, 2) as 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 || 0)
})),
inventory_value: rows.map(row => ({
date: row.date,
value: parseFloat(row.inventory_value || 0)
})),
gmroi: rows.map(row => ({
date: row.date,
value: parseFloat(row.gmroi || 0)
}))
};
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;