Skip to content

Commit

Permalink
done with quering sales data
Browse files Browse the repository at this point in the history
  • Loading branch information
JaberHPranto committed Oct 14, 2021
1 parent 2317a35 commit 935bcd1
Show file tree
Hide file tree
Showing 10 changed files with 300 additions and 8 deletions.
30 changes: 30 additions & 0 deletions client/src/components/Ecommerce/Screen/OrderDataScreen.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getOrderData } from '../../../redux/actions/orderActions'

function OrderDataScreen({history}) {

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

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

if(orderData) console.log(orderData)

useEffect(() => {
if (user && user.isAdmin) {
dispatch(getOrderData())
} else {
history.push("/login")
}
}, [dispatch,history,user])

return (
<div>
hello
</div>
)
}

export default OrderDataScreen
1 change: 0 additions & 1 deletion client/src/components/Ecommerce/Screen/RegisterScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ function RegisterScreen({location,history}) {

const handleSubmit = (e) => {
e.preventDefault()
console.log(name, email, password);
dispatch(register(name,email,password,confirmPassword))
}

Expand Down
30 changes: 30 additions & 0 deletions client/src/components/Ecommerce/Screen/SaleDataScreen.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getSaleData } from '../../../redux/actions/orderActions'

function SaleDataScreen({history}) {

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

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

if(orderSaleData) console.log(orderSaleData)

useEffect(() => {
if (user && user.isAdmin) {
dispatch(getSaleData())
} else {
history.push("/login")
}
}, [dispatch,history,user])

return (
<div>
hello
</div>
)
}

export default SaleDataScreen
10 changes: 10 additions & 0 deletions client/src/constants/orderConstants.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,13 @@ export const ORDER_CREATE_FAIL = "ORDER_CREATE_FAIL";
export const ORDER_LIST_REQUEST = "ORDER_LIST_REQUEST";
export const ORDER_LIST_SUCCESS = "ORDER_LIST_SUCCESS";
export const ORDER_LIST_FAIL = "ORDER_LIST_FAIL";

export const ORDER_DATA_REQUEST = "ORDER_DATA_REQUEST";
export const ORDER_DATA_SUCCESS = "ORDER_DATA_SUCCESS";
export const ORDER_DATA_FAIL = "ORDER_DATA_FAIL";

export const ORDER_SALE_DATA_REQUEST = "ORDER_SALE_DATA_REQUEST";
export const ORDER_SALE_DATA_SUCCESS = "ORDER_SALE_DATA_SUCCESS";
export const ORDER_SALE_DATA_FAIL = "ORDER_SALE_DATA_FAIL";


4 changes: 4 additions & 0 deletions client/src/pages/MainPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import CartScreen from '../components/Ecommerce/Screen/CartScreen';
import ForgetPasswordScreen from '../components/Ecommerce/Screen/ForgetPasswordScreen';
import HomeScreen from '../components/Ecommerce/Screen/HomeScreen';
import LoginScreen from '../components/Ecommerce/Screen/LoginScreen';
import OrderDataScreen from "../components/Ecommerce/Screen/OrderDataScreen";
import OrderListScreen from "../components/Ecommerce/Screen/OrderListScreen";
import PasswordResetScreen from '../components/Ecommerce/Screen/PasswordResetScreen';
import PaymentScreen from "../components/Ecommerce/Screen/PaymentScreen";
Expand All @@ -21,6 +22,7 @@ import ProductListScreen from "../components/Ecommerce/Screen/ProductListScreen"
import ProductScreen from '../components/Ecommerce/Screen/ProductScreen';
import ProfileScreen from '../components/Ecommerce/Screen/ProfileScreen';
import RegisterScreen from '../components/Ecommerce/Screen/RegisterScreen';
import SaleDataScreen from "../components/Ecommerce/Screen/SaleDataScreen";
import ShippingScreen from "../components/Ecommerce/Screen/ShippingScreen";
import UserListScreen from "../components/Ecommerce/Screen/UserListScreen";
import PlantIdentify from "../components/PlantIdentify/PlantIdentify";
Expand Down Expand Up @@ -52,6 +54,8 @@ function MainPage() {
<Route path="/admin/userlist" component={UserListScreen} />
<Route path="/admin/productlist" component={ProductListScreen} />
<Route path="/admin/orderlist" component={OrderListScreen} />
<Route path="/admin/orderData" component={OrderDataScreen} />
<Route path="/admin/saleData" component={SaleDataScreen} />
<Route path="/admin/product/:id/edit" component={ProductEditScreen} />
<Route path="/product/:id" component={ProductScreen} />
<Route path="/cart/:id?" component={CartScreen} />
Expand Down
76 changes: 75 additions & 1 deletion client/src/redux/actions/orderActions.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import axios from "axios";
import {
ORDER_CREATE_FAIL, ORDER_CREATE_REQUEST, ORDER_CREATE_SUCCESS, ORDER_LIST_FAIL, ORDER_LIST_REQUEST, ORDER_LIST_SUCCESS
ORDER_CREATE_FAIL, ORDER_CREATE_REQUEST, ORDER_CREATE_SUCCESS, ORDER_DATA_FAIL, ORDER_DATA_REQUEST, ORDER_DATA_SUCCESS, ORDER_LIST_FAIL, ORDER_LIST_REQUEST, ORDER_LIST_SUCCESS, ORDER_SALE_DATA_FAIL, ORDER_SALE_DATA_REQUEST, ORDER_SALE_DATA_SUCCESS
} from "../../constants/orderConstants";


Expand Down Expand Up @@ -86,4 +86,78 @@ export const getOrderList = () => async (dispatch,getState) => {

}

}


