Commit 708a8aaf authored by 이재연's avatar 이재연
Browse files

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

parents aa87bd28 7953e3c1
...@@ -2,8 +2,6 @@ import React from 'react' ...@@ -2,8 +2,6 @@ import React from 'react'
import { Card, Button, Container, Row, Col } from 'react-bootstrap'; import { Card, Button, Container, Row, Col } from 'react-bootstrap';
function CartCard(props) { function CartCard(props) {
return ( return (
<> <>
{props.cart.map((e) => ( {props.cart.map((e) => (
...@@ -13,13 +11,13 @@ function CartCard(props) { ...@@ -13,13 +11,13 @@ 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.main_image && `/images/${e.main_image}`} style={{ width: '20rem' }} /> <Card.Img className="img-fluid" variant="top" src={e.productId.main_image && `/images/${e.productId.main_image}`} 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.pro_name}</Card.Title> <Card.Title className="font-weight-bold mt-3">{e.productId.pro_name}</Card.Title>
<Card.Text>가격: {e.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>
<Card.Text>수량</Card.Text> <Card.Text>수량</Card.Text>
<div> <div>
......
...@@ -6,18 +6,29 @@ import catchErrors from '../utils/catchErrors'; ...@@ -6,18 +6,29 @@ import catchErrors from '../utils/catchErrors';
const INIT_PRODUCT = { const INIT_PRODUCT = {
pro_name: '스키니진', pro_name: '스키니진',
price: 12000, price: 12000,
count:1, count: 1,
main_category: 'PANTS', main_category: 'PANTS',
sub_category: ['SKINNY JEANS'], sub_category: ['SKINNY JEANS'],
sizes: [ 'L', 'M'], sizes: ['L', 'M'],
colors: ['연청', '진청'], colors: ['연청', '진청'],
main_image: "a8f4d63ead77717f940a2b27deb707a6" main_image: "a8f4d63ead77717f940a2b27deb707a6",
productId:"5ffda03428faf35de8319360"
} }
const preCart = []
function Product() { function Product() {
const [product, setProduct] = useState(INIT_PRODUCT) const [product, setProduct] = useState(INIT_PRODUCT)
const [cart, setCart] = useState(INIT_PRODUCT) const [cart, setCart] = useState(INIT_PRODUCT)
const [error, setError] = useState('') const [error, setError] = useState('')
const [selected, setSelected] = useState({ sizes: false, colors: false })
const [n, setN] = useState(1)
useEffect(() => {
if (selected.sizes === true && selected.colors === true) {
pushOptions()
console.log(preCart)
}
}, [cart])
function handleClick(e) { function handleClick(e) {
...@@ -25,10 +36,24 @@ function Product() { ...@@ -25,10 +36,24 @@ function Product() {
box.style.display = "none" box.style.display = "none"
} }
function pushOptions() {
preCart.push(cart)
selected.sizes = false
selected.colors = false
setN(n+1)
}
function handleChange(e) { function handleChange(e) {
const { name, value } = e.target const { name, value } = e.target
if (e.target.name === "sizes") {
setCart({ ...cart, [name]: value })
selected.sizes = true
} else if (e.target.name === "colors") {
setCart({ ...cart, [name]: value })
selected.colors = true
}
// setCart({ ...cart, [name]: value })
// handleCreate() // handleCreate()
setCart({ ...cart, [name]: value })
} }
function listDelete(e) { function listDelete(e) {
...@@ -39,29 +64,29 @@ function Product() { ...@@ -39,29 +64,29 @@ function Product() {
function handleCreate() { function handleCreate() {
console.log("실행", "cart=", product) console.log("실행", "cart=", product)
if (product !== undefined) { // if (product !== undefined) {
if (product.colors !== "" && product.sizes !== "") { // if (product.colors !== "" && product.sizes !== "") {
cart.push( // cart.push(
<div className="d-flex justify-content-between my-2" > // <div className="d-flex justify-content-between my-2" >
<p>{product.color} {product.size} </p> // <p>{product.color} {product.size} </p>
<input name="count" type="number" min="0" max="10" style="width: 40px" onChange={handleChange} /> // <input name="count" type="number" min="0" max="10" style="width: 40px" onChange={handleChange} />
<p style="margin-bottom: 0px">{product.price}</p> // <p style="margin-bottom: 0px">{product.price}</p>
</div> // </div>
) // )
// const list = document.getElementById('list') // const list = document.getElementById('list')
// list.style.borderBottom = "1px solid" // list.style.borderBottom = "1px solid"
// const shopping = document.createElement('div') // const shopping = document.createElement('div')
// shopping.className = "d-flex justify-content-between my-2" // shopping.className = "d-flex justify-content-between my-2"
// shopping.innerHTML = `${product.color} / ${product.size} // shopping.innerHTML = `${product.color} / ${product.size}
// <input type="number" min="0" max="10" value="1" style="width: 40px" /> // <input type="number" min="0" max="10" value="1" style="width: 40px" />
// <p style="margin-bottom: 0px">14,000원</p>` // <p style="margin-bottom: 0px">14,000원</p>`
// const deleteA = document.createElement('a') // const deleteA = document.createElement('a')
// deleteA.innerText = 'X' // deleteA.innerText = 'X'
// deleteA.addEventListener('click', listDelete) // deleteA.addEventListener('click', listDelete)
// shopping.appendChild(deleteA) // shopping.appendChild(deleteA)
// list.appendChild(shopping) // list.appendChild(shopping)
} // }
} // }
} }
async function addCart() { async function addCart() {
...@@ -69,8 +94,9 @@ function Product() { ...@@ -69,8 +94,9 @@ function Product() {
try { try {
// setError('') // setError('')
const response = await axios.put('/api/cart/addcart', { const response = await axios.put('/api/cart/addcart', {
count: cart.count, userId: localStorage.getItem('loginStatus'),
productId: "5ffd153b41bada58d8b12d92", productId: "a8f4d63ead77717f940a2b27deb707a6",
products: preCart
}) })
console.log(response) console.log(response)
} catch (error) { } catch (error) {
...@@ -124,8 +150,9 @@ function Product() { ...@@ -124,8 +150,9 @@ function Product() {
))} ))}
</Form.Control> </Form.Control>
</Form.Group> </Form.Group>
{/* {cart.map((e)=>(<div>{e}</div> {preCart.map((e) => (
))} */} <div>{e.colors}/{e.sizes}</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">14,000</Col> <Col className="text-right">14,000</Col>
......
...@@ -6,21 +6,12 @@ import catchErrors from '../utils/catchErrors'; ...@@ -6,21 +6,12 @@ import catchErrors from '../utils/catchErrors';
import { isAuthenticated } from '../utils/auth' import { isAuthenticated } from '../utils/auth'
import CartCard from '../Components/CartCard'; import CartCard from '../Components/CartCard';
const INIT_PRODUCT = [{ function ShoppingCart() {
pro_name: '체크셔츠',
price: 21000,
count: 1,
main_category: 'TOP',
sub_category: ['SHIRT'],
sizes: ['XL', 'L', 'M', 'S'],
colors: ['베이지', '블랙', '카키'],
main_image: 'e46b641ae11e6568c86f689d3dce7748'
}]
function ShoppingCart() { function ShoppingCart() {
const [num, setNum] = useState(0) const [num, setNum] = useState(0)
const [error, setError] = useState('') const [error, setError] = useState('')
const [cart, setCart] = useState(INIT_PRODUCT) const [cart, setCart] = useState()
const user = isAuthenticated() const user = isAuthenticated()
useEffect(() => { useEffect(() => {
...@@ -72,7 +63,7 @@ function ShoppingCart() { ...@@ -72,7 +63,7 @@ function ShoppingCart() {
<h3 className="my-5 font-weight-bold text-center">장바구니</h3> <h3 className="my-5 font-weight-bold text-center">장바구니</h3>
<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>
<CartCard cart={cart} deleteCart={deleteCart} minusNum={minusNum} plusNum={plusNum} num={num} /> {cart?<CartCard cart={cart} deleteCart={deleteCart} minusNum={minusNum} plusNum={plusNum} num={num} />:<div></div>}
</div> </div>
<div className="p-5 m-5" style={{ background: '#F7F3F3' }}> <div className="p-5 m-5" style={{ background: '#F7F3F3' }}>
......
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) // console.log(req.body)
const { count, productId } = req.body const { userId, products} = req.body
try { try {
const newProduct = { count, product: productId } const cart = await Cart.findOne({ userId: userId })
await Cart.findOneAndUpdate( console.log(cart)
// const newProduct = { products: products }
// const newProduct = {...newProduct}
// console.log(newProduct)
console.log(products)
await Cart.updateOne(
{ _id: cart._id }, { _id: cart._id },
{ $addToSet: { products: newProduct } } // { $addToSet: { products: newProduct } }
{$set: {products: products}}
) )
res.json(newCart) res.status(200).send('Cart updated')
} catch (error) { } catch (error) {
console.log(error) console.log(error)
res.status(500).send('죄송합니다. 다시 입력해 주십시오.') res.status(500).send('죄송합니다. 다시 입력해 주십시오.')
...@@ -18,15 +25,15 @@ const addcart = async (req, res) => { ...@@ -18,15 +25,15 @@ const addcart = async (req, res) => {
const showcart = async (req, res) => { const showcart = async (req, res) => {
// const {userId} = req.body // const {userId} = req.body
console.log(req.cart) // console.log(req.cart)
// console.log(req.id)
try { try {
const cart = await Cart.findOne({ user: userId }).populate({ const cart = await Cart.findOne({ userId: req.id }).populate({
path: 'products.product', path: 'products.productId',
model: 'Product' model: 'Product'
}) })
res.status(200).json(cart.products) res.status(200).json(cart.products)
} catch (error) { } catch (error) {
console.log(error) console.log(error)
res.status(500).send('쇼핑카트를 불러오지 못했습니다.') res.status(500).send('쇼핑카트를 불러오지 못했습니다.')
...@@ -53,6 +60,7 @@ const userById = async (req, res, next, id) => { ...@@ -53,6 +60,7 @@ const userById = async (req, res, next, id) => {
res.status(404).send("사용자를 찾을 수 없습니다.") res.status(404).send("사용자를 찾을 수 없습니다.")
} }
req.cart = cart req.cart = cart
req.id = id
next() next()
} catch (error) { } catch (error) {
res.status(500).send("사용자 아이디 검색 실패") res.status(500).send("사용자 아이디 검색 실패")
......
import Cart from "../schemas/Cart.js";
import User from "../schemas/User.js"; import User from "../schemas/User.js";
import isLength from 'validator/lib/isLength.js'; import isLength from 'validator/lib/isLength.js';
import bcrypt from 'bcryptjs'; import bcrypt from 'bcryptjs';
...@@ -16,7 +17,6 @@ const signup = async (req, res) => { ...@@ -16,7 +17,6 @@ const signup = async (req, res) => {
return res.status(422).send(`${id}가 이미 사용중입니다.`) return res.status(422).send(`${id}가 이미 사용중입니다.`)
} }
const hash = await bcrypt.hash(password, 10) const hash = await bcrypt.hash(password, 10)
const newUser = await new User({ const newUser = await new User({
...@@ -27,7 +27,7 @@ const signup = async (req, res) => { ...@@ -27,7 +27,7 @@ const signup = async (req, res) => {
password: hash, password: hash,
tel, tel,
}).save() }).save()
await new Cart({ user: newUser._id }).save() await new Cart({ userId: newUser._id }).save()
console.log(newUser) console.log(newUser)
res.json(newUser) res.json(newUser)
......
...@@ -13,9 +13,15 @@ const CartSchema = new mongoose.Schema({ ...@@ -13,9 +13,15 @@ const CartSchema = new mongoose.Schema({
type: Number, type: Number,
default: 1 default: 1
}, },
product: { productId: {
type: ObjectId, type: ObjectId,
ref: 'Product' ref: 'Product'
},
sizes: {
type: String
},
colors: {
type: String
} }
} }
] ]
......
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