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 { Link } from 'react-router-dom';
import ListCard from '../Components/ListCard';
import Pagination from "../Components/Pagination";
import axios from 'axios';
import catchError from '../utils/catchErrors';
import { Container, Row, Col, Form, FormControl, Button, Dropdown, ButtonGroup, Image } from 'react-bootstrap';
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 [subcategory, setSubcategory] = useState([])
const [subCategory, setSubCategory] = useState([])
const [productlist, setProductlist] = useState([])
const [status, setStatus] = useState(INIT_STATUS)
const [currentPage, setCurrentPage] = useState(1)
const [error, setError] = useState('')
const searchref = useRef(null)
const per = 10;
useEffect(() => {
setMainCategory(match.params.main.toUpperCase())
......@@ -17,18 +25,43 @@ function ProductsList({ match }) {
useEffect(() => {
getSubsCategories([])
getSubsCategories()
getProductlist()
}, [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 {
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}`)
setSubcategory(Object.values(response.data)[0])
setSubCategory(Object.values(response.data)[0])
} catch (error) {
catchError(error, setError)
}
......@@ -36,111 +69,181 @@ function ProductsList({ match }) {
async function getProductlist() {
try {
setError('')
const response = await axios.get(`/api/product/getproduct/main/${mainCategory}`)
console.log("response.data=main", response.data)
setProductlist(response.data)
setCurrentPage(1)
} catch (error) {
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) {
const subname = e.target.name
console.log("subname=", subname)
try {
console.log("first test!!!!!!!!")
setError('')
const response = await axios.get(`/api/product/getproduct/sub?subname=${subname}`)
console.log("subname response data=", response.data)
setProductlist(response.data)
setCurrentPage(1)
} catch (error) {
catchError(error, setError)
console.log("오류입니다.")
}
}
if (error) {
alert(`${error}`)
setError('')
searchref.current.value = ''
}
return (
<div>
<Container>
<style type="text/css">
{`
a, a:hover, a:active {
color: #000;
text-decoration: none;
}
.btn {
background-color: #CDC5C2;
border-color: #CDC5C2;
border-radius: 0;
}
.btn:hover, .btn:active, .btn:focus, .show>.btn-primary.dropdown-toggle {
.btn:hover, .btn:focus {
background-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>
<Container>
<Row className="justify-content-center" >
<Col className='px-3'>
<div className="text-center">
<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"}}>
{subcategory.map(el =>
(<Button className="m-1" style={{ fontSize: "0.8vw"}} name={el} onClick={handleSubname}>{el}
</Button>))}
</ButtonGroup>
</div>
</Col>
</Row>
<Row className="justify-content-end mx-0 my-2">
<Dropdown>
<Dropdown.Toggle className="mx-2">정렬</Dropdown.Toggle>
<Dropdown.Menu>
<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" />
</Button>
</Form>
</Row>
<Row md={8} sm={12} className="justify-content-center m-2">
{productlist.length > 0 ?
productlist.map(pro => (
<Link to={{
pathname: `/product/${pro._id}`,
state: {
id: pro._id,
name: pro.pro_name,
price: pro.price,
colors: pro.colors,
sizes: pro.sizes,
description: pro.description,
main_img: pro.main_imgUrl,
detail_imgs: pro.detail_imgUrls
}
}}>
<ListCard id={pro._id} name={pro.pro_name} price={pro.price} main_img={pro.main_imgUrl}
/>
</Link>
))
: (
<Image src="/sryimready.jpg" className='m-5'
style={{ objectFit: "contain", width: "45vw", height: "45vh" }}></Image>
)
}
</Row>
</Container>
</div>
<Row className="justify-content-center" >
<Col className='px-3'>
<div className="text-center">
<h1 style={{ fontSize: "5.5vmax" }} className="text-center m-1 py-3">{mainCategory}</h1>
<ButtonGroup className="mb-3" style={{ display: "inline" }}>
{subCategory.map(el =>(<Button className="m-1" style={{ fontSize: "0.8vw" }} name={el} onClick={handleSubname}>{el}</Button>))}
</ButtonGroup>
</div>
</Col>
</Row>
<Row className="justify-content-end mx-0 mt-5 mb-3">
<Form inline onSubmit={handleSearch} className="justify-content-end mx-0 my-2">
<FormControl ref={searchref} type="text" onChange={handleChange} placeholder="Search" style={{ width: "13rem" }} />
<Button type="submit" className="px-2 mr-2">
<img src="/icon/search.svg" width="20" height="20" />
</Button>
</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 md={8} sm={12} className="justify-content-center m-2">
{productlist.length > 0 ?
currentPosts(productlist).map(pro => (
<Link to={{
pathname: `/product/${pro._id}`,
state: {
id: pro._id,
name: pro.pro_name,
price: pro.price,
colors: pro.colors,
sizes: pro.sizes,
description: pro.description,
main_img: pro.main_imgUrl,
detail_imgs: pro.detail_imgUrls
}
}}>
<ListCard id={pro._id} name={pro.pro_name} price={pro.price} main_img={pro.main_imgUrl}
/>
</Link>
))
: (
<Image src="/sryimready.jpg" className='m-5'
style={{ objectFit: "contain", width: "45vw", height: "45vh" }}></Image>
)
}
</Row>
{productlist.length != 0 ? <Pagination index={currentPage} totalPages={Math.ceil(productlist.length / per)} handlePage={setCurrentPage} /> : ''}
</Container>
)
}
......
......@@ -15,7 +15,7 @@ function ShoppingCart() {
useEffect(() => {
getCart()
console.log(cart)
// console.log(cart)
}, [user])
function plusNum(e) {
......@@ -59,7 +59,7 @@ function ShoppingCart() {
async function deleteCart(e) {
//장바구니 DB에서 해당 항목 삭제
console.log(e.target.name)
// console.log(e.target.name)
try {
const response = await axios.post('/api/cart/deletecart', {
userId: user,
......@@ -70,7 +70,7 @@ function ShoppingCart() {
} catch (error) {
catchErrors(error, setError)
}
console.log('카트에 담긴 항목을 삭제했습니다.')
// console.log('카트에 담긴 항목을 삭제했습니다.')
}
async function getCart() {
......@@ -102,7 +102,7 @@ function ShoppingCart() {
return (
<div>
{console.log(cart)}
{/* {console.log(cart)} */}
<Container className="justify-content-center">
<h1 className="my-5 font-weight-bold text-center">장바구니</h1>
<div>
......
......@@ -33,12 +33,10 @@ function Signup() {
event.stopPropagation();
}
setValidated(true);
console.log(user)
try {
setError('')
const response = await axios.post('/api/users/signup', user)
console.log(response.data)
setSuccess(true)
} catch (error) {
catchErrors(error, setError)
......@@ -66,142 +64,135 @@ function Signup() {
}
return (
<div>
<Container className="my-5">
<Row className="justify-content-center">
<Col md={6} xs={10} className="border" style={{ background: '#F7F3F3' }}>
<h2 className="text-center pt-3 m-4">Sign Up</h2>
{error && <Alert variant='danger'>
{error}
</Alert>}
<Form
noValidate validated={validated}
onSubmit={handleSubmit}
className="p-4">
<Form.Group as={Row} controlId="formBasicName">
<Form.Label column sm="4" for='name'>
</Form.Label>
<Col sm="8">
<Form.Control
required type="text"
name="name"
placeholder="Name"
value={user.name}
onChange={handleChange} />
<Form.Control.Feedback type="invalid" >이름을 입력하세요. </Form.Control.Feedback>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formBasicNumber">
<Form.Label column sm="4" for='number'>
주민등록번호 </Form.Label>
<Col sm="4" xs='5'>
<Form.Control
className='pr-0'
required type="text"
name="number1"
maxlength="6"
placeholder="생년월일"
value={user.number1}
onChange={handleChange} />
<Form.Control.Feedback type="invalid" >주민등록번호 입력하세요. </Form.Control.Feedback>
</Col>
<strong className='pt-2 d-flex align-items-flex-start'>-</strong>
<Col md="2" xs='3'>
<Form.Control
className='pr-0'
required type="text"
name="number2"
maxlength="1"
value={user.number2}
onChange={handleChange} />
</Col>
<strong className='pt-2 d-flex align-items-flex-start'>* * * * * *</strong>
</Form.Group>
<Form.Group as={Row} controlId="formBasicId">
<Form.Label column sm="4" for='id'>
아이디 </Form.Label>
<Col sm="8">
<Form.Control
required type="text"
name="id"
placeholder="ID"
value={user.id}
onChange={handleChange} />
<Form.Control.Feedback type="invalid" >아이디를 입력하세요. </Form.Control.Feedback>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formBasicPassword">
<Form.Label column sm="4" for='password'>
비밀번호 </Form.Label>
<Col sm="8">
<Form.Control
type="password"
name="password"
placeholder="Password"
value={user.password}
required
onChange={handleChange} />
<Form.Control.Feedback type="invalid" >비밀번호를 입력하세요. </Form.Control.Feedback>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formBasicPassword2">
<Form.Label column sm="4" for='password'>
비밀번호 확인 </Form.Label>
<Col sm="8">
<Form.Control
type="password"
name="password2"
placeholder="Password"
value={user.password2}
required
onChange={handleChange} />
<Form.Control.Feedback type="invalid" >비밀번호를 한번 입력하세요.</Form.Control.Feedback>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formBasicEmail">
<Form.Label column sm="4" for='email'>
이메일 </Form.Label>
<Col sm="8">
<Form.Control
required type="email"
name="email"
placeholder="E-mail"
value={user.email}
onChange={handleChange} />
<Form.Control.Feedback type="invalid" >이메일을 입력하세요.</Form.Control.Feedback>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formBasicTel">
<Form.Label column sm="4" for='tel'>
휴대전화 </Form.Label>
<Col sm="8">
<Form.Control
required type="text"
name="tel"
placeholder="Telephone"
value={user.tel}
onChange={handleChange} />
<Form.Control.Feedback type="invalid" >휴대전화를 입력하세요.</Form.Control.Feedback>
<Row className='text-end pl-3 mt-1'><small >' - ' 함께 입력해주세요^^</small></Row>
</Col>
</Form.Group>
<Button
style={{ background: '#91877F', borderColor: '#91877F', margin: 'auto' }} type="submit" block
onClick={checkPassword} >
Sign Up
<Container className="my-5">
<Row className="justify-content-center">
<Col md={6} xs={10} className="border" style={{ background: '#F7F3F3' }}>
<h2 className="text-center pt-3 m-4">Sign Up</h2>
{error && <Alert variant='danger'>
{error}
</Alert>}
<Form
noValidate validated={validated}
onSubmit={handleSubmit}
className="p-4">
<Form.Group as={Row} controlId="formBasicName">
<Form.Label column sm="4" for='name'>
</Form.Label>
<Col sm="8">
<Form.Control
required type="text"
name="name"
placeholder="Name"
value={user.name}
onChange={handleChange} />
<Form.Control.Feedback type="invalid" >이름을 입력하세요. </Form.Control.Feedback>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formBasicNumber">
<Form.Label column sm="4" for='number'>
주민등록번호 </Form.Label>
<Col sm="4" xs='5'>
<Form.Control
className='pr-0'
required type="text"
name="number1"
maxlength="6"
placeholder="생년월일"
value={user.number1}
onChange={handleChange} />
<Form.Control.Feedback type="invalid" >주민등록번호 입력하세요. </Form.Control.Feedback>
</Col>
<strong className='pt-2 d-flex align-items-flex-start'>-</strong>
<Col md="2" xs='3'>
<Form.Control
className='pr-0'
required type="text"
name="number2"
maxlength="1"
value={user.number2}
onChange={handleChange} />
</Col>
<strong className='pt-2 d-flex align-items-flex-start'>* * * * * *</strong>
</Form.Group>
<Form.Group as={Row} controlId="formBasicId">
<Form.Label column sm="4" for='id'>
아이디 </Form.Label>
<Col sm="8">
<Form.Control
required type="text"
name="id"
placeholder="ID"
value={user.id}
onChange={handleChange} />
<Form.Control.Feedback type="invalid" >아이디를 입력하세요. </Form.Control.Feedback>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formBasicPassword">
<Form.Label column sm="4" for='password'>
비밀번호 </Form.Label>
<Col sm="8">
<Form.Control
type="password"
name="password"
placeholder="Password"
value={user.password}
required
onChange={handleChange} />
<Form.Control.Feedback type="invalid" >비밀번호를 입력하세요. </Form.Control.Feedback>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formBasicPassword2">
<Form.Label column sm="4" for='password'>
비밀번호 확인 </Form.Label>
<Col sm="8">
<Form.Control
type="password"
name="password2"
placeholder="Password"
value={user.password2}
required
onChange={handleChange} />
<Form.Control.Feedback type="invalid" >비밀번호를 한번 입력하세요.</Form.Control.Feedback>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formBasicEmail">
<Form.Label column sm="4" for='email'>
이메일 </Form.Label>
<Col sm="8">
<Form.Control
required type="email"
name="email"
placeholder="E-mail"
value={user.email}
onChange={handleChange} />
<Form.Control.Feedback type="invalid" >이메일을 입력하세요.</Form.Control.Feedback>
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formBasicTel">
<Form.Label column sm="4" for='tel'>
휴대전화 </Form.Label>
<Col sm="8">
<Form.Control
required type="text"
name="tel"
placeholder="Telephone"
value={user.tel}
onChange={handleChange} />
<Form.Control.Feedback type="invalid" >휴대전화를 입력하세요.</Form.Control.Feedback>
<Row className='text-end pl-3 mt-1'><small >' - ' 함께 입력해주세요^^</small></Row>
</Col>
</Form.Group>
<Button
style={{ background: '#91877F', borderColor: '#91877F', margin: 'auto' }} type="submit" block
onClick={checkPassword} >
Sign Up
</Button>
</Form>
</Col>
</Row>
</Container>
</div >
</Form>
</Col>
</Row>
</Container>
)
}
......
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('role', role)
localStorage.setItem('name', name)
localStorage.setItem('tel', tel)
localStorage.setItem('email', email)
}
export async function handleLogout() {
......@@ -15,7 +16,6 @@ export async function handleLogout() {
export function isAuthenticated() {
const userId = localStorage.getItem('id')
// console.log("suer ID =", userId)
if (userId) {
return userId
} else {
......
......@@ -5,15 +5,13 @@ import config from '../config.js'
const login = async (req, res) => {
const { id, password } = req.body
console.log(id, password)
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)
if (!user) {
return res.status(404).send(`${id}가 존재하지 않습니다.`)
}
const passwordMatch = await bcrypt.compare(password, user.password)
if (passwordMatch) {
const token = jwt.sign({ userId: user._id }, config.jwtSecret, {
expiresIn: '3d'
......@@ -23,7 +21,7 @@ const login = async (req, res) => {
httpOnly: true,
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 {
res.status(401).send('비밀번호가 일치하지 않습니다.')
......@@ -39,4 +37,5 @@ const logout = (req, res) => {
res.send('로그아웃 되었습니다.')
}
export default { login, logout }
\ No newline at end of file
......@@ -58,7 +58,6 @@ const deleteCart = async (req, res) => {
path: 'products.productId',
model: 'Product'
})
// res.send("삭제완료")
res.json(cart)
} catch (error) {
console.log(error)
......@@ -80,7 +79,7 @@ const deleteCart2 = async (req, res) => {
model: 'Product'
})
}
res.send("주문완료 쇼핑카트 삭제")
res.send("주문완료 쇼핑카트에서 삭제")
// res.json(cart)
} catch (error) {
console.log(error)
......
......@@ -3,7 +3,6 @@ import Category from "../schemas/Category.js";
const getCategory = async (req, res) => {
try {
const category = await Category.find({}, { _id: 0 })
// console.log("main= ", category);
res.json(category)
} catch (error) {
console.log(error)
......@@ -51,4 +50,4 @@ const getsubId = async (req, res, next, ele) => {
next()
}
export default { getCategory, getsubId, getSubCategory, getToHome }
\ No newline at end of file
export default { getCategory, getsubId, getSubCategory, getToHome }
import Order from "../schemas/Order.js";
import User from "../schemas/User.js";
const addorder = async (req, res) => {
const { userId, products, receiverInfo, total } = req.body
......@@ -26,11 +27,12 @@ const Ordered = async (req, res) => {
const showorder = async (req, res) => {
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',
model: 'Product'
})
res.status(200).json(order.products)
console.log(order)
res.status(200).json(order[0])
} catch (error) {
console.log(error)
res.status(500).send('쇼핑카트를 불러오지 못했습니다.')
......@@ -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, Ordered }
\ No newline at end of file
export default { addorder, showorder, orderById , Ordered }
\ No newline at end of file
......@@ -5,11 +5,10 @@ const upload = multer({ dest: 'uploads/' })
const imageUpload = upload.fields([
{ name: 'main_image' },
{ name: 'detail_image' }
{ name: 'detail_image'}
])
const regist = async (req, res) => {
console.log("req.body=", req.body)
try {
const { pro_name, price, stock, main_category, sub_category, description, colors, sizes } = req.body
const main_img = req.files['main_image'][0]
......@@ -24,7 +23,6 @@ const regist = async (req, res) => {
}).save()
res.json(newProduct)
} catch (error) {
console.log(error)
res.status(500).send('제품 정보 등록에 실패하였습니다. 다시 진행해 주십시오.')
}
}
......@@ -33,8 +31,6 @@ const getToHome = async (req, res) => {
try {
const bestProduct = await Product.find({}).sort({ purchase: -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 })
} catch {
res.status(500).send('상품을 불러오지 못했습니다.')
......@@ -43,8 +39,17 @@ const getToHome = async (req, res) => {
const getAll = async (req, res) => {
try {
const productslist = await Product.find({}).sort({ createdAt: -1 })
res.json(productslist)
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 })
res.json(productslist)
}
} catch (error) {
res.status(500).send('상품을 불러오지 못했습니다.')
}
......@@ -61,12 +66,17 @@ const getlist = (req, res) => {
const categoryId = async (req, res, next, category) => {
try {
const productslist = await Product.find({ main_category: category })
if (!productslist) {
res.status(404).send('상품을 찾을 수 없습니다.')
if (req.query.product) {
const productslist = await Product.find({ main_category: category, pro_name: { $regex: new RegExp(req.query.product) } })
if (productslist.length == 0) {
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()
} catch (error) {
res.status(500).send('상품을 불러오지 못했습니다.')
......@@ -74,19 +84,16 @@ const categoryId = async (req, res, next, category) => {
}
const subname = async (req, res) => {
console.log("req.query", req.query)
try {
const findSubname = await Product.find({ sub_category: req.query.subname })
console.log("findSubname111=", findSubname)
res.send(findSubname)
} catch (error) {
res.send('상품을 불러오지 못했습니다.')
res.status(500).send('상품을 불러오지 못했습니다.')
}
}
const plusPurchase = async (req, res) => {
const { products } = req.body
// console.log(products)
try {
for (let i = 0; i < products.length; i++) {
const count = products[i].count
......@@ -94,16 +101,35 @@ const plusPurchase = async (req, res) => {
{ _id: products[i].productId._id }
)
const purchase = product.purchase
const stock = product.stock
await Product.updateOne(
{ _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) {
res.status(500).send('구매숫자를 늘리지 못함')
}
}
export default { imageUpload, regist, getToHome, getAll, categoryId, getlist, subname, plusPurchase }
\ No newline at end of file
const deletePro = async (req, res) => {
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";
import isLength from 'validator/lib/isLength.js';
import bcrypt from 'bcryptjs';
import multer from "multer";
import Order from "../schemas/Order.js";
const uploadimg = multer({ dest: 'uploads/' });
......@@ -85,4 +86,20 @@ const update = async (req, res) => {
}
}
export default { signup, username, imgUpload, userById, update }
\ No newline at end of file
const addorder = async (req, res) => {
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')
router.route('/sub/:sub')
.get(categoryCtrl.getSubCategory)
// router.param('sub',categoryCtrl.getsubId)
export default router
\ No newline at end of file
......@@ -11,5 +11,6 @@ router.route('/addorder')
router.route('/showorder/:userId')
.get(orderCtrl.showorder)
router.param('userId', orderCtrl.orderById)
export default router
\ No newline at end of file
......@@ -22,7 +22,9 @@ router.route('/getproduct/sub')
router.route('/pluspurchase')
.post(productCtrl.plusPurchase)
router.route('/delete')
.delete(productCtrl.deletePro)
router.param('category', productCtrl.categoryId)
// router.param('subname',productCtrl.subcategoryId)
export default router
\ No newline at end of file
......@@ -10,6 +10,9 @@ router.route('/account/:userId')
.get(userCtrl.username)
.put(userCtrl.imgUpload, userCtrl.update)
router.route('/addorder')
.post(userCtrl.addorder)
router.param('userId', userCtrl.userById)
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