export const getOrderData = () => async (dispatch,getState) => {

try {
dispatch({
type:ORDER_DATA_REQUEST
})

const { userLogin: { userInfo } } = getState()


const config = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${userInfo.token}`
}
}

const { data } = await axios.get(`/api/orders/order-data`, config)

dispatch({
type: ORDER_DATA_SUCCESS,
payload:data
})

} catch (error) {
console.log(error);
dispatch({
type: ORDER_DATA_FAIL,
payload: error.response && error.response.data.message ? error.response.data.message : error.message

})

}

}


export const getSaleData = () => async (dispatch,getState) => {

try {
dispatch({
type:ORDER_SALE_DATA_REQUEST
})

const { userLogin: { userInfo } } = getState()


const config = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${userInfo.token}`
}
}

const { data } = await axios.get(`/api/orders/saleDataByYear`, config)

dispatch({
type: ORDER_SALE_DATA_SUCCESS,
payload:data
})

} catch (error) {
console.log(error);
dispatch({
type: ORDER_SALE_DATA_FAIL,
payload: error.response && error.response.data.message ? error.response.data.message : error.message

})

}

}
40 changes: 38 additions & 2 deletions client/src/redux/reducers/orderReducers.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {
ORDER_CREATE_FAIL, ORDER_CREATE_REQUEST, ORDER_CREATE_SUCCESS, ORDER_LIST_FAIL, ORDER_LIST_REQUEST, ORDER_LIST_SUCCESS
ORDER_CREATE_FAIL, ORDER_CREATE_REQUEST, ORDER_CREATE_SUCCESS, ORDER_DATA_FAIL, ORDER_DATA_REQUEST, ORDER_DATA_SUCCESS, ORDER_LIST_FAIL, ORDER_LIST_REQUEST, ORDER_LIST_SUCCESS, ORDER_SALE_DATA_FAIL, ORDER_SALE_DATA_REQUEST, ORDER_SALE_DATA_SUCCESS
} from "../../constants/orderConstants";

export const orderCreateReducer = (state = {}, action) => {
Expand Down Expand Up @@ -43,4 +43,40 @@ export const orderListReducer = (state = { orders: [] }, action) => {
default:
return state
}
}
}


export const orderDataReducer = (state = { orderData: [] }, action) => {
switch (action.type) {
case ORDER_DATA_REQUEST:
return { ...state,loading: true }

case ORDER_DATA_SUCCESS:
return { loading: false, orderData: action.payload }

case ORDER_DATA_FAIL:
return { loading: false, error: action.payload }


default:
return state
}
}


