Skip to content

Commit

Permalink
done with pie chart
Browse files Browse the repository at this point in the history
  • Loading branch information
JaberHPranto committed Oct 16, 2021
1 parent 99a4276 commit 83fb6f2
Show file tree
Hide file tree
Showing 9 changed files with 201 additions and 22 deletions.
5 changes: 5 additions & 0 deletions client/package-lock.json

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

1 change: 1 addition & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"react": "^17.0.2",
"react-bootstrap": "^1.6.1",
"react-chartjs-2": "^3.0.5",
"react-csv": "^2.0.3",
"react-dom": "^17.0.2",
"react-file-base64": "^1.0.3",
"react-google-login": "^5.2.2",
Expand Down
30 changes: 30 additions & 0 deletions client/src/components/Ecommerce/CSVReportGeneration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import React from 'react';
import { CSVLink } from 'react-csv';

function CSVReportGeneration({ data }) {

const csv_data = data
const headers = [
{ label: "Date", key: "date" },
{ label: "Product ID", key: "product_id" },
{ label: "Product Name", key: "product_name" },
{ label: "Price/Per unit", key: "product_price" },
{ label: "Quantity", key: "product_qty" },
{ label: "Total", key: "total" },
]

const csvReport = {
filename: 'SalesReport.csv',
headers,
data:csv_data
}


return (
<div style={{ marginTop: '2rem', textAlign: 'center', fontSize: '1.7rem', marginBottom: '5rem', fontFamily: 'Poppins' }} >
<CSVLink {...csvReport} >Export to CSV</CSVLink>
</div>
)
}

export default CSVReportGeneration
88 changes: 88 additions & 0 deletions client/src/components/Ecommerce/Charts/SalesPieChart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import React from 'react';
import { Pie } from 'react-chartjs-2';

function SalesPieChart({ pie_data }) {


const dataLabel = []
const dataValues = []

for (let pd of pie_data) {
const val = parseInt(pd.value)
dataLabel.push(pd.name)
dataValues.push(val)
}

const bgColPalette = [
'rgba(255, 99, 132, 0.2)', //Red
'rgba(54, 162, 235, 0.2)', //Blue
'rgba(255, 206, 86, 0.2)', // Yellow
'rgba(75, 192, 192, 0.2)', // Green
'rgba(153, 102, 255, 0.2)', // Purple
'rgba(255, 159, 64, 0.2)', // Orange
'rgba(255, 99, 132, 0.8)', //Red
'rgba(54, 162, 235, 0.8)', //Blue
'rgba(255, 206, 86, 0.8)', // Yellow
'rgba(75, 192, 192, 0.8)', // Green
'rgba(153, 102, 255, 0.8)', // Purple
'rgba(255, 159, 64, 0.8)', // Orange
'rgba(255, 99, 132,1)', //Red
'rgba(54, 162, 235, 1)', //Blue
'rgba(255, 206, 86, 1)', // Yellow
'rgba(75, 192, 192, 1)', // Green
'rgba(153, 102, 255, 1)', // Purple
'rgba(255, 159, 64, 1)', // Orange
]
const borderColPalette = [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
]


const background = []
const border = []

for (let i = 0; i < pie_data.length; i++){
background[i] = bgColPalette[i]
border[i] = borderColPalette[i]
}

const data = {
labels: dataLabel,
datasets: [
{
label: 'Contribution of each product',
data: dataValues,
backgroundColor:background ,
borderColor:border,
borderWidth: 1,
},
],

};

return (

<div style={{ width: '50%', margin: 'auto' }}>
<Pie data={data} />
</div>
)
}

