Skip to content

Commit

Permalink
Worked on Placing Order by User
Browse files Browse the repository at this point in the history
  • Loading branch information
moshiurrafialvi committed Jul 9, 2021
1 parent 38c8c1c commit 2b2a762
Show file tree
Hide file tree
Showing 10 changed files with 182 additions and 34 deletions.
2 changes: 1 addition & 1 deletion client/src/components/Ecommerce/Screen/PaymentScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const PaymentScreen = ({ history }) => {
id="Stripe"
name="paymentMethod"
value="Stripe"
checked={paymentMethod === "PayPal" ? true : false}
checked={paymentMethod === "PayPal"}
onChange={(e) => setPaymentMethod(e.target.value)}
></Form.Check>

Expand Down
45 changes: 31 additions & 14 deletions client/src/components/Ecommerce/Screen/PlaceOrderScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,34 @@ import { Button, Row, Col, ListGroup, Image, Card } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import Message from "../Message";
import CheckoutSteps from "../CheckoutSteps";

/* import { ORDER_CREATE_RESET } from "../constants/orderConstants";
import { USER_DETAILS_RESET } from "../constants/userConstants"; */
import { createOrder } from "../../../redux/actions/orderActions";

const PlaceOrderScreen = ({ history }) => {
const dispatch = useDispatch();

const cart = useSelector((state) => state.cart);

const orderCreate = useSelector((state) => state.orderCreate);
const { order, success, error } = orderCreate;

useEffect(() => {
if (success) {
history.push(`/order/${order._id}`);
}
// eslint-disable-next-line
}, [history, success]);

const placeOrderHandler = () => {
console.log("");
dispatch(
createOrder({
orderItems: cart.cartItems,
shippingAddress: cart.shippingAddress,
paymentMethod: cart.paymentMethod,
itemsPrice: cart.itemsPrice,
shippingPrice: cart.shippingPrice,
totalPrice: cart.totalPrice,
})
);
};
//Calculate Price
const addDecimals = (num) => {
Expand All @@ -22,10 +41,9 @@ const PlaceOrderScreen = ({ history }) => {
cart.itemsPrice = addDecimals(
cart.cartItems.reduce((acc, item) => acc + item.price * item.qty, 0)
);
cart.shippingPrice = 30; //addDecimals(cart.itemsPrice > 100 ? 0 : 100);
/* cart.taxPrice = addDecimals(Number((0.15 * cart.itemsPrice).toFixed(2))); */
cart.shippingPrice = 30;

cart.totalPrice = Number(cart.itemsPrice) + Number(cart.shippingPrice);
//Number(cart.taxPrice)

return (
<>
Expand All @@ -34,7 +52,7 @@ const PlaceOrderScreen = ({ history }) => {
<Col md={8}>
<ListGroup variant="flush">
<ListGroup.Item>
<h2>Shipping</h2>
<h2>Delivery Location</h2>
<p>
<strong>Address:</strong>
{cart.shippingAddress.address}, {cart.shippingAddress.city}{" "}
Expand All @@ -47,7 +65,6 @@ const PlaceOrderScreen = ({ history }) => {
<strong>Method: </strong>
{cart.paymentMethod}
</ListGroup.Item>

<ListGroup.Item>
<h2>Order Items</h2>
{cart.cartItems.length === 0 ? (
Expand Down Expand Up @@ -90,13 +107,13 @@ const PlaceOrderScreen = ({ history }) => {
<ListGroup.Item>
<Row>
<Col>Items</Col>
<Col>${cart.itemsPrice}</Col>
<Col>{cart.itemsPrice}</Col>
</Row>
</ListGroup.Item>
<ListGroup.Item>
<Row>
<Col>Delivery Charge</Col>
<Col>${cart.shippingPrice}</Col>
<Col>{cart.shippingPrice}</Col>
</Row>
</ListGroup.Item>
{/* <ListGroup.Item>
Expand All @@ -108,12 +125,12 @@ const PlaceOrderScreen = ({ history }) => {
<ListGroup.Item>
<Row>
<Col>Total</Col>
<Col>${cart.totalPrice}</Col>
<Col>{cart.totalPrice}</Col>
</Row>
</ListGroup.Item>
{/* <ListGroup.Item>
<ListGroup.Item>
{error && <Message variant="danger">{error}</Message>}
</ListGroup.Item> */}
</ListGroup.Item>
<ListGroup.Item>
<Button
type="button"
Expand Down
3 changes: 3 additions & 0 deletions client/src/constants/orderConstants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const ORDER_CREATE_REQUEST = "ORDER_CREATE_REQUEST";
export const ORDER_CREATE_SUCCESS = "ORDER_CREATE_SUCCESS";
export const ORDER_CREATE_FAIL = "ORDER_CREATE_FAIL";
53 changes: 53 additions & 0 deletions client/src/redux/actions/orderActions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {
ORDER_CREATE_SUCCESS,
ORDER_CREATE_REQUEST,
ORDER_CREATE_FAIL,
} from "../../constants/orderConstants";

import axios from "axios";

export const createOrder = (order) => async (dispatch, getState) => {
try {
dispatch({
type: ORDER_CREATE_REQUEST,
});

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

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

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

dispatch({
type: ORDER_CREATE_SUCCESS,
payload: data,
});
/* dispatch({
type: CART_CLEAR_ITEMS,
payload: data,
}) */
/* localStorage.removeItem('cartItems') */
} catch (error) {
dispatch({
type: ORDER_CREATE_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
});
/* if (message === 'Not authorized, token failed') {
dispatch(logout())
}
dispatch({
type: ORDER_CREATE_FAIL,
payload: message,
}) */
}
};
31 changes: 31 additions & 0 deletions client/src/redux/reducers/orderReducers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {
ORDER_CREATE_SUCCESS,
ORDER_CREATE_REQUEST,
ORDER_CREATE_FAIL,
} from "../../constants/orderConstants";

export const orderCreateReducer = (state = {}, action) => {
switch (action.type) {
case ORDER_CREATE_REQUEST:
return {
loading: true,
};
case ORDER_CREATE_SUCCESS:
return {
loading: false,
success: true,
order: action.payload,
};
case ORDER_CREATE_FAIL:
return {
loading: false,
error: action.payload,
};
default:
return state;
/* case ORDER_CREATE_RESET:
return {}
default:
return state */
}
};
2 changes: 2 additions & 0 deletions client/src/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
userProfileUpdateReducer,
userRegisterReducer,
} from "./redux/reducers/userReducers";
import { orderCreateReducer } from "./redux/reducers/orderReducers";

const reducer = combineReducers({
productList: productListReducer,
Expand All @@ -23,6 +24,7 @@ const reducer = combineReducers({
userDetails: userDetailsReducer,
userProfileUpdate: userProfileUpdateReducer,
productCreateReview: productCreateReviewReducer,
orderCreate: orderCreateReducer,
});

const cartItemsFromStorage = localStorage.getItem("cartItems")
Expand Down
38 changes: 38 additions & 0 deletions server/controller/orderController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import asyncHandler from "express-async-handler";
import Order from "../models/orderModel.js";

// @desc Create new order
// @route POST /api/orders
// @access Private
const addOrderItems = asyncHandler(async (req, res) => {
const {
orderItems,
shippingAddress,
paymentMethod,
itemsPrice,
shippingPrice,
totalPrice,
} = req.body;

if (orderItems && orderItems.length === 0) {
res.status(400);
throw new Error("No ordered items");
return;
} else {
const order = new Order({
orderItems,
user: req.user._id,
shippingAddress,
paymentMethod,
itemsPrice,
shippingPrice,
totalPrice,
});

const createdOrder = await order.save();

res.status(201).json(createdOrder);
}
});

export { addOrderItems };
27 changes: 14 additions & 13 deletions server/index.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import cors from 'cors';
import dotenv from 'dotenv';
import express from 'express';
import morgan from 'morgan';
import connectDB from './config/db.js';
import { errorHandler, notFound } from './middlewares/errorMiddleware.js';
import productRoutes from './routes/productRoutes.js';
import userRoutes from './routes/userRoutes.js';

import cors from "cors";
import dotenv from "dotenv";
import express from "express";
import morgan from "morgan";
import connectDB from "./config/db.js";
import { errorHandler, notFound } from "./middlewares/errorMiddleware.js";
import productRoutes from "./routes/productRoutes.js";
import userRoutes from "./routes/userRoutes.js";
import orderRoutes from "./routes/orderRoutes.js";

const app = express();
dotenv.config();

if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'))
if (process.env.NODE_ENV === "development") {
app.use(morgan("dev"));
}

// middlewares
Expand All @@ -25,8 +25,9 @@ app.get("/", (req, res) => {
});

//routes
app.use("/api/products", productRoutes)
app.use("/api/users", userRoutes)
app.use("/api/products", productRoutes);
app.use("/api/users", userRoutes);
app.use("/api/orders", orderRoutes);

// error handler
app.use(notFound);
Expand Down
7 changes: 1 addition & 6 deletions server/models/orderModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const orderSchema = mongoose.Schema(
shippingAddress: {
address: { type: String, required: true },
city: { type: String, required: true },
//postalCode: { type: String, required: true },

district: { type: String, required: true },
houseNumber: { type: String, required: true },
thana: { type: String, required: true },
Expand All @@ -40,11 +40,6 @@ const orderSchema = mongoose.Schema(
emailAddress: { type: String },
},

taxPrice: {
type: Number,
required: true,
default: 0.0,
},
shippingPrice: {
type: Number,
required: true,
Expand Down
8 changes: 8 additions & 0 deletions server/routes/orderRoutes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import express from "express";
import { addOrderItems } from "../controller/orderController.js";
import { isLoggedIn } from "../middlewares/authMiddleware.js";
const router = express.Router();

router.route("/").post(isLoggedIn, addOrderItems);

export default router;

0 comments on commit 2b2a762

Please sign in to comment.