Commit c7253d41 authored by 박상호's avatar 박상호 🎼
Browse files

Merge remote-tracking branch 'origin/ourMaster' into sangho

parents db86a0b7 02b3814f
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import ListCard from '../Components/ListCard'; import ListCard from '../Components/ListCard';
import Pagination from "../Components/Pagination";
import axios from 'axios'; import axios from 'axios';
import catchError from '../utils/catchErrors'; import catchError from '../utils/catchErrors';
import { Container, Row, Col, Form, FormControl, Button, Dropdown, ButtonGroup, Image } from 'react-bootstrap'; import { Container, Row, Col, Form, FormControl, Button, Dropdown, ButtonGroup, Image } from 'react-bootstrap';
function ProductsList({ match }) { function ProductsList({ match }) {
const INIT_STATUS = { indexOfFirst: 0, indexOfLast: 10 }
const [search, setSearch] = useState({ word: '' })
const [sortingName, setSortingName] = useState('정렬')
const [mainCategory, setMainCategory] = useState(match.params.main.toUpperCase()) const [mainCategory, setMainCategory] = useState(match.params.main.toUpperCase())
const [subcategory, setSubcategory] = useState([]) const [subCategory, setSubCategory] = useState([])
const [productlist, setProductlist] = useState([]) const [productlist, setProductlist] = useState([])
const [status, setStatus] = useState(INIT_STATUS)
const [currentPage, setCurrentPage] = useState(1)
const [error, setError] = useState('') const [error, setError] = useState('')
const searchref = useRef(null)
const per = 10;
useEffect(() => { useEffect(() => {
setMainCategory(match.params.main.toUpperCase()) setMainCategory(match.params.main.toUpperCase())
...@@ -17,18 +25,43 @@ function ProductsList({ match }) { ...@@ -17,18 +25,43 @@ function ProductsList({ match }) {
useEffect(() => { useEffect(() => {
getSubsCategories([]) getSubsCategories()
getProductlist() getProductlist()
}, [mainCategory]) }, [mainCategory])
function handleSearch() { useEffect(() => {
setStatus({ indexOfFirst: (currentPage - 1) * per, indexOfLast: currentPage * per })
}, [currentPage])
function currentPosts(items) {
let currentPosts = '';
currentPosts = items.slice(status.indexOfFirst, status.indexOfLast);
return currentPosts
}
function handleChange(event) {
setSearch({ word: event.target.value })
} }
async function getSubsCategories([]) { async function handleSearch(e) {
e.preventDefault()
try { try {
setError('')
const response = await axios.get(`/api/product/getproduct/main/${mainCategory}?product=${search.word}`)
setProductlist(response.data)
setCurrentPage(1)
} catch (error) {
catchError(error, setError)
} finally {
searchref.current.value = ''
}
}
async function getSubsCategories() {
try {
setError('')
const response = await axios.get(`/api/categories/sub/${mainCategory}`) const response = await axios.get(`/api/categories/sub/${mainCategory}`)
setSubcategory(Object.values(response.data)[0]) setSubCategory(Object.values(response.data)[0])
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} }
...@@ -36,85 +69,156 @@ function ProductsList({ match }) { ...@@ -36,85 +69,156 @@ function ProductsList({ match }) {
async function getProductlist() { async function getProductlist() {
try { try {
setError('')
const response = await axios.get(`/api/product/getproduct/main/${mainCategory}`) const response = await axios.get(`/api/product/getproduct/main/${mainCategory}`)
console.log("response.data=main", response.data)
setProductlist(response.data) setProductlist(response.data)
setCurrentPage(1)
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} }
} }
async function handleSort(method) {
console.log(method)
if (method === "purchase") {
console.log("thisispurchase")
productlist.sort(function (a, b) {
if (a.purchase > b.purchase) {
return -1;
}
if (a.purchase < b.purchase) {
return 1;
}
// a must be equal to b
return 0;
});
setSortingName("인기상품")
} else if (method === "newest") {
console.log("thisisnewest")
productlist.sort(function (a, b) {
if (a.createdAt > b.createdAt) {
return -1;
}
if (a.createdAt < b.createdAt) {
return 1;
}
// a must be equal to b
return 0;
});
setSortingName("신상품")
} else if (method === "lowest") {
console.log("thisislowest")
productlist.sort(function (a, b) {
if (a.price > b.price) {
return 1;
}
if (a.price < b.price) {
return -1;
}
// a must be equal to b
return 0;
});
setSortingName("낮은가격")
} else {
console.log("thisispurchase")
productlist.sort(function (a, b) {
if (a.price > b.price) {
return -1;
}
if (a.price < b.price) {
return 1;
}
// a must be equal to b
return 0;
});
setSortingName("높은가격")
}
}
async function handleSubname(e) { async function handleSubname(e) {
const subname = e.target.name const subname = e.target.name
console.log("subname=", subname)
try { try {
console.log("first test!!!!!!!!") setError('')
const response = await axios.get(`/api/product/getproduct/sub?subname=${subname}`) const response = await axios.get(`/api/product/getproduct/sub?subname=${subname}`)
console.log("subname response data=", response.data)
setProductlist(response.data) setProductlist(response.data)
setCurrentPage(1)
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
console.log("오류입니다.")
} }
} }
if (error) {
alert(`${error}`)
setError('')
searchref.current.value = ''
}
return ( return (
<div> <Container>
<style type="text/css"> <style type="text/css">
{` {`
a, a:hover, a:active { a, a:hover, a:active {
color: #000; color: #000;
text-decoration: none; text-decoration: none;
} }
.btn { .btn {
background-color: #CDC5C2; background-color: #CDC5C2;
border-color: #CDC5C2; border-color: #CDC5C2;
border-radius: 0;
} }
.btn:hover, .btn:focus {
.btn:hover, .btn:active, .btn:focus, .show>.btn-primary.dropdown-toggle {
background-color: #91877F; background-color: #91877F;
border-color: #91877F; border-color: #91877F;
box-shadow: 0 0 0 0;
}
.btn-primary:not(:disabled):not(.disabled).active, .btn-primary:not(:disabled):not(.disabled):active, .show>.btn-primary.dropdown-toggle {
background-color: #91877F;
border-color: #91877F;
}
.show>.btn-primary.dropdown-toggle:focus {
box-shadow: 0 0 0 0;
}
.dropdown-item {
color: #91877F;
}
.dropdown-item:hover, .dropdown-item:active {
background-color: #91877F;
color: #fff;
} }
`} `}
</style> </style>
<Container>
<Row className="justify-content-center" > <Row className="justify-content-center" >
<Col className='px-3'> <Col className='px-3'>
<div className="text-center"> <div className="text-center">
<h1 style={{ fontSize: "5.5vmax" }} className="text-center m-1 py-3">{mainCategory}</h1> <h1 style={{ fontSize: "5.5vmax" }} className="text-center m-1 py-3">{mainCategory}</h1>
<ButtonGroup className="mb-3" variant="outline-light secondary" style={{ display: "inline"}}> <ButtonGroup className="mb-3" style={{ display: "inline" }}>
{subcategory.map(el => {subCategory.map(el =>(<Button className="m-1" style={{ fontSize: "0.8vw" }} name={el} onClick={handleSubname}>{el}</Button>))}
(<Button className="m-1" style={{ fontSize: "0.8vw"}} name={el} onClick={handleSubname}>{el}
</Button>))}
</ButtonGroup> </ButtonGroup>
</div> </div>
</Col> </Col>
</Row> </Row>
<Row className="justify-content-end mx-0 my-2"> <Row className="justify-content-end mx-0 mt-5 mb-3">
<Dropdown> <Form inline onSubmit={handleSearch} className="justify-content-end mx-0 my-2">
<Dropdown.Toggle className="mx-2">정렬</Dropdown.Toggle> <FormControl ref={searchref} type="text" onChange={handleChange} placeholder="Search" style={{ width: "13rem" }} />
<Dropdown.Menu> <Button type="submit" className="px-2 mr-2">
<Dropdown.Item>인기상품</Dropdown.Item>
<Dropdown.Item>신상품</Dropdown.Item>
<Dropdown.Item>낮은가격</Dropdown.Item>
<Dropdown.Item>높은가격</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
<Form as={Row} onSubmit={handleSearch} className="justify-content-end mx-0">
<FormControl type="text" placeholder="Search" style={{ width: "13rem" }} />
<Button type="submit" className="search px-2" variant="secondary">
<img src="/icon/search.svg" width="20" height="20" /> <img src="/icon/search.svg" width="20" height="20" />
</Button> </Button>
</Form> </Form>
<Dropdown className="my-2">
<Dropdown.Toggle className="mx-2">{sortingName}</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item as="button" onClick={() => handleSort('purchase')}>인기상품</Dropdown.Item>
<Dropdown.Item as="button" onClick={() => handleSort('newest')}>신상품</Dropdown.Item>
<Dropdown.Item as="button" onClick={() => handleSort('lowest')}>낮은가격</Dropdown.Item>
<Dropdown.Item as="button" onClick={() => handleSort('highest')}>높은가격</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</Row> </Row>
<Row md={8} sm={12} className="justify-content-center m-2"> <Row md={8} sm={12} className="justify-content-center m-2">
{productlist.length > 0 ? {productlist.length > 0 ?
productlist.map(pro => ( currentPosts(productlist).map(pro => (
<Link to={{ <Link to={{
pathname: `/product/${pro._id}`, pathname: `/product/${pro._id}`,
state: { state: {
...@@ -135,12 +239,11 @@ function ProductsList({ match }) { ...@@ -135,12 +239,11 @@ function ProductsList({ match }) {
: ( : (
<Image src="/sryimready.jpg" className='m-5' <Image src="/sryimready.jpg" className='m-5'
style={{ objectFit: "contain", width: "45vw", height: "45vh" }}></Image> style={{ objectFit: "contain", width: "45vw", height: "45vh" }}></Image>
) )
} }
</Row> </Row>
{productlist.length != 0 ? <Pagination index={currentPage} totalPages={Math.ceil(productlist.length / per)} handlePage={setCurrentPage} /> : ''}
</Container> </Container>
</div>
) )
} }
......
...@@ -15,7 +15,7 @@ function ShoppingCart() { ...@@ -15,7 +15,7 @@ function ShoppingCart() {
useEffect(() => { useEffect(() => {
getCart() getCart()
console.log(cart) // console.log(cart)
}, [user]) }, [user])
function plusNum(e) { function plusNum(e) {
...@@ -59,7 +59,7 @@ function ShoppingCart() { ...@@ -59,7 +59,7 @@ function ShoppingCart() {
async function deleteCart(e) { async function deleteCart(e) {
//장바구니 DB에서 해당 항목 삭제 //장바구니 DB에서 해당 항목 삭제
console.log(e.target.name) // console.log(e.target.name)
try { try {
const response = await axios.post('/api/cart/deletecart', { const response = await axios.post('/api/cart/deletecart', {
userId: user, userId: user,
...@@ -70,7 +70,7 @@ function ShoppingCart() { ...@@ -70,7 +70,7 @@ function ShoppingCart() {
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
console.log('카트에 담긴 항목을 삭제했습니다.') // console.log('카트에 담긴 항목을 삭제했습니다.')
} }
async function getCart() { async function getCart() {
...@@ -102,7 +102,7 @@ function ShoppingCart() { ...@@ -102,7 +102,7 @@ function ShoppingCart() {
return ( return (
<div> <div>
{console.log(cart)} {/* {console.log(cart)} */}
<Container className="justify-content-center"> <Container className="justify-content-center">
<h1 className="my-5 font-weight-bold text-center">장바구니</h1> <h1 className="my-5 font-weight-bold text-center">장바구니</h1>
<div> <div>
......
...@@ -33,12 +33,10 @@ function Signup() { ...@@ -33,12 +33,10 @@ function Signup() {
event.stopPropagation(); event.stopPropagation();
} }
setValidated(true); setValidated(true);
console.log(user)
try { try {
setError('') setError('')
const response = await axios.post('/api/users/signup', user) const response = await axios.post('/api/users/signup', user)
console.log(response.data)
setSuccess(true) setSuccess(true)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
...@@ -66,7 +64,6 @@ function Signup() { ...@@ -66,7 +64,6 @@ function Signup() {
} }
return ( return (
<div>
<Container className="my-5"> <Container className="my-5">
<Row className="justify-content-center"> <Row className="justify-content-center">
<Col md={6} xs={10} className="border" style={{ background: '#F7F3F3' }}> <Col md={6} xs={10} className="border" style={{ background: '#F7F3F3' }}>
...@@ -119,7 +116,6 @@ function Signup() { ...@@ -119,7 +116,6 @@ function Signup() {
</Col> </Col>
<strong className='pt-2 d-flex align-items-flex-start'>* * * * * *</strong> <strong className='pt-2 d-flex align-items-flex-start'>* * * * * *</strong>
</Form.Group> </Form.Group>
<Form.Group as={Row} controlId="formBasicId"> <Form.Group as={Row} controlId="formBasicId">
<Form.Label column sm="4" for='id'> <Form.Label column sm="4" for='id'>
아이디 </Form.Label> 아이디 </Form.Label>
...@@ -133,7 +129,6 @@ function Signup() { ...@@ -133,7 +129,6 @@ function Signup() {
<Form.Control.Feedback type="invalid" >아이디를 입력하세요. </Form.Control.Feedback> <Form.Control.Feedback type="invalid" >아이디를 입력하세요. </Form.Control.Feedback>
</Col> </Col>
</Form.Group> </Form.Group>
<Form.Group as={Row} controlId="formBasicPassword"> <Form.Group as={Row} controlId="formBasicPassword">
<Form.Label column sm="4" for='password'> <Form.Label column sm="4" for='password'>
비밀번호 </Form.Label> 비밀번호 </Form.Label>
...@@ -148,7 +143,6 @@ function Signup() { ...@@ -148,7 +143,6 @@ function Signup() {
<Form.Control.Feedback type="invalid" >비밀번호를 입력하세요. </Form.Control.Feedback> <Form.Control.Feedback type="invalid" >비밀번호를 입력하세요. </Form.Control.Feedback>
</Col> </Col>
</Form.Group> </Form.Group>
<Form.Group as={Row} controlId="formBasicPassword2"> <Form.Group as={Row} controlId="formBasicPassword2">
<Form.Label column sm="4" for='password'> <Form.Label column sm="4" for='password'>
비밀번호 확인 </Form.Label> 비밀번호 확인 </Form.Label>
...@@ -163,7 +157,6 @@ function Signup() { ...@@ -163,7 +157,6 @@ function Signup() {
<Form.Control.Feedback type="invalid" >비밀번호를 한번 입력하세요.</Form.Control.Feedback> <Form.Control.Feedback type="invalid" >비밀번호를 한번 입력하세요.</Form.Control.Feedback>
</Col> </Col>
</Form.Group> </Form.Group>
<Form.Group as={Row} controlId="formBasicEmail"> <Form.Group as={Row} controlId="formBasicEmail">
<Form.Label column sm="4" for='email'> <Form.Label column sm="4" for='email'>
이메일 </Form.Label> 이메일 </Form.Label>
...@@ -177,7 +170,6 @@ function Signup() { ...@@ -177,7 +170,6 @@ function Signup() {
<Form.Control.Feedback type="invalid" >이메일을 입력하세요.</Form.Control.Feedback> <Form.Control.Feedback type="invalid" >이메일을 입력하세요.</Form.Control.Feedback>
</Col> </Col>
</Form.Group> </Form.Group>
<Form.Group as={Row} controlId="formBasicTel"> <Form.Group as={Row} controlId="formBasicTel">
<Form.Label column sm="4" for='tel'> <Form.Label column sm="4" for='tel'>
휴대전화 </Form.Label> 휴대전화 </Form.Label>
...@@ -201,7 +193,6 @@ function Signup() { ...@@ -201,7 +193,6 @@ function Signup() {
</Col> </Col>
</Row> </Row>
</Container> </Container>
</div >
) )
} }
......
import axios from "axios"; import axios from "axios";
export function handleLogin({ userId, role, name, tel }) { export function handleLogin({ userId, role, name, tel, email }) {
localStorage.setItem('id', userId) localStorage.setItem('id', userId)
localStorage.setItem('role', role) localStorage.setItem('role', role)
localStorage.setItem('name', name) localStorage.setItem('name', name)
localStorage.setItem('tel', tel) localStorage.setItem('tel', tel)
localStorage.setItem('email', email)
} }
export async function handleLogout() { export async function handleLogout() {
...@@ -15,7 +16,6 @@ export async function handleLogout() { ...@@ -15,7 +16,6 @@ export async function handleLogout() {
export function isAuthenticated() { export function isAuthenticated() {
const userId = localStorage.getItem('id') const userId = localStorage.getItem('id')
// console.log("suer ID =", userId)
if (userId) { if (userId) {
return userId return userId
} else { } else {
......
...@@ -5,15 +5,13 @@ import config from '../config.js' ...@@ -5,15 +5,13 @@ import config from '../config.js'
const login = async (req, res) => { const login = async (req, res) => {
const { id, password } = req.body const { id, password } = req.body
console.log(id, password)
try { try {
const user = await User.findOne({ id }).select('password role name tel') const user = await User.findOne({ id }).select('password role name tel email')
console.log('u=', user) console.log('u=', user)
if (!user) { if (!user) {
return res.status(404).send(`${id}가 존재하지 않습니다.`) return res.status(404).send(`${id}가 존재하지 않습니다.`)
} }
const passwordMatch = await bcrypt.compare(password, user.password) const passwordMatch = await bcrypt.compare(password, user.password)
if (passwordMatch) { if (passwordMatch) {
const token = jwt.sign({ userId: user._id }, config.jwtSecret, { const token = jwt.sign({ userId: user._id }, config.jwtSecret, {
expiresIn: '3d' expiresIn: '3d'
...@@ -23,7 +21,7 @@ const login = async (req, res) => { ...@@ -23,7 +21,7 @@ const login = async (req, res) => {
httpOnly: true, httpOnly: true,
secure: config.env === 'production' secure: config.env === 'production'
}) })
res.json({ userId: user._id, role: user.role, name: user.name, tel: user.tel }) res.json({ userId: user._id, role: user.role, name: user.name, tel: user.tel, email:user.email })
} else { } else {
res.status(401).send('비밀번호가 일치하지 않습니다.') res.status(401).send('비밀번호가 일치하지 않습니다.')
...@@ -39,4 +37,5 @@ const logout = (req, res) => { ...@@ -39,4 +37,5 @@ const logout = (req, res) => {
res.send('로그아웃 되었습니다.') res.send('로그아웃 되었습니다.')
} }
export default { login, logout } export default { login, logout }
\ No newline at end of file
...@@ -58,7 +58,6 @@ const deleteCart = async (req, res) => { ...@@ -58,7 +58,6 @@ const deleteCart = async (req, res) => {
path: 'products.productId', path: 'products.productId',
model: 'Product' model: 'Product'
}) })
// res.send("삭제완료")
res.json(cart) res.json(cart)
} catch (error) { } catch (error) {
console.log(error) console.log(error)
...@@ -80,7 +79,7 @@ const deleteCart2 = async (req, res) => { ...@@ -80,7 +79,7 @@ const deleteCart2 = async (req, res) => {
model: 'Product' model: 'Product'
}) })
} }
res.send("주문완료 쇼핑카트 삭제") res.send("주문완료 쇼핑카트에서 삭제")
// res.json(cart) // res.json(cart)
} catch (error) { } catch (error) {
console.log(error) console.log(error)
......
...@@ -3,7 +3,6 @@ import Category from "../schemas/Category.js"; ...@@ -3,7 +3,6 @@ import Category from "../schemas/Category.js";
const getCategory = async (req, res) => { const getCategory = async (req, res) => {
try { try {
const category = await Category.find({}, { _id: 0 }) const category = await Category.find({}, { _id: 0 })
// console.log("main= ", category);
res.json(category) res.json(category)
} catch (error) { } catch (error) {
console.log(error) console.log(error)
......
import Order from "../schemas/Order.js"; import Order from "../schemas/Order.js";
import User from "../schemas/User.js";
const addorder = async (req, res) => { const addorder = async (req, res) => {
const { userId, products, receiverInfo, total } = req.body const { userId, products, receiverInfo, total } = req.body
...@@ -26,11 +27,12 @@ const Ordered = async (req, res) => { ...@@ -26,11 +27,12 @@ const Ordered = async (req, res) => {
const showorder = async (req, res) => { const showorder = async (req, res) => {
try { try {
const order = await Order.findOne({ userId: req.id }).populate({ const order = await Order.find({ userId: req.userId }).sort({_id:-1}).limit(1).populate({
path: 'products.productId', path: 'products.productId',
model: 'Product' model: 'Product'
}) })
res.status(200).json(order.products) console.log(order)
res.status(200).json(order[0])
} catch (error) { } catch (error) {
console.log(error) console.log(error)
res.status(500).send('쇼핑카트를 불러오지 못했습니다.') res.status(500).send('쇼핑카트를 불러오지 못했습니다.')
...@@ -38,7 +40,18 @@ const showorder = async (req, res) => { ...@@ -38,7 +40,18 @@ const showorder = async (req, res) => {
} }
const orderById = async (req, res, next, id) => {
try {
const user = await User.findById(id)
if (!user) {
res.status(404).send('사용자를 찾을 수 없습니다')
}
req.userId = user
next()
} catch (error) {
console.log(error);
res.status(500).send('사용자 아이디 검색 실패')
}
}
export default { addorder, showorder, orderById , Ordered }
\ No newline at end of file
export default { addorder, showorder, Ordered }
\ No newline at end of file
...@@ -5,11 +5,10 @@ const upload = multer({ dest: 'uploads/' }) ...@@ -5,11 +5,10 @@ const upload = multer({ dest: 'uploads/' })
const imageUpload = upload.fields([ const imageUpload = upload.fields([
{ name: 'main_image' }, { name: 'main_image' },
{ name: 'detail_image' } { name: 'detail_image'}
]) ])
const regist = async (req, res) => { const regist = async (req, res) => {
console.log("req.body=", req.body)
try { try {
const { pro_name, price, stock, main_category, sub_category, description, colors, sizes } = req.body const { pro_name, price, stock, main_category, sub_category, description, colors, sizes } = req.body
const main_img = req.files['main_image'][0] const main_img = req.files['main_image'][0]
...@@ -24,7 +23,6 @@ const regist = async (req, res) => { ...@@ -24,7 +23,6 @@ const regist = async (req, res) => {
}).save() }).save()
res.json(newProduct) res.json(newProduct)
} catch (error) { } catch (error) {
console.log(error)
res.status(500).send('제품 정보 등록에 실패하였습니다. 다시 진행해 주십시오.') res.status(500).send('제품 정보 등록에 실패하였습니다. 다시 진행해 주십시오.')
} }
} }
...@@ -33,8 +31,6 @@ const getToHome = async (req, res) => { ...@@ -33,8 +31,6 @@ const getToHome = async (req, res) => {
try { try {
const bestProduct = await Product.find({}).sort({ purchase: -1 }).limit(6) const bestProduct = await Product.find({}).sort({ purchase: -1 }).limit(6)
const newProduct = await Product.find({}).sort({ createdAt: -1 }).limit(6) const newProduct = await Product.find({}).sort({ createdAt: -1 }).limit(6)
// console.log("best=", bestProduct)
// console.log("new=", newProduct)
res.json({ bestProduct, newProduct }) res.json({ bestProduct, newProduct })
} catch { } catch {
res.status(500).send('상품을 불러오지 못했습니다.') res.status(500).send('상품을 불러오지 못했습니다.')
...@@ -43,8 +39,17 @@ const getToHome = async (req, res) => { ...@@ -43,8 +39,17 @@ const getToHome = async (req, res) => {
const getAll = async (req, res) => { const getAll = async (req, res) => {
try { try {
if (req.query.product) {
const productslist = await Product.find({ pro_name: { $regex: new RegExp(req.query.product) } }).sort({ createdAt: -1 })
if (productslist.length == 0) {
res.status(404).send('상품을 찾을 수 없습니다.')
} else {
res.json(productslist)
}
} else {
const productslist = await Product.find({}).sort({ createdAt: -1 }) const productslist = await Product.find({}).sort({ createdAt: -1 })
res.json(productslist) res.json(productslist)
}
} catch (error) { } catch (error) {
res.status(500).send('상품을 불러오지 못했습니다.') res.status(500).send('상품을 불러오지 못했습니다.')
} }
...@@ -61,12 +66,17 @@ const getlist = (req, res) => { ...@@ -61,12 +66,17 @@ const getlist = (req, res) => {
const categoryId = async (req, res, next, category) => { const categoryId = async (req, res, next, category) => {
try { try {
const productslist = await Product.find({ main_category: category }) if (req.query.product) {
if (!productslist) { const productslist = await Product.find({ main_category: category, pro_name: { $regex: new RegExp(req.query.product) } })
if (productslist.length == 0) {
res.status(404).send('상품을 찾을 수 없습니다.') res.status(404).send('상품을 찾을 수 없습니다.')
} else {
req.productslist = productslist
} }
} else {
const productslist = await Product.find({ main_category: category })
req.productslist = productslist req.productslist = productslist
console.log("nononono", req.productslist) }
next() next()
} catch (error) { } catch (error) {
res.status(500).send('상품을 불러오지 못했습니다.') res.status(500).send('상품을 불러오지 못했습니다.')
...@@ -74,19 +84,16 @@ const categoryId = async (req, res, next, category) => { ...@@ -74,19 +84,16 @@ const categoryId = async (req, res, next, category) => {
} }
const subname = async (req, res) => { const subname = async (req, res) => {
console.log("req.query", req.query)
try { try {
const findSubname = await Product.find({ sub_category: req.query.subname }) const findSubname = await Product.find({ sub_category: req.query.subname })
console.log("findSubname111=", findSubname)
res.send(findSubname) res.send(findSubname)
} catch (error) { } catch (error) {
res.send('상품을 불러오지 못했습니다.') res.status(500).send('상품을 불러오지 못했습니다.')
} }
} }
const plusPurchase = async (req, res) => { const plusPurchase = async (req, res) => {
const { products } = req.body const { products } = req.body
// console.log(products)
try { try {
for (let i = 0; i < products.length; i++) { for (let i = 0; i < products.length; i++) {
const count = products[i].count const count = products[i].count
...@@ -94,16 +101,35 @@ const plusPurchase = async (req, res) => { ...@@ -94,16 +101,35 @@ const plusPurchase = async (req, res) => {
{ _id: products[i].productId._id } { _id: products[i].productId._id }
) )
const purchase = product.purchase const purchase = product.purchase
const stock = product.stock
await Product.updateOne( await Product.updateOne(
{ _id: products[i].productId._id }, { _id: products[i].productId._id },
{ $set: { purchase: count + purchase } } {
$set:
{
purchase: count + purchase,
stock: stock - count
}
}
) )
// console.log("i=", i)
} }
res.send("구매수 늘리기 성공") res.send("구매수 늘리기, 재고수 줄이기 성공")
} catch (error) { } catch (error) {
res.status(500).send('구매숫자를 늘리지 못함') res.status(500).send('구매숫자를 늘리지 못함')
} }
} }
export default { imageUpload, regist, getToHome, getAll, categoryId, getlist, subname, plusPurchase } const deletePro = async (req, res) => {
\ No newline at end of file const pro_id = req.query.pro_id
try {
const productOne = await Product.findById(pro_id)
if (productOne) {
await Product.remove({ _id: pro_id })
}
res.send('삭제 성공')
} catch (error) {
res.status(500).send('삭제할 상품을 찾지 못하거나 삭제 중 문제가 발생했습니다.')
}
}
export default { imageUpload, regist, getToHome, getAll, categoryId, getlist, subname, plusPurchase, deletePro }
\ No newline at end of file
...@@ -3,6 +3,7 @@ import User from "../schemas/User.js"; ...@@ -3,6 +3,7 @@ import User from "../schemas/User.js";
import isLength from 'validator/lib/isLength.js'; import isLength from 'validator/lib/isLength.js';
import bcrypt from 'bcryptjs'; import bcrypt from 'bcryptjs';
import multer from "multer"; import multer from "multer";
import Order from "../schemas/Order.js";
const uploadimg = multer({ dest: 'uploads/' }); const uploadimg = multer({ dest: 'uploads/' });
...@@ -85,4 +86,20 @@ const update = async (req, res) => { ...@@ -85,4 +86,20 @@ const update = async (req, res) => {
} }
} }
export default { signup, username, imgUpload, userById, update } const addorder = async (req, res) => {
\ No newline at end of file const {userId}=req.body
try {
const order = await Order.find({ userId: userId }).populate({
path: 'products.productId',
model: 'Product'
})
console.log("hey", order)
res.status(200).json(order)
} catch (error) {
console.log(error)
res.status(500).send('주문현황을 불러오지 못했습니다.')
}
}
export default { signup, username, imgUpload, userById,update, addorder }
\ No newline at end of file
...@@ -9,6 +9,4 @@ router.route('/main') ...@@ -9,6 +9,4 @@ router.route('/main')
router.route('/sub/:sub') router.route('/sub/:sub')
.get(categoryCtrl.getSubCategory) .get(categoryCtrl.getSubCategory)
// router.param('sub',categoryCtrl.getsubId)
export default router export default router
\ No newline at end of file
...@@ -11,5 +11,6 @@ router.route('/addorder') ...@@ -11,5 +11,6 @@ router.route('/addorder')
router.route('/showorder/:userId') router.route('/showorder/:userId')
.get(orderCtrl.showorder) .get(orderCtrl.showorder)
router.param('userId', orderCtrl.orderById)
export default router export default router
\ No newline at end of file
...@@ -22,7 +22,9 @@ router.route('/getproduct/sub') ...@@ -22,7 +22,9 @@ router.route('/getproduct/sub')
router.route('/pluspurchase') router.route('/pluspurchase')
.post(productCtrl.plusPurchase) .post(productCtrl.plusPurchase)
router.route('/delete')
.delete(productCtrl.deletePro)
router.param('category', productCtrl.categoryId) router.param('category', productCtrl.categoryId)
// router.param('subname',productCtrl.subcategoryId)
export default router export default router
\ No newline at end of file
...@@ -10,6 +10,9 @@ router.route('/account/:userId') ...@@ -10,6 +10,9 @@ router.route('/account/:userId')
.get(userCtrl.username) .get(userCtrl.username)
.put(userCtrl.imgUpload, userCtrl.update) .put(userCtrl.imgUpload, userCtrl.update)
router.route('/addorder')
.post(userCtrl.addorder)
router.param('userId', userCtrl.userById) router.param('userId', userCtrl.userById)
export default router export default router
\ No newline at end of file
const inventory = {
sibal: [
{ name: 'apples', quantity: 2 },
{ name: 'bananas', quantity: 4 },
{ name: 'cherries', quantity: 9 }
]
}
const result = inventory.find(fruit => fruit.name === 'cherries');
const what = inventory.find({},{ sibal: { $elemMatch: { quantity: 2 } } })
// db.schools.find( { zipcode: "63109" },
// { students: { $elemMatch: { school: 102, age: { $gt: 10} } } } )
console.log(result);
console.log(what);
\ No newline at end of file
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