Commit e645ff20 authored by 이재연's avatar 이재연
Browse files

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

parents ffb8ee80 fbce3d1a
...@@ -40,6 +40,9 @@ function App() { ...@@ -40,6 +40,9 @@ function App() {
<PrivateRoute path="/payment"> <PrivateRoute path="/payment">
<Payment /> <Payment />
</PrivateRoute> </PrivateRoute>
<PrivateRoute path="/paymentcompleted">
<PaymentCompleted />
</PrivateRoute>
<PrivateRoute path="/account"> <PrivateRoute path="/account">
<Account /> <Account />
</PrivateRoute> </PrivateRoute>
......
...@@ -9,11 +9,13 @@ function MainNav() { ...@@ -9,11 +9,13 @@ function MainNav() {
return ( return (
<Navbar sticky="top" style={{ background: "#CDC5C2" }}> <Navbar sticky="top" style={{ background: "#CDC5C2" }}>
<Navbar.Brand href="/home" className="text-light"> <Navbar.Brand href="/home" className="text-light">
<img alt="로고" src="/icon/footprint.svg" width="24" height="24" /> <img alt="로고" src="/icon/footprint.svg" width="18" height="18" />
{' '}KU# {' '}KU#
</Navbar.Brand> </Navbar.Brand>
<Nav className="ml-auto"> <Nav className="ml-auto d-flex align-items-center">
{user ? <> <Nav.Link className="text-light" onClick={() => handleLogout()}>Logout</Nav.Link> {user ?
<>
<Nav.Link className="text-light" onClick={() => handleLogout()}>Logout</Nav.Link>
<Nav.Link className="text-light" href="/account"> Mypage </Nav.Link> <Nav.Link className="text-light" href="/account"> Mypage </Nav.Link>
<Nav.Link href="/shoppingcart"> <Nav.Link href="/shoppingcart">
<img alt="카트" src="/icon/cart.svg" width="30" height="30" /> <img alt="카트" src="/icon/cart.svg" width="30" height="30" />
......
import { Pagination } from "react-bootstrap";
import React from 'react'; import React from 'react';
import { Pagination } from 'react-bootstrap';
function Paginations(props) { function Paginations({ index, endPage, handlePage }) {
return ( return (
<Pagination> <Pagination>
<Pagination.First onClick={() => props.handlePage(1)} /> <Pagination.First onClick={() => handlePage(1)} />
{props.index === 1 ? <Pagination.Prev onClick={()=>props.handlePage(props.index)} /> : <Pagination.Prev onClick={()=>props.handlePage(props.index - 1)} />} {index === 1 ? <Pagination.Prev onClick={()=>handlePage(index)} /> : <Pagination.Prev onClick={()=>handlePage(index - 1)} />}
{props.index === props.endPage-1 ? <Pagination.Item onClick={()=>props.handlePage(props.index - 3)}>{props.index - 3}</Pagination.Item> : ""} {index === endPage-1 ? <Pagination.Item onClick={()=>handlePage(index - 3)}>{index - 3}</Pagination.Item> : ""}
{props.index === props.endPage ? <Pagination.Item onClick={()=>props.handlePage(props.index - 4)}>{props.index - 4}</Pagination.Item> : ""} {index === endPage ? <Pagination.Item onClick={()=>handlePage(index - 4)}>{index - 4}</Pagination.Item> : ""}
{props.index === props.endPage ? <Pagination.Item onClick={()=>props.handlePage(props.index - 3)}>{props.index - 3}</Pagination.Item> : ""} {index === endPage ? <Pagination.Item onClick={()=>handlePage(index - 3)}>{index - 3}</Pagination.Item> : ""}
{props.index < 3 ? "" : <Pagination.Item onClick={()=>props.handlePage(props.index - 2)}>{props.index - 2}</Pagination.Item>} {index < 3 ? "" : <Pagination.Item onClick={()=>handlePage(index - 2)}>{index - 2}</Pagination.Item>}
{props.index === 1 ? "" : <Pagination.Item onClick={()=>props.handlePage(props.index - 1)}>{props.index - 1}</Pagination.Item>} {index === 1 ? "" : <Pagination.Item onClick={()=>handlePage(index - 1)}>{index - 1}</Pagination.Item>}
<Pagination.Item active>{props.index}</Pagination.Item> <Pagination.Item active>{index}</Pagination.Item>
{index === endPage ? "" : <Pagination.Item onClick={()=>handlePage(index + 1)}>{index + 1}</Pagination.Item>}
{props.index === props.endPage ? "" : <Pagination.Item onClick={()=>props.handlePage(props.index + 1)}>{props.index + 1}</Pagination.Item>} {index > endPage-2 ? "" : <Pagination.Item onClick={()=>handlePage(index + 2)}>{index + 2}</Pagination.Item>}
{props.index > props.endPage-2 ? "" : <Pagination.Item onClick={()=>props.handlePage(props.index + 2)}>{props.index + 2}</Pagination.Item>} {index === 1 ? <Pagination.Item onClick={()=>handlePage(index + 3)}>{index + 3}</Pagination.Item> : ""}
{props.index === 1 ? <Pagination.Item onClick={()=>props.handlePage(props.index + 3)}>{props.index + 3}</Pagination.Item> : ""} {index === 1 ? <Pagination.Item onClick={()=>handlePage(index + 4)}>{index + 4}</Pagination.Item> : ""}
{props.index === 1 ? <Pagination.Item onClick={()=>props.handlePage(props.index + 4)}>{props.index + 4}</Pagination.Item> : ""} {index === 2 ? <Pagination.Item onClick={()=>handlePage(index + 3)}>{index + 3}</Pagination.Item> : ""}
{props.index === 2 ? <Pagination.Item onClick={()=>props.handlePage(props.index + 3)}>{props.index + 3}</Pagination.Item> : ""} {index === endPage ? "" : <Pagination.Next onClick={()=>handlePage(index + 1)} />}
{props.index === props.endPage ? "" : <Pagination.Next onClick={()=>props.handlePage(props.index + 1)} />}
<Pagination.Last onClick={() =>handlePage(endPage)} />
<Pagination.Last onClick={() =>props.handlePage(props.endPage)} />
</Pagination> </Pagination>
) )
} }
export default Paginations export default Paginations
\ No newline at end of file
...@@ -15,8 +15,7 @@ function SubNav() { ...@@ -15,8 +15,7 @@ function SubNav() {
Object.keys(response.data[0]).forEach((ele) => { Object.keys(response.data[0]).forEach((ele) => {
const url = ele.toLowerCase() const url = ele.toLowerCase()
list.push( list.push(
<Nav.Link as={Link} to={`/categories/${url}`}>{ele}</Nav.Link> <Nav.Link href={`/categories/${url}`}>{ele}</Nav.Link>
//categories/${SubNav.url}/&{url}
) )
}) })
setCategoriesDiv(list) setCategoriesDiv(list)
......
...@@ -92,6 +92,7 @@ function Account() { ...@@ -92,6 +92,7 @@ function Account() {
} }
} }
return ( return (
<Container className="px-3"> <Container className="px-3">
<style type="text/css"> <style type="text/css">
......
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { Redirect } from 'react-router-dom'; import { Redirect } from 'react-router-dom';
import AllCard from '../Components/AllCard'; import AllCard from '../Components/AllCard';
import Pagination from '../Components/Pagination'; import Pagination from "../Components/Pagination";
import axios from 'axios'; import axios from 'axios';
import catchError from '../utils/catchErrors'; import catchError from '../utils/catchErrors';
import { Row, Form, FormControl, Button, Container } from 'react-bootstrap'; import { Row, Form, FormControl, Button, Container } from 'react-bootstrap';
function Admin() { function Admin() {
const INIT_STATUS = { indexOfFirst: 0, indexOfLast: 10 }
const [search, setSearch] = useState({ word: '' })
const [productlist, setProductlist] = useState([]) const [productlist, setProductlist] = useState([])
const [status, setStatus] = useState(INIT_STATUS)
const [currentPage, setCurrentPage] = useState(1);
const [per, setPer] = useState(10);
const [error, setError] = useState('') const [error, setError] = useState('')
const searchref = useRef(null)
const indexOfLast = currentPage * per;
const indexOfFirst = indexOfLast - per;
useEffect(() => { useEffect(() => {
getProductlist() getProductlist()
}, []) }, [])
function paginate(items, index, itemNumber) {
const posts = [];
const startIndex = (index - 1) * itemNumber
for (var i = 0; i < itemNumber; i++) {
posts.push(items[(startIndex + i)])
}
return posts
}
function currentPosts(tmp) {
let currentPosts = 0;
currentPosts = tmp.slice(indexOfFirst, indexOfLast);
console.log("postsPerPage=",currentPage)
return currentPosts;
}
async function getProductlist() { async function getProductlist() {
try { try {
const response = await axios.get(`/api/product/getproduct/all`) const response = await axios.get(`/api/product/getproduct/all`)
...@@ -24,12 +48,28 @@ function Admin() { ...@@ -24,12 +48,28 @@ function Admin() {
} }
} }
function handleSearch() { function handleChange(event) {
setSearch({ word: event.target.value })
} }
function handleSubmit(e) { async function handleSubmit(e) {
e.preventDefault() e.preventDefault()
try {
setError('')
const response = await axios.get(`/api/product/getproduct/all?product=${search.word}`)
console.log("response.data=", response.data)
setProductlist(response.data)
} catch (error) {
catchError(error, setError)
} finally {
searchref.current.value = ''
}
}
if (error) {
alert(`${error}`)
setError('')
searchref.current.value = ''
} }
return ( return (
...@@ -48,18 +88,18 @@ function Admin() { ...@@ -48,18 +88,18 @@ function Admin() {
`} `}
</style> </style>
<Row as={Form} onSubmit={handleSubmit} className="justify-content-end mx-0 my-5"> <Row as={Form} onSubmit={handleSubmit} className="justify-content-end mx-0 my-5">
<FormControl type="text" placeholder="Search" style={{ width: "13rem" }} /> <FormControl ref={searchref} type="text" onChange={handleChange} placeholder="Search" style={{ width: "13rem" }} />
<Button type="submit" className="px-2"> <Button type="submit" className="px-2">
<img src="icon/search.svg" width="20" height="20" /> <img src="icon/search.svg" width="20" height="20" />
</Button> </Button>
<Button sm={2} xs={6} type="button" href="/regist" className="ml-1">상품 등록</Button> <Button sm={2} xs={6} type="button" href="/regist" className="ml-1">상품 등록</Button>
</Row> </Row>
<Row className="justify-content-center m-5"> <Row className="justify-content-center m-5">
{productlist.map(pro => ( {currentPosts(productlist).map(pro => (
<AllCard id={pro._id} name={pro.pro_name} price={pro.price} main_img={pro.main_imgUrl} /> <AllCard id={pro._id} name={pro.pro_name} price={pro.price} main_img={pro.main_imgUrl} />
))} ))}
</Row> </Row>
<Pagination /> <Pagination index={currentPage} totalPosts={Math.ceil(productlist.length / per)} handlePage={setCurrentPage} />
</Container> </Container>
) )
} }
......
import axios from 'axios'; import axios from 'axios';
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import DaumPostcode from "react-daum-postcode"; import DaumPostcode from "react-daum-postcode";
import { Container, Card, Row, Col, Button, Form, FormGroup } from 'react-bootstrap'; import { Container, Row, Col, Button, Form } from 'react-bootstrap';
import { Redirect, Link, useHistory } from 'react-router-dom'; import { Redirect, Link, useHistory } from 'react-router-dom';
import PaymentCard from '../Components/PaymentCard'; import PaymentCard from '../Components/PaymentCard';
import { isAuthenticated } from '../utils/auth'; import { isAuthenticated } from '../utils/auth';
...@@ -9,7 +9,7 @@ import catchErrors from '../utils/catchErrors'; ...@@ -9,7 +9,7 @@ import catchErrors from '../utils/catchErrors';
function Payment({ match, location }) { function Payment({ match, location }) {
const [cart, setCart] = useState([]) const [cart, setCart] = useState([])
const [order, setOrder] = useState({products: []}) const [order, setOrder] = useState({ products: [] })
const [userData, setUserData] = useState({}) const [userData, setUserData] = useState({})
const [error, setError] = useState() const [error, setError] = useState()
const [post, setPost] = useState([]) const [post, setPost] = useState([])
...@@ -217,7 +217,6 @@ function Payment({ match, location }) { ...@@ -217,7 +217,6 @@ function Payment({ match, location }) {
}) })
}) })
const data = await response.json() const data = await response.json()
window.location.href = data.redirect_url
} else { } else {
console.log(response.data) console.log(response.data)
console.log(response2.data) console.log(response2.data)
...@@ -231,16 +230,7 @@ function Payment({ match, location }) { ...@@ -231,16 +230,7 @@ function Payment({ match, location }) {
} }
} }
if (redirect) {
console.log(redirect)
return <Redirect to={'/kakao'} />
}
return ( return (
<div>
{/* {console.log(completeState)} */}
<Container> <Container>
<h3 className="my-5 font-weight-bold text-center">주문/결제</h3> <h3 className="my-5 font-weight-bold text-center">주문/결제</h3>
<div> <div>
...@@ -264,7 +254,6 @@ function Payment({ match, location }) { ...@@ -264,7 +254,6 @@ function Payment({ match, location }) {
</Col> </Col>
</Row> </Row>
</div> </div>
<div> <div>
<h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>받는사람 정보</h5> <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>받는사람 정보</h5>
<Row className="justify-content-center"> <Row className="justify-content-center">
...@@ -305,7 +294,6 @@ function Payment({ match, location }) { ...@@ -305,7 +294,6 @@ function Payment({ match, location }) {
<h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h5> <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h5>
<PaymentCard cart={cart} deleteOrder={deleteOrder} /> <PaymentCard cart={cart} deleteOrder={deleteOrder} />
</div> </div>
<div className="p-5 m-3" style={{ background: '#F7F3F3' }}> <div className="p-5 m-3" style={{ background: '#F7F3F3' }}>
<ul className="pl-0" style={{ listStyle: 'none' }}> <ul className="pl-0" style={{ listStyle: 'none' }}>
<li> <li>
...@@ -320,7 +308,6 @@ function Payment({ match, location }) { ...@@ -320,7 +308,6 @@ function Payment({ match, location }) {
<div className="my-1 pt-2 border-top font-weight-bold"> <div className="my-1 pt-2 border-top font-weight-bold">
결제금액<span className="float-right">{finalPrice + 2500}</span> 결제금액<span className="float-right">{finalPrice + 2500}</span>
</div> </div>
</div>
<div> <div>
<h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>결제수단</h5> <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>결제수단</h5>
<div className="text-center m-3"> <div className="text-center m-3">
...@@ -332,8 +319,12 @@ function Payment({ match, location }) { ...@@ -332,8 +319,12 @@ function Payment({ match, location }) {
<div className="text-center"> <div className="text-center">
<Button type="button" onClick={paymentCompleted} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} block>결제완료</Button> <Button type="button" onClick={paymentCompleted} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} block>결제완료</Button>
</div> </div>
</Container> {paymentWay}
</div> </div>
<div className="text-center">
<Button className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} onClick={paymentCompleted} block>결제완료</Button>
</div>
</Container>
) )
} }
......
...@@ -12,6 +12,7 @@ function PaymentCompleted() { ...@@ -12,6 +12,7 @@ function PaymentCompleted() {
const [order, setOrder] = useState([]) const [order, setOrder] = useState([])
const [total, setTotal] = useState(0) const [total, setTotal] = useState(0)
const [receiverInfo, setReceiverInfo] = useState({}) const [receiverInfo, setReceiverInfo] = useState({})
const [num, setNum] = useState('')
useEffect(() => { useEffect(() => {
getOrder() getOrder()
...@@ -22,6 +23,7 @@ function PaymentCompleted() { ...@@ -22,6 +23,7 @@ function PaymentCompleted() {
setError('') setError('')
const response = await axios.get(`/api/order/showorder/${user}`) const response = await axios.get(`/api/order/showorder/${user}`)
console.log(response.data) console.log(response.data)
setNum(response.data._id)
setOrder(response.data.products) setOrder(response.data.products)
setTotal(response.data.total) setTotal(response.data.total)
setReceiverInfo(response.data.receiverInfo) setReceiverInfo(response.data.receiverInfo)
...@@ -37,6 +39,7 @@ function PaymentCompleted() { ...@@ -37,6 +39,7 @@ function PaymentCompleted() {
<h5 className=" font-weight-bold text-danger" style={{ display: 'inline' }}>주문이 완료</h5> <h5 className=" font-weight-bold text-danger" style={{ display: 'inline' }}>주문이 완료</h5>
<h5 className=" font-weight-bold " style={{ display: 'inline' }}>되었습니다!</h5> <h5 className=" font-weight-bold " style={{ display: 'inline' }}>되었습니다!</h5>
</div> </div>
<div className="my-2">주문번호: {num}</div>
<div className="mb-0">주문내역 확인은 마이페이지의 </div> <div className="mb-0">주문내역 확인은 마이페이지의 </div>
<div> "주문/배송조회"에서 하실 있습니다.</div> <div> "주문/배송조회"에서 하실 있습니다.</div>
</div> </div>
......
import axios from 'axios'; import axios from 'axios';
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { Row, Col, Form, Card, Button, Image , Modal} from 'react-bootstrap'; import { Row, Col, Form, Card, Button, Modal, Image } from 'react-bootstrap';
import { Redirect, useHistory } from 'react-router-dom'; import { Redirect, useHistory } from 'react-router-dom';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
...@@ -18,7 +18,9 @@ function Product({ match, location }) { ...@@ -18,7 +18,9 @@ function Product({ match, location }) {
let history = useHistory(); let history = useHistory();
const handleClose = () => setShow(false); const handleClose = () => setShow(false);
const handleShow = () => setShow(true); const handleShow = () => setShow(true);
const replace = product.description.replaceAll('\n', '<br />')
console.log("objectasdasd", replace)
useEffect(() => { useEffect(() => {
if (size && color) { if (size && color) {
...@@ -33,15 +35,31 @@ function Product({ match, location }) { ...@@ -33,15 +35,31 @@ function Product({ match, location }) {
} }
function pushOptions() { function pushOptions() {
setCart([...cart, { color, size, productId: product.id, count: 1 }]) // console.log(cart)
const a = cart.map(el => {
const rObj = {}
rObj["color"] = el.color;
rObj["size"] = el.size;
return rObj
})
const isDuplicated = a.some(el => el.color === color && el.size === size)
if (isDuplicated) {
selected.sizes = false
selected.colors = false
setColor("")
setSize("")
alert("이미 선택한 옵션입니다.")
} else {
selected.sizes = false selected.sizes = false
selected.colors = false selected.colors = false
console.log(product) setCart([...cart, { color, size, productId: product.id, count: 1, checked: false }])
setColor("") setColor("")
setSize("") setSize("")
setPrice(product.price + price) setPrice(product.price + price)
} }
}
function handleChange(e) { function handleChange(e) {
const { name, value } = e.target const { name, value } = e.target
if (name === "sizes") { if (name === "sizes") {
...@@ -103,7 +121,7 @@ function Product({ match, location }) { ...@@ -103,7 +121,7 @@ function Product({ match, location }) {
} else { } else {
try { try {
setError('') setError('')
cart.map((el)=>{ cart.map((el) => {
el.checked = true el.checked = true
}) })
const response = await axios.put('/api/cart/addcart', { const response = await axios.put('/api/cart/addcart', {
...@@ -202,20 +220,20 @@ function Product({ match, location }) { ...@@ -202,20 +220,20 @@ function Product({ match, location }) {
<h3 style={{ borderBottom: "1px solid #91877F", paddingBottom: "5px", marginBottom: "1em" }} className="p-3"> <h3 style={{ borderBottom: "1px solid #91877F", paddingBottom: "5px", marginBottom: "1em" }} className="p-3">
설명 설명
</h3> </h3>
<Col className='m-3 text-center d-flex justify-content-center'> <Col className='justify-content-center '>
<div style={{ wordBreak: 'break-all', wordWrap: 'break-word', fontFamily: "맑은 고딕" }} className="p-3"> <h2 className='p-2 text-center border' style={{ background: '#CDC5C2' }}>{product.name} </h2>
<h1 className='m-3'>{product.name} </h1>
<> <>
<Image src={`/images/${product.main_img}`} style={{ objectFit: "contain", width: '100%'}} /> <Image src={`/images/${product.main_img}`} style={{ objectFit: "contain", maxWidth: "100%" }} />
</> </>
<Card className='m-3 d-flex justify-content-center'> <Card className='m-3 d-flex justify-content-center'>
<Card.Body> <Card.Body className='text-center'>
{product.description} {replace}
</Card.Body> </Card.Body>
</Card> </Card>
<h3 className='mt-5'>[ Detail Images ]</h3> <>
<Image src={`/images/${product.detail_imgs}`} style={{ objectFit: "contain"}} className='m-3' /> <h4 className='my-4 text-center'>[ Detail Images ]</h4>
</div> <Image src={`/images/${product.detail_imgs}`} style={{ objectFit: "contain", maxWidth: "100%" }} />
</>
</Col> </Col>
</Col> </Col>
</Row> </Row>
......
...@@ -4,9 +4,6 @@ import { Row, Col, Button, Form, Container, Alert, Spinner } from 'react-bootstr ...@@ -4,9 +4,6 @@ import { Row, Col, Button, Form, Container, Alert, Spinner } from 'react-bootstr
import axios from 'axios'; import axios from 'axios';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
let preColors = []
let colorHtml = []
let list = []
function ProductsRegist() { function ProductsRegist() {
const INIT_PRODUCT = { const INIT_PRODUCT = {
...@@ -21,11 +18,13 @@ function ProductsRegist() { ...@@ -21,11 +18,13 @@ function ProductsRegist() {
main_image: [], main_image: [],
detail_image: [] detail_image: []
} }
const [preColors, setPreColors] = useState([])
const [categories, setCategories] = useState({ 0: [], 1: [[]] }) const [categories, setCategories] = useState({ 0: [], 1: [[]] })
const [product, setProduct] = useState(INIT_PRODUCT) const [product, setProduct] = useState(INIT_PRODUCT)
const [categoryNum, setCategoryNum] = useState('') const [categoryNum, setCategoryNum] = useState('')
const [tag, setTag] = useState(0) const [tag, setTag] = useState(0)
const [subCate, setSubCate] = useState('') const [subCate, setSubCate] = useState([])
const [cateList, setCateList] = useState([])
const [color, setColor] = useState({}) const [color, setColor] = useState({})
const [error, setError] = useState('') const [error, setError] = useState('')
const [success, setSuccess] = useState(false) const [success, setSuccess] = useState(false)
...@@ -50,38 +49,22 @@ function ProductsRegist() { ...@@ -50,38 +49,22 @@ function ProductsRegist() {
isProduct ? setDisabled(false) : setDisabled(true) isProduct ? setDisabled(false) : setDisabled(true)
}, [product]) }, [product])
function addCategory(e) {
if (selectRef.current.value === '') {
alert('하위 분류를 반드시 선택해 주세요.')
} else {
list.push(
<div>
<span name={subCate} >{product["main_category"]} / {subCate} </span>
<input name={subCate} type="image" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right align-middle" onClick={deleteCategory} />
</div>)
setTag(tag + 1)
selectRef.current.selectedIndex = 0
}
}
function deleteCategory(e) { function deleteCategory(e) {
e.target.parentNode.remove() const pdcate = product.sub_category.filter((el) => el !== e.target.name)
const index = product["sub_category"].findIndex((item) => { return item === e.target.name }) setProduct({ ...product, "sub_category": pdcate })
product["sub_category"].splice(index, 1) setSubCate([])
setSubCate('')
console.log(product["sub_category"].length)
} }
function handleCategory(e) { function handleCategory(e) {
const { name, value, selectedIndex } = e.target const { name, value, selectedIndex } = e.target
if (name === "main_category") { if (name === "main_category") {
setProduct({ ...product, [name]: value })
setCategoryNum(selectedIndex - 1) setCategoryNum(selectedIndex - 1)
} }
if (name === "sub_category") { else {
product[name].push(value) subCate.push(value)
setSubCate(value) setProduct({ ...product, [name]: subCate })
} else { selectRef.current.selectedIndex = 0
setProduct({ ...product, [name]: value })
} }
} }
...@@ -90,20 +73,15 @@ function ProductsRegist() { ...@@ -90,20 +73,15 @@ function ProductsRegist() {
} }
function addColor() { function addColor() {
preColors.push(color["colors"])
colorHtml.push(
<div>
<span>{color["colors"]}</span>
<input name={subCate} type="image" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right align-middle" onClick={deleteColor} />
</div>
)
colorRef.current.value = '' colorRef.current.value = ''
setProduct({ ...product, "colors": preColors }) setProduct({ ...product, "colors":[...product.colors, color["colors"]] })
} }
function deleteColor(e) { function deleteColor(e) {
e.target.parentNode.remove() console.log(product.colors)
product["colors"].splice(e.name, 1) console.log(e.target.name)
const pdcolors = product.colors.filter((el) => el !== e.target.name)
setProduct({ ...product, "colors": pdcolors })
} }
function handleColor(e) { function handleColor(e) {
...@@ -133,8 +111,8 @@ function ProductsRegist() { ...@@ -133,8 +111,8 @@ function ProductsRegist() {
for (let key in product) { for (let key in product) {
if (key === "main_image" || key === "detail_image") { if (key === "main_image" || key === "detail_image") {
formData.append(key, product[key][0]) formData.append(key, product[key][0])
} else if(key === "sizes" || key === "colors" || key === 'sub_category'){ } else if (key === "sizes" || key === "colors" || key === "sub_category") {
for (let i = 0; i < product[key].length ; i++){ for (let i = 0; i < product[key].length; i++) {
formData.append([key], product[key][i]) formData.append([key], product[key][i])
} }
} }
...@@ -162,6 +140,7 @@ function ProductsRegist() { ...@@ -162,6 +140,7 @@ function ProductsRegist() {
return ( return (
<Container> <Container>
{console.log(product)}
<Row className="justify-content-md-center"> <Row className="justify-content-md-center">
<Col md={8} className="border p-1" style={{ background: '#F7F3F3' }}> <Col md={8} className="border p-1" style={{ background: '#F7F3F3' }}>
{error && <Alert variant="danger" className="text-center">{error}</Alert>} {error && <Alert variant="danger" className="text-center">{error}</Alert>}
...@@ -182,15 +161,15 @@ function ProductsRegist() { ...@@ -182,15 +161,15 @@ function ProductsRegist() {
<Form.Group> <Form.Group>
<Form.Label>분류</Form.Label> <Form.Label>분류</Form.Label>
<Row> <Row>
<Col md={4}> <Col md={4} className="mb-1">
<Form.Control as="select" name="main_category" onChange={handleCategory} disabled={product["sub_category"].length > 0}> <Form.Control as="select" name="main_category" onChange={handleCategory} disabled={product["sub_category"].length > 0} >
<option value="" >상위분류</option> <option value="" >상위분류</option>
{categories[0].map((main) => ( {categories[0].map((main) => (
<option value={main}>{main}</option> <option value={main}>{main}</option>
))} ))}
</Form.Control> </Form.Control>
</Col> </Col>
<Col md={6}> <Col md={6} className="mb-2">
<Form.Control as="select" ref={selectRef} name="sub_category" onChange={handleCategory}> <Form.Control as="select" ref={selectRef} name="sub_category" onChange={handleCategory}>
<option value="" >하위분류</option> <option value="" >하위분류</option>
{(categoryNum === '') ? '' : (categories[1][categoryNum].map((sub) => ( {(categoryNum === '') ? '' : (categories[1][categoryNum].map((sub) => (
...@@ -198,15 +177,19 @@ function ProductsRegist() { ...@@ -198,15 +177,19 @@ function ProductsRegist() {
)))} )))}
</Form.Control> </Form.Control>
</Col> </Col>
<Col >
<Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addCategory}>추가</Button>
</Col>
</Row> </Row>
{list.map((element) => element)} {product.sub_category.map((el) => (
<div className="my-2">
<p name={el} className="mb-0" style={{ display: 'inline-block'}} >{product["main_category"]} / {el} </p>
<Button name={el} type="button" className="float-right p-0 btn-light" style={{ display: 'inline-block' }} onClick={deleteCategory} >
<img className="align-top" name={el} alt="삭제" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" />
</Button>
</div>
))}
</Form.Group> </Form.Group>
<Form.Group> <Form.Group>
<Form.Label>사이즈</Form.Label> <Form.Label>사이즈</Form.Label>
<Row> <Row className="px-3">
<Col> <Col>
<Form.Check type="checkbox" name="sizes" label="210" value="210" onChange={handleCheckBox} /> <Form.Check type="checkbox" name="sizes" label="210" value="210" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="215" value="215" onChange={handleCheckBox} /> <Form.Check type="checkbox" name="sizes" label="215" value="215" onChange={handleCheckBox} />
...@@ -235,14 +218,21 @@ function ProductsRegist() { ...@@ -235,14 +218,21 @@ function ProductsRegist() {
<Form.Group> <Form.Group>
<Form.Label>색상</Form.Label> <Form.Label>색상</Form.Label>
<Row> <Row>
<Col md={10}> <Col md={9} xs={9} className="pr-0">
<Form.Control as="input" ref={colorRef} name="colors" placeholder="색상" onChange={handleColor} /> <Form.Control as="input" ref={colorRef} name="colors" placeholder="색상" onChange={handleColor} />
</Col> </Col>
<Col> <Col className="pl-0">
<Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addColor}>추가</Button> <Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addColor}>추가</Button>
</Col> </Col>
</Row> </Row>
{colorHtml.map((element) => element)} {product.colors.map((el) => (
<div className="my-2">
<p className="mb-0" style={{ display: 'inline-block' }}>{el}</p>
<Button style={{ display: 'inline-block' }} name={el} type="button" className="float-right p-0 btn-light" onClick={deleteColor}>
<img className="align-top" name={el} alt="삭제" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" />
</Button>
</div>
))}
</Form.Group> </Form.Group>
<Form.Group controlId="productDescriptionform"> <Form.Group controlId="productDescriptionform">
<Form.Label>상품설명</Form.Label> <Form.Label>상품설명</Form.Label>
......
...@@ -4,7 +4,7 @@ import ListCard from '../Components/ListCard'; ...@@ -4,7 +4,7 @@ import ListCard from '../Components/ListCard';
import Pagination from "../Components/Pagination"; 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 } from 'react-bootstrap'; import { Container, Row, Col, Form, FormControl, Button, Dropdown, ButtonGroup, Image } from 'react-bootstrap';
function ProductsList({ match }) { function ProductsList({ match }) {
const [search, setSearch] = useState({ word: '' }) const [search, setSearch] = useState({ word: '' })
...@@ -16,6 +16,9 @@ function ProductsList({ match }) { ...@@ -16,6 +16,9 @@ function ProductsList({ match }) {
const [error, setError] = useState('') const [error, setError] = useState('')
const indexOfLast = currentPage * postsPerPage; const indexOfLast = currentPage * postsPerPage;
const indexOfFirst = indexOfLast - postsPerPage; const indexOfFirst = indexOfLast - postsPerPage;
const searchref = useRef(null)
const [sortingName, setSortingName] = useState('정렬')
function currentPosts(tmp) { function currentPosts(tmp) {
let currentPosts = 0; let currentPosts = 0;
...@@ -34,24 +37,26 @@ function ProductsList({ match }) { ...@@ -34,24 +37,26 @@ function ProductsList({ match }) {
}, [mainCategory]) }, [mainCategory])
function handleChange(event) { function handleChange(event) {
console.log('handle change', event.target.value)
setSearch({ word: event.target.value }) setSearch({ word: event.target.value })
} }
async function handleSearch(event) { async function handleSearch(e) {
event.preventDefault() e.preventDefault()
try { try {
setError('') setError('')
const response = await axios.post(`/api/product/getproduct/main/${mainCategory}`, search) const response = await axios.get(`/api/product/getproduct/main/${mainCategory}?product=${search.word}`)
console.log("response.data=", response.data) console.log("response.data=", response.data)
setProductlist(response.data) setProductlist(response.data)
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} finally {
searchref.current.value = ''
} }
} }
async function getSubsCategories() { async function getSubsCategories() {
try { 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])
console.log("object value=", Object.values(response.data)); console.log("object value=", Object.values(response.data));
...@@ -61,8 +66,8 @@ function ProductsList({ match }) { ...@@ -61,8 +66,8 @@ function ProductsList({ match }) {
} }
async function getProductlist() { async function getProductlist() {
console.log("tlfgpd")
try { try {
setError('')
const response = await axios.get(`/api/product/getproduct/main/${mainCategory}`) const response = await axios.get(`/api/product/getproduct/main/${mainCategory}`)
setProductlist(response.data) setProductlist(response.data)
} catch (error) { } catch (error) {
...@@ -71,28 +76,85 @@ function ProductsList({ match }) { ...@@ -71,28 +76,85 @@ function ProductsList({ match }) {
} }
async function handleSort(method) { async function handleSort(method) {
try { console.log(method)
const response = await axios.get(`/api/product/getproduct/?q=${method}`) if (method === "purchase") {
setProductlist(response.data) console.log("thisispurchase")
} catch (error) { productlist.sort(function (a, b) {
catchError(error, setError) 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 {
const response = await axios.get(`/api/product/getproduct/sub/${subname}`) console.log("first test!!!!!!!!")
const response = await axios.get(`/api/product/getproduct/sub?subname=${subname}`)
console.log("subname response data=", response.data) console.log("subname response data=", response.data)
setProductlist(response.data) setProductlist(response.data)
} catch (error) { } catch (error) {
console.log("error22") catchError(error, setError)
}
} }
if (error) {
alert(`${error}`)
setError('')
searchref.current.value = ''
} }
return ( return (
<Container> <Container>
{console.log(productlist)}
<style type="text/css"> <style type="text/css">
{` {`
a, a:hover, a:active { a, a:hover, a:active {
...@@ -104,9 +166,13 @@ function ProductsList({ match }) { ...@@ -104,9 +166,13 @@ function ProductsList({ match }) {
border-color: #CDC5C2; border-color: #CDC5C2;
} }
.btn:hover { .btn:hover {
background: #91877F; background-color: #91877F;
border-color: #91877F; border-color: #91877F;
} }
.dropdown-item:hover, .dropdown-item:active {
background-color: #91877F;
color: #fff;
}
`} `}
</style> </style>
<Row className="justify-content-center"> <Row className="justify-content-center">
...@@ -119,25 +185,26 @@ function ProductsList({ match }) { ...@@ -119,25 +185,26 @@ function ProductsList({ match }) {
</div> </div>
</Col> </Col>
</Row> </Row>
<Row className="justify-content-end mx-0 my-5"> <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 onClick={() => handleSort('purchase')}>인기상품</Dropdown.Item>
<Dropdown.Item onClick={() => handleSort('newest')}>신상품</Dropdown.Item>
<Dropdown.Item onClick={() => handleSort('lowest')}>낮은가격</Dropdown.Item>
<Dropdown.Item onClick={() => handleSort('highest')}>높은가격</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
<Form inline onSubmit={handleSearch} className="justify-content-end mx-0">
<FormControl type="text" onChange={handleChange} placeholder="Search" style={{ width: "13rem" }} />
<Button type="submit" className="px-2">
<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.map(pro => ( {productlist.length > 0 ?
productlist.map(pro => (
<Link to={{ <Link to={{
pathname: `/product/${pro._id}`, pathname: `/product/${pro._id}`,
state: { state: {
...@@ -151,10 +218,15 @@ function ProductsList({ match }) { ...@@ -151,10 +218,15 @@ function ProductsList({ match }) {
detail_imgs: pro.detail_imgUrls detail_imgs: pro.detail_imgUrls
} }
}}> }}>
<ListCard id={pro._id} name={pro.pro_name} price={pro.price} main_img={pro.main_imgUrl} /> <ListCard id={pro._id} name={pro.pro_name} price={pro.price} main_img={pro.main_imgUrl}
/>
</Link> </Link>
))} ))
{/* <Pagination className="justify-content-center" index={} endPage={} handlePage={}/> */} : (
<Image src="/sryimready.jpg"
style={{ objectFit: "cover", width: "45 rem", height: "45 rem" }}></Image>
)
}
</Row> </Row>
</Container> </Container>
) )
......
...@@ -43,15 +43,23 @@ const getToHome = async (req, res) => { ...@@ -43,15 +43,23 @@ 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('상품을 불러오지 못했습니다.')
} }
} }
const getlist = (req, res) => { const getlist = (req, res) => {
console.log('get list')
try { try {
res.json(req.productslist) res.json(req.productslist)
} catch (error) { } catch (error) {
...@@ -59,47 +67,32 @@ const getlist = (req, res) => { ...@@ -59,47 +67,32 @@ const getlist = (req, res) => {
} }
} }
const subname = async (req, res) => {
try {
console.log("last subname::: LET ME SEE")
res.json(req.findsubname)
} catch (error) {
res.status(500).send('상품을 불러오지 못했습니다.')
}
}
const categoryId = async (req, res, next, category) => { const categoryId = async (req, res, next, category) => {
const { search } = req.body console.log("req=", req.query.product)
console.log("server search=", search)
try { try {
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 }) const productslist = await Product.find({ main_category: category })
// if (!productslist) {
// res.status(404).send('상품을 찾을 수 없습니다.')
// }
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('상품을 불러오지 못했습니다.')
} }
} }
const subcategoryId = async (req, res, next, subname) => { const subname = async (req, res) => {
console.log("req.query", req.query)
try { try {
console.log("Please===>>>", subname) const findSubname = await Product.find({ sub_category: req.query.subname })
const findSubname = await Product.find({ sub_category: subname })
console.log("findSubname111=", findSubname) console.log("findSubname111=", findSubname)
if (!findSubname) {
const findSubname = {
_id: 'nothing',
pro_name: '상품준비중',
price: 0,
main_imgUrl:''
}
console.log("findSubname2222=", findSubname)
res.send(findSubname)
}
res.send(findSubname) res.send(findSubname)
} catch (error) { } catch (error) {
res.send('상품을 불러오지 못했습니다.') res.send('상품을 불러오지 못했습니다.')
...@@ -132,4 +125,4 @@ const plusPurchase = async (req, res) => { ...@@ -132,4 +125,4 @@ const plusPurchase = async (req, res) => {
} }
} }
export default { imageUpload, regist, getToHome, getAll, categoryId, getlist, subcategoryId, subname, plusPurchase } export default { imageUpload, regist, getToHome, getAll, categoryId, getlist, subname, plusPurchase }
\ No newline at end of file
...@@ -16,13 +16,13 @@ router.route('/getproduct/all') ...@@ -16,13 +16,13 @@ router.route('/getproduct/all')
router.route('/getproduct/main/:category') router.route('/getproduct/main/:category')
.get(productCtrl.getlist) .get(productCtrl.getlist)
router.route('/getproduct/sub/:subname') router.route('/getproduct/sub')
.get(productCtrl.subname) .get(productCtrl.subname)
router.route('/pluspurchase') router.route('/pluspurchase')
.post(productCtrl.plusPurchase) .post(productCtrl.plusPurchase)
router.param('category', productCtrl.categoryId) router.param('category', productCtrl.categoryId)
router.param('subname',productCtrl.subcategoryId) // router.param('subname',productCtrl.subcategoryId)
export default router export default router
\ 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