Commit c932e6d2 authored by kusang96's avatar kusang96
Browse files

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

parents ac6f366c 2c4b1328
...@@ -11,11 +11,11 @@ function CartCard(props) { ...@@ -11,11 +11,11 @@ function CartCard(props) {
<input className="" type="checkbox" id="exampleCheck1" /> <input className="" type="checkbox" id="exampleCheck1" />
</Col> </Col>
<Col className="text-center"> <Col className="text-center">
<Card.Img className="img-fluid" variant="top" src={e.productId.main_image && `/images/${e.productId.main_image}`} 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.productId._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>가격: {e.productId.price}</Card.Text> <Card.Text>가격: {e.productId.price}</Card.Text>
<Card.Text>옵션: {e.sizes}/{e.colors}</Card.Text> <Card.Text>옵션: {e.sizes}/{e.colors}</Card.Text>
......
...@@ -11,7 +11,7 @@ function MainNav() { ...@@ -11,7 +11,7 @@ function MainNav() {
<img alt="로고" src="/icon/footprint.svg" width="24" height="24" /> <img alt="로고" src="/icon/footprint.svg" width="24" height="24" />
{' '}KU# {' '}KU#
</Navbar.Brand> </Navbar.Brand>
<Nav> <Nav className="ml-auto">
{user ? <Nav.Link className="text-light" onClick={() => handleLogout()}>Logout</Nav.Link> {user ? <Nav.Link className="text-light" onClick={() => handleLogout()}>Logout</Nav.Link>
: ( : (
<> <>
......
import React from 'react'
function PaymentCard() {
return (
<Card >
<Row className="mx-1">
<Col className="text-center">
<Card.Img className="img-fluid" variant="top" src="img/asd.jpg" style={{ width: '20rem' }} />
</Col>
<Col md={6} className="p-2">
<Card.Body>
<input type="image" alt="삭제버튼" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right" onClick={deleteCart} />
<Card.Title className="font-weight-bold mt-3">제품명</Card.Title>
<Card.Text>가격</Card.Text>
<Card.Text>옵션</Card.Text>
<Card.Text>수량</Card.Text>
<div>
<input type="image" alt="마이너스" src="https://img.icons8.com/ios-glyphs/20/000000/minus-math.png" className="align-middle" onClick={minusNum} />
<input type="text" style={{ width: '30px' }} className="text-center align-middle mx-1" placeholder="1" value={num} readOnly></input>
<input type="image" alt="플러스" src="https://img.icons8.com/ios-glyphs/20/000000/plus-math.png" className="align-middle" onClick={plusNum} />
</div>
</Card.Body>
</Col>
</Row>
</Card>
)
}
export default PaymentCard
...@@ -34,7 +34,7 @@ function SubNav() { ...@@ -34,7 +34,7 @@ function SubNav() {
} }
`} `}
</style> </style>
<Nav> <Nav style={{overflowX: "auto"}}>
{categoriesDiv.map(item => item)} {categoriesDiv.map(item => item)}
</Nav> </Nav>
</Navbar> </Navbar>
......
...@@ -210,9 +210,6 @@ function Payment() { ...@@ -210,9 +210,6 @@ function Payment() {
<h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h5> <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h5>
<Card > <Card >
<Row className="mx-1"> <Row className="mx-1">
<Col xs={2} sm={2} className="text-center my-auto">
<input className="" type="checkbox" id="exampleCheck1" />
</Col>
<Col className="text-center"> <Col className="text-center">
<Card.Img className="img-fluid" variant="top" src="img/asd.jpg" style={{ width: '20rem' }} /> <Card.Img className="img-fluid" variant="top" src="img/asd.jpg" style={{ width: '20rem' }} />
</Col> </Col>
......
...@@ -10,7 +10,7 @@ function Product({ match, location }) { ...@@ -10,7 +10,7 @@ function Product({ match, location }) {
const [cart, setCart] = useState(location.state) const [cart, setCart] = useState(location.state)
const [error, setError] = useState('') const [error, setError] = useState('')
const [selected, setSelected] = useState({ sizes: false, colors: false }) const [selected, setSelected] = useState({ sizes: false, colors: false })
const [n, setN] = useState(1) const [price, setPrice] = useState(0)
useEffect(() => { useEffect(() => {
if (selected.sizes === true && selected.colors === true) { if (selected.sizes === true && selected.colors === true) {
...@@ -29,7 +29,7 @@ function Product({ match, location }) { ...@@ -29,7 +29,7 @@ function Product({ match, location }) {
preCart.push(cart) preCart.push(cart)
selected.sizes = false selected.sizes = false
selected.colors = false selected.colors = false
setN(n+1) setPrice(product.price+price)
} }
function handleChange(e) { function handleChange(e) {
const { name, value } = e.target const { name, value } = e.target
...@@ -78,9 +78,9 @@ function Product({ match, location }) { ...@@ -78,9 +78,9 @@ function Product({ match, location }) {
} }
async function addCart() { async function addCart() {
// color, size, count, productId(productlist에서 props), userId(로컬) 를 보내줌 // preCart(color, size, count), productId(productlist에서 props), userId(로컬) 를 보내줌
try { try {
// setError('') setError('')
const response = await axios.put('/api/cart/addcart', { const response = await axios.put('/api/cart/addcart', {
userId: localStorage.getItem('loginStatus'), userId: localStorage.getItem('loginStatus'),
productId: "a8f4d63ead77717f940a2b27deb707a6", productId: "a8f4d63ead77717f940a2b27deb707a6",
...@@ -90,7 +90,6 @@ function Product({ match, location }) { ...@@ -90,7 +90,6 @@ function Product({ match, location }) {
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
} }
// useEffect(() => { // useEffect(() => {
...@@ -142,7 +141,7 @@ function Product({ match, location }) { ...@@ -142,7 +141,7 @@ function Product({ match, location }) {
))} ))}
<Row className="justify-content-between mx-0 my-3" style={{ width: "100%" }}> <Row className="justify-content-between mx-0 my-3" style={{ width: "100%" }}>
<Col> 금액</Col> <Col> 금액</Col>
<Col className="text-right">14,000</Col> <Col className="text-right">{price}</Col>
</Row> </Row>
<Row className="justify-content-between mx-0 my-3" style={{ width: "100%" }}> <Row className="justify-content-between mx-0 my-3" style={{ width: "100%" }}>
<Button onClick={addCart} style={{ width: "49%" }}>장바구니</Button> <Button onClick={addCart} style={{ width: "49%" }}>장바구니</Button>
......
...@@ -4,7 +4,6 @@ import { Row, Col, Button, Form, Container, Alert } from 'react-bootstrap'; ...@@ -4,7 +4,6 @@ import { Row, Col, Button, Form, Container, Alert } from 'react-bootstrap';
import axios from 'axios'; import axios from 'axios';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
let color = {}
let preColors = [] let preColors = []
let colorHtml = [] let colorHtml = []
let list = [] let list = []
...@@ -22,10 +21,12 @@ function ProductsRegist() { ...@@ -22,10 +21,12 @@ function ProductsRegist() {
main_image: [], main_image: [],
detail_image: [] detail_image: []
} }
const [categorys, setCategorys] = 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(0)
const [tag, setTag] = useState(0) const [tag, setTag] = useState(0)
const [subCate, setSubCate] = 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 })
...@@ -34,26 +35,42 @@ function ProductsRegist() { ...@@ -34,26 +35,42 @@ function ProductsRegist() {
try { try {
const response = await axios.get('/api/categories') const response = await axios.get('/api/categories')
const data = response.data[0] const data = response.data[0]
setCategorys([Object.keys(data), Object.values(data)]) setCategories([Object.keys(data), Object.values(data)])
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
}, []) }, [])
function addCategory() { function addCategory() {
console.log(product)
list.push( list.push(
<div> <div>
<span i={tag}>{product["main_category"]} / {product["sub_category"][tag]}</span> <span name={subCate} >{product["main_category"]} / {subCate} </span>
<input 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)
} }
function deleteCategory(e) { function deleteCategory(e) {
const categ = e.target.parentNode e.target.parentNode.remove()
categ.remove() const index = product["sub_category"].findIndex((item)=>{return item === e.target.name})
product["sub_category"].splice(categ.firstElementChild.getAttribute("i"), 1) product["sub_category"].splice(index, 1)
setSubCate('')
console.log(product["sub_category"].length)
}
function handleCategory(e) {
const { name, value } = e.target
if (e.target.name === "main_category") {
setCategoryNum(e.target.selectedIndex - 1)
}
if (name === "sub_category") {
product[name].push(value)
setSubCate(value)
} else {
setProduct({ ...product, [name]: value })
}
console.log(value)
} }
function handleCheckBox(e) { function handleCheckBox(e) {
...@@ -63,29 +80,35 @@ function ProductsRegist() { ...@@ -63,29 +80,35 @@ function ProductsRegist() {
function addColor() { function addColor() {
preColors.push(color["colors"]) preColors.push(color["colors"])
colorHtml.push( colorHtml.push(
<p>{color["colors"]}</p> <div>
<span>{color["colors"]}</span>
<input name={subCate} type="image" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right align-middle" onClick={deleteColor} />
</div>
) )
setColor({})
setProduct({ ...product, "colors": preColors }) setProduct({ ...product, "colors": preColors })
} }
function colorChange(e) { function deleteColor(e) {
e.target.parentNode.remove()
product["colors"].splice(e.name, 1)
setColor({})
console.log(product)
}
function handleColor(e) {
color[e.target.name] = e.target.value color[e.target.name] = e.target.value
} }
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) console.log("event.target.name=", name, "event.target.value=", value)
if (name === "sub_category") { if (files) {
product[name].push(value)
} else if (files) {
setProduct({ ...product, [name]: files }) setProduct({ ...product, [name]: files })
} else { } else {
setProduct({ ...product, [name]: value }) setProduct({ ...product, [name]: value })
} }
if (event.target.name === "main_category") {
setCategoryNum(event.target.selectedIndex - 1)
}
} }
async function handleSubmit(e) { async function handleSubmit(e) {
...@@ -120,7 +143,7 @@ function ProductsRegist() { ...@@ -120,7 +143,7 @@ function ProductsRegist() {
} }
return ( return (
<Container className="mt-5"> <Container>
<Row className="justify-content-md-center"> <Row className="justify-content-md-center">
<Col md={8} className="border p-1" style={{ background: '#F7F3F3' }}> <Col md={8} className="border p-1" style={{ background: '#F7F3F3' }}>
{error && <Alert variant="danger" className="text-center">{error}</Alert>} {error && <Alert variant="danger" className="text-center">{error}</Alert>}
...@@ -142,17 +165,17 @@ function ProductsRegist() { ...@@ -142,17 +165,17 @@ function ProductsRegist() {
<Form.Label>분류</Form.Label> <Form.Label>분류</Form.Label>
<Row> <Row>
<Col md={4}> <Col md={4}>
<Form.Control as="select" name="main_category" onChange={handleChange}> <Form.Control as="select" name="main_category" onChange={handleCategory} disabled={product["sub_category"].length > 0}>
<option value="" >상위분류</option> <option value="" >상위분류</option>
{categorys[0].map((main) => ( {categories[0].map((main) => (
<option value={main}>{main}</option> <option value={main}>{main}</option>
))} ))}
</Form.Control> </Form.Control>
</Col> </Col>
<Col md={6}> <Col md={6}>
<Form.Control as="select" name="sub_category" onChange={handleChange}> <Form.Control as="select" name="sub_category" onChange={handleCategory} disabled={product["main_category"] === "TRAINING"}>
<option value="" >하위분류</option> <option value="" >하위분류</option>
{categorys[1][categoryNum].map((sub) => ( {categories[1][categoryNum].map((sub) => (
<option value={sub}>{sub}</option> <option value={sub}>{sub}</option>
))} ))}
</Form.Control> </Form.Control>
...@@ -176,11 +199,9 @@ function ProductsRegist() { ...@@ -176,11 +199,9 @@ function ProductsRegist() {
<Form.Label>색상</Form.Label> <Form.Label>색상</Form.Label>
<Row> <Row>
<Col md={10}> <Col md={10}>
<Form.Control as="textarea" rows={1} name="colors" placeholder="색상" onChange={colorChange} /> <Form.Control as="textarea" rows={1} name="colors" value={color["colors"]} placeholder="색상" onChange={handleColor} />
</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>
</Col> </Col>
</Row> </Row>
......
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { Redirect } from 'react-router-dom'; import { Link, Redirect } from 'react-router-dom';
import { Card, Button, Container, Row, Col } from 'react-bootstrap'; import { Card, Button, Container, Row, Col } from 'react-bootstrap';
import axios from 'axios'; import axios from 'axios';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
...@@ -7,9 +7,10 @@ import { isAuthenticated } from '../utils/auth' ...@@ -7,9 +7,10 @@ import { isAuthenticated } from '../utils/auth'
import CartCard from '../Components/CartCard'; import CartCard from '../Components/CartCard';
function ShoppingCart() { function ShoppingCart() {
const [num, setNum] = useState(0) const [num, setNum] = useState()
const [error, setError] = useState('') const [error, setError] = useState('')
const [cart, setCart] = useState() const [cart, setCart] = useState([])
const [finalPrice, setFinalPrice] = useState(0)
const user = isAuthenticated() const user = isAuthenticated()
useEffect(() => { useEffect(() => {
...@@ -17,6 +18,7 @@ function ShoppingCart() { ...@@ -17,6 +18,7 @@ function ShoppingCart() {
}, [user]) }, [user])
function plusNum() { function plusNum() {
num = num + 1
setNum(num + 1) setNum(num + 1)
} }
function minusNum() { function minusNum() {
...@@ -25,7 +27,6 @@ function ShoppingCart() { ...@@ -25,7 +27,6 @@ function ShoppingCart() {
} }
else { else {
setNum(num - 1) setNum(num - 1)
} }
} }
async function deleteCart(e) { async function deleteCart(e) {
...@@ -42,11 +43,14 @@ function ShoppingCart() { ...@@ -42,11 +43,14 @@ function ShoppingCart() {
} }
async function getCart() { async function getCart() {
// const userId= localStorage.getItem('loginStatus')
try { try {
const response = await axios.get(`/api/cart/showcart/${user}`) const response = await axios.get(`/api/cart/showcart/${user}`)
console.log(response.data) console.log(response.data)
setCart(response.data) setCart(response.data)
const finalPrices = response.data.map((e) => {
return e.count * e.productId.price
})
setFinalPrice(finalPrices.reduce((a, b) => (a + b)))
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
...@@ -54,33 +58,35 @@ function ShoppingCart() { ...@@ -54,33 +58,35 @@ function ShoppingCart() {
return ( return (
<div> <div>
{/* {getCart()} */}
{/* {console.log(user)} */}
{/* {console.log(cart)} */}
<Container className="justify-content-center"> <Container className="justify-content-center">
<h3 className="my-5 font-weight-bold text-center">장바구니</h3> <h1 className="my-5 font-weight-bold text-center">장바구니</h1>
<div> <div>
<h4 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h4> <h4 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h4>
{cart?<CartCard cart={cart} deleteCart={deleteCart} minusNum={minusNum} plusNum={plusNum} num={num} />:<div></div>} {cart.length >0
? <CartCard cart={cart} deleteCart={deleteCart} minusNum={minusNum} plusNum={plusNum} num={num} />
: <div className="text-center my-5">장바구니에 담긴 상품이 없습니다.</div>}
</div> </div>
<div className="p-5 m-5" style={{ background: '#F7F3F3' }}> <div className="p-5 m-3" style={{ background: '#F7F3F3' }}>
<ul className="pl-0" style={{ listStyle: 'none' }}> <ul className="pl-0" style={{ listStyle: 'none' }}>
<li> <li>
<span className="text-secondary"> 상품금액</span> <span className="text-secondary"> 상품금액</span>
<span className="text-secondary float-right">12,000</span> <span className="text-secondary float-right">{finalPrice}</span>
</li> </li>
<li> <li>
<span className="text-secondary">배송비</span> <span className="text-secondary">배송비</span>
<span className="text-secondary float-right">2,500</span> <span className="text-secondary float-right">2500</span>
</li> </li>
</ul> </ul>
<div className="my-1 pt-2 border-top font-weight-bold"> <div className="my-1 pt-2 border-top font-weight-bold">
결제금액<span className="float-right">14,500</span> 결제금액<span className="float-right">{finalPrice + 2500}</span>
</div> </div>
</div> </div>
<div className="text-center"> <div className="text-center">
<Button className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} href="/payment" block>결제하기</Button> <Button as={Link} to={{
pathname: `/payment`,
state: { cart }
}} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} block>결제하기</Button>
</div> </div>
</Container> </Container>
......
import Cart from "../schemas/Cart.js"; import Cart from "../schemas/Cart.js";
const addcart = async (req, res) => { const addcart = async (req, res) => {
// console.log(req.body)
const { userId, products} = req.body const { userId, products} = req.body
try { try {
const cart = await Cart.findOne({ userId: userId }) const cart = await Cart.findOne({ userId: userId })
console.log(cart)
// const newProduct = { products: products }
// const newProduct = {...newProduct}
// console.log(newProduct)
console.log(products)
await Cart.updateOne( await Cart.updateOne(
{ _id: cart._id }, { _id: cart._id },
// { $addToSet: { products: newProduct } }
{$set: {products: products}} {$set: {products: products}}
) )
res.status(200).send('Cart updated') res.status(200).send('카트에 저장되었습니다.')
} catch (error) { } catch (error) {
console.log(error) console.log(error)
res.status(500).send('죄송합니다. 다시 입력해 주십시오.') res.status(500).send('카트에 저장할 수 없습니다.')
} }
} }
const showcart = async (req, res) => { const showcart = async (req, res) => {
// const {userId} = req.body
// console.log(req.cart)
// console.log(req.id)
try { try {
const cart = await Cart.findOne({ userId: req.id }).populate({ const cart = await Cart.findOne({ userId: req.id }).populate({
path: 'products.productId', path: 'products.productId',
model: 'Product' model: 'Product'
}) })
res.status(200).json(cart.products) res.status(200).json(cart.products)
} catch (error) { } catch (error) {
...@@ -44,9 +32,8 @@ const deletecart = async (req, res) => { ...@@ -44,9 +32,8 @@ const deletecart = async (req, res) => {
console.log(req.body) console.log(req.body)
const { cartId } = req.body const { cartId } = req.body
try { try {
await Cart.remove({ _id: cartId }) await Cart.deleteOne({ _id: cartId })
res.send("삭제완료") res.send("삭제완료")
// res.json()
} catch (error) { } catch (error) {
console.log(error) console.log(error)
res.status(500).send('해당 카트를 삭제하지 못했습니다.') res.status(500).send('해당 카트를 삭제하지 못했습니다.')
......
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