Commit 4815e070 authored by kusang96's avatar kusang96
Browse files

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

parents 2f10d714 4ae42d2f
import React from 'react' import React from 'react'
import { Card, Button, Container, 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" id="exampleCheck1" /> <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.productId._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>가격: {e.productId.price}</Card.Text> <Card.Text>가격: {e.productId.price}</Card.Text>
<Card.Text>옵션: {e.sizes}/{e.colors}</Card.Text> <Card.Text>옵션: {e.size}/{e.color}</Card.Text>
<Card.Text>수량</Card.Text> <Card.Text>수량</Card.Text>
<div> <div>
<input type="image" 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="text" 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" 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>
......
...@@ -12,7 +12,7 @@ function MainNav() { ...@@ -12,7 +12,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>
<Nav.Link className="text-light" href="/account"> Mypage </Nav.Link> <Nav.Link className="text-light" href="/account"> Mypage </Nav.Link>
</> </>
......
import React from 'react' import React from 'react'
import { Card, Row, Col } from 'react-bootstrap';
function PaymentCard() {
function PaymentCard(props) {
return ( return (
<Card > <>
<Row className="mx-1"> {props.cart.map((e) => (
<Col className="text-center"> <Card>
<Card.Img className="img-fluid" variant="top" src="img/asd.jpg" style={{ width: '20rem' }} /> <Row className="mx-1">
</Col> <Col className="text-center">
<Col md={6} className="p-2"> <Card.Img className="img-fluid" variant="top" src={e.productId.main_imgUrl && `/images/${e.productId.main_imgUrl}`} style={{ width: '20rem' }} />
<Card.Body> </Col>
<input type="image" alt="삭제버튼" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right" onClick={deleteCart} /> <Col md={6} className="p-2">
<Card.Title className="font-weight-bold mt-3">제품명</Card.Title> <Card.Body>
<Card.Text>가격</Card.Text> <Card.Title className="font-weight-bold mt-3">{e.productId.pro_name}</Card.Title>
<Card.Text>옵션</Card.Text> <Card.Text>가격: {e.productId.price}</Card.Text>
<Card.Text>수량</Card.Text> <Card.Text>옵션: {e.size}/{e.color}</Card.Text>
<div> <Card.Text>수량: {e.count}</Card.Text>
<input type="image" alt="마이너스" src="https://img.icons8.com/ios-glyphs/20/000000/minus-math.png" className="align-middle" onClick={minusNum} /> </Card.Body>
<input type="text" style={{ width: '30px' }} className="text-center align-middle mx-1" placeholder="1" value={num} readOnly></input> </Col>
<input type="image" alt="플러스" src="https://img.icons8.com/ios-glyphs/20/000000/plus-math.png" className="align-middle" onClick={plusNum} /> </Row>
</div> </Card>
</Card.Body> ))
</Col> }
</Row> </>
</Card>
) )
} }
......
import axios from 'axios';
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import DaumPostcode from "react-daum-postcode"; import DaumPostcode from "react-daum-postcode";
import { Container, Card, Row, Col, Button, Form, FormGroup } from 'react-bootstrap'; import { Container, Card, Row, Col, Button, Form, FormGroup } from 'react-bootstrap';
import { Redirect } from 'react-router-dom'; import { Redirect } from 'react-router-dom';
import PaymentCard from '../Components/PaymentCard';
import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors';
function Payment() { function Payment({ match, location }) {
const [cart, setCart] = useState(location.state)
const [order, setOrder] = useState({products: location.state})
const [userData, setUserData] = useState({})
const [error, setError] = useState()
const [paymentWay, setPaymentWay] = useState([]) const [paymentWay, setPaymentWay] = useState([])
const [isAddress, setIsAddress] = useState(""); // const [isAddress, setIsAddress] = useState("");
const [isZoneCode, setIsZoneCode] = useState(); // const [isZoneCode, setIsZoneCode] = useState();
const [isPostOpen, setIsPostOpen] = useState(); // const [isPostOpen, setIsPostOpen] = useState();
const [post, setPost] = useState([]) const [post, setPost] = useState([])
const [redirect, setRedirect] = useState(null) const [redirect, setRedirect] = useState(null)
const [address, setAddress] = useState("") const [address, setAddress] = useState("")
const [finalPrice, setFinalPrice] = useState(0)
const [num, setNum] = useState(0) const [num, setNum] = useState(0)
const user = isAuthenticated()
useEffect(() => {
getUser()
let price = 0
cart.map((el) => {
price = Number(el.count) * Number(el.productId.price) + price
})
setFinalPrice(price)
}, [user])
async function getUser() {
try {
const response = await axios.get(`/api/users/getuser/${user}`)
console.log(response.data)
setUserData(response.data)
} catch (error) {
catchErrors(error, setError)
}
}
function handleReceiverInfo(e) {
const { name, value } = e.target
console.log(name,value)
setOrder({ ...order, receiverInfo: {...order.receiverInfo, [name]: value } })
}
function postClick() { function postClick() {
if (post.length !== 0) { if (post.length !== 0) {
...@@ -42,8 +77,8 @@ function Payment() { ...@@ -42,8 +77,8 @@ function Payment() {
} }
fullAddress += extraAddress !== "" ? ` (${extraAddress})` : ""; fullAddress += extraAddress !== "" ? ` (${extraAddress})` : "";
} }
setAddress({ full: fullAddress, zone: data.zonecode }); setAddress({ full: fullAddress, code: data.zonecode });
setOrder({ ...order, receiverInfo: {...order.receiverInfo, address: fullAddress, postalCode: data.zonecode } })
console.log(fullAddress); console.log(fullAddress);
} }
...@@ -89,12 +124,6 @@ function Payment() { ...@@ -89,12 +124,6 @@ function Payment() {
} }
} }
function handleClick2() {
if (paymentWay.length !== 0) {
setPaymentWay([])
}
}
async function kakaopay() { async function kakaopay() {
const response = await fetch('/api/kakaopay/test/single', { const response = await fetch('/api/kakaopay/test/single', {
method: "POST", method: "POST",
...@@ -121,22 +150,21 @@ function Payment() { ...@@ -121,22 +150,21 @@ function Payment() {
// setRedirect(data.redirect_url) // setRedirect(data.redirect_url)
} }
function plusNum() { async function paymentCompleted(){
setNum(num + 1) console.log(user)
} console.log(order)
function minusNum() { console.log(finalPrice)
if (num === 0) { try {
setNum(0) const response = await axios.post(`/api/order/addorder`, {
} userId : user,
else { ...order,
setNum(num - 1) total : finalPrice+2500
})
console.log(response.data)
} catch (error) {
catchErrors(error, setError)
} }
} }
function deleteCart() {
//장바구니 DB에서 해당 항목 삭제
console.log('카트에 담긴 항목을 삭제했습니다.')
}
if (redirect) { if (redirect) {
console.log(redirect) console.log(redirect)
...@@ -145,6 +173,7 @@ function Payment() { ...@@ -145,6 +173,7 @@ function Payment() {
return ( return (
<div> <div>
{/* {console.log(order)} */}
<Container> <Container>
<h3 className="my-5 font-weight-bold text-center">주문/결제</h3> <h3 className="my-5 font-weight-bold text-center">주문/결제</h3>
<div> <div>
...@@ -154,15 +183,15 @@ function Payment() { ...@@ -154,15 +183,15 @@ function Payment() {
<Form> <Form>
<Form.Group controlId="formBasicName"> <Form.Group controlId="formBasicName">
<Form.Label>이름</Form.Label> <Form.Label>이름</Form.Label>
<Form.Control type="text" placeholder="윤지원" /> <Form.Control type="text" value={userData.name} readOnly />
</Form.Group>
<Form.Group controlId="formBasicEmail">
<Form.Label>이메일</Form.Label>
<Form.Control type="email" placeholder="jiwon5393@naver.com" />
</Form.Group> </Form.Group>
<Form.Group controlId="formBasicTel"> <Form.Group controlId="formBasicTel">
<Form.Label>휴대전화</Form.Label> <Form.Label>휴대전화</Form.Label>
<Form.Control type="tel" placeholder="010-0000-0000" /> <Form.Control type="tel" value={userData.tel} readOnly />
</Form.Group>
<Form.Group controlId="formBasicEmail">
<Form.Label>이메일</Form.Label>
<Form.Control type="email" placeholder="이메일 주소를 입력해주세요" />
</Form.Group> </Form.Group>
</Form> </Form>
</Col> </Col>
...@@ -176,13 +205,17 @@ function Payment() { ...@@ -176,13 +205,17 @@ function Payment() {
<Form> <Form>
<Form.Group> <Form.Group>
<Form.Label>이름</Form.Label> <Form.Label>이름</Form.Label>
<Form.Control></Form.Control> <Form.Control type="text" name="name" onChange={handleReceiverInfo}></Form.Control>
</Form.Group>
<Form.Group>
<Form.Label>휴대전화</Form.Label>
<Form.Control type="text" name="tel" onChange={handleReceiverInfo}></Form.Control>
</Form.Group> </Form.Group>
<Form.Group controlId="formBasicAdd"> <Form.Group controlId="formBasicAdd">
<Form.Label>주소</Form.Label> <Form.Label>주소</Form.Label>
<Form.Row> <Form.Row>
<Col xs={4} sm={4}> <Col xs={4} sm={4}>
<Form.Control type="text" id="add" value={address.zone} disabled={(address.zone == null) ? false : true} placeholder="우편번호" required ></Form.Control> <Form.Control type="text" name="postalCode" id="add" onChange={handleReceiverInfo} value={address.code} disabled={(address.code == null) ? false : true} placeholder="우편번호" required ></Form.Control>
</Col> </Col>
<Col > <Col >
<Button style={{ background: '#91877F', borderColor: '#91877F' }} className="mx-1" onClick={postClick}>우편번호</Button> <Button style={{ background: '#91877F', borderColor: '#91877F' }} className="mx-1" onClick={postClick}>우편번호</Button>
...@@ -191,16 +224,12 @@ function Payment() { ...@@ -191,16 +224,12 @@ function Payment() {
</Form.Row> </Form.Row>
<Form.Row> <Form.Row>
<Col> <Col>
<Form.Control type="text" id="add1" value={address.full} disabled={(address.zone == null) ? false : true} placeholder="주소" required></Form.Control> <Form.Control type="text" name="address" id="add1" onChange={handleReceiverInfo} value={address.full} disabled={(address.code == null) ? false : true} placeholder="주소" required></Form.Control>
<Form.Control type="text" id="add2" placeholder="상세주소" required></Form.Control> <Form.Control type="text" name="address2" id="add2" onChange={handleReceiverInfo} placeholder="상세주소" required></Form.Control>
<Form.Control.Feedback type="invalid" > 상세 주소를 입력하세요. </Form.Control.Feedback> <Form.Control.Feedback type="invalid" > 상세 주소를 입력하세요. </Form.Control.Feedback>
</Col> </Col>
</Form.Row> </Form.Row>
</Form.Group> </Form.Group>
<Form.Group>
<Form.Label>휴대전화</Form.Label>
<Form.Control></Form.Control>
</Form.Group>
</Form> </Form>
</Col> </Col>
</Row> </Row>
...@@ -208,42 +237,22 @@ function Payment() { ...@@ -208,42 +237,22 @@ function Payment() {
<div> <div>
<h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h5> <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h5>
<Card > <PaymentCard cart={cart} />
<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>
</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>
...@@ -256,7 +265,7 @@ function Payment() { ...@@ -256,7 +265,7 @@ function Payment() {
{paymentWay} {paymentWay}
</div> </div>
<div className="text-center"> <div className="text-center">
<Button className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} href="/account" block>결제완료</Button> <Button className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} onClick={paymentCompleted} block>결제완료</Button>
</div> </div>
</Container> </Container>
</div> </div>
......
import axios from 'axios'; import axios from 'axios';
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { Row, Col, Form, Card, Button } from 'react-bootstrap'; import { Row, Col, Form, Card, Button } from 'react-bootstrap';
import { Redirect } from 'react-router-dom';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
const preCart = []
function Product({ match, location }) { function Product({ match, location }) {
const [product, setProduct] = useState(location.state) const [product, setProduct] = useState(location.state)
const [cart, setCart] = useState(location.state) const [color, setColor] = useState("")
const [size, setSize] = useState("")
const [cart, setCart] = useState([])
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 [count, setCount] = useState(1)
const [price, setPrice] = useState(0) const [price, setPrice] = useState(0)
useEffect(() => { useEffect(() => {
if (selected.sizes === true && selected.colors === true) { if (size && color) {
pushOptions() pushOptions()
console.log(preCart) console.log(cart)
} }
}, [cart]) }, [size, color])
function handleClick(e) { function handleClick(e) {
...@@ -26,79 +29,68 @@ function Product({ match, location }) { ...@@ -26,79 +29,68 @@ function Product({ match, location }) {
} }
function pushOptions() { function pushOptions() {
preCart.push(cart) setCart([...cart, { color, size, productId: product.id }])
selected.sizes = false selected.sizes = false
selected.colors = false selected.colors = false
setPrice(product.price+price) setColor("")
setSize("")
setPrice(product.price + price)
} }
function handleChange(e) { function handleChange(e) {
const { name, value } = e.target const { name, value } = e.target
if (e.target.name === "sizes") { if (name === "sizes") {
setCart({ ...cart, [name]: value }) setSize(value)
selected.sizes = true selected.sizes = true
} else if (e.target.name === "colors") { } else if (name === "colors") {
setCart({ ...cart, [name]: value }) setColor(value)
selected.colors = true selected.colors = true
} }
// setCart({ ...cart, [name]: value })
// handleCreate()
} }
function listDelete(e) { function deleteOption(e) {
e.preventDefault() e.preventDefault()
const parent = e.target.parentNode const asd = cart.filter((el) => el.color !== e.target.id || el.size !== e.target.name)
parent.remove() setCart(asd)
} }
function handleCreate() { function handleCount(e) {
// if (product !== undefined) { e.preventDefault()
// if (product.colors !== "" && product.sizes !== "") { const addCount = cart.map((el)=>{
// cart.push( if(el.color !== e.target.id || el.size !== e.target.name){
// <div className="d-flex justify-content-between my-2" > return {el}
// <p>{product.color} {product.size} </p> } else {
// <input name="count" type="number" min="0" max="10" style="width: 40px" onChange={handleChange} /> return {...el, count : e.target.value}
// <p style="margin-bottom: 0px">{product.price}</p> }
// </div> })
// ) setCart(addCount)
// const list = document.getElementById('list') setCount(e.value)
// list.style.borderBottom = "1px solid"
// const shopping = document.createElement('div')
// shopping.className = "d-flex justify-content-between my-2"
// shopping.innerHTML = `${product.color} / ${product.size}
// <input type="number" min="0" max="10" value="1" style="width: 40px" />
// <p style="margin-bottom: 0px">14,000원</p>`
// const deleteA = document.createElement('a')
// deleteA.innerText = 'X'
// deleteA.addEventListener('click', listDelete)
// shopping.appendChild(deleteA)
// list.appendChild(shopping)
// }
// }
} }
async function addCart() { async function addCart() {
// preCart(color, size, count), productId(productlist에서 props), userId(로컬) 를 보내줌 console.log(cart)
try { if (localStorage.getItem('id')) {
setError('') // preCart(color, size, count), productId(productlist에서 props), userId(로컬) 를 보내줌
const response = await axios.put('/api/cart/addcart', { try {
userId: localStorage.getItem('loginStatus'), setError('')
productId: "a8f4d63ead77717f940a2b27deb707a6", const response = await axios.put('/api/cart/addcart', {
products: preCart userId: localStorage.getItem('id'),
}) products: cart
console.log(response) })
} catch (error) { console.log(response)
catchErrors(error, setError) } catch (error) {
catchErrors(error, setError)
}
} else {
alert("로그인을 해주세요.")
return <Redirect to='/login' />
} }
} }
// useEffect(() => {
// handleCreate()
// }, [product])
return ( return (
<div> <div>
{console.log("match=",match.params, "location=",location.state, "product=",product)} {/* {console.log("match=", match.params, "location=", location.state, "product=", product)} */}
<style type="text/css"> <style type="text/css">
{` {`
.btn { .btn {
...@@ -122,29 +114,37 @@ function Product({ match, location }) { ...@@ -122,29 +114,37 @@ function Product({ match, location }) {
<Form style={{ borderBottom: "1px solid" }}> <Form style={{ borderBottom: "1px solid" }}>
<Form.Group style={{ borderBottom: "1px solid", paddingBottom: "2rem" }}> <Form.Group style={{ borderBottom: "1px solid", paddingBottom: "2rem" }}>
<Form.Label>색상</Form.Label> <Form.Label>색상</Form.Label>
<Form.Control as="select" className="mb-2" name="colors" defaultValue="옵션 선택" onChange={handleChange}> <Form.Control as="select" className="mb-2" name="colors" value={color} defaultValue="옵션 선택" onChange={handleChange}>
<option>옵션선택</option> <option>옵션선택</option>
{product.colors.map((e) => ( {product.colors.map((e) => (
<option>{e}</option> <option>{e}</option>
))} ))}
</Form.Control> </Form.Control>
<Form.Label>사이즈</Form.Label> <Form.Label>사이즈</Form.Label>
<Form.Control as="select" className="mb-2" name="sizes" defaultValue="옵션 선택" onChange={handleChange}> <Form.Control as="select" className="mb-2" name="sizes" value={size} defaultValue="옵션 선택" onChange={handleChange}>
<option>옵션선택</option> <option>옵션선택</option>
{product.sizes.map((e) => ( {product.sizes.map((e) => (
<option>{e}</option> <option>{e}</option>
))} ))}
</Form.Control> </Form.Control>
</Form.Group> </Form.Group>
{preCart.map((e) => ( {cart.map((e) => (
<div>{e.colors}/{e.sizes}</div> <div>
<span>{e.color}/{e.size}</span>
<input onClick={deleteOption} id={e.color} name={e.size} type="image" alt="삭제버튼" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right align-middle" />
<span>{e.price}</span>
<span className="float-right mx-2">
<input type='number' id={e.color} name={e.size} onChange={handleCount} value={count} style={{ width: '3rem' }} className="text-center" />
</span>
</div>
))} ))}
<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">{price}</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 type='button' onClick={addCart} style={{ width: "49%" }}>장바구니</Button>
<Button style={{ width: "49%" }}>구매하기</Button> <Button style={{ width: "49%" }}>구매하기</Button>
</Row> </Row>
</Form> </Form>
......
...@@ -50,13 +50,6 @@ function ProductsRegist() { ...@@ -50,13 +50,6 @@ function ProductsRegist() {
isProduct ? setDisabled(false) : setDisabled(true) isProduct ? setDisabled(false) : setDisabled(true)
}, [product]) }, [product])
function handleKeyPress(e) {
if (e.key === "Enter") {
addColor()
e.preventDefault()
}
}
function addCategory(e) { function addCategory(e) {
if (selectRef.current.value === '') { if (selectRef.current.value === '') {
alert('하위 분류를 반드시 선택해 주세요.') alert('하위 분류를 반드시 선택해 주세요.')
...@@ -138,11 +131,17 @@ function ProductsRegist() { ...@@ -138,11 +131,17 @@ function ProductsRegist() {
} }
} }
product["sizes"] = sizes product["sizes"] = sizes
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" || key === "detail_image") {
formData.append(key, product[key][0]) formData.append(key, product[key][0])
} else { } else if(key === "sizes" || key === "colors"){
for (let i = 0; i < product[key].length ; i++){
formData.append([key], product[key][i])
}
}
else {
formData.append(key, product[key]) formData.append(key, product[key])
} }
} }
...@@ -240,7 +239,7 @@ function ProductsRegist() { ...@@ -240,7 +239,7 @@ function ProductsRegist() {
<Form.Label>색상</Form.Label> <Form.Label>색상</Form.Label>
<Row> <Row>
<Col md={10}> <Col md={10}>
<Form.Control as="input" ref={colorRef} name="colors" placeholder="색상" onChange={handleColor} onKeyPress={handleKeyPress} /> <Form.Control as="input" ref={colorRef} name="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>
......
...@@ -7,50 +7,80 @@ import { isAuthenticated } from '../utils/auth' ...@@ -7,50 +7,80 @@ import { isAuthenticated } from '../utils/auth'
import CartCard from '../Components/CartCard'; import CartCard from '../Components/CartCard';
function ShoppingCart() { function ShoppingCart() {
const [num, setNum] = useState()
const [error, setError] = useState('') const [error, setError] = useState('')
const [cart, setCart] = useState([]) const [cart, setCart] = useState([])
const [finalCart, setFinalCart] = useState([])
const [finalPrice, setFinalPrice] = useState(0) const [finalPrice, setFinalPrice] = useState(0)
const user = isAuthenticated() const user = isAuthenticated()
useEffect(() => { useEffect(() => {
getCart() getCart()
console.log(cart)
}, [user]) }, [user])
function plusNum() { function plusNum(e) {
num = num + 1 const addCount = cart.map((el) => {
setNum(num + 1) if (el._id === e.target.name) {
return { ...el, count: el.count+1}
} else {
return { ...el }
}
})
setCart(addCount)
} }
function minusNum() { function minusNum(e) {
if (num === 0) { const addCount = cart.map((el) => {
setNum(0) if (el._id === e.target.name) {
} return { ...el, count: el.count-1 }
else { } else {
setNum(num - 1) return { ...el }
} }
})
setCart(addCount)
}
function checkedCart(e) {
let price = 0
const cartCheck = cart.map((el) => {
if (el._id === e.target.name) {
return { ...el, checked: !el.checked }
} else {
return { ...el }
}
})
const asd = cartCheck.filter((el) => el.checked === true)
asd.map((el)=>{
price = el.count*el.productId.price + price
})
setFinalPrice(price)
setCart(cartCheck)
setFinalCart(asd)
} }
async function deleteCart(e) { async function deleteCart(e) {
//장바구니 DB에서 해당 항목 삭제 //장바구니 DB에서 해당 항목 삭제
console.log(e.target.name) console.log(e.target.name)
try { try {
const response = await axios.post('/api/cart/deletecart', { cartId: e.target.name }) const response = await axios.post('/api/cart/deletecart', {
userId: user,
cartId: e.target.name
})
console.log(response.data) console.log(response.data)
setCart(response.data.products)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
console.log('카트에 담긴 항목을 삭제했습니다.') console.log('카트에 담긴 항목을 삭제했습니다.')
} }
async function getCart() { async function getCart() {
try { try {
const response = await axios.get(`/api/cart/showcart/${user}`) const response = await axios.get(`/api/cart/showcart/${user}`)
console.log(response.data) const addChecked = response.data.map((el) => {
setCart(response.data) return { ...el, checked: false }
const finalPrices = response.data.map((e) => {
return e.count * e.productId.price
}) })
setFinalPrice(finalPrices.reduce((a, b) => (a + b))) console.log("addchecked=",addChecked)
setCart(addChecked)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
...@@ -62,8 +92,8 @@ function ShoppingCart() { ...@@ -62,8 +92,8 @@ function ShoppingCart() {
<h1 className="my-5 font-weight-bold text-center">장바구니</h1> <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.length >0 {cart.length > 0
? <CartCard cart={cart} deleteCart={deleteCart} minusNum={minusNum} plusNum={plusNum} num={num} /> ? <CartCard cart={cart} deleteCart={deleteCart} minusNum={minusNum} plusNum={plusNum} checkedCart={checkedCart} />
: <div className="text-center my-5">장바구니에 담긴 상품이 없습니다.</div>} : <div className="text-center my-5">장바구니에 담긴 상품이 없습니다.</div>}
</div> </div>
...@@ -84,9 +114,9 @@ function ShoppingCart() { ...@@ -84,9 +114,9 @@ function ShoppingCart() {
</div> </div>
<div className="text-center"> <div className="text-center">
<Button as={Link} to={{ <Button as={Link} to={{
pathname: `/payment`, pathname: `/payment`,
state: { cart } state: finalCart
}} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} block>결제하기</Button> }} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} block>결제하기</Button>
</div> </div>
</Container> </Container>
......
...@@ -9,6 +9,7 @@ import path from 'path' ...@@ -9,6 +9,7 @@ import path from 'path'
import kakaopayRoutes from './routes/kakaopay.routes.js' import kakaopayRoutes from './routes/kakaopay.routes.js'
import config from './config.js' import config from './config.js'
import authRouter from './routes/auth.routes.js' import authRouter from './routes/auth.routes.js'
import orderRouter from './routes/order.routes.js'
import cors from 'cors' import cors from 'cors'
fs.readdir('uploads', (error) => { fs.readdir('uploads', (error) => {
...@@ -33,6 +34,7 @@ app.use('/api/users',userRouter) ...@@ -33,6 +34,7 @@ app.use('/api/users',userRouter)
app.use('/api/auth',authRouter) app.use('/api/auth',authRouter)
app.use('/api/product', productRouter) app.use('/api/product', productRouter)
app.use('/api/cart', cartRouter) app.use('/api/cart', cartRouter)
app.use('/api/order', orderRouter)
app.listen(config.port, () => { app.listen(config.port, () => {
console.info('Server started on port %s.', config.port) console.info('Server started on port %s.', config.port)
......
...@@ -6,7 +6,7 @@ const addcart = async (req, res) => { ...@@ -6,7 +6,7 @@ const addcart = async (req, res) => {
const cart = await Cart.findOne({ userId: userId }) const cart = await Cart.findOne({ userId: userId })
await Cart.updateOne( await Cart.updateOne(
{ _id: cart._id }, { _id: cart._id },
{$set: {products: products}} {$push: {products: products}}
) )
res.status(200).send('카트에 저장되었습니다.') res.status(200).send('카트에 저장되었습니다.')
} catch (error) { } catch (error) {
...@@ -30,10 +30,18 @@ const showcart = async (req, res) => { ...@@ -30,10 +30,18 @@ const showcart = async (req, res) => {
const deletecart = async (req, res) => { const deletecart = async (req, res) => {
console.log(req.body) console.log(req.body)
const { cartId } = req.body const { userId,cartId } = req.body
try { try {
await Cart.deleteOne({ _id: cartId }) const cart = await Cart.findOneAndUpdate(
res.send("삭제완료") { userId: userId },
{ $pull: { products: {_id:cartId} } },
{ new: true }
).populate({
path: 'products.productId',
model: 'Product'
})
// res.send("삭제완료")
res.json(cart)
} catch (error) { } catch (error) {
console.log(error) console.log(error)
res.status(500).send('해당 카트를 삭제하지 못했습니다.') res.status(500).send('해당 카트를 삭제하지 못했습니다.')
......
import Order from "../schemas/Order.js";
const addorder = async (req, res) => {
const { userId, products, receiverInfo, total } = req.body
try {
const newOrder = await new Order({
userId, products, receiverInfo, total
}).save()
res.status(200).send('Order DB에 저장 완료')
} catch (error) {
console.log(error)
res.status(500).send('Order DB에 저장 실패')
}
}
const showorder = async (req, res) => {
try {
const order = await Order.findOne({ userId: req.id }).populate({
path: 'products.productId',
model: 'Product'
})
res.status(200).json(order.products)
} catch (error) {
console.log(error)
res.status(500).send('쇼핑카트를 불러오지 못했습니다.')
}
}
export default { addorder, showorder }
\ No newline at end of file
...@@ -92,4 +92,4 @@ const subcategoryId = async (req, res, next, subcategory) => { ...@@ -92,4 +92,4 @@ const subcategoryId = async (req, res, next, subcategory) => {
} }
} }
export default { imageUpload, regist, getToHome, getAll, categoryId, getlist, subcategoryId, subgetlist } export default { imageUpload, regist, getToHome, getAll, categoryId, getlist, subcategoryId, subgetlist }
\ No newline at end of file
...@@ -31,9 +31,7 @@ const userById = async (req, res, next, id) => { ...@@ -31,9 +31,7 @@ const userById = async (req, res, next, id) => {
const signup = async (req, res) => { const signup = async (req, res) => {
const { name, number1, number2, id, password, tel } = req.body
const { name, number1, number2, id, password, tel } = req.body
console.log(req.body) console.log(req.body)
try { try {
if (!isLength(password, { min: 8, max: 15 })) { if (!isLength(password, { min: 8, max: 15 })) {
...@@ -54,7 +52,7 @@ const signup = async (req, res) => { ...@@ -54,7 +52,7 @@ const signup = async (req, res) => {
password: hash, password: hash,
tel, tel,
}).save() }).save()
await new Cart({ userId: newUser._id,role}).save() await new Cart({ userId: newUser._id, role }).save()
console.log(newUser) console.log(newUser)
res.json(newUser) res.json(newUser)
...@@ -79,7 +77,7 @@ const update = async (req, res) => { ...@@ -79,7 +77,7 @@ const update = async (req, res) => {
const updateUser = await user.save() const updateUser = await user.save()
res.json(updateUser) res.json(updateUser)
} }
} catch (error) { } catch (error) {
console.log(error); console.log(error);
res.status(500).send('이미지 업데이트 실패') res.status(500).send('이미지 업데이트 실패')
......
import express from "express";
import orderCtrl from '../controllers/order.controller.js';
const router = express.Router()
router.route('/addorder')
.post(orderCtrl.addorder)
// .get()
router.route('/showorder/:userId')
.get(orderCtrl.showorder)
export default router
\ No newline at end of file
...@@ -10,8 +10,6 @@ router.route('/account/:userId') ...@@ -10,8 +10,6 @@ router.route('/account/:userId')
.get(userCtrl.username) .get(userCtrl.username)
.put(userCtrl.imgUpload, userCtrl.update) .put(userCtrl.imgUpload, userCtrl.update)
router.param('userId', userCtrl.userById) router.param('userId', userCtrl.userById)
export default router export default router
\ No newline at end of file
...@@ -17,10 +17,10 @@ const CartSchema = new mongoose.Schema({ ...@@ -17,10 +17,10 @@ const CartSchema = new mongoose.Schema({
type: ObjectId, type: ObjectId,
ref: 'Product' ref: 'Product'
}, },
sizes: { size: {
type: String type: String
}, },
colors: { color: {
type: String type: String
} }
} }
......
import mongoose from 'mongoose'
const { ObjectId, Number, String } = mongoose.Schema.Types
const OrderSchema = new mongoose.Schema({
userId: {
type: ObjectId,
ref: 'User'
},
products: [
{
productId: {
type: ObjectId,
ref: 'Product'
},
count: {
type: Number,
required: true
},
size: {
type: String,
required: true
},
color: {
type: String,
required: true
}
}
],
receiverInfo:
{
name: {
type:String,
required:true
},
tel: {
type: String,
required:true
},
postalCode:{
type:String,
required:true
},
address: {
type: String,
required: true
},
address2: {
type: String,
required: true
}
}
,
total: {
type: Number,
required: true
}
}, {
timestamps: true
})
export default mongoose.models.Order || mongoose.model('Order', OrderSchema)
\ No newline at end of file
import mongoose from 'mongoose' import mongoose from 'mongoose'
const { String, Number } = mongoose.Schema.Types const { String, Array, Number } = mongoose.Schema.Types
const ProductSchema = new mongoose.Schema({ const ProductSchema = new mongoose.Schema({
pro_name: { pro_name: {
...@@ -33,7 +33,7 @@ const ProductSchema = new mongoose.Schema({ ...@@ -33,7 +33,7 @@ const ProductSchema = new mongoose.Schema({
required: true, required: true,
}, },
sub_category: { sub_category: {
type: [String], type: Array,
required: true, required: true,
}, },
description: { description: {
...@@ -45,7 +45,7 @@ const ProductSchema = new mongoose.Schema({ ...@@ -45,7 +45,7 @@ const ProductSchema = new mongoose.Schema({
required: true required: true
}, },
detail_imgUrls: { detail_imgUrls: {
type: [String] type: Array
} }
}, { }, {
timestamps: true timestamps: true
......
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