Commit 1016dabf authored by Nawasan Wisitsingkhon's avatar Nawasan Wisitsingkhon

convert to use mongodb database

parent 3e1e91e5
...@@ -25,8 +25,8 @@ const AdminOrderController = { ...@@ -25,8 +25,8 @@ const AdminOrderController = {
const { id, sending } = req.body; const { id, sending } = req.body;
if (!id) throw 300; if (!id) throw 300;
await db.order.update({ await db.order.update({
where: { id: Number(id) }, where: { id: id },
data: { send_status: Number(sending) }, data: { send_status: sending },
}); });
await db.$disconnect(); await db.$disconnect();
res.json({ status: 301, message: "update sending success" }); res.json({ status: 301, message: "update sending success" });
...@@ -44,7 +44,7 @@ const AdminOrderController = { ...@@ -44,7 +44,7 @@ const AdminOrderController = {
try { try {
const { id } = req.query; const { id } = req.query;
let orderdetail = await db.order_detail.findMany({ let orderdetail = await db.order_detail.findMany({
where: { order_id: Number(id) }, where: { order_id: id },
}); });
res.json(orderdetail); res.json(orderdetail);
} catch (err) { } catch (err) {
......
...@@ -17,7 +17,7 @@ const AdminProductController = { ...@@ -17,7 +17,7 @@ const AdminProductController = {
discount: Number(discount), discount: Number(discount),
stock: Number(stock), stock: Number(stock),
image: image ?? "", image: image ?? "",
cateId: Number(category), cateId: category,
buy_count: 0, buy_count: 0,
watch_count: 0, watch_count: 0,
}, },
...@@ -43,7 +43,7 @@ const AdminProductController = { ...@@ -43,7 +43,7 @@ const AdminProductController = {
const { id, name, price, detail, discount, stock, image, category } = const { id, name, price, detail, discount, stock, image, category } =
req.body; req.body;
await db.product.update({ await db.product.update({
where: { id: Number(id) }, where: { id: id },
data: { data: {
name, name,
price, price,
...@@ -51,7 +51,7 @@ const AdminProductController = { ...@@ -51,7 +51,7 @@ const AdminProductController = {
discount: Number(discount), discount: Number(discount),
stock, stock,
image, image,
cateId: Number(category), cateId: category,
}, },
}); });
await db.$disconnect(); await db.$disconnect();
...@@ -73,7 +73,7 @@ const AdminProductController = { ...@@ -73,7 +73,7 @@ const AdminProductController = {
try { try {
const { id } = req.query; const { id } = req.query;
if (!id) throw 400; if (!id) throw 400;
await db.product.delete({ where: { id: Number(id) } }); await db.product.delete({ where: { id: id } });
res.json({ status: 401, message: "delete success" }); res.json({ status: 401, message: "delete success" });
} catch (err) { } catch (err) {
console.log(err); console.log(err);
......
...@@ -21,7 +21,7 @@ const AdminUserController = { ...@@ -21,7 +21,7 @@ const AdminUserController = {
const { id, rank } = req.body; const { id, rank } = req.body;
if (!id) throw 300; if (!id) throw 300;
await db.user.update({ await db.user.update({
where: { id: Number(id) }, where: { id: id },
data: { rank: !!rank }, data: { rank: !!rank },
}); });
await db.$disconnect(); await db.$disconnect();
...@@ -39,7 +39,7 @@ const AdminUserController = { ...@@ -39,7 +39,7 @@ const AdminUserController = {
try { try {
const { id } = req.query; const { id } = req.query;
if (!id) throw 400; if (!id) throw 400;
await db.user.delete({ where: { id: Number(id) } }); await db.user.delete({ where: { id: id } });
await db.$disconnect(); await db.$disconnect();
res.json({ res.json({
status: 401, status: 401,
......
...@@ -10,7 +10,7 @@ const CartController = { ...@@ -10,7 +10,7 @@ const CartController = {
async index(req, res) { async index(req, res) {
try { try {
let cart = await db.cart.findMany({ let cart = await db.cart.findMany({
where: { user_id: Number(req.user.id) }, where: { user_id: req.user.id },
}); });
res.json({ status: 101, message: "fetch success", cart }); res.json({ status: 101, message: "fetch success", cart });
} catch (err) { } catch (err) {
...@@ -28,14 +28,14 @@ const CartController = { ...@@ -28,14 +28,14 @@ const CartController = {
if (!id) throw 200; if (!id) throw 200;
let check_cart = await db.cart.findFirst({ let check_cart = await db.cart.findFirst({
where: { where: {
AND: { product_id: Number(id), user_id: Number(req.user.id) }, AND: { product_id: id, user_id: req.user.id },
}, },
}); });
if (check_cart) throw 202; if (check_cart) throw 202;
await db.cart.create({ await db.cart.create({
data: { data: {
user_id: Number(req.user.id), user_id: req.user.id,
product_id: Number(id), product_id: id,
}, },
}); });
await db.$disconnect(); await db.$disconnect();
...@@ -60,7 +60,7 @@ const CartController = { ...@@ -60,7 +60,7 @@ const CartController = {
if (!id) throw 400; if (!id) throw 400;
let check_cart = await db.cart.findFirst({ let check_cart = await db.cart.findFirst({
where: { where: {
AND: { user_id: Number(req.user.id), product_id: Number(id) }, AND: { user_id: req.user.id, product_id: id },
}, },
}); });
if (!check_cart) throw 400; if (!check_cart) throw 400;
......
...@@ -60,7 +60,7 @@ const CategoryController = { ...@@ -60,7 +60,7 @@ const CategoryController = {
try { try {
const { id } = req.query; const { id } = req.query;
if (!id) throw 400; if (!id) throw 400;
await db.category.delete({ where: { id: Number(id) } }); await db.category.delete({ where: { id: id } });
await db.$disconnect(); await db.$disconnect();
res.json({ res.json({
status: 401, status: 401,
......
...@@ -10,7 +10,7 @@ const OrderController = { ...@@ -10,7 +10,7 @@ const OrderController = {
async index(req, res) { async index(req, res) {
try { try {
const order = await db.order.findMany({ const order = await db.order.findMany({
where: { user_id: Number(req.user.id) }, where: { user_id: req.user.id },
orderBy: {id: "desc"} orderBy: {id: "desc"}
}); });
res.json(order); res.json(order);
...@@ -27,7 +27,7 @@ const OrderController = { ...@@ -27,7 +27,7 @@ const OrderController = {
try { try {
const { address, sending } = req.body; const { address, sending } = req.body;
let cart = await db.cart.findMany({ let cart = await db.cart.findMany({
where: { user_id: Number(req.user.id) }, where: { user_id: req.user.id },
}); });
if (!cart.length || !address || !sending) throw 200; if (!cart.length || !address || !sending) throw 200;
...@@ -35,7 +35,7 @@ const OrderController = { ...@@ -35,7 +35,7 @@ const OrderController = {
const cartProduct = []; const cartProduct = [];
for (let i = 0; i < cart.length; i++) { for (let i = 0; i < cart.length; i++) {
let getpd = await db.product.findFirst({ let getpd = await db.product.findFirst({
where: { id: Number(cart[i].product_id) }, where: { id: cart[i].product_id },
}); });
getpd.real_price = getpd.price - getpd.price * (getpd.discount / 100); getpd.real_price = getpd.price - getpd.price * (getpd.discount / 100);
total_price += getpd.real_price; total_price += getpd.real_price;
...@@ -45,7 +45,7 @@ const OrderController = { ...@@ -45,7 +45,7 @@ const OrderController = {
// return res.json({ cartProduct, total_price }); // return res.json({ cartProduct, total_price });
const order = await db.order.create({ const order = await db.order.create({
data: { data: {
user_id: Number(req.user.id), user_id: req.user.id,
total_price: Number(total_price), total_price: Number(total_price),
product_count: cart.length, product_count: cart.length,
// **** // ****
...@@ -65,16 +65,16 @@ const OrderController = { ...@@ -65,16 +65,16 @@ const OrderController = {
product_discount: cartProduct[i].discount, product_discount: cartProduct[i].discount,
product_id: cartProduct[i].id, product_id: cartProduct[i].id,
product_price: cartProduct[i].price, product_price: cartProduct[i].price,
user_id: Number(req.user.id), user_id: req.user.id,
}); });
} }
await db.order_detail.createMany({ await db.order_detail.createMany({
data: orderDetail, data: orderDetail,
}); });
await db.cart.deleteMany({ where: { user_id: Number(req.user.id) } }); await db.cart.deleteMany({ where: { user_id: req.user.id } });
await db.user.update({ await db.user.update({
data: { address }, data: { address },
where: { id: Number(req.user.id) }, where: { id: req.user.id },
}); });
await db.$disconnect(); await db.$disconnect();
res.json({ status: 201, message: "create order success" }); res.json({ status: 201, message: "create order success" });
...@@ -92,7 +92,7 @@ const OrderController = { ...@@ -92,7 +92,7 @@ const OrderController = {
try { try {
const { id } = req.query; const { id } = req.query;
if (!id) throw 300; if (!id) throw 300;
await db.order.update({ where: { id: Number(id) }, data: { pay_status: 1 } }); await db.order.update({ where: { id: id }, data: { pay_status: 1 } });
res.json({ res.json({
status: 301, message: "check order success" status: 301, message: "check order success"
}) })
......
...@@ -11,7 +11,7 @@ const OrderDetailController = { ...@@ -11,7 +11,7 @@ const OrderDetailController = {
try { try {
const { id } = req.query; const { id } = req.query;
const orderDetail = await db.order_detail.findMany({ const orderDetail = await db.order_detail.findMany({
where: { user_id: Number(req.user.id), order_id: Number(id) }, where: { user_id: req.user.id, order_id: id },
}); });
await db.$disconnect(); await db.$disconnect();
res.json(orderDetail); res.json(orderDetail);
......
...@@ -9,11 +9,12 @@ const WishlistController = { ...@@ -9,11 +9,12 @@ const WishlistController = {
async index(req, res) { async index(req, res) {
try { try {
const wishlists = await db.wishlist.findMany({ const wishlists = await db.wishlist.findMany({
where: { user_id: Number(req.user.id) }, where: { user_id: req.user.id },
}); });
await db.$disconnect(); await db.$disconnect();
res.json({ status: 101, wishlists }); res.json({ status: 101, wishlists });
} catch (err) { } catch (err) {
console.log(err);
res.json({ status: 100, message: "found some error" }); res.json({ status: 100, message: "found some error" });
} }
}, },
...@@ -28,14 +29,14 @@ const WishlistController = { ...@@ -28,14 +29,14 @@ const WishlistController = {
if (!id) throw 200; if (!id) throw 200;
const check = await db.wishlist.findFirst({ const check = await db.wishlist.findFirst({
where: { where: {
AND: { user_id: Number(req.user.id), product_id: Number(id) }, AND: { user_id: req.user.id, product_id: id },
}, },
}); });
if (check) throw 200; if (check) throw 200;
await db.wishlist.create({ await db.wishlist.create({
data: { data: {
user_id: Number(req.user.id), user_id: req.user.id,
product_id: Number(id), product_id: id,
}, },
}); });
res.json({ status: 201, message: "add wishlist success" }); res.json({ status: 201, message: "add wishlist success" });
...@@ -54,8 +55,8 @@ const WishlistController = { ...@@ -54,8 +55,8 @@ const WishlistController = {
if (!id) throw 400; if (!id) throw 400;
const wishlist_find = await db.wishlist.findFirst({ const wishlist_find = await db.wishlist.findFirst({
where: { where: {
product_id: Number(id), product_id: id,
user_id: Number(req.user.id), user_id: req.user.id,
}, },
}); });
if (!wishlist_find) throw 400; if (!wishlist_find) throw 400;
......
...@@ -6,17 +6,17 @@ generator client { ...@@ -6,17 +6,17 @@ generator client {
} }
datasource db { datasource db {
provider = "mysql" provider = "mongodb"
url = env("DATABASE_URL") url = env("DATABASE_URL")
} }
model user { model user {
id Int @id @default(autoincrement()) id String @id @default(auto()) @map("_id") @db.ObjectId
name String name String
email String email String
phone String phone String
address String @db.LongText @default("") address String @default("")
photo String @db.LongText photo String
google_token String google_token String
username String @unique username String @unique
password String password String
...@@ -29,16 +29,16 @@ model user { ...@@ -29,16 +29,16 @@ model user {
} }
model product { model product {
id Int @id @default(autoincrement()) id String @id @default(auto()) @map("_id") @db.ObjectId
name String name String
detail String @db.LongText detail String
price Int price Int
discount Int discount Int
cate category @relation(fields: [cateId], references: [id]) cate category @relation(fields: [cateId], references: [id])
cateId Int cateId String @db.ObjectId
watch_count Int watch_count Int
buy_count Int buy_count Int
image String @db.LongText image String
stock Int stock Int
wishlist wishlist[] wishlist wishlist[]
cart cart[] cart cart[]
...@@ -46,35 +46,35 @@ model product { ...@@ -46,35 +46,35 @@ model product {
} }
model category { model category {
id Int @id @default(autoincrement()) id String @id @default(auto()) @map("_id") @db.ObjectId
name String @unique name String @unique
product product[] product product[]
} }
model wishlist { model wishlist {
id Int @id @default(autoincrement()) id String @id @default(auto()) @map("_id") @db.ObjectId
product_id Int product_id String @db.ObjectId
product product @relation(fields: [product_id], references: [id]) product product @relation(fields: [product_id], references: [id])
user_id Int user_id String @db.ObjectId
user user @relation(fields: [user_id], references: [id]) user user @relation(fields: [user_id], references: [id])
date DateTime @default(now()) date DateTime @default(now())
} }
model cart { model cart {
id Int @id @default(autoincrement()) id String @id @default(auto()) @map("_id") @db.ObjectId
user_id Int user_id String @db.ObjectId
user user @relation(fields: [user_id], references: [id]) user user @relation(fields: [user_id], references: [id])
product_id Int product_id String @db.ObjectId
product product @relation(fields: [product_id], references: [id]) product product @relation(fields: [product_id], references: [id])
} }
model order { model order {
id Int @id @default(autoincrement()) id String @id @default(auto()) @map("_id") @db.ObjectId
user_id Int user_id String @db.ObjectId
user user @relation(fields: [user_id], references: [id]) user user @relation(fields: [user_id], references: [id])
total_price Int total_price Int
product_count Int product_count Int
address String @db.LongText @default("") address String @default("")
date DateTime @default(now()) date DateTime @default(now())
shipping_price Int shipping_price Int
pay_status Int pay_status Int
...@@ -83,12 +83,12 @@ model order { ...@@ -83,12 +83,12 @@ model order {
} }
model order_detail { model order_detail {
id Int @id @default(autoincrement()) id String @id @default(auto()) @map("_id") @db.ObjectId
order_id Int order_id String @db.ObjectId
order order @relation(fields: [order_id], references: [id]) order order @relation(fields: [order_id], references: [id])
user_id Int user_id String @db.ObjectId
user user @relation(fields: [user_id], references: [id]) user user @relation(fields: [user_id], references: [id])
product_id Int product_id String @db.ObjectId
product product @relation(fields: [product_id], references: [id]) product product @relation(fields: [product_id], references: [id])
product_price Int product_price Int
product_discount Int product_discount Int
......
...@@ -26,7 +26,7 @@ export default function AddProduct({ open, handleClose }) { ...@@ -26,7 +26,7 @@ export default function AddProduct({ open, handleClose }) {
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(0); const [category, setCategory] = useState("");
useEffect(() => { useEffect(() => {
axios.get("/api/category").then((res) => { axios.get("/api/category").then((res) => {
...@@ -61,7 +61,7 @@ export default function AddProduct({ open, handleClose }) { ...@@ -61,7 +61,7 @@ export default function AddProduct({ open, handleClose }) {
setDiscount(""); setDiscount("");
setStock(""); setStock("");
setImage(""); setImage("");
setCategory(0); setCategory("");
setMessage({ message: "เพิ่มสินค้าสำเร็จ", error: false }); setMessage({ message: "เพิ่มสินค้าสำเร็จ", error: false });
handleClose(); handleClose();
setTimeout(() => { setTimeout(() => {
...@@ -151,7 +151,7 @@ export default function AddProduct({ open, handleClose }) { ...@@ -151,7 +151,7 @@ export default function AddProduct({ open, handleClose }) {
<InputLabel>หมวดหมู่</InputLabel> <InputLabel>หมวดหมู่</InputLabel>
<Select <Select
value={category} value={category}
onChange={(e) => setCategory(Number(e.target.value))} onChange={(e) => setCategory(e.target.value)}
required required
> >
{categoryList.map((cat, idx) => ( {categoryList.map((cat, idx) => (
......
...@@ -27,7 +27,7 @@ export default function UpdateProduct({ open, handleClose, data }) { ...@@ -27,7 +27,7 @@ export default function UpdateProduct({ open, handleClose, data }) {
const [discount, setDiscount] = useState(data.discount); const [discount, setDiscount] = useState(data.discount);
const [stock, setStock] = useState(data.stock); const [stock, setStock] = useState(data.stock);
const [image, setImage] = useState(data.image); const [image, setImage] = useState(data.image);
const [category, setCategory] = useState(Number(data.cateId)); const [category, setCategory] = useState(data.cateId);
useEffect(() => { useEffect(() => {
axios.get("/api/category").then((res) => { axios.get("/api/category").then((res) => {
...@@ -151,7 +151,7 @@ export default function UpdateProduct({ open, handleClose, data }) { ...@@ -151,7 +151,7 @@ export default function UpdateProduct({ open, handleClose, data }) {
<InputLabel>หมวดหมู่</InputLabel> <InputLabel>หมวดหมู่</InputLabel>
<Select <Select
value={category} value={category}
onChange={(e) => setCategory(Number(e.target.value))} onChange={(e) => setCategory(e.target.value)}
required required
> >
{categoryList.map((cat, idx) => ( {categoryList.map((cat, idx) => (
...@@ -166,7 +166,7 @@ export default function UpdateProduct({ open, handleClose, data }) { ...@@ -166,7 +166,7 @@ export default function UpdateProduct({ open, handleClose, data }) {
<Button color="error" onClick={handleClose}> <Button color="error" onClick={handleClose}>
ยกเลิก ยกเลิก
</Button> </Button>
<Button type="submit">เพิ่ม</Button> <Button type="submit">บันทึก</Button>
</DialogActions> </DialogActions>
</form> </form>
</Dialog> </Dialog>
......
...@@ -47,6 +47,7 @@ export default function App({ Component, pageProps }) { ...@@ -47,6 +47,7 @@ export default function App({ Component, pageProps }) {
let response = await axios.get("/api/u/wishlist", { let response = await axios.get("/api/u/wishlist", {
headers: { token: user.token }, headers: { token: user.token },
}); });
console.log(response.data);
setWishlist(response.data.wishlists); setWishlist(response.data.wishlists);
}; };
useEffect(() => { useEffect(() => {
......
...@@ -159,7 +159,7 @@ export default function Order() { ...@@ -159,7 +159,7 @@ export default function Order() {
value={Number(order.send_status)} value={Number(order.send_status)}
onChange={(e) => { onChange={(e) => {
onSendingChange( onSendingChange(
Number(order.id), order.id,
Number(e.target.value) Number(e.target.value)
); );
}} }}
......
...@@ -28,7 +28,7 @@ export default function Stock() { ...@@ -28,7 +28,7 @@ export default function Stock() {
const [products, setProducts] = useState([]); const [products, setProducts] = useState([]);
const [updateState, setUpdateState] = useState({ open: false, data: {} }); const [updateState, setUpdateState] = useState({ open: false, data: {} });
const [deleteState, setDeleteState] = useState({ open: false, id: -1 }); const [deleteState, setDeleteState] = useState({ open: false, id: -1 });
const [category, setCategory] = useState(-1); const [category, setCategory] = useState("");
const [categoryList, setCategoryList] = useState([]); const [categoryList, setCategoryList] = useState([]);
const productsFilter = !!router.query?.q const productsFilter = !!router.query?.q
...@@ -52,9 +52,9 @@ export default function Stock() { ...@@ -52,9 +52,9 @@ export default function Stock() {
useEffect(() => { useEffect(() => {
if (router.query?.cat) { if (router.query?.cat) {
setCategory(Number(router.query.cat)); setCategory(router.query.cat);
} else { } else {
setCategory(-1); setCategory('');
} }
}, [router]); }, [router]);
...@@ -74,8 +74,8 @@ export default function Stock() { ...@@ -74,8 +74,8 @@ export default function Stock() {
<Box className="flex justify-start mb-3 sm:px-10 max-w-[1520px] mx-auto"> <Box className="flex justify-start mb-3 sm:px-10 max-w-[1520px] mx-auto">
<Box sx={{ display: "flex", overflowX: "scroll", maxWidth: "100vw" }}> <Box sx={{ display: "flex", overflowX: "scroll", maxWidth: "100vw" }}>
<Button <Button
variant={category === -1 ? "contained" : "text"} variant={category.length === 0 ? "contained" : "text"}
className={`${category === -1 ? "" : "bg-white"} mx-1`} className={`${category.length === 0 ? "" : "bg-white"} mx-1`}
onClick={() => { onClick={() => {
let que = router.query; let que = router.query;
delete que.cat; delete que.cat;
...@@ -117,7 +117,7 @@ export default function Stock() { ...@@ -117,7 +117,7 @@ export default function Stock() {
<div className="mx-auto text-left grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-4 max-w-[1520px]"> <div className="mx-auto text-left grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-4 max-w-[1520px]">
{productsFilter.map( {productsFilter.map(
(product, idx) => (product, idx) =>
(category === -1 || category === product.cateId) && ( (category.length === 0 || category === product.cateId) && (
<Card <Card
key={idx} key={idx}
sx={{ sx={{
......
...@@ -142,7 +142,7 @@ export default function Home() { ...@@ -142,7 +142,7 @@ export default function Home() {
useEffect(() => { useEffect(() => {
if (router.query?.cat) { if (router.query?.cat) {
setCategory(Number(router.query.cat)); setCategory(router.query.cat);
} else if (category !== -1) { } else if (category !== -1) {
setCategory(-1); setCategory(-1);
} }
...@@ -210,12 +210,12 @@ export default function Home() { ...@@ -210,12 +210,12 @@ export default function Home() {
key={idx} key={idx}
isFav={ isFav={
!!wishlist.value.filter( !!wishlist.value.filter(
(wish) => wish.product_id === Number(products[pid].id) (wish) => wish.product_id === products[pid].id
).length ).length
} }
isCart={ isCart={
!!cart.value.filter( !!cart.value.filter(
(ct) => ct.product_id === Number(products[pid].id) (ct) => ct.product_id === products[pid].id
).length ).length
} }
product={products[pid]} product={products[pid]}
...@@ -223,7 +223,7 @@ export default function Home() { ...@@ -223,7 +223,7 @@ export default function Home() {
onCart( onCart(
products[pid].id, products[pid].id,
!!cart.value.filter( !!cart.value.filter(
(ct) => ct.product_id === Number(products[pid].id) (ct) => ct.product_id === products[pid].id
).length ).length
) )
} }
...@@ -231,7 +231,7 @@ export default function Home() { ...@@ -231,7 +231,7 @@ export default function Home() {
onWishlist( onWishlist(
products[pid].id, products[pid].id,
!!wishlist.value.filter( !!wishlist.value.filter(
(wish) => wish.product_id === Number(products[pid].id) (wish) => wish.product_id === products[pid].id
).length ).length
) )
} }
......
...@@ -28,7 +28,7 @@ export default function Wishlist() { ...@@ -28,7 +28,7 @@ export default function Wishlist() {
const [wishlistProduct, setWishlistProduct] = useState([]); const [wishlistProduct, setWishlistProduct] = useState([]);
const isInCart = (id) => { const isInCart = (id) => {
return !!cart.value.filter((ct) => ct.product_id === Number(id)).length; return !!cart.value.filter((ct) => ct.product_id === id).length;
}; };
async function onCart(id, isRemove = false) { async function onCart(id, isRemove = false) {
......
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