export default SalesPieChart
2 changes: 1 addition & 1 deletion client/src/components/Ecommerce/SaleDataCategory.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const SaleDataCategory = ({onSelect,data}) => {
return (
<div className='dropdown'>
<div className='dropdown-header' onClick={toggleDropdown}>
{selectedItem ? items.find(item => item.id === selectedItem).label : "Select Blog Category"}
{selectedItem ? items.find(item => item.id === selectedItem).label : "Select Month"}
<i className={`fa fa-chevron-right icon ${isOpen && "open"}`}></i>
</div>
<div className={`dropdown-body ${isOpen && 'open'}`}>
Expand Down
10 changes: 6 additions & 4 deletions client/src/components/Ecommerce/Screen/ProductListScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,15 +79,17 @@ function ProductListScreen({history}) {

<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Category</th>
<th>In Stock</th>
<th>Product ID</th>
<th>Name</th>
<th>Price</th>
<th>Category</th>
<th>In Stock</th>
</tr>
</thead>
<tbody>
{products.map(product=>(
<tr key={product._id}>
<td>{product._id}</td>
<td>{product.name}</td>
<td><span style={{fontSize:'1.5rem',marginRight:'0.1rem'}}></span>&nbsp;{product.price}</td>
<td>{product.category}</td>
Expand Down
58 changes: 51 additions & 7 deletions client/src/components/Ecommerce/Screen/SaleDataScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import BarChart from '../Charts/BarChart';
import LineChart from '../Charts/LineChart';
import MonthBarChart from '../Charts/MonthBarChart';
import ProductSaleBarChart from '../Charts/ProductSaleBarChart';
import SalesPieChart from '../Charts/SalesPieChart';
import CSVReportGeneration from '../CSVReportGeneration';
import { monthData } from "../EcommSeedData";
import SaleDataCategory from '../SaleDataCategory';
import Sidebar from '../Sidebar';
Expand All @@ -18,14 +20,14 @@ function SaleDataScreen({ history }) {
const [monthSale, setMonthSale] = useState("")
const [productSale, setProductSale] = useState("")
const [search, setSearch] = useState("")
const [reportData, setReportData] = useState("")
const [salesPieData, setSalesPieData] = useState("")

const dispatch = useDispatch()
const { userInfo: { user,token } } = useSelector(state => state.userLogin)

const order = useSelector(state => state.orderSaleData)
const { loading, error, orderSaleData } = order

// if (orderSaleData) console.log(orderSaleData)
const { orderSaleData } = order


useEffect(() => {
Expand All @@ -38,7 +40,38 @@ function SaleDataScreen({ history }) {

const handleSelect = (e) => {
setGraphType(e)

}

const onSalesMonthSelect = (e) => {
const { totalOrder } = orderSaleData?.find(el => el.month === e)
const saleData = []
const salesPieData = []

for (let data of totalOrder) {
for (let pd of data.orderedItems) {
const date = data.createdAt.substring(0, 10);
const product_id = pd._id;
const product_name = pd.name;
const product_price = pd.price;
const product_qty = pd.qty;
const total = pd.price * pd.qty
saleData.push({ date, product_id, product_name, product_price, product_qty, total })

// for pie chart
salesPieData.push({ name: product_name, value: total })

}
}

// console.log(salesPieData);

// for pie chart
const res = Array.from(salesPieData.reduce(
(m, { name, value }) => m.set(name, (m.get(name) || 0) + value), new
Map()), ([name, value]) => ({ name, value }));

setSalesPieData(res)
setReportData(saleData)
}

const onMonthSelect = async (e) => {
Expand All @@ -52,7 +85,6 @@ function SaleDataScreen({ history }) {
}
}
const { data } = await axios.post(`/api/orders/saleDataByMonth`, { selectedMonth }, config)

setMonthSale(data)

} catch (error) {
Expand All @@ -72,7 +104,6 @@ function SaleDataScreen({ history }) {
}
}
const { data } = await axios.post(`/api/orders/saleByAProduct`, {product_id:search }, config)
console.log(data);
setProductSale(data)

} catch (error) {
Expand Down Expand Up @@ -121,7 +152,20 @@ function SaleDataScreen({ history }) {
<Button className="bg-col-primary" type="submit" >Search</Button>
</Form>
</div>
{productSale && <ProductSaleBarChart monthWiseQty={productSale.monthWiseQty} productName={productSale.productName} />}
{productSale && <ProductSaleBarChart monthWiseQty={productSale.monthWiseQty} productName={productSale.productName} />}

<div className="sales-report">
<h3 className='sale-day-heading'>Sales Report Generation</h3>
<SaleDataCategory onSelect={onSalesMonthSelect} data={monthData} />
{reportData && <CSVReportGeneration data={reportData} />}
{salesPieData &&
<div>
<h4 className='pie-heading'>Contribution of sold products</h4>
<SalesPieChart pie_data={salesPieData} />
</div>
}
</div>


</>
</Col>
Expand Down
5 changes: 5 additions & 0 deletions client/src/styles/ecommerce.css
Original file line number Diff line number Diff line change
Expand Up @@ -243,3 +243,8 @@ main {
min-width: 33% !important;
margin-top: 1.5rem;
}
.pie-heading {
text-align: center;
font-family: "Poppins";
margin: 0.5rem 0 2rem 0;
}
24 changes: 14 additions & 10 deletions server/controller/orderController.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,19 @@ const getSaleDataByYear = async (req, res) => {
saleDataByMonths.push({ month, totalOrder: saleByMonth, numOfOrder: saleByMonth.length })
}


// New
const dd = new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 120).toISOString()
const numOfDays = 120
const dd = new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * numOfDays).toISOString()

// console.log(dd.substring(0,10))
console.log(dd.substring(0,10))
const test = [
// Get only records created in the last 30 days
{
$match: {
"createdAt": {
// $gte: new Date(`${dd}`)
$gte: new Date(`${year}-07-01`), $lt: new Date(`${year}-07-31`)
$gte: new Date(`${dd.substring(0,10)}`)
// $gte: new Date(`${year}-07-01`), $lt: new Date(`${year}-07-31`)
}
}
},
Expand All @@ -141,12 +143,14 @@ const getSaleDataByYear = async (req, res) => {
]


const dayCount = await Order.aggregate(test)
const dayWiseSale = new Array(30).fill(0)

for (let i of dayCount) {
dayWiseSale[i.day]=dayWiseSale[i.day]+1
}
// const dayCount = await Order.aggregate(test)
// console.log(dayCount)
// console.log(dayCount.length)

// const dayWiseSale = new Array(30).fill(0)
// for (let i of dayCount) {
// dayWiseSale[i.day]=dayWiseSale[i.day]+1
// }


return res.status(200).json(saleDataByMonths)
Expand Down

0 comments on commit 83fb6f2

Please sign in to comment.