0
0 Comments

OrderModel.js

import mongoose from ‘mongoose’;

const orderSchema = new mongoose.Schema(
{
orderItems: [
{
slug: { type: String, required: true },
name: { type: String, required: true },
quantity: { type: Number, required: true },
image: { type: String, required: true },
price: { type: Number, required: true },

product: {
type: mongoose.Schema.Types.ObjectId,
ref: ‘ Product ‘,
required: true,
},
},
],
shippingAddress: {
fullName: { type: String, required: true },
address: { type: String, required: true },
city: { type: String, required: true },
postalCode: { type: String, required: true },
country: { type: String, required: true },
},
paymentMethod: { type: String, required: true },
paymentResult: {
id: String,
status: String,
update_time: String,
email_address: String,
},
itemsPrice: { type: Number, required: true },
shippingPrice: { type: Number, required: true },
taxPrice: { type: Number, required: true },
totalPrice: { type: Number, required: true },
user: {
type: mongoose.Schema.Types.ObjectId,
ref: ‘ User ‘,
required: true,
},
isPaid: { type: Boolean, default: false },
paidAt: { type: Date },
isDelivered: { type: Boolean, default: false },
deliveredAt: { type: Date },
},
{
timestamps: true,
}
);

const Order = mongoose.model(‘Order’, orderSchema);
export default Order;

orderRoutes.js

import express from ‘express’;
import expressAsyncHandler from ‘express-async-handler’;
import Order from ‘../models/orderModel.js’;
import { isAuth } from ‘../utils.js’;

const orderRouter = express.Router();
orderRouter.post(
‘/’,
isAuth,
expressAsyncHandler(async (req, res) => {
const newOrder = new Order({
orderItems: req.body.orderItems.map((x) => ({ …x, product: x._id })),
shippingAddress: req.body.shippingAddress,
paymentMethod: req.body.paymentMethod,
itemsPrice: req.body.itemsPrice,
shippingPrice: req.body.shippingPrice,
taxPrice: req.body.taxPrice,
totalPrice: req.body.totalPrice,
user: req.user._id,
});

const order = await newOrder.save();
res.status(201).send({ message: ‘New Order Created’, order });
})
);

orderRouter.get(
‘/mine’,
isAuth,
expressAsyncHandler(async (req, res) => {
const orders = await Order.find({ user: req.user._id });
res.send(orders);
})
);

orderRouter.get(
‘/:id’,
isAuth,
expressAsyncHandler(async (req, res) => {
const order = await Order.findById(req.params.id);
if (order) {
res.send(order);
} else {
res.status(404).send({ message: ‘Order Not Found’ });
}
})
);

orderRouter.put(
‘/:id/pay’,
isAuth,
expressAsyncHandler(async (req, res) => {
const order = await Order.findById(req.params.id);
if (order) {
order.isPaid = true;
order.paidAt = Date.now();
order.paymentResult = {
id: req.body.id,
status: req.body.status,
update_time: req.body.update_time,
email_address: req.body.email_address,
};

const updatedOrder = await order.save();
res.send({ message: ‘Order Paid’, order: updatedOrder });
} else {
res.status(404).send({ message: ‘Order Not Found’ });
}
})
);

export default orderRouter;

OrderHistoryScreen.js

import React, { useContext, useEffect, useReducer } from ‘react’;
import { Helmet } from ‘react-helmet-async’;
import { useNavigate } from ‘react-router-dom’;
import axios from ‘axios’;
import Button from ‘react-bootstrap/Button’;

import LoadingSpinner from ‘../components/LoadingSpinner’;
import MesssageBox from ‘../components/MessageBox’;
import { Store } from ‘../store/store’;
import { getError } from ‘../utils’;

const reducer = (state, action) => {
switch (action.type) {
case ‘FETCH_REQUEST’:
return { …state, loading: true };
case ‘FETCH_SUCCESS’:
return { …state, orders: action.payload, loading: false };
case ‘FETCH_FAIL’:
return { …state, loading: false, error: action.payload };
default:
return state;
}
};

export default function OrderHistoryScreen() {
const { state } = useContext(Store);
const { userInfo } = state;
const navigate = useNavigate();

const [{ loading, error, orders }, dispatch] = useReducer(reducer, {
loading: true,
error: ”,
});

useEffect(() => {
const fetchData = async () => {
dispatch({ type: ‘FETCH_REQUEST’ });
try {
const { data } = await axios.get(`/api/orders/mine`, {
headers: { Authorization: `Bearer ${userInfo.token}` },
});
dispatch({ type: ‘FETCH_SUCCESS’, payload: data });
} catch (error) {
dispatch({
type: ‘FETCH_FAIL’,
payload: getError(error),
});
}
};
fetchData();
}, [userInfo]);

return (

Order History – Moyozon

Order History
{loading ? (

) : error ? (
{error}
) : (

ID
DATE
TOTAL
PAID?
DELIVERED?
ACTIONS

{orders.map((order) => (

{order._id}
{order.createdAt.substring(0, 10)}
${order.totalPrice.toFixed(2)}
{/* order.paidAt.tosubstring(0, 10) */}
{order.isPaid ? order.paidAt.tosubstring(0, 10) : ‘NO’}

{/* order.deliveredAt.tosubstring(0, 10) */}
{order.isDelivered ? order.deliveredAt.tosubstring(0, 10): ‘NO’}

{
navigate(`/order/${order._id}`);
}}
>
Details

))}

)}

);
}

Basir Changed status to publish October 11, 2022