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 AdminUserController from "../controllers/AdminUserController";
import AdminProductController from "../controllers/AdminProductController";
const adminRouter = express.Router();
adminRouter.get('/user', AdminUserController.index)
adminRouter.post('/product', AdminProductController.create)
export default adminRouter;
......@@ -3,6 +3,7 @@ import WelcomeController from "../controllers/WelcomeController";
import UserController from "../controllers/UserController";
import adminRouter from "./admin";
import { JwtAdminMiddleware } from "./middleware";
import CategoryController from "../controllers/CategoryController";
const route = express.Router();
route.use("/admin/", JwtAdminMiddleware, adminRouter);
......@@ -10,5 +11,6 @@ route.get("/", WelcomeController.index);
route.get("/user", UserController.index);
route.post("/user/auth", UserController.login);
route.post("/user", UserController.create);
route.get('/category', CategoryController.index)
export default route;
import { useState } from "react";
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 { 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 }) {
const user = useContext(UserContext);
const [categoryList, setCategoryList] = useState([]);
const [message, setMessage] = useState({ message: "", error: false });
const [name, setName] = useState("");
const [price, setPrice] = useState();
const [detail, setDetail] = useState("");
const [discount, setDiscount] = useState();
const [stock, setStock] = useState();
const [image, setImage] = useState("");
const [category, setCategory] = useState();
const [category, setCategory] = useState(0);
const CategoryList = [
{
id: 0,
name: "computer",
},
{
id: 1,
name: "phone",
},
useEffect(() => {
axios.get("/api/category").then((res) => {
setCategoryList(res.data);
});
}, []);
/**
*
* @param {FormDataEvent} e
*/
async function fetchAddProduct(e) {
e.preventDefault();
let response = await axios.post(
"/api/admin/product",
{
id: 2,
name: "tablet",
name,
price,
detail,
discount,
stock,
image,
category,
},
];
{ headers: { token: user.value.token } }
);
console.log(response.data);
if (response.data.status === 201) {
setName("");
setPrice("");
setDetail("");
setDiscount("");
setStock("");
setImage("");
setCategory(0);
setMessage({ message: "เพิ่มสินค้าสำเร็จ", error: false });
setTimeout(() => {
setMessage({ message: "", error: false });
}, 3000);
} else {
setMessage({ message: "เกิดข้อผิดพลาด กรุณาลองอีกคร้ัง", error: true });
setTimeout(() => {
setMessage({ message: "", error: false });
}, 3000);
}
}
return (
<>
<Snackbar
anchorOrigin={{ horizontal: "center", vertical: "top" }}
ContentProps={{
className: message.error ? "bg-red-500" : "bg-green-500",
}}
open={!!message.message.length}
message={message.message}
/>
<Dialog open={open} onClose={handleClose}>
<form onSubmit={fetchAddProduct}>
<DialogTitle>เพิ่มสินค้า</DialogTitle>
<DialogContent className="text-center">
<TextField
......@@ -89,13 +142,23 @@ export default function AddProduct({ open, handleClose }) {
fullWidth
helperText="https://www.domain.com/image.png"
value={image}
onChange={(e)=> setImage(e.target.value)}
onChange={(e) => setImage(e.target.value)}
/>
<FormControl className="m-1" variant="standard" sx={{ minWidth: 100 }} >
<FormControl
className="m-1"
variant="standard"
sx={{ minWidth: 100 }}
>
<InputLabel>หมวดหมู่</InputLabel>
<Select value={category} onChange={(e) => setCategory(Number(e.target.value))}>
{CategoryList.map((cat, idx) => (
<MenuItem key={idx} value={cat.id}>{cat.name}</MenuItem>
<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>
......@@ -104,8 +167,10 @@ export default function AddProduct({ open, handleClose }) {
<Button color="error" onClick={handleClose}>
ยกเลิก
</Button>
<Button 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