Commit 1c292013 authored by 이재연's avatar 이재연
Browse files

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

parents e645ff20 02b3814f
...@@ -2,7 +2,7 @@ import React from 'react'; ...@@ -2,7 +2,7 @@ import React from 'react';
import { Redirect, Route } from 'react-router-dom'; import { Redirect, Route } from 'react-router-dom';
import { isAdmin } from '../utils/auth'; import { isAdmin } from '../utils/auth';
function PrivateRoute({path, children}) { function PrivateRoute({ path, children }) {
if (isAdmin()) { if (isAdmin()) {
return ( return (
<Route path={path}> <Route path={path}>
......
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { Redirect } from 'react-router-dom';
import axios from 'axios';
import catchError from '../utils/catchErrors';
import { Card, Button } from 'react-bootstrap'; import { Card, Button } from 'react-bootstrap';
function AllCard({ id, name, price, main_img }) { function AllCard({ id, name, price, main_img }) {
function handleDelete(e) { const [success, setSuccess] = useState(false)
const card = e.target.parentNode.parentNode const [error, setError] = useState('')
alert('해당 상품을 성공적으로 삭제하였습니다.') const cardRef = useRef(null)
card.remove()
async function handleDelete() {
const pro_id = cardRef.current.id
try {
setError('')
const response = await axios.delete(`/api/product/delete?pro_id=${pro_id}`)
alert('해당 상품을 성공적으로 삭제하였습니다.')
setSuccess(true)
} catch (error) {
catchError(error, setError)
setSuccess(false)
}
}
if (success) {
return <Redirect to="/admin" />
} }
return ( return (
<Card id={id} className="m-3" style={{ width: "18rem" }}> <Card id={id} ref={cardRef} 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>
......
...@@ -2,38 +2,36 @@ import React from 'react' ...@@ -2,38 +2,36 @@ import React from 'react'
import { Card, Row, Col } from 'react-bootstrap'; import { Card, Row, Col } from 'react-bootstrap';
function CartCard(props) { function CartCard(props) {
console.log(props)
return ( return (
<> <>
{props.cart.map((e) => ( {props.cart.map((e) => (
<Card> <Card>
<Row className="mx-1"> <Row className="mx-1">
<Col xs={2} sm={2} className="text-center my-auto"> <Col xs={2} sm={2} className="text-center my-auto">
<input className="" type="checkbox" name={String(e._id)} onChange={props.checkedCart} /> <input className="" type="checkbox" name={String(e._id)} onChange={props.checkedCart} />
</Col> </Col>
<Col className="text-center"> <Col className="text-center">
<Card.Img className="img-fluid" variant="top" src={e.productId.main_imgUrl && `/images/${e.productId.main_imgUrl}`} style={{ width: '20rem' }} /> <Card.Img className="img-fluid" variant="top" src={e.productId.main_imgUrl && `/images/${e.productId.main_imgUrl}`} style={{ width: '20rem' }} />
</Col> </Col>
<Col md={6} className="p-2"> <Col md={6} className="p-2">
<Card.Body> <Card.Body>
<input type="image" name={String(e._id)} alt="삭제버튼" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right" onClick={props.deleteCart} /> <input type="image" name={String(e._id)} alt="삭제버튼" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right" onClick={props.deleteCart} />
<Card.Title className="font-weight-bold mt-3">{e.productId.pro_name}</Card.Title> <Card.Title className="font-weight-bold mt-3">{e.productId.pro_name}</Card.Title>
<Card.Text className="mb-0">가격: {e.productId.price}</Card.Text> <Card.Text className="mb-0">가격: {e.productId.price}</Card.Text>
<Card.Text className="mb-0">옵션: {e.size}/{e.color}</Card.Text> <Card.Text className="mb-0">옵션: {e.size}/{e.color}</Card.Text>
<Card.Text >수량</Card.Text> <Card.Text >수량</Card.Text>
<div> <div>
<input type="image" name={String(e._id)} alt="마이너스" src="https://img.icons8.com/ios-glyphs/20/000000/minus-math.png" className="align-middle" onClick={props.minusNum} /> <input type="image" name={String(e._id)} alt="마이너스" src="https://img.icons8.com/ios-glyphs/20/000000/minus-math.png" className="align-middle" onClick={props.minusNum} />
<input type="number" style={{ width: '30px' }} className="text-center align-middle mx-1" placeholder={e.count} value={e.count} readOnly></input> <input type="number" style={{ width: '30px' }} className="text-center align-middle mx-1" placeholder={e.count} value={e.count} readOnly></input>
<input type="image" name={String(e._id)} alt="플러스" src="https://img.icons8.com/ios-glyphs/20/000000/plus-math.png" className="align-middle" onClick={props.plusNum} /> <input type="image" name={String(e._id)} alt="플러스" src="https://img.icons8.com/ios-glyphs/20/000000/plus-math.png" className="align-middle" onClick={props.plusNum} />
</div> </div>
</Card.Body> </Card.Body>
</Col> </Col>
</Row> </Row>
</Card> </Card>
)) ))
} }
</> </>
) )
} }
......
import React, { useState, useEffect, useRef } from 'react'; import React from 'react';
import { Card, Button } from 'react-bootstrap'; import { Card } 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="m-3" style={{ width: "18rem" }}> <Card id={id} className="m-3" style={{ width: "18rem" }}>
......
...@@ -21,7 +21,7 @@ function MainNav() { ...@@ -21,7 +21,7 @@ function MainNav() {
<img alt="카트" src="/icon/cart.svg" width="30" height="30" /> <img alt="카트" src="/icon/cart.svg" width="30" height="30" />
</Nav.Link> </Nav.Link>
</> </>
: ( : (
<> <>
<Nav.Link className="text-light" href='/login'>Login</Nav.Link> <Nav.Link className="text-light" href='/login'>Login</Nav.Link>
<Nav.Link className="text-light" href='/signup'>Sign Up</Nav.Link> <Nav.Link className="text-light" href='/signup'>Sign Up</Nav.Link>
......
import { Pagination } from "react-bootstrap"; import { Pagination } from "react-bootstrap";
import React from 'react'; import React from 'react';
function Paginations({ index, endPage, handlePage }) { function Paginations({ index, totalPages, handlePage }) {
return ( return (
<Pagination> <Pagination className="d-flex justify-content-center">
<style type="text/css">
{`
.page-link, .page-link:hover {
color: #91877F;
margin: 0;
border: 0;
}
.page-link:focus {
box-shadow: 0 0 0 0;
}
.page-item.active .page-link {
background-color: #CDC5C2;
border-color: #CDC5C2;
color: #fff;
}
`}
</style>
<Pagination.First onClick={() => handlePage(1)} /> <Pagination.First onClick={() => handlePage(1)} />
{index === 1 ? <Pagination.Prev onClick={()=>handlePage(index)} /> : <Pagination.Prev onClick={()=>handlePage(index - 1)} />} {index === 1 ? <Pagination.Prev onClick={()=>handlePage(index)} /> : <Pagination.Prev onClick={()=>handlePage(index - 1)} />}
{index === endPage-1 ? <Pagination.Item onClick={()=>handlePage(index - 3)}>{index - 3}</Pagination.Item> : ""} {index === totalPages && index > 4 ? <Pagination.Item onClick={()=>handlePage(index - 4)}>{index - 4}</Pagination.Item> : ""}
{index === endPage ? <Pagination.Item onClick={()=>handlePage(index - 4)}>{index - 4}</Pagination.Item> : ""} {index > 3 && index >= totalPages-1 ? <Pagination.Item onClick={()=>handlePage(index - 3)}>{index - 3}</Pagination.Item> : ""}
{index === endPage ? <Pagination.Item onClick={()=>handlePage(index - 3)}>{index - 3}</Pagination.Item> : ""}
{index < 3 ? "" : <Pagination.Item onClick={()=>handlePage(index - 2)}>{index - 2}</Pagination.Item>} {index < 3 ? "" : <Pagination.Item onClick={()=>handlePage(index - 2)}>{index - 2}</Pagination.Item>}
{index === 1 ? "" : <Pagination.Item onClick={()=>handlePage(index - 1)}>{index - 1}</Pagination.Item>} {index === 1 ? "" : <Pagination.Item onClick={()=>handlePage(index - 1)}>{index - 1}</Pagination.Item>}
<Pagination.Item active>{index}</Pagination.Item> <Pagination.Item active>{index}</Pagination.Item>
{index === endPage ? "" : <Pagination.Item onClick={()=>handlePage(index + 1)}>{index + 1}</Pagination.Item>} {index === totalPages ? "" : <Pagination.Item onClick={()=>handlePage(index + 1)}>{index + 1}</Pagination.Item>}
{index > endPage-2 ? "" : <Pagination.Item onClick={()=>handlePage(index + 2)}>{index + 2}</Pagination.Item>} {index > totalPages-2 ? "" : <Pagination.Item onClick={()=>handlePage(index + 2)}>{index + 2}</Pagination.Item>}
{index === 1 ? <Pagination.Item onClick={()=>handlePage(index + 3)}>{index + 3}</Pagination.Item> : ""} {index < totalPages-3 && index >= 1 ? <Pagination.Item onClick={()=>handlePage(index + 3)}>{index + 3}</Pagination.Item> : ""}
{index === 1 ? <Pagination.Item onClick={()=>handlePage(index + 4)}>{index + 4}</Pagination.Item> : ""} {index < totalPages-4 && index >= 1 ? <Pagination.Item onClick={()=>handlePage(index + 4)}>{index + 4}</Pagination.Item> : ""}
{index === 2 ? <Pagination.Item onClick={()=>handlePage(index + 3)}>{index + 3}</Pagination.Item> : ""} {index === totalPages ? <Pagination.Next onClick={()=>handlePage(index)} /> : <Pagination.Next onClick={()=>handlePage(index + 1)} />}
{index === endPage ? "" : <Pagination.Next onClick={()=>handlePage(index + 1)} />}
<Pagination.Last onClick={() =>handlePage(endPage)} /> <Pagination.Last onClick={() =>handlePage(totalPages)} />
</Pagination> </Pagination>
) )
} }
......
...@@ -2,7 +2,7 @@ import React from 'react'; ...@@ -2,7 +2,7 @@ import React from 'react';
import { Redirect, Route } from 'react-router-dom'; import { Redirect, Route } from 'react-router-dom';
import { isAuthenticated } from '../utils/auth'; import { isAuthenticated } from '../utils/auth';
function PrivateRoute({path, children}) { function PrivateRoute({ path, children }) {
if (isAuthenticated()) { if (isAuthenticated()) {
return ( return (
<Route path={path}> <Route path={path}>
......
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, Button, Form, Modal } from 'react-bootstrap';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import axios from 'axios'; import axios from 'axios';
import catchError from '../utils/catchErrors'; import catchError from '../utils/catchErrors';
...@@ -38,18 +38,16 @@ function Account() { ...@@ -38,18 +38,16 @@ function Account() {
if (files) { if (files) {
setAccount({ ...account, [name]: files }) setAccount({ ...account, [name]: files })
} else { } else {
console.log("name=", name, "value=", value);
setAccount({ ...account, [name]: value }) setAccount({ ...account, [name]: value })
} }
} }
const handleBasic = async (event) => { const handleBasic = async () => {
const formData = new FormData() const formData = new FormData()
formData.append('avatar', '') formData.append('avatar', '')
try { try {
if (userId) { if (userId) {
const response = await axios.put(`/api/users/account/${userId}`, formData) const response = await axios.put(`/api/users/account/${userId}`, formData)
console.log(response.data)
window.location.reload() window.location.reload()
} }
} catch (error) { } catch (error) {
...@@ -67,7 +65,6 @@ function Account() { ...@@ -67,7 +65,6 @@ function Account() {
try { try {
if (userId) { if (userId) {
const response = await axios.put(`/api/users/account/${userId}`, formData) const response = await axios.put(`/api/users/account/${userId}`, formData)
console.log(response.data)
window.location.reload() window.location.reload()
} }
} catch (error) { } catch (error) {
...@@ -78,13 +75,12 @@ function Account() { ...@@ -78,13 +75,12 @@ function Account() {
} }
} }
async function getOrdered() { async function getOrdered({ }) {
console.log("object")
try { try {
const response = await axios.post(`/api/users/addorder`,{ const response = await axios.post(`/api/users/addorder`, {
userId:userId userId: userId
}) })
const a=response.data const a = response.data
setOrdered(a) setOrdered(a)
console.log("what=", response.data) console.log("what=", response.data)
} catch (error) { } catch (error) {
...@@ -92,7 +88,7 @@ function Account() { ...@@ -92,7 +88,7 @@ function Account() {
} }
} }
return ( return (
<Container className="px-3"> <Container className="px-3">
<style type="text/css"> <style type="text/css">
...@@ -128,7 +124,6 @@ function Account() { ...@@ -128,7 +124,6 @@ function Account() {
<Col className="px-0"> <Col className="px-0">
<Button variant="outline-secondary" onClick={handleBasic} <Button variant="outline-secondary" onClick={handleBasic}
className="d-flex justify-content-start"><small>기본이미지로</small></Button> className="d-flex justify-content-start"><small>기본이미지로</small></Button>
{/* 기본이미지로 보내기 */}
</Col> </Col>
<Button variant="secondary" onClick={() => setShow(false)}>취소</Button> <Button variant="secondary" onClick={() => setShow(false)}>취소</Button>
<Button variant="primary" type="submit" onClick={() => setShow(false)}>저장</Button> <Button variant="primary" type="submit" onClick={() => setShow(false)}>저장</Button>
...@@ -144,7 +139,6 @@ function Account() { ...@@ -144,7 +139,6 @@ function Account() {
{account.name} {account.name}
</strong> </strong>
<Modal <Modal
size="sm" size="sm"
show={proshow} show={proshow}
onHide={() => setProshow(false)}> onHide={() => setProshow(false)}>
...@@ -182,13 +176,12 @@ function Account() { ...@@ -182,13 +176,12 @@ function Account() {
<a href="mailto:shoppingmall_KU@korea.ac.kr"> <a href="mailto:shoppingmall_KU@korea.ac.kr">
<small title="메일보내기"> * 문의 : shoppingmall_KU@korea.ac.kr </small> <small title="메일보내기"> * 문의 : shoppingmall_KU@korea.ac.kr </small>
</a> </a>
{/* 쇼핑몰 문의 메일보내기 */}
</Row> </Row>
</Col> </Col>
</Row> </Row>
</Card> </Card>
<Card> <Card>
<OrderCard ordered ={ordered}/> <OrderCard ordered={ordered} />
</Card> </Card>
</Container > </Container >
) )
......
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
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';
...@@ -11,38 +10,31 @@ function Admin() { ...@@ -11,38 +10,31 @@ function Admin() {
const [search, setSearch] = useState({ word: '' }) const [search, setSearch] = useState({ word: '' })
const [productlist, setProductlist] = useState([]) const [productlist, setProductlist] = useState([])
const [status, setStatus] = useState(INIT_STATUS) const [status, setStatus] = useState(INIT_STATUS)
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1)
const [per, setPer] = useState(10);
const [error, setError] = useState('') const [error, setError] = useState('')
const searchref = useRef(null) const searchref = useRef(null)
const indexOfLast = currentPage * per; const per = 10;
const indexOfFirst = indexOfLast - per;
useEffect(() => { useEffect(() => {
getProductlist() getProductlist()
}, []) }, [])
function paginate(items, index, itemNumber) { useEffect(() => {
const posts = []; setStatus({ indexOfFirst: (currentPage - 1) * per, indexOfLast: currentPage * per })
const startIndex = (index - 1) * itemNumber }, [currentPage])
for (var i = 0; i < itemNumber; i++) {
posts.push(items[(startIndex + i)])
}
return posts
}
function currentPosts(tmp) { function currentPosts(items) {
let currentPosts = 0; let currentPosts = 0;
currentPosts = tmp.slice(indexOfFirst, indexOfLast); currentPosts = items.slice(status.indexOfFirst, status.indexOfLast);
console.log("postsPerPage=",currentPage) return currentPosts
return currentPosts;
} }
async function getProductlist() { async function getProductlist() {
try { try {
setError('')
const response = await axios.get(`/api/product/getproduct/all`) const response = await axios.get(`/api/product/getproduct/all`)
console.log("response.data=", response.data)
setProductlist(response.data) setProductlist(response.data)
setCurrentPage(1)
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} }
...@@ -57,8 +49,8 @@ function Admin() { ...@@ -57,8 +49,8 @@ function Admin() {
try { try {
setError('') setError('')
const response = await axios.get(`/api/product/getproduct/all?product=${search.word}`) const response = await axios.get(`/api/product/getproduct/all?product=${search.word}`)
console.log("response.data=", response.data)
setProductlist(response.data) setProductlist(response.data)
setCurrentPage(1)
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} finally { } finally {
...@@ -80,8 +72,16 @@ function Admin() { ...@@ -80,8 +72,16 @@ function Admin() {
background-color: #CDC5C2; background-color: #CDC5C2;
border-color: #CDC5C2; border-color: #CDC5C2;
} }
.btn:hover {
.btn:hover, .btn:active, .btn:focus { background-color: #91877F;
border-color: #91877F;
}
.btn-primary.focus, .btn-primary: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; background-color: #91877F;
border-color: #91877F; border-color: #91877F;
} }
...@@ -99,7 +99,7 @@ function Admin() { ...@@ -99,7 +99,7 @@ function Admin() {
<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 index={currentPage} totalPosts={Math.ceil(productlist.length / per)} handlePage={setCurrentPage} /> <Pagination index={currentPage} totalPages={Math.ceil(productlist.length / per)} handlePage={setCurrentPage} />
</Container> </Container>
) )
} }
......
...@@ -3,26 +3,18 @@ import { Link, Redirect } from 'react-router-dom'; ...@@ -3,26 +3,18 @@ import { Link, Redirect } from 'react-router-dom';
import { Form, Col, Container, Button, Row, Alert } from 'react-bootstrap'; import { Form, Col, Container, Button, Row, Alert } from 'react-bootstrap';
import axios from 'axios' import axios from 'axios'
import catchErrors from '../utils/catchErrors' import catchErrors from '../utils/catchErrors'
import { handleLogin, handleLoginAdmin } from '../utils/auth' import { handleLogin } from '../utils/auth'
const INIT_USER = { const INIT_USER = {
id: '', id: '',
password: '' password: ''
} }
const INIT_ADMIN = {
id: '',
password: ''
}
function Login() { function Login() {
const [validated, setValidated] = useState(false); const [validated, setValidated] = useState(false);
const [user, setUser] = useState(INIT_USER) const [user, setUser] = useState(INIT_USER)
const [error, setError] = useState('') const [error, setError] = useState('')
const [success, setSuccess] = useState(false) const [success, setSuccess] = useState(false)
const [admin, setAdmin] = useState(INIT_ADMIN)
function handleChange(event) { function handleChange(event) {
const { name, value } = event.target const { name, value } = event.target
...@@ -39,13 +31,9 @@ function Login() { ...@@ -39,13 +31,9 @@ function Login() {
setValidated(true); setValidated(true);
try { try {
setError('') setError('')
if (user) { const response = await axios.post('/api/auth/login', user)
const response = await axios.post('/api/auth/login', user) handleLogin(response.data)
handleLogin(response.data) setSuccess(true)
setSuccess(true)
}else{
return false
}
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
...@@ -82,7 +70,6 @@ function Login() { ...@@ -82,7 +70,6 @@ function Login() {
<Form.Control.Feedback className="text-center" type="invalid"> 아이디를 입력하세요.</Form.Control.Feedback> <Form.Control.Feedback className="text-center" type="invalid"> 아이디를 입력하세요.</Form.Control.Feedback>
</Form.Row> </Form.Row>
</Form.Group> </Form.Group>
<Form.Group controlId="formBasicPassword"> <Form.Group controlId="formBasicPassword">
<Form.Row> <Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="password">비밀번호</Col> <Col sm={4} xs={6} as={Form.Label} for="password">비밀번호</Col>
......
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 { 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 DaumPostcode from "react-daum-postcode";
import PaymentCard from '../Components/PaymentCard'; import PaymentCard from '../Components/PaymentCard';
import axios from 'axios';
import { isAuthenticated } from '../utils/auth'; import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
import { Container, Row, Col, Button, Form } from 'react-bootstrap';
function Payment({ match, location }) { function Payment({ match, location }) {
const [cart, setCart] = useState([]) const [cart, setCart] = useState([])
...@@ -46,7 +46,6 @@ function Payment({ match, location }) { ...@@ -46,7 +46,6 @@ function Payment({ match, location }) {
try { try {
setError('') setError('')
const response = await axios.get(`/api/cart/showcart/${user}`) const response = await axios.get(`/api/cart/showcart/${user}`)
console.log(response.data)
const preCart = response.data.filter((el) => el.checked === true) const preCart = response.data.filter((el) => el.checked === true)
if (preCart.length) { if (preCart.length) {
setCart(preCart) setCart(preCart)
...@@ -67,7 +66,6 @@ function Payment({ match, location }) { ...@@ -67,7 +66,6 @@ function Payment({ match, location }) {
userId: user, userId: user,
cartId: e.target.name cartId: e.target.name
}) })
console.log(response.data)
const preCart = response.data.products.filter((el) => el.checked === true) const preCart = response.data.products.filter((el) => el.checked === true)
setCart(preCart) setCart(preCart)
setOrder({ products: preCart }) setOrder({ products: preCart })
...@@ -78,7 +76,6 @@ function Payment({ match, location }) { ...@@ -78,7 +76,6 @@ function Payment({ match, location }) {
function handleReceiverInfo(e) { function handleReceiverInfo(e) {
const { name, value } = e.target const { name, value } = e.target
console.log(name, value)
setOrder({ ...order, receiverInfo: { ...order.receiverInfo, [name]: value } }) setOrder({ ...order, receiverInfo: { ...order.receiverInfo, [name]: value } })
} }
...@@ -98,11 +95,9 @@ function Payment({ match, location }) { ...@@ -98,11 +95,9 @@ function Payment({ match, location }) {
const handleComplete = (data) => { const handleComplete = (data) => {
let fullAddress = data.address; let fullAddress = data.address;
let extraAddress = ""; let extraAddress = "";
console.log(data)
if (data.addressType === "R") { if (data.addressType === "R") {
if (data.bname !== "") { if (data.bname !== "") {
extraAddress += data.bname; extraAddress += data.bname;
console.log(extraAddress)
} }
if (data.buildingName !== "") { if (data.buildingName !== "") {
extraAddress += extraAddress +=
......
import axios from 'axios';
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
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 axios from 'axios';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
import { Row, Col, Form, Card, Button, Modal, Image } from 'react-bootstrap';
function Product({ match, location }) { function Product({ match, location }) {
...@@ -18,9 +18,7 @@ function Product({ match, location }) { ...@@ -18,9 +18,7 @@ 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 />') const replace = product.description.replaceAll('{\n\n}', '<br />')
console.log("objectasdasd", replace)
useEffect(() => { useEffect(() => {
if (size && color) { if (size && color) {
...@@ -144,17 +142,6 @@ function Product({ match, location }) { ...@@ -144,17 +142,6 @@ function Product({ match, location }) {
return ( return (
<div> <div>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>장바구니에 상품담기</Modal.Title>
</Modal.Header>
<Modal.Body>정상적으로 장바구니에 상품을 담았습니다.</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>쇼핑계속하기</Button>
<Button variant="primary" href='/shoppingcart'>장바구니로 이동</Button>
</Modal.Footer>
</Modal>
{/* {console.log(cart)} */}
<style type="text/css"> <style type="text/css">
{` {`
.btn { .btn {
...@@ -168,6 +155,16 @@ function Product({ match, location }) { ...@@ -168,6 +155,16 @@ function Product({ match, location }) {
} }
`} `}
</style> </style>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>장바구니에 상품담기</Modal.Title>
</Modal.Header>
<Modal.Body>정상적으로 장바구니에 상품을 담았습니다.</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>쇼핑계속하기</Button>
<Button variant="primary" href='/shoppingcart'>장바구니로 이동</Button>
</Modal.Footer>
</Modal>
<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={`/images/${product.main_img}`} style={{ objectFit: "contain", width: "100%" }} /> <img src={`/images/${product.main_img}`} style={{ objectFit: "contain", width: "100%" }} />
...@@ -220,20 +217,25 @@ function Product({ match, location }) { ...@@ -220,20 +217,25 @@ 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='justify-content-center '> <Col className='text-center' style={{ fontSize: '1px' }}>
<h2 className='p-2 text-center border' style={{ background: '#CDC5C2' }}>{product.name} </h2> <div className='p-2 text-center border' style={{ background: '#CDC5C2', width: '50%', margin: 'auto', fontSize: '3.5vmin' }} >
<> {product.name}
<Image src={`/images/${product.main_img}`} style={{ objectFit: "contain", maxWidth: "100%" }} /> </div>
</> <Image src={`/images/${product.main_img}`} className='d-flex justify-content-center p-4' style={{ objectFit: "contain", maxWidth: "100%", margin: 'auto' }} />
<Card className='m-3 d-flex justify-content-center'>
<Card.Body className='text-center'> <Card style={{ width: '70%', margin: 'auto' }} className='my-4' >
{replace} <Card.Header className='text-center' style={{ background: '#CDC5C2' }}>
<h5 className='m-0' style={{ whiteSpace: 'nowrap' }}> [ Description ]</h5>
</Card.Header>
<Card.Body className='text-center m-4' style={{ whiteSpace: "pre-line", background: '#F7F3F3', fontSize: '1vw' }}>
<small>{replace}</small>
</Card.Body> </Card.Body>
</Card> </Card>
<> <Col className='p-5'>
<h4 className='my-4 text-center'>[ Detail Images ]</h4> <div className='border p-2' style={{ width: '60%', margin: 'auto', fontSize: '3.5vmin' }}>[ Detail Images ]</div>
<Image src={`/images/${product.detail_imgs}`} style={{ objectFit: "contain", maxWidth: "100%" }} /> <Image src={`/images/${product.detail_imgs}`} style={{ objectFit: "contain", maxWidth: "100%", margin: 'auto' }} className='p-4 d-flex justify-content-center' />
</>
</Col>
</Col> </Col>
</Col> </Col>
</Row> </Row>
......
...@@ -109,9 +109,9 @@ function ProductsRegist() { ...@@ -109,9 +109,9 @@ function ProductsRegist() {
console.log(product) console.log(product)
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") {
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" || key === "detail_image") {
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])
} }
...@@ -244,7 +244,7 @@ function ProductsRegist() { ...@@ -244,7 +244,7 @@ function ProductsRegist() {
</Form.Group> </Form.Group>
<Form.Group> <Form.Group>
<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} multiple />
</Form.Group> </Form.Group>
<Button type="submit" style={{ background: '#91877F', borderColor: '#91877F' }} block> <Button type="submit" style={{ background: '#91877F', borderColor: '#91877F' }} block>
{loading && <Spinner as='span' animation='border' size='sm' role='status' aria-hidden='true' />}{' '}등록 {loading && <Spinner as='span' animation='border' size='sm' role='status' aria-hidden='true' />}{' '}등록
......
...@@ -7,24 +7,17 @@ import catchError from '../utils/catchErrors'; ...@@ -7,24 +7,17 @@ import catchError from '../utils/catchErrors';
import { Container, Row, Col, Form, FormControl, Button, Dropdown, ButtonGroup, Image } from 'react-bootstrap'; import { Container, Row, Col, Form, FormControl, Button, Dropdown, ButtonGroup, Image } from 'react-bootstrap';
function ProductsList({ match }) { function ProductsList({ match }) {
const INIT_STATUS = { indexOfFirst: 0, indexOfLast: 10 }
const [search, setSearch] = useState({ word: '' }) const [search, setSearch] = useState({ word: '' })
const [sortingName, setSortingName] = useState('정렬')
const [mainCategory, setMainCategory] = useState(match.params.main.toUpperCase()) const [mainCategory, setMainCategory] = useState(match.params.main.toUpperCase())
const [subCategory, setSubCategory] = useState([]) const [subCategory, setSubCategory] = useState([])
const [productlist, setProductlist] = useState([]) const [productlist, setProductlist] = useState([])
const [currentPage, setCurrentPage] = useState(1); const [status, setStatus] = useState(INIT_STATUS)
const [postsPerPage, setPostsPerPage] = useState(6); const [currentPage, setCurrentPage] = useState(1)
const [error, setError] = useState('') const [error, setError] = useState('')
const indexOfLast = currentPage * postsPerPage;
const indexOfFirst = indexOfLast - postsPerPage;
const searchref = useRef(null) const searchref = useRef(null)
const per = 10;
const [sortingName, setSortingName] = useState('정렬')
function currentPosts(tmp) {
let currentPosts = 0;
currentPosts = tmp.slice(indexOfFirst, indexOfLast);
return currentPosts;
}
useEffect(() => { useEffect(() => {
setMainCategory(match.params.main.toUpperCase()) setMainCategory(match.params.main.toUpperCase())
...@@ -36,6 +29,16 @@ function ProductsList({ match }) { ...@@ -36,6 +29,16 @@ function ProductsList({ match }) {
getProductlist() getProductlist()
}, [mainCategory]) }, [mainCategory])
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) { function handleChange(event) {
setSearch({ word: event.target.value }) setSearch({ word: event.target.value })
} }
...@@ -45,8 +48,8 @@ function ProductsList({ match }) { ...@@ -45,8 +48,8 @@ function ProductsList({ match }) {
try { try {
setError('') setError('')
const response = await axios.get(`/api/product/getproduct/main/${mainCategory}?product=${search.word}`) const response = await axios.get(`/api/product/getproduct/main/${mainCategory}?product=${search.word}`)
console.log("response.data=", response.data)
setProductlist(response.data) setProductlist(response.data)
setCurrentPage(1)
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} finally { } finally {
...@@ -59,7 +62,6 @@ function ProductsList({ match }) { ...@@ -59,7 +62,6 @@ function ProductsList({ match }) {
setError('') 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));
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} }
...@@ -70,6 +72,7 @@ function ProductsList({ match }) { ...@@ -70,6 +72,7 @@ function ProductsList({ match }) {
setError('') 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)
setCurrentPage(1)
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} }
...@@ -81,55 +84,55 @@ function ProductsList({ match }) { ...@@ -81,55 +84,55 @@ function ProductsList({ match }) {
console.log("thisispurchase") console.log("thisispurchase")
productlist.sort(function (a, b) { productlist.sort(function (a, b) {
if (a.purchase > b.purchase) { if (a.purchase > b.purchase) {
return -1; return -1;
} }
if (a.purchase < b.purchase) { if (a.purchase < b.purchase) {
return 1; return 1;
} }
// a must be equal to b // a must be equal to b
return 0; return 0;
}); });
setSortingName("인기상품") setSortingName("인기상품")
} else if(method === "newest"){ } else if (method === "newest") {
console.log("thisisnewest") console.log("thisisnewest")
productlist.sort(function (a, b) { productlist.sort(function (a, b) {
if (a.createdAt > b.createdAt) { if (a.createdAt > b.createdAt) {
return -1; return -1;
} }
if (a.createdAt < b.createdAt) { if (a.createdAt < b.createdAt) {
return 1; return 1;
} }
// a must be equal to b // a must be equal to b
return 0; return 0;
}); });
setSortingName("신상품") setSortingName("신상품")
} else if(method === "lowest"){ } else if (method === "lowest") {
console.log("thisislowest") console.log("thisislowest")
productlist.sort(function (a, b) { productlist.sort(function (a, b) {
if (a.price > b.price) { if (a.price > b.price) {
return 1; return 1;
} }
if (a.price < b.price) { if (a.price < b.price) {
return -1; return -1;
} }
// a must be equal to b // a must be equal to b
return 0; return 0;
}); });
setSortingName("낮은가격") setSortingName("낮은가격")
} else { } else {
console.log("thisispurchase") console.log("thisispurchase")
productlist.sort(function (a, b) { productlist.sort(function (a, b) {
if (a.price > b.price) { if (a.price > b.price) {
return -1; return -1;
} }
if (a.price < b.price) { if (a.price < b.price) {
return 1; return 1;
} }
// a must be equal to b // a must be equal to b
return 0; return 0;
}); });
setSortingName("높은가격") setSortingName("높은가격")
} }
} }
...@@ -137,10 +140,10 @@ function ProductsList({ match }) { ...@@ -137,10 +140,10 @@ function ProductsList({ match }) {
async function handleSubname(e) { async function handleSubname(e) {
const subname = e.target.name const subname = e.target.name
try { try {
console.log("first test!!!!!!!!") setError('')
const response = await axios.get(`/api/product/getproduct/sub?subname=${subname}`) const response = await axios.get(`/api/product/getproduct/sub?subname=${subname}`)
console.log("subname response data=", response.data)
setProductlist(response.data) setProductlist(response.data)
setCurrentPage(1)
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} }
...@@ -154,7 +157,6 @@ function ProductsList({ match }) { ...@@ -154,7 +157,6 @@ function ProductsList({ match }) {
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 {
...@@ -164,10 +166,22 @@ function ProductsList({ match }) { ...@@ -164,10 +166,22 @@ function ProductsList({ match }) {
.btn { .btn {
background-color: #CDC5C2; background-color: #CDC5C2;
border-color: #CDC5C2; border-color: #CDC5C2;
border-radius: 0;
} }
.btn:hover { .btn:hover, .btn:focus {
background-color: #91877F; background-color: #91877F;
border-color: #91877F; border-color: #91877F;
box-shadow: 0 0 0 0;
}
.btn-primary:not(:disabled):not(.disabled).active, .btn-primary:not(:disabled):not(.disabled):active, .show>.btn-primary.dropdown-toggle {
background-color: #91877F;
border-color: #91877F;
}
.show>.btn-primary.dropdown-toggle:focus {
box-shadow: 0 0 0 0;
}
.dropdown-item {
color: #91877F;
} }
.dropdown-item:hover, .dropdown-item:active { .dropdown-item:hover, .dropdown-item:active {
background-color: #91877F; background-color: #91877F;
...@@ -175,12 +189,12 @@ function ProductsList({ match }) { ...@@ -175,12 +189,12 @@ function ProductsList({ match }) {
} }
`} `}
</style> </style>
<Row className="justify-content-center"> <Row className="justify-content-center" >
<Col sm={10} xs={12} > <Col className='px-3'>
<h1 style={{ fontSize: "3rem" }} className="text-center">{mainCategory}</h1>
<div className="text-center"> <div className="text-center">
<ButtonGroup className="m-3" variant="outline-light secondary" style={{ display: "inline-block" }}> <h1 style={{ fontSize: "5.5vmax" }} className="text-center m-1 py-3">{mainCategory}</h1>
{subCategory.map(el => (<Button className="m-1" variant="secondary" name={el} onClick={handleSubname}>{el}</Button>))} <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> </ButtonGroup>
</div> </div>
</Col> </Col>
...@@ -188,7 +202,7 @@ function ProductsList({ match }) { ...@@ -188,7 +202,7 @@ function ProductsList({ match }) {
<Row className="justify-content-end mx-0 mt-5 mb-3"> <Row className="justify-content-end mx-0 mt-5 mb-3">
<Form inline onSubmit={handleSearch} className="justify-content-end mx-0 my-2"> <Form inline onSubmit={handleSearch} className="justify-content-end mx-0 my-2">
<FormControl ref={searchref} type="text" onChange={handleChange} placeholder="Search" style={{ width: "13rem" }} /> <FormControl ref={searchref} type="text" onChange={handleChange} placeholder="Search" style={{ width: "13rem" }} />
<Button type="submit" className="px-2 mr-2"> <Button type="submit" className="px-2 mr-2">
<img src="/icon/search.svg" width="20" height="20" /> <img src="/icon/search.svg" width="20" height="20" />
</Button> </Button>
</Form> </Form>
...@@ -204,7 +218,7 @@ function ProductsList({ match }) { ...@@ -204,7 +218,7 @@ function ProductsList({ match }) {
</Row> </Row>
<Row md={8} sm={12} className="justify-content-center m-2"> <Row md={8} sm={12} className="justify-content-center m-2">
{productlist.length > 0 ? {productlist.length > 0 ?
productlist.map(pro => ( currentPosts(productlist).map(pro => (
<Link to={{ <Link to={{
pathname: `/product/${pro._id}`, pathname: `/product/${pro._id}`,
state: { state: {
...@@ -223,11 +237,12 @@ function ProductsList({ match }) { ...@@ -223,11 +237,12 @@ function ProductsList({ match }) {
</Link> </Link>
)) ))
: ( : (
<Image src="/sryimready.jpg" <Image src="/sryimready.jpg" className='m-5'
style={{ objectFit: "cover", width: "45 rem", height: "45 rem" }}></Image> style={{ objectFit: "contain", width: "45vw", height: "45vh" }}></Image>
) )
} }
</Row> </Row>
{productlist.length != 0 ? <Pagination index={currentPage} totalPages={Math.ceil(productlist.length / per)} handlePage={setCurrentPage} /> : ''}
</Container> </Container>
) )
} }
......
...@@ -33,12 +33,10 @@ function Signup() { ...@@ -33,12 +33,10 @@ function Signup() {
event.stopPropagation(); event.stopPropagation();
} }
setValidated(true); setValidated(true);
console.log(user)
try { try {
setError('') setError('')
const response = await axios.post('/api/users/signup', user) const response = await axios.post('/api/users/signup', user)
console.log(response.data)
setSuccess(true) setSuccess(true)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
...@@ -66,155 +64,135 @@ function Signup() { ...@@ -66,155 +64,135 @@ function Signup() {
} }
return ( return (
<div> <Container className="my-5">
<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">
<Row className="justify-content-center"> <Form.Group as={Row} controlId="formBasicName">
<Col md={6} xs={10} className="border" style={{ background: '#F7F3F3' }}> <Form.Label column sm="4" for='name'>
<h2 className="text-center m-5">Sign Up</h2> </Form.Label>
{error && <Alert variant='danger'> <Col sm="8">
{error} <Form.Control
</Alert>} required type="text"
<Form name="name"
noValidate validated={validated} placeholder="Name"
onSubmit={handleSubmit} value={user.name}
className="p-4"> onChange={handleChange} />
<Form.Group as={Col} controlId="formBasicName" className="justify-content-end"> <Form.Control.Feedback type="invalid" >이름을 입력하세요. </Form.Control.Feedback>
<Form.Row> </Col>
<Col sm={4} xs={6} as={Form.Label} for="id"> </Col> </Form.Group>
<Col sm={8} xs={6} as={Form.Control}
required type="text"
name="name"
placeholder="Name"
style={{ width: '160px' }}
value={user.name}
onChange={handleChange} />
<Form.Control.Feedback type="invalid" >이름을 입력하세요. </Form.Control.Feedback>
</Form.Row>
</Form.Group>
<Form.Group as={Col} controlId="formBasicNumber">
<Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="number">주민등록번호</Col>
<Col xs={3}>
<Form.Control
required type="text"
name="number1"
maxlength="6"
className="ml-1 mr-3 p-1" style={{ width: '80px' }}
value={user.number1}
onChange={handleChange}>
</Form.Control>
</Col>
<Col xs={1}>
<div className='font-weight-bold d-flex align-items-center' style={{ text: 'center' }}>-</div>
</Col>
<Col xs={2}>
<Form.Control
required type="text"
name="number2"
maxlength="1" className="mx-3 p-1"
style={{ width: '30px' }}
value={user.number2}
onChange={handleChange}>
</Form.Control>
</Col>
<div className='font-weight-bold d-flex align-items-center'>* * * * * * </div>
<Form.Control.Feedback type="invalid">주민등록번호를 입력하세요.</Form.Control.Feedback>
</Form.Row>
</Form.Group>
<Form.Group as={Col} controlId="formBasicId">
<Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="id">아이디</Col>
<Col sm={8} xs={12} as={Form.Control}
required
type="text"
name="id"
placeholder="ID"
style={{ width: '160px' }}
value={user.id}
onChange={handleChange} />
<Form.Control.Feedback type="invalid"> 아이디를 입력하세요.</Form.Control.Feedback>
</Form.Row>
</Form.Group>
<Form.Group as={Col} controlId="formBasicPassword">
<Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="password">비밀번호</Col>
<Col sm={8} xs={12} as={Form.Control}
type="password"
name="password"
placeholder="Password"
style={{ width: '160px' }}
value={user.password}
required
onChange={handleChange}
/>
<Form.Control.Feedback className="text-end" type="invalid">
비밀번호를 입력하세요.
</Form.Control.Feedback>
</Form.Row>
</Form.Group>
<Form.Group as={Col} controlId="formBasicPassword2">
<Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="password">비밀번호 확인</Col>
<Col sm={8} xs={12} as={Form.Control}
type="password"
name="password2"
placeholder="Password"
style={{ width: '160px' }}
value={user.password2}
required
onChange={handleChange}
/>
<Form.Control.Feedback type="invalid"> 비밀번호를 한번 입력하세요.
</Form.Control.Feedback>
</Form.Row>
</Form.Group>
<Form.Group as={Col} controlId="formBasicEmail">
<Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="email">이메일</Col>
<Col sm={8} xs={12} as={Form.Control}
required type="email"
name="email"
placeholder="E-mail"
style={{ width: '160px' }}
value={user.email}
onChange={handleChange} />
<Form.Control.Feedback type="invalid"> 이메일 입력하세요. </Form.Control.Feedback>
</Form.Row>
</Form.Group>
<Form.Group as={Col} controlId="formBasicTel">
<Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="tel">휴대전화</Col>
<Col sm={8} xs={12} style={{ width: '160px' }} className='p-0'>
<Col
as={Form.Control}
required type="text"
name="tel"
placeholder="Telephone"
className='p-1'
value={user.tel}
onChange={handleChange}>
</Col> <Form.Group as={Row} controlId="formBasicNumber">
<div className='d-flex justify-content-end mt-1'><small >' - ' 함께 입력해주세요^^</small></div> <Form.Label column sm="4" for='number'>
</Col> 주민등록번호 </Form.Label>
<Form.Control.Feedback type="invalid"> 휴대전화를 입력하세요. </Form.Control.Feedback> <Col sm="4" xs='5'>
</Form.Row> <Form.Control
<Form.Control.Feedback className="text-end" type="invalid"> className='pr-0'
비밀번호를 입력하세요. required type="text"
</Form.Control.Feedback> name="number1"
</Form.Group > maxlength="6"
<Button placeholder="생년월일"
style={{ background: '#91877F', borderColor: '#91877F' }} type="submit" block value={user.number1}
onClick={checkPassword} onChange={handleChange} />
> <Form.Control.Feedback type="invalid" >주민등록번호 입력하세요. </Form.Control.Feedback>
Sign Up </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> </Button>
</Form> </Form>
</Col> </Col>
</Row> </Row>
</Container> </Container>
</div >
) )
} }
......
...@@ -5,13 +5,11 @@ import config from '../config.js' ...@@ -5,13 +5,11 @@ import config from '../config.js'
const login = async (req, res) => { const login = async (req, res) => {
const { id, password } = req.body const { id, password } = req.body
console.log(req.body)
try { try {
const user = await User.findOne({ id }).select('password role name tel email') const user = await User.findOne({ id }).select('password role name tel email')
console.log('u=', user) console.log('u=', user)
if (!user) { if (!user) {
return res.status(404).send(`${user.id}가 존재하지 않습니다.`) return res.status(404).send(`${id}가 존재하지 않습니다.`)
} }
const passwordMatch = await bcrypt.compare(password, user.password) const passwordMatch = await bcrypt.compare(password, user.password)
if (passwordMatch) { if (passwordMatch) {
...@@ -34,47 +32,10 @@ const login = async (req, res) => { ...@@ -34,47 +32,10 @@ const login = async (req, res) => {
} }
} }
const admin = (req, res) => {
try {
res.json(admin)
} catch (error) {
res.status(500).send('다시 시도하세요.')
}
}
const adminId = async (req, res, next, admin) => {
try {
const admin = await User.findOne({ role: "admin" }).select('id password role name')
console.log('a=',admin)
if (!admin) {
res.status(404).send(`${id}가 존재하지 않습니다.`)
}
const adminpasswordMatch = await bcrypt.compare(password, admin.password)
if (adminpasswordMatch) {
const token = jwt.sign({ adminId: admin.id }, config.jwtSecret, {
expiresIn: '3d'
})
res.cookie('token', token, {
maxAge: config.cookieMaxAge,
httpOnly: true,
secure: config.env === 'production'
})
res.json({ adminId: admin.id, role: admin.role, name: admin.name })
}else {
res.status(401).send('비밀번호가 일치하지 않습니다.')
}
req.admin = admin
next()
} catch (error) {
res.status(500).send('로그인 실패. 다시 시도하세요.')
}
}
const logout = (req, res) => { const logout = (req, res) => {
res.clearCookie('token') res.clearCookie('token')
res.send('로그아웃 되었습니다.') res.send('로그아웃 되었습니다.')
} }
export default { login, logout, admin, adminId } export default { login, logout }
\ No newline at end of file \ No newline at end of file
...@@ -54,6 +54,4 @@ const orderById = async (req, res, next, id) => { ...@@ -54,6 +54,4 @@ const orderById = async (req, res, next, id) => {
} }
} }
export default { addorder, showorder, orderById , Ordered }
export default { addorder, showorder, Ordered, orderById}
...@@ -5,11 +5,10 @@ const upload = multer({ dest: 'uploads/' }) ...@@ -5,11 +5,10 @@ const upload = multer({ dest: 'uploads/' })
const imageUpload = upload.fields([ const imageUpload = upload.fields([
{ name: 'main_image' }, { name: 'main_image' },
{ name: 'detail_image' } { name: 'detail_image'}
]) ])
const regist = async (req, res) => { const regist = async (req, res) => {
console.log("req.body=", req.body)
try { try {
const { pro_name, price, stock, main_category, sub_category, description, colors, sizes } = req.body const { pro_name, price, stock, main_category, sub_category, description, colors, sizes } = req.body
const main_img = req.files['main_image'][0] const main_img = req.files['main_image'][0]
...@@ -24,7 +23,6 @@ const regist = async (req, res) => { ...@@ -24,7 +23,6 @@ const regist = async (req, res) => {
}).save() }).save()
res.json(newProduct) res.json(newProduct)
} catch (error) { } catch (error) {
console.log(error)
res.status(500).send('제품 정보 등록에 실패하였습니다. 다시 진행해 주십시오.') res.status(500).send('제품 정보 등록에 실패하였습니다. 다시 진행해 주십시오.')
} }
} }
...@@ -33,8 +31,6 @@ const getToHome = async (req, res) => { ...@@ -33,8 +31,6 @@ const getToHome = async (req, res) => {
try { try {
const bestProduct = await Product.find({}).sort({ purchase: -1 }).limit(6) const bestProduct = await Product.find({}).sort({ purchase: -1 }).limit(6)
const newProduct = await Product.find({}).sort({ createdAt: -1 }).limit(6) const newProduct = await Product.find({}).sort({ createdAt: -1 }).limit(6)
// console.log("best=", bestProduct)
// console.log("new=", newProduct)
res.json({ bestProduct, newProduct }) res.json({ bestProduct, newProduct })
} catch { } catch {
res.status(500).send('상품을 불러오지 못했습니다.') res.status(500).send('상품을 불러오지 못했습니다.')
...@@ -69,7 +65,6 @@ const getlist = (req, res) => { ...@@ -69,7 +65,6 @@ const getlist = (req, res) => {
const categoryId = async (req, res, next, category) => { const categoryId = async (req, res, next, category) => {
console.log("req=", req.query.product)
try { try {
if (req.query.product) { if (req.query.product) {
const productslist = await Product.find({ main_category: category, pro_name: { $regex: new RegExp(req.query.product) } }) const productslist = await Product.find({ main_category: category, pro_name: { $regex: new RegExp(req.query.product) } })
...@@ -89,13 +84,11 @@ const categoryId = async (req, res, next, category) => { ...@@ -89,13 +84,11 @@ const categoryId = async (req, res, next, category) => {
} }
const subname = async (req, res) => { const subname = async (req, res) => {
console.log("req.query", req.query)
try { try {
const findSubname = await Product.find({ sub_category: req.query.subname }) const findSubname = await Product.find({ sub_category: req.query.subname })
console.log("findSubname111=", findSubname)
res.send(findSubname) res.send(findSubname)
} catch (error) { } catch (error) {
res.send('상품을 불러오지 못했습니다.') res.status(500).send('상품을 불러오지 못했습니다.')
} }
} }
...@@ -111,11 +104,12 @@ const plusPurchase = async (req, res) => { ...@@ -111,11 +104,12 @@ const plusPurchase = async (req, res) => {
const stock = product.stock const stock = product.stock
await Product.updateOne( await Product.updateOne(
{ _id: products[i].productId._id }, { _id: products[i].productId._id },
{ $set: {
{ $set:
purchase: count + purchase, {
stock: stock - count purchase: count + purchase,
} stock: stock - count
}
} }
) )
} }
...@@ -125,4 +119,17 @@ const plusPurchase = async (req, res) => { ...@@ -125,4 +119,17 @@ const plusPurchase = async (req, res) => {
} }
} }
export default { imageUpload, regist, getToHome, getAll, categoryId, getlist, subname, plusPurchase } const deletePro = async (req, res) => {
\ No newline at end of file const pro_id = req.query.pro_id
try {
const productOne = await Product.findById(pro_id)
if (productOne) {
await Product.remove({ _id: pro_id })
}
res.send('삭제 성공')
} catch (error) {
res.status(500).send('삭제할 상품을 찾지 못하거나 삭제 중 문제가 발생했습니다.')
}
}
export default { imageUpload, regist, getToHome, getAll, categoryId, getlist, subname, plusPurchase, deletePro }
\ No newline at end of file
...@@ -22,7 +22,9 @@ router.route('/getproduct/sub') ...@@ -22,7 +22,9 @@ router.route('/getproduct/sub')
router.route('/pluspurchase') router.route('/pluspurchase')
.post(productCtrl.plusPurchase) .post(productCtrl.plusPurchase)
router.route('/delete')
.delete(productCtrl.deletePro)
router.param('category', productCtrl.categoryId) router.param('category', productCtrl.categoryId)
// router.param('subname',productCtrl.subcategoryId)
export default router export default router
\ No newline at end of file
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