Commit 4f5be806 authored by Nawasan Wisitsingkhon's avatar Nawasan Wisitsingkhon

finish: admin create product front and back;

parent 7749aa23
import { Request, Response } from "express";
import db from "../models/prismaClient";
const AdminProductController = {
/**
*
* @param {Request} req
* @param {Response} res
*/
async create(req, res) {
try {
let { name, price, detail, discount, stock, image, category } = req.body;
await db.product.create({
data: {
name,
detail,
price,
discount: Number(discount),
stock: Number(stock),
image: image ?? "",
cateId: Number(category),
buy_count: 0,
watch_count: 0,
},
});
await db.$disconnect();
res.json({ status: 201, message: "add product success" });
} catch (err) {
console.log(err);
res.json({
status: 200,
message: "error in server",
err
});
}
},
}
export default AdminProductController;
\ No newline at end of file
import { Request, Response } from "express";
import db from "../models/prismaClient";
const CategoryController = {
/**
*
* @param {Request} req
* @param {Response} res
*/
async index(req, res) {
let category = await db.category.findMany({orderBy: {id: "asc"}});
await db.$disconnect();
res.json(category);
},
};
export default CategoryController;
const ProductController = {
}
export default ProductController;
\ No newline at end of file
import express from "express"; import express from "express";
import AdminUserController from "../controllers/AdminUserController"; import AdminUserController from "../controllers/AdminUserController";
import AdminProductController from "../controllers/AdminProductController";
const adminRouter = express.Router(); const adminRouter = express.Router();
adminRouter.get('/user', AdminUserController.index) adminRouter.get('/user', AdminUserController.index)
adminRouter.post('/product', AdminProductController.create)
export default adminRouter; export default adminRouter;
...@@ -3,6 +3,7 @@ import WelcomeController from "../controllers/WelcomeController"; ...@@ -3,6 +3,7 @@ import WelcomeController from "../controllers/WelcomeController";
import UserController from "../controllers/UserController"; import UserController from "../controllers/UserController";
import adminRouter from "./admin"; import adminRouter from "./admin";
import { JwtAdminMiddleware } from "./middleware"; import { JwtAdminMiddleware } from "./middleware";
import CategoryController from "../controllers/CategoryController";
const route = express.Router(); const route = express.Router();
route.use("/admin/", JwtAdminMiddleware, adminRouter); route.use("/admin/", JwtAdminMiddleware, adminRouter);
...@@ -10,5 +11,6 @@ route.get("/", WelcomeController.index); ...@@ -10,5 +11,6 @@ route.get("/", WelcomeController.index);
route.get("/user", UserController.index); route.get("/user", UserController.index);
route.post("/user/auth", UserController.login); route.post("/user/auth", UserController.login);
route.post("/user", UserController.create); route.post("/user", UserController.create);
route.get('/category', CategoryController.index)
export default route; export default route;
import { useState } from "react"; import { useState, useEffect, useContext } from "react";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField"; import TextField from "@mui/material/TextField";
import Dialog from "@mui/material/Dialog"; import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions"; import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent"; import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle"; import DialogTitle from "@mui/material/DialogTitle";
import { FormControl, InputLabel, MenuItem, Select } from "@mui/material"; import {
FormControl,
InputLabel,
MenuItem,
Select,
Snackbar,
} from "@mui/material";
import axios from "axios";
import { UserContext } from "@/pages/_app";
export default function AddProduct({ open, handleClose }) { export default function AddProduct({ open, handleClose }) {
const user = useContext(UserContext);
const [categoryList, setCategoryList] = useState([]);
const [message, setMessage] = useState({ message: "", error: false });
const [name, setName] = useState(""); const [name, setName] = useState("");
const [price, setPrice] = useState(); const [price, setPrice] = useState();
const [detail, setDetail] = useState(""); const [detail, setDetail] = useState("");
const [discount, setDiscount] = useState(); const [discount, setDiscount] = useState();
const [stock, setStock] = useState(); const [stock, setStock] = useState();
const [image, setImage] = useState(""); const [image, setImage] = useState("");
const [category, setCategory] = useState(); const [category, setCategory] = useState(0);
const CategoryList = [ useEffect(() => {
{ axios.get("/api/category").then((res) => {
id: 0, setCategoryList(res.data);
name: "computer", });
}, }, []);
{
id: 1, /**
name: "phone", *
}, * @param {FormDataEvent} e
{ */
id: 2, async function fetchAddProduct(e) {
name: "tablet", e.preventDefault();
}, let response = await axios.post(
]; "/api/admin/product",
return ( {
<Dialog open={open} onClose={handleClose}> name,
<DialogTitle>เพิ่มสินค้า</DialogTitle> price,
<DialogContent className="text-center"> detail,
<TextField discount,
className="m-1" stock,
label="ชื่อสินค้า" image,
variant="standard" category,
value={name} },
onChange={(e) => setName(e.target.value)} { headers: { token: user.value.token } }
required );
/> console.log(response.data);
<TextField if (response.data.status === 201) {
className="m-1" setName("");
label="ราคา" setPrice("");
variant="standard" setDetail("");
type="number" setDiscount("");
value={price} setStock("");
onChange={(e) => setPrice(Number(e.target.value))} setImage("");
required setCategory(0);
/> setMessage({ message: "เพิ่มสินค้าสำเร็จ", error: false });
<div className="text-left"> setTimeout(() => {
<TextField setMessage({ message: "", error: false });
className="m-1" }, 3000);
label="รายละเอียด" } else {
variant="standard" setMessage({ message: "เกิดข้อผิดพลาด กรุณาลองอีกคร้ัง", error: true });
multiline setTimeout(() => {
rows={3} setMessage({ message: "", error: false });
value={detail} }, 3000);
onChange={(e) => setDetail(e.target.value)} }
required }
/>
</div> return (
<div className="text-left"> <>
<TextField <Snackbar
className="m-1" anchorOrigin={{ horizontal: "center", vertical: "top" }}
label="ส่วนลด (%)" ContentProps={{
variant="standard" className: message.error ? "bg-red-500" : "bg-green-500",
type="number" }}
value={discount} open={!!message.message.length}
onChange={(e) => setDiscount(e.target.value)} message={message.message}
required />
/> <Dialog open={open} onClose={handleClose}>
<TextField <form onSubmit={fetchAddProduct}>
className="m-1" <DialogTitle>เพิ่มสินค้า</DialogTitle>
label="จำนวนสินค้า" <DialogContent className="text-center">
variant="standard" <TextField
type="number" className="m-1"
value={stock} label="ชื่อสินค้า"
onChange={(e) => setStock(e.target.value)} variant="standard"
required value={name}
/> onChange={(e) => setName(e.target.value)}
</div> required
<TextField />
label="รูปภาพ" <TextField
variant="standard" className="m-1"
fullWidth label="ราคา"
helperText="https://www.domain.com/image.png" variant="standard"
value={image} type="number"
onChange={(e)=> setImage(e.target.value)} value={price}
/> onChange={(e) => setPrice(Number(e.target.value))}
<FormControl className="m-1" variant="standard" sx={{ minWidth: 100 }} > required
<InputLabel>หมวดหมู่</InputLabel> />
<Select value={category} onChange={(e) => setCategory(Number(e.target.value))}> <div className="text-left">
{CategoryList.map((cat, idx) => ( <TextField
<MenuItem key={idx} value={cat.id}>{cat.name}</MenuItem> className="m-1"
))} label="รายละเอียด"
</Select> variant="standard"
</FormControl> multiline
</DialogContent> rows={3}
<DialogActions> value={detail}
<Button color="error" onClick={handleClose}> onChange={(e) => setDetail(e.target.value)}
ยกเลิก required
</Button> />
<Button onClick={handleClose}>เพิ่ม</Button> </div>
</DialogActions> <div className="text-left">
</Dialog> <TextField
className="m-1"
label="ส่วนลด (%)"
variant="standard"
type="number"
value={discount}
onChange={(e) => setDiscount(e.target.value)}
required
/>
<TextField
className="m-1"
label="จำนวนสินค้า"
variant="standard"
type="number"
value={stock}
onChange={(e) => setStock(e.target.value)}
required
/>
</div>
<TextField
label="รูปภาพ"
variant="standard"
fullWidth
helperText="https://www.domain.com/image.png"
value={image}
onChange={(e) => setImage(e.target.value)}
/>
<FormControl
className="m-1"
variant="standard"
sx={{ minWidth: 100 }}
>
<InputLabel>หมวดหมู่</InputLabel>
<Select
value={category}
onChange={(e) => setCategory(Number(e.target.value))}
required
>
{categoryList.map((cat, idx) => (
<MenuItem key={idx} value={cat.id}>
{cat.name}
</MenuItem>
))}
</Select>
</FormControl>
</DialogContent>
<DialogActions>
<Button color="error" onClick={handleClose}>
ยกเลิก
</Button>
<Button type="submit">เพิ่ม</Button>
</DialogActions>
</form>
</Dialog>
</>
); );
} }
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