Skip to content

Commit

Permalink
Sales chart added and made few updates
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaushalya193 committed Jan 6, 2024
1 parent 92ea294 commit 70e83f0
Show file tree
Hide file tree
Showing 9 changed files with 175 additions and 44 deletions.
27 changes: 27 additions & 0 deletions code/Software/Frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions code/Software/Frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@
"axios": "^1.6.3",
"bootstrap": "^5.3.2",
"bootstrap-icons": "^1.11.2",
"chart.js": "^4.4.1",
"mqtt": "^5.3.4",
"react": "^18.2.0",
"react-chartjs-2": "^5.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.21.1"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ const Dashboard = () => {

const fetchProductQuantities = async () => {
try {
const response = await axios.get("http://localhost:5555/itemPurchased/quantity");
const response = await axios.get("http://localhost:5555/itemPurchased/quantity/t");
const data = response.data;
console.log(data);

Expand Down Expand Up @@ -95,7 +95,7 @@ const Dashboard = () => {
<p className="card-text">LKR {totalSaleToday}</p>
Total Sales
</h5>
<p>{percentageChange}% from yesterday</p>
<p>{percentageChange.toFixed(0)}% from yesterday</p>
</div>
</div>
</div>
Expand All @@ -108,7 +108,7 @@ const Dashboard = () => {
<p className="card-text">{billCountToday}</p>
Total Bills
</h5>
<p>{percentageChangeBills}% from yesterday</p>
<p>{percentageChangeBills.toFixed(0)}% from yesterday</p>
</div>
</div>
</div>
Expand Down
6 changes: 3 additions & 3 deletions code/Software/Frontend/src/AdminDashboard/Invoices.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ function Invoices() {
name="totalAmount"
value={updateFormData[invoice._id]?.totalAmount || ""}
onChange={(e) => handleUpdateInputChange(e, invoice._id)}
style={{ width: '70px' }}
style={{ width: '70px',height:'27px',borderRadius:'1px'}}
/>
</form>
</td>
Expand All @@ -165,7 +165,7 @@ function Invoices() {
name="discountApplied"
value={updateFormData[invoice._id]?.discountApplied || ""}
onChange={(e) => handleUpdateInputChange(e, invoice._id)}
style={{ width: '90px'}}
style={{ width: '90px',height:'27px',borderRadius:'1px'}}
/></form>
</td>
<td>{invoice.paymentMethod}
Expand All @@ -176,7 +176,7 @@ function Invoices() {
name="paymentMethod"
value={updateFormData[invoice._id]?.paymentMethod || ""}
onChange={(e) => handleUpdateInputChange(e, invoice._id)}
style={{ width: '100px' }}
style={{ width: '100px' ,height:'27px',borderRadius:'1px'}}
/>
</form>
</td>
Expand Down
96 changes: 87 additions & 9 deletions code/Software/Frontend/src/AdminDashboard/Sales.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,89 @@
import React from "react";
import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
//import { Line } from 'react-chartjs-2';
import Chart from 'chart.js/auto';

function Sales(){
return(
<div>
<h6>Sales details here...</h6>
</div>
)
}

export default Sales;
const Sales = () => {
const [data, setData] = useState([]);
const [labels, setLabels] = useState([]);
const chartRef = useRef(null);

useEffect(() => {
const fetchData = async () => {
try {
const today = new Date();
const lastTenDays = Array.from({ length: 10 }, (_, i) => {
const day = new Date(today);
day.setDate(today.getDate() - i+1);
return day.toISOString().split('T')[0];
});

const fetchDataPromises = lastTenDays.map(async (day) => {
const response = await axios.get(`http://localhost:5555/bill/billCountPerDay/${day}`);
return response.data.billCountSelectedDay;

});

const fetchedData = await Promise.all(fetchDataPromises);

setData(fetchedData.reverse());
setLabels(lastTenDays.reverse());
} catch (error) {
console.error('Error fetching data:', error.message);
}
};

fetchData();
}, []);

useEffect(() => {
const renderChart = () => {
if (chartRef.current) {
const chartInstance = chartRef.current.chartInstance;
if (chartInstance) {
chartInstance.destroy();
}

chartRef.current.chartInstance = new Chart(chartRef.current.getContext('2d'), {
type: 'line',
data: {
labels: labels,
datasets: [
{
label: 'Bill Issued Per Day (customer count)',
data: data,
fill: false,
borderColor: 'rgba(75,192,192,1)',
},
],
},
options: {
scales: {
x: {
type: 'category',
labels: labels,
},
y: {
beginAtZero: true,
min: 0,
},
},
},
});
}
};

renderChart();
}, [data, labels]);

return (
<div>
<h2>Sales Data Variation</h2><br/>
<canvas ref={chartRef}></canvas>
</div>
);
};

export default Sales;

26 changes: 25 additions & 1 deletion code/Software/Server/controllers/billController.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,4 +172,28 @@ export async function getBillsToday(request, response) {
}

return ((currentValue - previousValue) / Math.abs(previousValue)) * 100;
}
}
export async function getBillCountPerdate(request, response) {
try {
const { day } = request.params;

// Parse the day parameter to a Date object
const selectedDay = new Date(day);
selectedDay.setHours(0, 0, 0, 0); // Set hours, minutes, seconds, and milliseconds to 0

// Get bills created on the selected day
const billsOnSelectedDay = await Bill.find({
createdAt: { $gte: selectedDay, $lt: new Date(selectedDay.getTime() + 24 * 60 * 60 * 1000) },
});

// Calculate the bill count for the selected day
const billCountSelectedDay = billsOnSelectedDay.length;

response.status(200).json({ billCountSelectedDay });
} catch (error) {
console.error(error.message);
response.status(500).json({ error: 'An error occurred while fetching the bill count for the selected day.' });
}
}


49 changes: 23 additions & 26 deletions code/Software/Server/controllers/itemPurchasedController.js
Original file line number Diff line number Diff line change
Expand Up @@ -214,29 +214,26 @@ export async function deleteItemsPurchasedById(request, response) {
}

export const getTotalProductQuantities = async () => {
try {
// Get the current date
const today = moment().startOf('day');

// Use Mongoose aggregation to sum the total quantities
const result = await ItemPurchased.aggregate([
{
$match: {
createdAt: { $gte: today.toDate() },
},
},
{
$group: {
_id: null,
totalQuantity: { $sum: "$quantity" },
},
},
]);

return result.length > 0 ? result[0].totalQuantity : 0;
} catch (error) {
console.error("Error fetching total product sold:", error);
throw error;
}
};

try {

const today = new Date();
today.setHours(0, 0, 0, 0);

// Get items purchased today
const itemsPurchased = await ItemPurchased.find({
createdAt: { $gte: today },
});

// Calculate the total quantity by summing the quantity field
const totalQuantity = itemsPurchased.reduce(
(total, item) => total + item.quantity,
0
);

return totalQuantity;
} catch (error) {

console.error("Error fetching total product sold:", error);
throw error;
}
};
4 changes: 3 additions & 1 deletion code/Software/Server/routes/billRoute.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@ import {
saveNewBill,
updateBill,
deleteBillById,
getBillsToday
getBillsToday,
getBillCountPerdate
} from "../controllers/billController.js";

const router = express.Router();

// Route for get bills today
router.get("/today", getBillsToday);

router.get("/billCountPerDay/:day",getBillCountPerdate)
// Route for get all bills
router.get("/", getAllBills);

Expand Down
3 changes: 2 additions & 1 deletion code/Software/Server/routes/itemPurchasedRoute.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ router.use(cors());
// Route for get total sale today
router.get("/saletoday", getProductsSoldToday);

router.get("/quantity", getTotalProductQuantities);
// Route for get total product quantities in today
router.get("/quantity/t", getTotalProductQuantities);

// Route for get all purchased item
router.get("/", getAllItemsPurchased);
Expand Down

0 comments on commit 70e83f0

Please sign in to comment.