Commit 5d635a06 authored by Nawasan Wisitsingkhon's avatar Nawasan Wisitsingkhon

add order from cart

parent d3d5cc44
import { Request, Response } from "express";
import db from "../models/prismaClient";
const OrderController = {
/**
*
* @param {Request} req
* @param {Response} res
*/
async create(req, res) {
try {
const { address, sending } = req.body;
let cart = await db.cart.findMany({
where: { user_id: Number(req.user.id) },
});
if (!cart.length || !address || !sending) throw 200;
let total_price = 0;
const cartProduct = [];
for (let i = 0; i < cart.length; i++) {
let getpd = await db.product.findFirst({
where: { id: Number(cart[i].product_id) },
});
getpd.real_price = getpd.price - getpd.price * (getpd.discount / 100);
total_price += getpd.real_price;
cartProduct.push(getpd);
}
// return res.json({ cartProduct, total_price });
const order = await db.order.create({
data: {
user_id: Number(req.user.id),
total_price: Number(total_price),
product_count: cart.length,
// ****
address: address,
// ****
shipping_price: sending,
pay_status: 0,
send_status: 0,
},
});
const orderDetail = [];
for (let i = 0; i < cartProduct.length; i++) {
orderDetail.push({
count: 1,
order_id: order.id,
product_discount: cartProduct[i].discount,
product_id: cartProduct[i].id,
product_price: cartProduct[i].price,
user_id: Number(req.user.id),
});
}
await db.order_detail.createMany({
data: orderDetail,
});
await db.cart.deleteMany({ where: { user_id: Number(req.user.id) } });
await db.user.update({
data: { address },
where: { id: Number(req.user.id) },
});
await db.$disconnect();
res.json({ status: 201, message: "create order success" });
} catch (err) {
console.log(err);
res.json({ status: 200, message: "server error with some error" });
}
},
};
export default OrderController;
......@@ -16,6 +16,7 @@ const UserController = {
delete userAll[i].google_token;
delete userAll[i].rank;
delete userAll[i].password;
delete userAll[i].address;
}
res.json(userAll);
},
......@@ -99,6 +100,7 @@ const UserController = {
name: user.name,
email: user.email,
phone: user.phone,
address: user.address ?? "",
photo: user.photo,
username: user.username,
rank: user.rank,
......
import express from "express";
import WishlistController from "../controllers/WishlistController";
import CartController from "../controllers/CartController";
import OrderController from "../controllers/OrderController";
const UserRouter = express.Router();
UserRouter.get("/wishlist", WishlistController.index);
......@@ -11,4 +12,6 @@ UserRouter.get("/cart", CartController.index);
UserRouter.post("/cart", CartController.create);
UserRouter.delete("/cart", CartController.delete);
UserRouter.post("/order", OrderController.create);
export default UserRouter;
import { useState, useEffect, useContext } from "react";
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import {
Alert,
FormControl,
InputLabel,
MenuItem,
Select,
Snackbar,
} from "@mui/material";
import axios from "axios";
import { CartContext, UserContext } from "@/pages/_app";
export default function ConfirmOrder({ open, handleClose }) {
const user = useContext(UserContext);
const cart = useContext(CartContext);
const [message, setMessage] = useState({ message: "", error: false });
const [address, setAddress] = useState(user.value?.address ?? "");
const [sending, setSending] = useState(40);
/**
*
* @param {FormDataEvent} e
*/
async function onOrder(e) {
e.preventDefault();
try {
let response = await axios.post(
"/api/u/order",
{ address, sending },
{ headers: { token: user.value.token } }
);
console.log(response.data);
setMessage({ message: "สั่งซื้อสำเร็จ", error: false });
setTimeout(() => {
setMessage({ message: "", error: false });
}, 2000);
cart.fetch();
handleClose();
} catch (err) {
setMessage({ message: "พบข้อผิดพลาด กรุณาลองใหม่อีกครั้ง", error: true });
setTimeout(() => {
setMessage({ message: "", error: true });
}, 2000);
}
}
return (
<>
<Snackbar
anchorOrigin={{ horizontal: "center", vertical: "top" }}
open={!!message.message.length}
>
<Alert severity={message.error ? "error" : "success"}>
{message.message}
</Alert>
</Snackbar>
<Dialog open={open} onClose={handleClose}>
<form onSubmit={onOrder}>
<DialogTitle>ยืนยันการสั่งซื้อ</DialogTitle>
<DialogContent className="text-center">
<div className="text-left">
<TextField
fullWidth
className="m-1"
label="ที่อยู่"
variant="standard"
multiline
rows={3}
value={address}
onChange={(e) => setAddress(e.target.value)}
required
/>
</div>
<FormControl
className="m-1"
variant="standard"
sx={{ minWidth: 100 }}
>
<InputLabel>จัดส่ง</InputLabel>
<Select
value={sending}
onChange={(e) => setSending(Number(e.target.value))}
required
>
{[
["เร็ว", 100],
["ธรรมดา", 40],
["ช้า", 20],
].map((ls, idx) => (
<MenuItem key={idx} selected={ls[1] === 40} value={ls[1]}>
{ls[0]}
</MenuItem>
))}
</Select>
</FormControl>
</DialogContent>
<DialogActions>
<Button color="error" onClick={handleClose}>
ยกเลิก
</Button>
<Button type="submit">ยืนยัน</Button>
</DialogActions>
</form>
</Dialog>
</>
);
}
......@@ -17,6 +17,7 @@ import { ShoppingCart } from "@mui/icons-material";
import PopupAlert from "@/components/PopupAlert";
import Head from "next/head";
import { ShoppingBag } from "@mui/icons-material";
import ConfirmOrder from "@/components/order/ConfirmOrder";
export default function Cart() {
const user = useContext(UserContext);
......@@ -24,6 +25,7 @@ export default function Cart() {
const cart = useContext(CartContext);
const [products, setProducts] = useState([]);
const [message, setMessage] = useState({ error: false, message: "" });
const [orderState, setOrderState] = useState(false);
const router = useRouter();
const [CartProduct, setCartProduct] = useState([]);
......@@ -135,7 +137,7 @@ export default function Cart() {
</TableBody>
</Table>
<Box sx={{ textAlign: "right", p: 1 }}>
<Button size="large">
<Button size="large" onClick={() => setOrderState(true)}>
<ShoppingBag /> สั่งซื้อ
</Button>
</Box>
......@@ -148,6 +150,10 @@ export default function Cart() {
</div>
)}
</Paper>
<ConfirmOrder
open={orderState}
handleClose={() => setOrderState(false)}
/>
</Box>
</>
);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment