Commit 2f10d714 authored by kusang96's avatar kusang96
Browse files

merge kimpen

parent ccc8f484
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { Card } from 'react-bootstrap'; import { Card, Button } from 'react-bootstrap';
function ListCard({ id, name, price, main_img }) { function ListCard({ id, name, price, main_img }) {
function handleDelete(e) {
const card = e.target.parentNode.parentNode
alert('해당 상품을 성공적으로 삭제하였습니다.')
card.remove()
}
return ( return (
<Card id={id} className="mt-5" style={{ width: "18rem", margin: "auto" }}> <Card id={id} className="m-3" style={{ width: "18rem" }}>
<Card.Img variant="top" src={main_img && `/images/${main_img}`} style={{ objectFit: "contain", height: "22rem" }} /> <Card.Img variant="top" src={main_img && `/images/${main_img}`} style={{ objectFit: "contain", height: "22rem" }} />
<Card.Body> <Card.Body>
<Card.Title style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{name}</Card.Title> <Card.Title style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{name}</Card.Title>
<Card.Text>{price} </Card.Text> <Card.Text>{price} </Card.Text>
<Button className="float-right" onClick={handleDelete}>삭제</Button>
</Card.Body> </Card.Body>
</Card> </Card>
) )
} }
export default ListCard export default ListCard
\ No newline at end of file
...@@ -8,7 +8,6 @@ function SubNav() { ...@@ -8,7 +8,6 @@ function SubNav() {
const [categoriesDiv, setCategoriesDiv] = useState([]) const [categoriesDiv, setCategoriesDiv] = useState([])
const [error, setError] = useState('') const [error, setError] = useState('')
useEffect(async () => { useEffect(async () => {
try { try {
const response = await axios.get('/api/categories/main') const response = await axios.get('/api/categories/main')
...@@ -34,7 +33,7 @@ function SubNav() { ...@@ -34,7 +33,7 @@ function SubNav() {
} }
`} `}
</style> </style>
<Nav style={{overflowX: "auto"}}> <Nav style={{ overflowX: "auto" }}>
{categoriesDiv.map(item => item)} {categoriesDiv.map(item => item)}
</Nav> </Nav>
</Navbar> </Navbar>
......
import React, { useEffect, useState } from 'react' import React, { useEffect, useState } from 'react'
import { Card, Image, Container, Row, Col, Table, Accordion, Button, Form, Modal, Alert } from 'react-bootstrap' import { Card, Image, Container, Row, Col, Table, Accordion, Button, Form, Modal, Alert } from 'react-bootstrap'
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import axios from 'axios' import axios from 'axios';
import catchErrors from '../utils/catchErrors'; import catchError from '../utils/catchErrors';
import { isAuthenticated } from '../utils/auth'; import { isAuthenticated } from '../utils/auth';
const INIT_ACCOUNT = { const INIT_ACCOUNT = {
...@@ -10,13 +10,12 @@ const INIT_ACCOUNT = { ...@@ -10,13 +10,12 @@ const INIT_ACCOUNT = {
avatarUrl: '' avatarUrl: ''
} }
function Account() { function Account() {
const [account, setAccount] = useState(INIT_ACCOUNT) const [account, setAccount] = useState(INIT_ACCOUNT)
const [show, setShow] = useState(false);
const [error, setError] = useState("") const [error, setError] = useState("")
const userId = isAuthenticated() const userId = isAuthenticated()
async function getUsername(user) { async function getUsername(user) {
// console.log("tlg") // console.log("tlg")
try { try {
...@@ -24,7 +23,7 @@ function Account() { ...@@ -24,7 +23,7 @@ function Account() {
setAccount(response.data) setAccount(response.data)
// console.log('555555555', response.data); // console.log('555555555', response.data);
} catch (error) { } catch (error) {
catchErrors(error, setError) catchError(error, setError)
// console.log('error2222', error) // console.log('error2222', error)
} }
} }
...@@ -33,13 +32,6 @@ function Account() { ...@@ -33,13 +32,6 @@ function Account() {
getUsername(userId) getUsername(userId)
}, [userId]) }, [userId])
const [show, setShow] = useState(false);
const handleClose = () => setShow(false)
const handleShow = () => setShow(true)
const handleChange = (event) => { const handleChange = (event) => {
const { name, value, files } = event.target const { name, value, files } = event.target
if (files) { if (files) {
...@@ -63,7 +55,7 @@ function Account() { ...@@ -63,7 +55,7 @@ function Account() {
window.location.reload() window.location.reload()
} }
} catch (error) { } catch (error) {
catchErrors(error, setError) catchError(error, setError)
} }
setShow(false) setShow(false)
} }
...@@ -81,7 +73,7 @@ function Account() { ...@@ -81,7 +73,7 @@ function Account() {
window.location.reload() window.location.reload()
} }
} catch (error) { } catch (error) {
catchErrors(error, setError) catchError(error, setError)
} }
} else { } else {
alert("파일을 선택해주세요.") alert("파일을 선택해주세요.")
...@@ -89,22 +81,29 @@ function Account() { ...@@ -89,22 +81,29 @@ function Account() {
} }
return ( return (
<Container className="px-3"> <Container className="px-3">
<style type="text/css">
{`
a, a:hover, a:active {
color: #91877F;
text-decoration-color: #91877F;
}
`}
</style>
<h3 className="my-4 mx-3 font-weight-bold">My Page</h3> <h3 className="my-4 mx-3 font-weight-bold">My Page</h3>
<Card md={3} className="p-1 mb-4" style={{ background: '#F7F3F3' }}> <Card md={3} className="p-1 mb-4" style={{ background: '#F7F3F3' }}>
<Row className="p-2"> <Row className="p-2">
<Col md={5} className="d-flex align-content-center justify-content-center"> <Col md={5} className="d-flex align-content-center justify-content-center">
<Button variant="outline-light" onClick={handleShow}> <Button variant="outline-light" onClick={() => setShow(true)}>
{account.avatarUrl ? ( {account.avatarUrl ? (
<Image src={account.avatarUrl && `/image/${account.avatarUrl}`} className="img-thumbnail" <Image src={account.avatarUrl && `/images/${account.avatarUrl}`} className="img-thumbnail"
roundedCircle style={{ objectFit: "cover", width: "10rem", height: "10rem" }} /> roundedCircle style={{ objectFit: "cover", width: "10rem", height: "10rem" }} />
) : ( ) : (
<Image src="/icon/person.svg" className="img-thumbnail" <Image src="/icon/person.svg" className="img-thumbnail"
roundedCircle style={{ objectFit: "cover", width: "10rem", height: "10rem" }} /> roundedCircle style={{ objectFit: "cover", width: "10rem", height: "10rem" }} />
)} )}
</Button> </Button>
<Modal show={show} onHide={handleClose}> <Modal show={show} onHide={() => setShow(false)}>
<Modal.Header closeButton> <Modal.Header closeButton>
<Modal.Title>이미지를 변경하시겠습니까?</Modal.Title> <Modal.Title>이미지를 변경하시겠습니까?</Modal.Title>
</Modal.Header> </Modal.Header>
...@@ -118,8 +117,8 @@ function Account() { ...@@ -118,8 +117,8 @@ function Account() {
className="d-flex justify-content-start"><small>기본이미지로</small></Button> className="d-flex justify-content-start"><small>기본이미지로</small></Button>
{/* 기본이미지로 보내기 */} {/* 기본이미지로 보내기 */}
</Col> </Col>
<Button variant="secondary" onClick={handleClose}>취소</Button> <Button variant="secondary" onClick={() => setShow(false)}>취소</Button>
<Button variant="primary" type="submit" onClick={handleClose}>저장</Button> <Button variant="primary" type="submit" onClick={() => setShow(false)}>저장</Button>
</Modal.Footer> </Modal.Footer>
</Form> </Form>
</Modal> </Modal>
...@@ -134,15 +133,15 @@ function Account() { ...@@ -134,15 +133,15 @@ function Account() {
</Row> </Row>
<Row className="px-3"> <Row className="px-3">
<Card.Body className="p-2 text-center"> <Card.Body className="p-2 text-center">
<h4><Link to="/" class="link-warning"> <h4><Link to="/">
<strong title="홈으로"> <strong title="홈으로">
<Image src="/icon/mypagetiger.svg" width={"30rem"} roundedCircle className="img-thumbnail" > <Image src="/icon/mypagetiger.svg" width={"30rem"} roundedCircle className="img-thumbnail" >
</Image>KU# </Image>KU#
</strong> </strong>
</Link> </Link>
{/* 홈페이지로 돌아가기 */} 방문해주신 <em>{account.name}</em> 님,<br />
방문해주신 <em>{account.name}</em> 님,<br></br> 진심으로 환영합니다! 즐거운 쇼핑 되세요.
진심으로 환영합니다! 즐거운 쇼핑 되세요.</h4> </h4>
</Card.Body> </Card.Body>
</Row> </Row>
<Row className="mr-1 text-muted d-flex justify-content-end"> <Row className="mr-1 text-muted d-flex justify-content-end">
......
import React from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { Redirect } from 'react-router-dom';
import ListCard from '../Components/ListCard';
import Pagination from '../Components/Pagination'; import Pagination from '../Components/Pagination';
import axios from 'axios';
import { isAdmin } from "../utils/auth";
import catchError from '../utils/catchErrors';
import { Row, Form, FormControl, Button, Card, Container } from 'react-bootstrap'; import { Row, Form, FormControl, Button, Card, Container } from 'react-bootstrap';
function Admin() { function Admin() {
function handleClick(e) { const [productlist, setProductlist] = useState([])
const card = e.target.parentNode.parentNode const [error, setError] = useState('')
alert('해당 상품을 성공적으로 삭제하였습니다.') const role = isAdmin()
card.remove()
useEffect(() => {
getProductlist()
}, [])
async function getProductlist() {
try {
const response = await axios.get(`/api/product/getproduct/all`)
console.log("response.data=", response.data)
setProductlist(response.data)
} catch (error) {
catchError(error, setError)
}
}
function handleSearch() {
} }
function handleSubmit(e) { function handleSubmit(e) {
e.preventDefault() e.preventDefault()
} }
if(!role) {
alert('죄송합니다.접근 권한이 없습니다.')
return <Redirect to="/" />
}
return ( return (
<div> <Container>
<style type="text/css"> <style type="text/css">
{` {`
.btn { .btn {
...@@ -28,7 +54,6 @@ function Admin() { ...@@ -28,7 +54,6 @@ function Admin() {
} }
`} `}
</style> </style>
<Container>
<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 type="text" placeholder="Search" style={{ width: "13rem" }} />
<Button type="submit" className="px-2"> <Button type="submit" className="px-2">
...@@ -36,89 +61,13 @@ function Admin() { ...@@ -36,89 +61,13 @@ function Admin() {
</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-start m-5"> <Row className="justify-content-center m-5">
<Card className="mt-5" style={{ width: "18rem", margin: "auto" }}> {productlist.map(pro => (
<Card.Img variant="top" src="https://img.sonyunara.com/files/goods/67460/1607053816_0.jpg" style={{ objectFit: "contain", height: "22rem" }} /> <ListCard id={pro._id} name={pro.pro_name} price={pro.price} main_img={pro.main_imgUrl} />
<Card.Body> ))}
<Card.Title>케이시앵글부츠(SH)</Card.Title>
<Card.Text>
재고: 8<br />
구매자 : 10
</Card.Text>
<Button className="float-right" onClick={(e) => handleClick(e)}>삭제</Button>
</Card.Body>
</Card>
<Card className="mt-5" style={{ width: "18rem", margin: "auto" }}>
<Card.Img variant="top" src="https://img.sonyunara.com/files/goods/48705/1552562469_0.jpg" style={{ objectFit: "contain", height: "22rem" }} />
<Card.Body>
<Card.Title>메리제인플랫(SH)</Card.Title>
<Card.Text>
재고: 20<br />
구매자 : 60
</Card.Text>
<Button className="float-right" onClick={(e) => handleClick(e)}>삭제</Button>
</Card.Body>
</Card>
<Card className="mt-5" style={{ width: "18rem", margin: "auto" }}>
<Card.Img variant="top" src="https://img.sonyunara.com/files/goods/53386/1567390097_2.jpg" style={{ objectFit: "contain", height: "22rem" }} />
<Card.Body>
<Card.Title>솔티드스니커즈(SH)</Card.Title>
<Card.Text>
재고: 34<br />
구매자 : 5
</Card.Text>
<Button className="float-right" onClick={(e) => handleClick(e)}>삭제</Button>
</Card.Body>
</Card>
<Card className="mt-5" style={{ width: "18rem", margin: "auto" }}>
<Card.Img variant="top" src="https://img.sonyunara.com/files/goods/61286/1587540563_0.jpg" style={{ objectFit: "contain", height: "22rem" }} />
<Card.Body>
<Card.Title>버켄슬리퍼(SH)</Card.Title>
<Card.Text>
재고: 50<br />
구매자 : 18
</Card.Text>
<Button className="float-right" onClick={(e) => handleClick(e)}>삭제</Button>
</Card.Body>
</Card>
<Card className="mt-5" style={{ width: "18rem", margin: "auto" }}>
<Card.Img variant="top" src="https://hotping.co.kr/web/product/big/202011/b8f4c6471955b80fc3991b7d6df8926a.jpg" style={{ objectFit: "contain", height: "22rem" }} />
<Card.Body>
<Card.Title>크레센도 하이힐펌프스</Card.Title>
<Card.Text>
재고: 35<br />
구매자 : 70
</Card.Text>
<Button className="float-right" onClick={(e) => handleClick(e)}>삭제</Button>
</Card.Body>
</Card>
<Card className="mt-5" style={{ width: "18rem", margin: "auto" }}>
<Card.Img variant="top" src="https://hotping.co.kr/web/product/big/202011/888e4e8d6a2c2e7da385b079151fcba2.jpg" style={{ objectFit: "contain", height: "22rem" }} />
<Card.Body>
<Card.Title>어텀솔져1cm 스웨이드로퍼</Card.Title>
<Card.Text>
재고: 40<br />
구매자 : 30
</Card.Text>
<Button className="float-right" onClick={(e) => handleClick(e)}>삭제</Button>
</Card.Body>
</Card>
<Card className="mt-5" style={{ width: "18rem", margin: "auto" }}>
<Card.Img variant="top" src="https://hotping.co.kr/web/product/big/202007/3308564012eb14e6c11ed621fa7555fb.jpg" style={{ objectFit: "contain", height: "22rem" }} />
<Card.Body>
<Card.Title>포웰3.5cm 스니커즈</Card.Title>
<Card.Text>
재고: 15<br />
구매자 : 50
</Card.Text>
<Button className="float-right" onClick={(e) => handleClick(e)}>삭제</Button>
</Card.Body>
</Card>
</Row> </Row>
<Pagination /> <Pagination />
</Container> </Container>
</div>
) )
} }
......
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { Link } from 'react-router-dom';
import ListCard from '../Components/ListCard'; import ListCard from '../Components/ListCard';
import axios from 'axios'; import axios from 'axios';
import catchError from '../utils/catchErrors'; import catchError from '../utils/catchErrors';
import { Card, Container, Row } from 'react-bootstrap'; import { Container, Row } from 'react-bootstrap';
function Home() { function Home() {
const [productlist, setProductlist] = useState([]) const INIT_PRODUCT = {
bestProduct: [],
newProduct: [],
}
const [productlist, setProductlist] = useState(INIT_PRODUCT)
const [error, setError] = useState('') const [error, setError] = useState('')
useEffect(() => { useEffect(() => {
...@@ -16,78 +21,67 @@ function Home() { ...@@ -16,78 +21,67 @@ function Home() {
async function getProductlist() { async function getProductlist() {
try { try {
const response = await axios.get(`/api/product/getproduct`) const response = await axios.get(`/api/product/getproduct`)
console.log(response.data) console.log("res=", response.data)
setProductlist(response.data) setProductlist({ bestProduct: response.data.bestProduct, newProduct: response.data.newProduct })
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} }
} }
return ( return (
<div> <Container>
<Container className="my-5"> <style type="text/css">
{`
a, a:hover, a:active {
color: #000;
text-decoration: none;
`}
</style>
<div className="my-4"> <div className="my-4">
<h2 style={{ marginRight: "5rem", marginLeft: "3rem", marginBottom: "2rem" }}><u>Best</u></h2> <h2 style={{ marginRight: "5rem", marginLeft: "3rem", marginBottom: "2rem" }}><u>Best</u></h2>
<Row className="justify-content-center mx-0"> <Row className="justify-content-center mx-0">
<ListCard productlist={productlist} /> {productlist.bestProduct.map(pro => (
<Card className="mx-1 my-2" style={{ width: '18rem' }}> <Link to={{
<Card.Img className="img-fluid" variant="top" src="/icon/asd.jpg" /> pathname: `/product/${pro._id}`,
<Card.Body> state: {
<Card.Title className="font-weight-bold">제품명</Card.Title> id: pro._id,
<Card.Text>가격</Card.Text> name: pro.pro_name,
</Card.Body> price: pro.price,
</Card> 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>
))}
</Row> </Row>
</div> </div>
<div className="my-4"> <div className="my-4">
<h2 style={{ marginRight: "5rem", marginLeft: "3rem", marginBottom: "2rem", marginTop: "2rem" }}><u>New Arrival</u></h2> <h2 style={{ marginRight: "5rem", marginLeft: "3rem", marginBottom: "2rem", marginTop: "2rem" }}><u>New Arrival</u></h2>
<Row className="justify-content-center mx-0"> <Row className="justify-content-center mx-0">
<Card className="mx-1 my-2" style={{ width: '18rem' }}> {productlist.newProduct.map(pro => (
<Card.Img className="img-fluid" variant="top" src="/icon/asd.jpg" /> <Link to={{
<Card.Body> pathname: `/product/${pro._id}`,
<Card.Title className="font-weight-bold">제품명</Card.Title> state: {
<Card.Text>가격</Card.Text> id: pro._id,
</Card.Body> name: pro.pro_name,
</Card> price: pro.price,
<Card className="mx-1 my-2" style={{ width: '18rem' }}> colors: pro.colors,
<Card.Img className="img-fluid" variant="top" src="/icon/asd.jpg" /> sizes: pro.sizes,
<Card.Body> description: pro.description,
<Card.Title className="font-weight-bold">제품명</Card.Title> main_img: pro.main_imgUrl,
<Card.Text>가격</Card.Text> detail_imgs: pro.detail_imgUrls
</Card.Body> }
</Card> }}>
<Card className="mx-1 my-2" style={{ width: '18rem' }}> <ListCard id={pro._id} name={pro.pro_name} price={pro.price} main_img={pro.main_imgUrl} />
<Card.Img className="img-fluid" variant="top" src="/icon/asd.jpg" /> </Link>
<Card.Body> ))}
<Card.Title className="font-weight-bold">제품명</Card.Title>
<Card.Text>가격</Card.Text>
</Card.Body>
</Card>
<Card className="mx-1 my-2" style={{ width: '18rem' }}>
<Card.Img className="img-fluid" variant="top" src="/icon/asd.jpg" />
<Card.Body>
<Card.Title className="font-weight-bold">제품명</Card.Title>
<Card.Text>가격</Card.Text>
</Card.Body>
</Card>
<Card className="mx-1 my-2" style={{ width: '18rem' }}>
<Card.Img className="img-fluid" variant="top" src="/icon/asd.jpg" />
<Card.Body>
<Card.Title className="font-weight-bold">제품명</Card.Title>
<Card.Text>가격</Card.Text>
</Card.Body>
</Card>
<Card className="mx-1 my-2" style={{ width: '18rem' }}>
<Card.Img className="img-fluid" variant="top" src="/icon/asd.jpg" />
<Card.Body>
<Card.Title className="font-weight-bold">제품명</Card.Title>
<Card.Text>가격</Card.Text>
</Card.Body>
</Card>
</Row> </Row>
</div> </div>
</Container> </Container>
</div>
) )
} }
......
...@@ -21,7 +21,6 @@ function Login() { ...@@ -21,7 +21,6 @@ function Login() {
function handleChange(event) { function handleChange(event) {
const { name, value } = event.target const { name, value } = event.target
setUser({ ...user, [name]: value }) setUser({ ...user, [name]: value })
} }
async function handleSubmit(event) { async function handleSubmit(event) {
...@@ -47,8 +46,6 @@ function Login() { ...@@ -47,8 +46,6 @@ function Login() {
window.location.href='/' window.location.href='/'
} }
return ( return (
<Container className="my-5"> <Container className="my-5">
<Row className="justify-content-center"> <Row className="justify-content-center">
......
...@@ -114,7 +114,7 @@ function Product({ match, location }) { ...@@ -114,7 +114,7 @@ function Product({ match, location }) {
</style> </style>
<Row className="justify-content-center mt-5 mx-0"> <Row className="justify-content-center mt-5 mx-0">
<Col sm={11} md={4}> <Col sm={11} md={4}>
<img src={product.main_img} style={{ objectFit: "contain", width: "100%" }} /> <img src={`/images/${product.main_img}`} style={{ objectFit: "contain", width: "100%" }} />
</Col> </Col>
<Col sm={11} md={4} className="align-middle mt-4"> <Col sm={11} md={4} className="align-middle mt-4">
<h3 className="mb-4">{product.name}</h3> <h3 className="mb-4">{product.name}</h3>
......
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 { Row, Col, Button, Form, Container, Alert } from 'react-bootstrap'; import { Row, Col, Button, Form, Container, Alert, Spinner } from 'react-bootstrap';
import axios from 'axios'; import axios from 'axios';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
...@@ -23,13 +23,17 @@ function ProductsRegist() { ...@@ -23,13 +23,17 @@ function ProductsRegist() {
} }
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(0) const [categoryNum, setCategoryNum] = useState('')
const [tag, setTag] = useState(0) const [tag, setTag] = useState(0)
const [subCate, setSubCate] = useState('') const [subCate, setSubCate] = 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)
const [checked, setChecked] = useState({ "Free": false, "XL": false, "L": false, "M": false, "S": false, "XS": false }) const [checked, setChecked] = useState({ "Free": false, "XL": false, "L": false, "M": false, "S": false, "XS": false })
const [disabled, setDisabled] = useState(true)
const [loading, setLoading] = useState(false)
const selectRef = useRef(null)
const colorRef = useRef(null)
useEffect(async () => { useEffect(async () => {
try { try {
...@@ -41,28 +45,44 @@ function ProductsRegist() { ...@@ -41,28 +45,44 @@ function ProductsRegist() {
} }
}, []) }, [])
function addCategory() { useEffect(() => {
const isProduct = Object.values(product).every(el => { console.log("el=", el); Boolean(el) })
isProduct ? setDisabled(false) : setDisabled(true)
}, [product])
function handleKeyPress(e) {
if (e.key === "Enter") {
addColor()
e.preventDefault()
}
}
function addCategory(e) {
if (selectRef.current.value === '') {
alert('하위 분류를 반드시 선택해 주세요.')
} else {
list.push( list.push(
<div> <div>
<span name={subCate} >{product["main_category"]} / {subCate} </span> <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} /> <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>) </div>)
setTag(tag + 1) setTag(tag + 1)
console.log(list) selectRef.current.selectedIndex = 0
}
} }
function deleteCategory(e) { function deleteCategory(e) {
e.target.parentNode.remove() e.target.parentNode.remove()
const index = product["sub_category"].findIndex((item)=>{return item === e.target.name}) const index = product["sub_category"].findIndex((item) => { return item === e.target.name })
product["sub_category"].splice(index, 1) product["sub_category"].splice(index, 1)
setSubCate('') setSubCate('')
console.log(product["sub_category"].length) console.log(product["sub_category"].length)
} }
function handleCategory(e) { function handleCategory(e) {
const { name, value } = e.target const { name, value, selectedIndex } = e.target
if (e.target.name === "main_category") { if (name === "main_category") {
setCategoryNum(e.target.selectedIndex - 1) setCategoryNum(selectedIndex - 1)
} }
if (name === "sub_category") { if (name === "sub_category") {
product[name].push(value) product[name].push(value)
...@@ -70,7 +90,6 @@ function ProductsRegist() { ...@@ -70,7 +90,6 @@ function ProductsRegist() {
} else { } else {
setProduct({ ...product, [name]: value }) setProduct({ ...product, [name]: value })
} }
console.log(value)
} }
function handleCheckBox(e) { function handleCheckBox(e) {
...@@ -85,15 +104,16 @@ function ProductsRegist() { ...@@ -85,15 +104,16 @@ function ProductsRegist() {
<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} /> <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> </div>
) )
setColor({}) colorRef.current.value = ''
setProduct({ ...product, "colors": preColors }) setProduct({ ...product, "colors": preColors })
} }
function deleteColor(e) { function deleteColor(e) {
// console.log("e.name=",e.target.name)
e.target.parentNode.remove() e.target.parentNode.remove()
product["colors"].splice(e.name, 1) product["colors"].splice(e.name, 1)
setColor({}) // setColor({})
console.log(product) // console.log(product)
} }
function handleColor(e) { function handleColor(e) {
...@@ -102,13 +122,11 @@ function ProductsRegist() { ...@@ -102,13 +122,11 @@ function ProductsRegist() {
function handleChange(event) { function handleChange(event) {
const { name, value, files } = event.target const { name, value, files } = event.target
console.log("event.target.name=", name, "event.target.value=", value)
if (files) { if (files) {
setProduct({ ...product, [name]: files }) setProduct({ ...product, [name]: files })
} else { } else {
setProduct({ ...product, [name]: value }) setProduct({ ...product, [name]: value })
} }
} }
async function handleSubmit(e) { async function handleSubmit(e) {
...@@ -122,23 +140,27 @@ function ProductsRegist() { ...@@ -122,23 +140,27 @@ function ProductsRegist() {
product["sizes"] = sizes product["sizes"] = sizes
const formData = new FormData(); const formData = new FormData();
for (let key in product) { for (let key in product) {
if (key === "main_image" ||key === "detail_image") { if (key === "main_image" || key === "detail_image") {
console.log(product[key][0])
formData.append(key, product[key][0]) formData.append(key, product[key][0])
} else { } else {
formData.append(key, product[key]) formData.append(key, product[key])
} }
} }
try { try {
setLoading(true)
setError('')
const response = await axios.post('/api/product/regist', formData) const response = await axios.post('/api/product/regist', formData)
console.log(response) console.log(response)
setSuccess(true) setSuccess(true)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} finally {
setLoading(false)
} }
} }
if (success) { if (success) {
alert('상품 등록을 완료하였습니다.')
return <Redirect to='/admin' /> return <Redirect to='/admin' />
} }
...@@ -173,11 +195,11 @@ function ProductsRegist() { ...@@ -173,11 +195,11 @@ function ProductsRegist() {
</Form.Control> </Form.Control>
</Col> </Col>
<Col md={6}> <Col md={6}>
<Form.Control as="select" name="sub_category" onChange={handleCategory} disabled={product["main_category"] === "TRAINING"}> <Form.Control as="select" ref={selectRef} name="sub_category" onChange={handleCategory}>
<option value="" >하위분류</option> <option value="" >하위분류</option>
{categories[1][categoryNum].map((sub) => ( {(categoryNum === '') ? '' : (categories[1][categoryNum].map((sub) => (
<option value={sub}>{sub}</option> <option value={sub}>{sub}</option>
))} )))}
</Form.Control> </Form.Control>
</Col> </Col>
<Col > <Col >
...@@ -188,18 +210,37 @@ function ProductsRegist() { ...@@ -188,18 +210,37 @@ function ProductsRegist() {
</Form.Group> </Form.Group>
<Form.Group> <Form.Group>
<Form.Label>사이즈</Form.Label> <Form.Label>사이즈</Form.Label>
<Form.Check type="checkbox" name="sizes" label="Free" value="Free" onChange={handleCheckBox} /> <Row>
<Col>
<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="220" value="220" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="225" value="225" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="230" value="230" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="235" value="235" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="240" value="240" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="245" value="245" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="250" value="250" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="255" value="255" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="260" value="260" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="265" value="265" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="270" value="270" onChange={handleCheckBox} />
</Col>
<Col>
<Form.Check type="checkbox" name="sizes" label="FREE" value="FREE" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="XL" value="XL" onChange={handleCheckBox} /> <Form.Check type="checkbox" name="sizes" label="XL" value="XL" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="L" value="L" onChange={handleCheckBox} /> <Form.Check type="checkbox" name="sizes" label="L" value="L" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="M" value="M" onChange={handleCheckBox} /> <Form.Check type="checkbox" name="sizes" label="M" value="M" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="S" value="S" onChange={handleCheckBox} /> <Form.Check type="checkbox" name="sizes" label="S" value="S" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="sizes" label="XS" value="XS" onChange={handleCheckBox} /> <Form.Check type="checkbox" name="sizes" label="XS" value="XS" onChange={handleCheckBox} />
</Col>
</Row>
</Form.Group> </Form.Group>
<Form.Group> <Form.Group>
<Form.Label>색상</Form.Label> <Form.Label>색상</Form.Label>
<Row> <Row>
<Col md={10}> <Col md={10}>
<Form.Control as="textarea" rows={1} name="colors" value={color["colors"]} placeholder="색상" onChange={handleColor} /> <Form.Control as="input" ref={colorRef} name="colors" placeholder="색상" onChange={handleColor} onKeyPress={handleKeyPress} />
</Col> </Col>
<Col> <Col>
<Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addColor}>추가</Button> <Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addColor}>추가</Button>
...@@ -207,7 +248,6 @@ function ProductsRegist() { ...@@ -207,7 +248,6 @@ function ProductsRegist() {
</Row> </Row>
{colorHtml.map((element) => element)} {colorHtml.map((element) => element)}
</Form.Group> </Form.Group>
<Form.Group controlId="productDescriptionform"> <Form.Group controlId="productDescriptionform">
<Form.Label>상품설명</Form.Label> <Form.Label>상품설명</Form.Label>
<Form.Control as="textarea" name="description" rows={3} placeholder="상품을 설명해주세요" onChange={handleChange} /> <Form.Control as="textarea" name="description" rows={3} placeholder="상품을 설명해주세요" onChange={handleChange} />
...@@ -220,7 +260,9 @@ function ProductsRegist() { ...@@ -220,7 +260,9 @@ function ProductsRegist() {
<Form.Label>상세이미지</Form.Label> <Form.Label>상세이미지</Form.Label>
<Form.File id="productImageform" name="detail_image" onChange={handleChange} /> <Form.File id="productImageform" name="detail_image" onChange={handleChange} />
</Form.Group> </Form.Group>
<Button className="float-right" type="submit" style={{ background: '#91877F', borderColor: '#91877F' }}>등록</Button> <Button type="submit" style={{ background: '#91877F', borderColor: '#91877F' }} block>
{loading && <Spinner as='span' animation='border' size='sm' role='status' aria-hidden='true' />}{' '}등록
</Button>
</Form> </Form>
</Col> </Col>
</Row> </Row>
......
...@@ -5,8 +5,8 @@ import Pagination from '../Components/Pagination'; ...@@ -5,8 +5,8 @@ import Pagination from '../Components/Pagination';
import axios from 'axios'; import axios from 'axios';
import catchError from '../utils/catchErrors'; import catchError from '../utils/catchErrors';
import { isAuthenticated } from '../utils/auth'; import { isAuthenticated } from '../utils/auth';
import catchError from '../utils/catchErrors';
import { Container, Row, Col, Form, FormControl, Button, Dropdown } from 'react-bootstrap'; import { Container, Row, Col, Form, FormControl, Button, Dropdown } from 'react-bootstrap';
import catchErrors from '../utils/catchErrors';
function ProductsList({ match }) { function ProductsList({ match }) {
const [mainCategory, setMainCategory] = useState(match.params.main.toUpperCase()) const [mainCategory, setMainCategory] = useState(match.params.main.toUpperCase())
...@@ -64,24 +64,24 @@ function ProductsList({ match }) { ...@@ -64,24 +64,24 @@ function ProductsList({ match }) {
} }
} }
function handleClick(e){ function handleClick(e) {
e.preventDefault() e.preventDefault()
return getsubproductlist() return getsubproductlist()
} }
async function getsubproductlist(){ async function getsubproductlist() {
try { try {
const response = await axios.get(`/api/product/getproduct/${subcategory}`) const response = await axios.get(`/api/product/getproduct/${subcategory}`)
console.log("response.data sub=",response.data) console.log("response.data sub=", response.data)
setProductlist(response.data) setProductlist(response.data)
} catch (error) { } catch (error) {
catchErrors(error,setError) catchError(error, setError)
} }
} }
return ( return (
<div> <div>
{console.log("main=",mainCategory)} {console.log("main=", mainCategory)}
<style type="text/css"> <style type="text/css">
{` {`
a, a:hover, a:active { a, a:hover, a:active {
...@@ -104,9 +104,12 @@ function ProductsList({ match }) { ...@@ -104,9 +104,12 @@ function ProductsList({ match }) {
<Row className="justify-content-center" > <Row className="justify-content-center" >
<Col sm={10} xs={12} > <Col sm={10} xs={12} >
<h1 style={{ fontSize: "3rem" }} className="text-center">{mainCategory}</h1> <h1 style={{ fontSize: "3rem" }} className="text-center">{mainCategory}</h1>
<div className="text-center">{subcategory.map((ele) => ( <div className="text-center">
<Button className="m-1" onClick={getProductlist}>ALL</Button>
{subcategory.map((ele) => (
<Button className="m-1" onClick={(ele) => handleClick(ele)}>{ele}</Button> <Button className="m-1" onClick={(ele) => handleClick(ele)}>{ele}</Button>
))}</div> ))}
</div>
</Col> </Col>
</Row> </Row>
<Row className="justify-content-end mx-0 my-5"> <Row className="justify-content-end mx-0 my-5">
...@@ -128,9 +131,9 @@ function ProductsList({ match }) { ...@@ -128,9 +131,9 @@ function ProductsList({ match }) {
</Form> </Form>
{/* </Form> */} {/* </Form> */}
</Row> </Row>
<Row md={8} sm={12} className="justify-content-start m-2"> <Row md={8} sm={12} className="justify-content-center m-2">
{productlist.map(pro => ( {productlist.map(pro => (
<Link to={{ <ListCard as={Link} id={pro._id} name={pro.pro_name} price={pro.price} main_img={pro.main_imgUrl} to={{
pathname: `/product/${pro._id}`, pathname: `/product/${pro._id}`,
state: { state: {
id: pro._id, id: pro._id,
...@@ -142,9 +145,7 @@ function ProductsList({ match }) { ...@@ -142,9 +145,7 @@ function ProductsList({ match }) {
main_img: pro.main_imgUrl, main_img: pro.main_imgUrl,
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} />
</Link>
))} ))}
</Row> </Row>
</Container> </Container>
......
import axios from "axios" import axios from "axios";
export function handleLogin({userId,role,name}){ export function handleLogin({ userId, role, name }) {
localStorage.setItem('id',userId) localStorage.setItem('id', userId)
localStorage.setItem('role',role) localStorage.setItem('role', role)
localStorage.setItem('name',name) localStorage.setItem('name', name)
} }
export async function handleLogout(){ export async function handleLogout() {
localStorage.removeItem('id') localStorage.removeItem('id')
localStorage.removeItem('role') localStorage.removeItem('role')
localStorage.removeItem('name') localStorage.removeItem('name')
...@@ -14,12 +14,20 @@ export async function handleLogout(){ ...@@ -14,12 +14,20 @@ export async function handleLogout(){
window.location.href = '/' window.location.href = '/'
} }
export function isAuthenticated(){ export function isAuthenticated() {
const userId= localStorage.getItem('id') const userId = localStorage.getItem('id')
if(userId){ if (userId) {
return userId return userId
} else { } else {
return false return false
}
}
export function isAdmin() {
const role = localStorage.getItem('role')
if (role === 'admin') {
return true
} else {
return false
} }
} }
\ No newline at end of file
...@@ -16,7 +16,7 @@ const getSubCategory=(req,res)=>{ ...@@ -16,7 +16,7 @@ const getSubCategory=(req,res)=>{
} }
const getsubId=(req,res,next,sub)=>{ const getsubId=(req,res,next,sub)=>{
const subcategory = await category.find({"Dress"}) // const subcategory = await category.find({})
console.log('sub=',sub) console.log('sub=',sub)
next() next()
......
...@@ -6,10 +6,10 @@ const upload = multer({ dest: 'uploads/' }) ...@@ -6,10 +6,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) 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]
...@@ -29,30 +29,38 @@ const regist = async (req, res) => { ...@@ -29,30 +29,38 @@ const regist = async (req, res) => {
} }
} }
const getToHome = async (res, req) => { 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("best=", bestProduct)
console.log("new=",newProduct) console.log("new=", newProduct)
res.json(bestProduct, newProduct) res.json({ bestProduct, newProduct })
} catch { } catch {
res.status(500).send('상품을 불러오지 못했습니다.') res.status(500).send('상품을 불러오지 못했습니다.')
} }
} }
const getlist=(req,res)=>{ const getAll = async (req, res) => {
try { try {
res.json(req.productslist) const productslist = await Product.find({}).sort({ createdAt: -1 })
res.json(productslist)
} catch (error) { } catch (error) {
res.status(500).send('상품을 불러오지 못했습니다.') res.status(500).send('상품을 불러오지 못했습니다.')
} }
} }
const getlist = (req, res) => {
try {
res.json(req.productslist)
} catch (error) {
res.status(500).send('상품을 불러오지 못했습니다.')
}
}
const categoryId = async (req, res, next, category) => { const categoryId = async (req, res, next, category) => {
try { try {
const productslist = await Product.find({main_category: category}) const productslist = await Product.find({ main_category: category })
if (!productslist) { if (!productslist) {
res.status(404).send('상품을 찾을 수 없습니다.') res.status(404).send('상품을 찾을 수 없습니다.')
} }
...@@ -63,16 +71,17 @@ const categoryId = async (req, res, next, category) => { ...@@ -63,16 +71,17 @@ const categoryId = async (req, res, next, category) => {
} }
} }
const subgetlist=(req,res)=>{ const subgetlist = (req, res) => {
try{ try {
res.json(req.subproductslist) res.json(req.subproductslist)
}catch(error){ } catch (error) {
res.status(500).send('상품을 불러오지 못했습니다.') res.status(500).send('상품을 불러오지 못했습니다.')
} }
} }
const subcategoryId = async (req, res, next, subcategory) => { const subcategoryId = async (req, res, next, subcategory) => {
try { try {
const subproductslist = await Product.find({sub_category:subcategory}) const subproductslist = await Product.find({ sub_category: subcategory })
if (!subproductslist) { if (!subproductslist) {
res.status(404).send('상품을 찾을 수 없습니다.') res.status(404).send('상품을 찾을 수 없습니다.')
} }
...@@ -83,4 +92,4 @@ const subcategoryId = async (req, res, next, subcategory) => { ...@@ -83,4 +92,4 @@ const subcategoryId = async (req, res, next, subcategory) => {
} }
} }
export default { imageUpload, regist, categoryId, getlist, subcategoryId, subgetlist } export default { imageUpload, regist, getToHome, getAll, categoryId, getlist, subcategoryId, subgetlist }
\ No newline at end of file
...@@ -10,6 +10,9 @@ router.route('/regist') ...@@ -10,6 +10,9 @@ router.route('/regist')
router.route('/getproduct') router.route('/getproduct')
.get(productCtrl.getToHome) .get(productCtrl.getToHome)
router.route('/getproduct/all')
.get(productCtrl.getAll)
router.route('/getproduct/:category') router.route('/getproduct/:category')
.get(productCtrl.getlist) .get(productCtrl.getlist)
......
...@@ -21,11 +21,11 @@ const ProductSchema = new mongoose.Schema({ ...@@ -21,11 +21,11 @@ const ProductSchema = new mongoose.Schema({
default: 0 default: 0
}, },
sizes: { sizes: {
type: Array, type: [String],
required: true required: true
}, },
colors: { colors: {
type: Array, type: [String],
required: true required: true
}, },
main_category: { main_category: {
......
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