-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchart-data.js
167 lines (147 loc) · 5.69 KB
/
chart-data.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
const express = require('express');
const mysql = require('mysql2');
const moment = require('moment');
const app = express();
const port = 3000;
// Create a MySQL connection pool
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '', // Your DB password
database: 'dbs13455438'
});
// Helper function to execute queries
const executeQuery = (query, params) => {
return new Promise((resolve, reject) => {
pool.execute(query, params, (err, results) => {
if (err) {
reject(err);
} else {
resolve(results);
}
});
});
};
app.get('/getData', async (req, res) => {
try {
const range = req.query.range || 'yearly';
let startDate = '';
let endDate = '';
// Define the date range based on the selected period
switch (range) {
case 'weekly':
startDate = moment().startOf('week').format('YYYY-MM-DD');
endDate = moment().endOf('week').format('YYYY-MM-DD');
break;
case 'monthly':
startDate = moment().startOf('month').format('YYYY-MM-DD');
endDate = moment().endOf('month').format('YYYY-MM-DD');
break;
case 'yearly':
startDate = moment().startOf('year').format('YYYY-MM-DD');
endDate = moment().format('YYYY-MM-DD');
break;
default:
startDate = moment().startOf('year').format('YYYY-MM-DD');
endDate = moment().format('YYYY-MM-DD');
break;
}
// Fetch sales quantity data for Apex Basic Chart with 3-letter month and 2-digit year abbreviation (e.g., Jun 24)
const salesQuery = `
SELECT DATE_FORMAT(sale_date, '%b %y') AS date, SUM(sales_qty) AS total_sales
FROM sales
WHERE DATE(sale_date) BETWEEN ? AND ?
GROUP BY DATE_FORMAT(sale_date, '%b %y')
`;
const salesData = await executeQuery(salesQuery, [startDate, endDate]);
// Fetch sell-through rate and inventory turnover rate for Apex Line Area Chart
const metricsQuery = `
SELECT DATE_FORMAT(report_date, '%b %y') AS date,
AVG(sell_through_rate) AS avg_sell_through_rate,
AVG(inventory_turnover_rate) AS avg_inventory_turnover_rate
FROM reports
WHERE DATE(report_date) BETWEEN ? AND ?
GROUP BY DATE_FORMAT(report_date, '%b %y')
`;
const metricsData = await executeQuery(metricsQuery, [startDate, endDate]);
// Fetch revenue by product for Apex 3D Pie Chart
const revenueByProductQuery = `
SELECT report_date, revenue_by_product
FROM reports
WHERE DATE(report_date) BETWEEN ? AND ?
`;
const revenueByProductData = await executeQuery(revenueByProductQuery, [startDate, endDate]);
// Decode the revenue_by_product JSON data and aggregate it
let revenueByProduct = {};
revenueByProductData.forEach(report => {
const products = JSON.parse(report.revenue_by_product);
if (Array.isArray(products)) {
products.forEach(product => {
if (product.product_name && product.total_sales) {
const productName = product.product_name;
const totalSales = parseFloat(product.total_sales);
revenueByProduct[productName] = (revenueByProduct[productName] || 0) + totalSales;
}
});
}
});
// Sort and get the top 5 products
const top5Products = Object.entries(revenueByProduct)
.sort((a, b) => b[1] - a[1])
.slice(0, 5)
.map(([productName, totalSales]) => ({ product_name: productName, total_sales: totalSales }));
// Fetch revenue, total cost, and additional expenses for Apex 3-Column Chart
const revenueQuery = `
SELECT DATE_FORMAT(sale_date, '%b %y') AS date, SUM(sales_qty * price) AS revenue
FROM sales
JOIN products ON sales.product_id = products.id
WHERE DATE(sale_date) BETWEEN ? AND ?
GROUP BY DATE_FORMAT(sale_date, '%b %y')
`;
const revenueData = await executeQuery(revenueQuery, [startDate, endDate]);
const totalCostQuery = `
SELECT DATE_FORMAT(sale_date, '%b %y') AS date, SUM(sales_qty * cost) AS total_cost
FROM sales
JOIN products ON sales.product_id = products.id
WHERE DATE(sale_date) BETWEEN ? AND ?
GROUP BY DATE_FORMAT(sale_date, '%b %y')
`;
const totalCostData = await executeQuery(totalCostQuery, [startDate, endDate]);
const expenseQuery = `
SELECT DATE_FORMAT(expense_date, '%b %y') AS date, SUM(amount) AS total_expenses
FROM expenses
WHERE DATE(expense_date) BETWEEN ? AND ?
GROUP BY DATE_FORMAT(expense_date, '%b %y')
`;
const expenseData = await executeQuery(expenseQuery, [startDate, endDate]);
// Combine revenue, total cost, and additional expenses for Apex 3-Column Chart
const combinedData = revenueData.map(data => {
const date = data.date;
const revenue = parseFloat(data.revenue || 0);
const totalCost = parseFloat(totalCostData.find(item => item.date === date)?.total_cost || 0);
const expenses = parseFloat(expenseData.find(item => item.date === date)?.total_expenses || 0);
const totalExpenses = totalCost + expenses;
const profit = revenue - totalExpenses;
return {
date,
revenue: revenue.toFixed(2),
total_expenses: totalExpenses.toFixed(2),
profit: profit.toFixed(2)
};
});
// Prepare final data for each chart
const response = {
'apex-basic': salesData,
'apex-line-area': metricsData,
'am-3dpie-chart': top5Products,
'apex-column': combinedData
};
res.json(response);
} catch (err) {
console.error('Database error:', err);
res.status(500).json({ error: 'Failed to retrieve data.' });
}
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});