Commit 6a18a7a0 authored by Jiwon Yoon's avatar Jiwon Yoon
Browse files

오류수정(장바구니에서삭제, purchase+1)

parent 43450898
...@@ -15,7 +15,7 @@ function ListCard({ id, name, price, main_img }) { ...@@ -15,7 +15,7 @@ function ListCard({ id, name, price, main_img }) {
<Card.Body> <Card.Body>
<Card.Title style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{name}</Card.Title> <Card.Title style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{name}</Card.Title>
<Card.Text>{price} </Card.Text> <Card.Text>{price} </Card.Text>
<Button className="float-right" onClick={handleDelete}>삭제</Button> {/* <Button className="float-right" onClick={handleDelete}>삭제</Button> */}
</Card.Body> </Card.Body>
</Card> </Card>
) )
......
...@@ -10,7 +10,7 @@ import catchErrors from '../utils/catchErrors'; ...@@ -10,7 +10,7 @@ import catchErrors from '../utils/catchErrors';
function Payment({ match, location }) { function Payment({ match, location }) {
const [cart, setCart] = useState([]) const [cart, setCart] = useState([])
const [order, setOrder] = useState({ products: location.state }) const [order, setOrder] = useState({ products: [] })
const [userData, setUserData] = useState({}) const [userData, setUserData] = useState({})
const [error, setError] = useState() const [error, setError] = useState()
const [paymentWay, setPaymentWay] = useState([]) const [paymentWay, setPaymentWay] = useState([])
...@@ -38,13 +38,10 @@ function Payment({ match, location }) { ...@@ -38,13 +38,10 @@ function Payment({ match, location }) {
}, [cart]) }, [cart])
async function getUser() { async function getUser() {
try { const name = localStorage.getItem('name')
const response = await axios.get(`/api/users/getuser/${user}`) const tel = localStorage.getItem('tel')
// console.log(response.data) // const email = localStorage.getItem('email')
setUserData(response.data) setUserData({ name: name, tel: tel })
} catch (error) {
catchErrors(error, setError)
}
} }
async function getCart() { async function getCart() {
...@@ -53,6 +50,7 @@ function Payment({ match, location }) { ...@@ -53,6 +50,7 @@ function Payment({ match, location }) {
console.log(response.data) console.log(response.data)
const preCart = response.data.filter((el) => el.checked === true) const preCart = response.data.filter((el) => el.checked === true)
setCart(preCart) setCart(preCart)
setOrder({ products: preCart })
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
...@@ -141,30 +139,30 @@ function Payment({ match, location }) { ...@@ -141,30 +139,30 @@ function Payment({ match, location }) {
async function kakaopay() { async function kakaopay() {
let itemNames = "" let itemNames = ""
if (cart.length > 1){ if (cart.length > 1) {
itemNames = cart[0].productId.pro_name + '' + String(cart.length-1) + '' itemNames = cart[0].productId.pro_name + '' + String(cart.length - 1) + ''
} else { } else {
itemNames = cart[0].productId.pro_name itemNames = cart[0].productId.pro_name
} }
const response = await fetch('/api/kakaopay/test/single', { const response = await fetch('/api/kakaopay/test/single', {
method: "POST", method: "POST",
headers: { headers: {
'Content-type': 'application/json' 'Content-type': 'application/json'
}, },
body: JSON.stringify({ body: JSON.stringify({
cid: 'TC0ONETIME', cid: 'TC0ONETIME',
partner_order_id: 'partner_order_id', partner_order_id: 'partner_order_id',
partner_user_id: user, partner_user_id: user,
item_name: itemNames, item_name: itemNames,
quantity: cart.length, quantity: cart.length,
total_amount: finalPrice+2500, total_amount: finalPrice + 2500,
vat_amount: 200, vat_amount: 200,
tax_free_amount: 0, tax_free_amount: 0,
approval_url: 'http://localhost:3000/payment', approval_url: 'http://localhost:3000/payment',
fail_url: 'http://localhost:3000/payment', fail_url: 'http://localhost:3000/payment',
cancel_url: 'http://localhost:3000/payment', cancel_url: 'http://localhost:3000/payment',
})
}) })
})
const data = await response.json() const data = await response.json()
console.log(data) console.log(data)
window.location.href = data.redirect_url window.location.href = data.redirect_url
...@@ -172,20 +170,31 @@ function Payment({ match, location }) { ...@@ -172,20 +170,31 @@ function Payment({ match, location }) {
} }
async function paymentCompleted() { async function paymentCompleted() {
console.log(user)
console.log(order) console.log(order)
console.log(finalPrice) const cartIds = []
order.products.map((el) => {
cartIds.push(el._id)
})
try { try {
const response = await axios.post(`/api/order/addorder`, { const response = await axios.post(`/api/order/addorder`, {
userId: user, userId: user,
...order, ...order,
total: finalPrice + 2500 total: finalPrice + 2500
}) })
const response2 = await axios.post(`/api/cart/deletecart2`, {
userId: user,
cartId: cartIds
})
const response3 = await axios.post(`/api/product/pluspurchase`, {
products: order.products
})
console.log(response.data) console.log(response.data)
alert("주문이 완료되었습니다.")
return <Redirect to={'/account'} />
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
alert("주문에 실패하셨습니다. 다시 확인해주세요.")
} }
alert("주문이 완료되었습니다.")
} }
if (redirect) { if (redirect) {
...@@ -280,14 +289,14 @@ function Payment({ match, location }) { ...@@ -280,14 +289,14 @@ function Payment({ match, location }) {
<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>
<div className="text-center mt-5"> <div className="text-center m-3">
<Button variant="success" className="align-top" onClick={handleClick} >무통장입금</Button> <Button variant="success" className="align-top" onClick={handleClick} >무통장입금</Button>
<input type="image" alt="카카오페이결제" src="icon/payment_icon_yellow_small.png" onClick={kakaopay} /> <input type="image" alt="카카오페이결제" src="icon/payment_icon_yellow_small.png" onClick={kakaopay} />
</div> </div>
{paymentWay} {paymentWay}
</div> </div>
<div className="text-center"> <div className="text-center">
<Button href="/account" className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} onClick={paymentCompleted} block>결제완료</Button> <Button className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} onClick={paymentCompleted} block>결제완료</Button>
</div> </div>
</Container> </Container>
</div> </div>
......
...@@ -14,6 +14,7 @@ function Product({ match, location }) { ...@@ -14,6 +14,7 @@ function Product({ match, location }) {
const [selected, setSelected] = useState({ sizes: false, colors: false }) const [selected, setSelected] = useState({ sizes: false, colors: false })
const [count, setCount] = useState(1) const [count, setCount] = useState(1)
const [price, setPrice] = useState(0) const [price, setPrice] = useState(0)
// let price = 0
useEffect(() => { useEffect(() => {
if (size && color) { if (size && color) {
...@@ -22,16 +23,16 @@ function Product({ match, location }) { ...@@ -22,16 +23,16 @@ function Product({ match, location }) {
} }
}, [size, color]) }, [size, color])
function handleClick(e) { function handleClick(e) {
const box = e.target.parentNode.parentNode const box = e.target.parentNode.parentNode
box.style.display = "none" box.style.display = "none"
} }
function pushOptions() { function pushOptions() {
setCart([...cart, { color, size, productId: product.id }]) setCart([...cart, { color, size, productId: product.id, count:1 }])
selected.sizes = false selected.sizes = false
selected.colors = false selected.colors = false
console.log(product)
setColor("") setColor("")
setSize("") setSize("")
setPrice(product.price + price) setPrice(product.price + price)
...@@ -50,19 +51,28 @@ function Product({ match, location }) { ...@@ -50,19 +51,28 @@ function Product({ match, location }) {
function deleteOption(e) { function deleteOption(e) {
e.preventDefault() e.preventDefault()
let preprice = 0
const asd = cart.filter((el) => el.color !== e.target.id || el.size !== e.target.name) const asd = cart.filter((el) => el.color !== e.target.id || el.size !== e.target.name)
asd.map((el)=>{
preprice = preprice + el.count *product.price
})
setCart(asd) setCart(asd)
setPrice(Number(preprice))
} }
function handleCount(e) { function handleCount(e) {
e.preventDefault() const addCount = cart.map((el) => {
const addCount = cart.map((el)=>{ if (el.color !== e.target.id || el.size !== e.target.name) {
if(el.color !== e.target.id || el.size !== e.target.name){ return { ...el }
return {el}
} else { } else {
return {...el, count : e.target.value} return { ...el, count: e.target.value }
} }
}) })
let preprice = 0
addCount.map((el)=>{
preprice = preprice + el.count *product.price
})
setPrice(Number(preprice))
setCart(addCount) setCart(addCount)
setCount(e.value) setCount(e.value)
} }
...@@ -90,7 +100,7 @@ function Product({ match, location }) { ...@@ -90,7 +100,7 @@ function Product({ match, location }) {
return ( return (
<div> <div>
{/* {console.log("match=", match.params, "location=", location.state, "product=", product)} */} {console.log(cart)}
<style type="text/css"> <style type="text/css">
{` {`
.btn { .btn {
...@@ -129,14 +139,15 @@ function Product({ match, location }) { ...@@ -129,14 +139,15 @@ function Product({ match, location }) {
</Form.Control> </Form.Control>
</Form.Group> </Form.Group>
{cart.map((e) => ( {cart.map((e) => (
<div> <Row className="mx-1">
<span>{e.color}/{e.size}</span> <Col xs={6}>{e.color}/{e.size}</Col>
<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" /> <Col xs={4} className="text-right" >
<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" /> <input type='number' id={e.color} name={e.size} onChange={handleCount} value={count} style={{ width: '3rem' }} className="text-center" />
</span> </Col>
</div> <Col xs={2} className="text-right">
<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="align-middle" />
</Col>
</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%" }}>
......
...@@ -99,7 +99,20 @@ function ProductsList({ match }) { ...@@ -99,7 +99,20 @@ 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.map(pro => ( {productlist.map(pro => (
<ListCard as={Link} id={pro._id} name={pro.pro_name} price={pro.price} main_img={pro.main_imgUrl} to={{ // <ListCard as={Link} id={pro._id} name={pro.pro_name} price={pro.price} main_img={pro.main_imgUrl} to={{
// pathname: `/product/${pro._id}`,
// state: {
// id: pro._id,
// name: pro.pro_name,
// price: pro.price,
// colors: pro.colors,
// sizes: pro.sizes,
// description: pro.description,
// main_img: pro.main_imgUrl,
// detail_imgs: pro.detail_imgUrls
// }
// }} />
<Link to={{
pathname: `/product/${pro._id}`, pathname: `/product/${pro._id}`,
state: { state: {
id: pro._id, id: pro._id,
...@@ -111,7 +124,9 @@ function ProductsList({ match }) { ...@@ -111,7 +124,9 @@ function ProductsList({ match }) {
main_img: pro.main_imgUrl, main_img: pro.main_imgUrl,
detail_imgs: pro.detail_imgUrls detail_imgs: pro.detail_imgUrls
} }
}} /> }}>
<ListCard id={pro._id} name={pro.pro_name} price={pro.price} main_img={pro.main_imgUrl} />
</Link>
))} ))}
</Row> </Row>
</Container> </Container>
......
...@@ -43,7 +43,6 @@ const showCart = async (req, res) => { ...@@ -43,7 +43,6 @@ const showCart = async (req, res) => {
} }
} }
const deleteCart = async (req, res) => { const deleteCart = async (req, res) => {
console.log(req.body) console.log(req.body)
const { userId, cartId } = req.body const { userId, cartId } = req.body
...@@ -64,6 +63,29 @@ const deleteCart = async (req, res) => { ...@@ -64,6 +63,29 @@ const deleteCart = async (req, res) => {
} }
} }
const deleteCart2 = async (req, res) => {
console.log(req.body)
const { userId, cartId } = req.body
try {
for( let i = 0; i < cartId.length; i++ ){
await Cart.findOneAndUpdate(
{ userId: userId },
{ $pull: { products: { _id: cartId[i] } } },
{ new: true }
).populate({
path: 'products.productId',
model: 'Product'
})
}
res.send("주문완료 쇼핑카트 삭제")
// res.json(cart)
} catch (error) {
console.log(error)
res.status(500).send('해당 카트를 삭제하지 못했습니다.')
}
}
const userById = async (req, res, next, id) => { const userById = async (req, res, next, id) => {
try { try {
const cart = await Cart.findOne({ userId: id }) const cart = await Cart.findOne({ userId: id })
...@@ -79,4 +101,4 @@ const userById = async (req, res, next, id) => { ...@@ -79,4 +101,4 @@ const userById = async (req, res, next, id) => {
} }
export default { addCart, changeCart, showCart, deleteCart, userById } export default { addCart, changeCart, showCart, deleteCart,deleteCart2, userById }
\ No newline at end of file \ No newline at end of file
...@@ -3,7 +3,7 @@ import Category from "../schemas/Category.js"; ...@@ -3,7 +3,7 @@ import Category from "../schemas/Category.js";
const getCategory = async (req, res) => { const getCategory = async (req, res) => {
try { try {
const category = await Category.find({}, { _id: 0 }) const category = await Category.find({}, { _id: 0 })
console.log("main= ", category); // console.log("main= ", category);
res.json(category) res.json(category)
} catch (error) { } catch (error) {
console.log(error) console.log(error)
...@@ -12,11 +12,11 @@ const getCategory = async (req, res) => { ...@@ -12,11 +12,11 @@ const getCategory = async (req, res) => {
} }
const getSubCategory = async (req, res) => { const getSubCategory = async (req, res) => {
console.log("req.params=", req.params); // console.log("req.params=", req.params);
const { sub } = req.params const { sub } = req.params
try { try {
const subcategory = await Category.findOne({}, { _id: 0}).select(`${sub}`) const subcategory = await Category.findOne({}, { _id: 0}).select(`${sub}`)
console.log("sub= ",subcategory); // console.log("sub= ",subcategory);
res.json(subcategory); res.json(subcategory);
} catch (error) { } catch (error) {
res.status(500).send('카테고리를 불러오지 못했습니다.') res.status(500).send('카테고리를 불러오지 못했습니다.')
...@@ -27,8 +27,8 @@ const getToHome = async (res, req) => { ...@@ -27,8 +27,8 @@ const getToHome = async (res, req) => {
try { try {
const bestProduct = await Product.find({}).sort({ purchase: 1 }).limit(6) const bestProduct = await Product.find({}).sort({ purchase: 1 }).limit(6)
const newProduct = await Product.find({}).sort({ createdAt: -1 }).limit(6) const newProduct = await Product.find({}).sort({ createdAt: -1 }).limit(6)
console.log("best=", bestProduct) // console.log("best=", bestProduct)
console.log("new=", newProduct) // console.log("new=", newProduct)
res.json(bestProduct, newProduct) res.json(bestProduct, newProduct)
} catch { } catch {
res.status(500).send('상품을 불러오지 못했습니다.') res.status(500).send('상품을 불러오지 못했습니다.')
......
...@@ -33,8 +33,8 @@ const getToHome = async (req, res) => { ...@@ -33,8 +33,8 @@ const getToHome = async (req, res) => {
try { try {
const bestProduct = await Product.find({}).sort({ purchase: -1 }).limit(6) const bestProduct = await Product.find({}).sort({ purchase: -1 }).limit(6)
const newProduct = await Product.find({}).sort({ createdAt: -1 }).limit(6) const newProduct = await Product.find({}).sort({ createdAt: -1 }).limit(6)
console.log("best=", bestProduct) // console.log("best=", bestProduct)
console.log("new=", newProduct) // console.log("new=", newProduct)
res.json({ bestProduct, newProduct }) res.json({ bestProduct, newProduct })
} catch { } catch {
res.status(500).send('상품을 불러오지 못했습니다.') res.status(500).send('상품을 불러오지 못했습니다.')
...@@ -92,4 +92,26 @@ const subcategoryId = async (req, res, next, subcategory) => { ...@@ -92,4 +92,26 @@ const subcategoryId = async (req, res, next, subcategory) => {
} }
} }
export default { imageUpload, regist, getToHome, getAll, categoryId, getlist, subcategoryId, subgetlist } const plusPurchase = async (req, res) => {
\ No newline at end of file const { products } = req.body
// console.log(products)
try {
for (let i = 0; i < products.length; i++) {
const count = products[i].count
const product = await Product.findOne(
{_id: products[i].productId._id }
)
const purchase = product.purchase
await Product.updateOne(
{ _id: products[i].productId._id },
{ $set: { purchase: count + purchase } }
)
// console.log("i=", i)
}
res.send("구매수 늘리기 성공")
} catch (error) {
res.status(500).send('구매숫자를 늘리지 못함')
}
}
export default { imageUpload, regist, getToHome, getAll, categoryId, getlist, subcategoryId, subgetlist, plusPurchase }
\ No newline at end of file
...@@ -52,7 +52,7 @@ const signup = async (req, res) => { ...@@ -52,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 }).save()
console.log(newUser) console.log(newUser)
res.json(newUser) res.json(newUser)
......
...@@ -16,6 +16,8 @@ router.route('/changecart') ...@@ -16,6 +16,8 @@ router.route('/changecart')
router.route('/deletecart') router.route('/deletecart')
.post(cartCtrl.deleteCart) .post(cartCtrl.deleteCart)
router.route('/deletecart2')
.post(cartCtrl.deleteCart2)
router.param('userId', cartCtrl.userById) router.param('userId', cartCtrl.userById)
......
...@@ -19,8 +19,10 @@ router.route('/getproduct/:category') ...@@ -19,8 +19,10 @@ router.route('/getproduct/:category')
router.route('/getproduct/:subcategory') router.route('/getproduct/:subcategory')
.get(productCtrl.subgetlist) .get(productCtrl.subgetlist)
router.param('category', productCtrl.categoryId) router.route('/pluspurchase')
.post(productCtrl.plusPurchase)
router.param('category', productCtrl.categoryId)
router.param('subcategory',productCtrl.subcategoryId) router.param('subcategory',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