export const orderSaleDataReducer = (state = { orderSaleData: [] }, action) => {
switch (action.type) {
case ORDER_SALE_DATA_REQUEST:
return { ...state,loading: true }

case ORDER_SALE_DATA_SUCCESS:
return { loading: false, orderSaleData: action.payload }

case ORDER_SALE_DATA_FAIL:
return { loading: false, error: action.payload }


default:
return state
}
}
4 changes: 3 additions & 1 deletion client/src/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import thunk from "redux-thunk";
import { blogDetailsReducer, blogListReducer } from "./redux/reducers/blogReducers";
import { cartReducer } from "./redux/reducers/cartReducers";
import {
orderCreateReducer, orderListReducer
orderCreateReducer, orderDataReducer, orderListReducer, orderSaleDataReducer
} from "./redux/reducers/orderReducers";
import {
productCreateReducer, productCreateReviewReducer, productDeleteReducer, productDetailsReducer,
Expand Down Expand Up @@ -33,6 +33,8 @@ const reducer = combineReducers({
cart: cartReducer,
orderCreate: orderCreateReducer,
orderList: orderListReducer,
orderData: orderDataReducer,
orderSaleData: orderSaleDataReducer,
blogList: blogListReducer,
blogDetails: blogDetailsReducer
});
Expand Down
107 changes: 106 additions & 1 deletion server/controller/orderController.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncHandler from "express-async-handler";
import Order from "../models/orderModel.js";
import User from "../models/userModel.js";

// @desc Create new order
// @route POST /api/orders
Expand Down Expand Up @@ -46,5 +47,109 @@ const getOrders = asyncHandler(async (req, res) => {
res.json(orders)
})

export { addOrderItems, getOrders };
const getOrderData = async (req, res) => {
try {

const eachProductTotalSale = [
{ $match: {} },
{ $unwind: "$orderedItems" },
{ $group: { "_id": "$orderedItems.name", "total": { "$sum": "$orderedItems.qty" } } },
{$sort:{"total":-1}}
]

const eachCustomerTotalBuy = [
{ $match: {} },
{ $group: { "_id": "$user", "total": { "$sum": "$totalPrice" } } },
{ $sort: { "total": -1 } }
]


const productSaleData = await Order.aggregate(eachProductTotalSale)
const customerBuy = await Order.aggregate(eachCustomerTotalBuy).limit(5)

const customerBuyData = []
for (let cb of customerBuy) {
const { name } = await User.findById(cb._id)
customerBuyData.push({ customer: name, total: cb.total })
}

const totalOrder = await Order.countDocuments()
const totalPaidOrder = await Order.find({ isPaid: true }).countDocuments()
const totalDelivered = await Order.find({ isDelivered: true }).countDocuments()


// console.log(productSale);
// console.log("--------");
// console.log(customerBuyData);

res.status(200).json({ productSaleData, customerBuyData, totalOrder, totalPaidOrder, totalDelivered })

}catch(err){
console.log(err)
res.status(401).json({error:"Something went wrong"})
}
}


const getSaleDataByYear = async (req, res) => {
try {
const year = 2021

const months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]

const saleDataByMonths=[]
for (let i = 1; i <= 12; i++){
const monthQuery = { createdAt: { $gte: new Date(`${year}-0${i}-01`), $lt: new Date(`${year}-0${i}-31`) } }
const saleByMonth = await Order.find(monthQuery)
const month = months[i-1]
saleDataByMonths.push({ month, totalOrder: saleByMonth, numOfOrder: saleByMonth.length })
}

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

console.log(dd.substring(0,10))
const test = [
// Get only records created in the last 30 days
{
$match: {
"createdAt": {
$gte: new Date(`${dd}`)
}
}
},
// Get the year, month and day from the createdTimeStamp
{
$project: {
"year": {
$year: "$createdAt"
},
"month": {
$month: "$createdAt"
},
"day": {
$dayOfMonth: "$createdAt"
}
}
},
]


const dayCount = await Order.aggregate(test)
// for (let i of dayCount) {
// if()
// }

// console.log(dayCount);


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

} catch (err) {
console.log(err);
return res.status(500).json({ error: "Server Error"})
}
}

export { addOrderItems, getOrders, getOrderData, getSaleDataByYear };

6 changes: 4 additions & 2 deletions server/routes/orderRoutes.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import express from "express";
import { addOrderItems, getOrders } from "../controller/orderController.js";
import { addOrderItems, getOrderData, getOrders, getSaleDataByYear } from "../controller/orderController.js";
import { isAdmin, isLoggedIn } from "../middlewares/authMiddleware.js";
const router = express.Router();

router.route("/").post(isLoggedIn, addOrderItems);
router.route("/").get(isLoggedIn,isAdmin,getOrders);
router.route("/").get(isLoggedIn, isAdmin, getOrders);
router.get("/order-data", isLoggedIn, isAdmin, getOrderData)
router.get("/saleDataByYear",isLoggedIn,isAdmin,getSaleDataByYear)

export default router;

0 comments on commit 935bcd1

Please sign in to comment.