62 lines
2.0 KiB
JavaScript
62 lines
2.0 KiB
JavaScript
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
|
|
make_date(pta.year, pta.month, 1) as date,
|
|
ROUND(COALESCE(SUM(pta.total_revenue), 0)::numeric, 3) as revenue,
|
|
ROUND(COALESCE(SUM(pta.total_cost), 0)::numeric, 3) as cost,
|
|
ROUND(COALESCE(SUM(pm.inventory_value), 0)::numeric, 3) as inventory_value,
|
|
CASE
|
|
WHEN SUM(pm.inventory_value) > 0
|
|
THEN ROUND((SUM(pta.total_revenue - pta.total_cost) / SUM(pm.inventory_value) * 100)::numeric, 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) >=
|
|
EXTRACT(YEAR FROM CURRENT_DATE - INTERVAL '12 months')::integer * 100 +
|
|
EXTRACT(MONTH FROM CURRENT_DATE - INTERVAL '12 months')::integer
|
|
GROUP BY pta.year, pta.month
|
|
ORDER BY date ASC
|
|
)
|
|
SELECT
|
|
to_char(date, 'Mon YY') 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;
|