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 }) {
<Card.Body>
<Card.Title style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{name}</Card.Title>
<Card.Text>{price} </Card.Text>
<Button className="float-right" onClick={handleDelete}>삭제</Button>
{/* <Button className="float-right" onClick={handleDelete}>삭제</Button> */}
</Card.Body>
</Card>
)
......
......@@ -10,7 +10,7 @@ import catchErrors from '../utils/catchErrors';
function Payment({ match, location }) {
const [cart, setCart] = useState([])
const [order, setOrder] = useState({ products: location.state })
const [order, setOrder] = useState({ products: [] })
const [userData, setUserData] = useState({})
const [error, setError] = useState()
const [paymentWay, setPaymentWay] = useState([])
......@@ -38,13 +38,10 @@ function Payment({ match, location }) {
}, [cart])
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)
}
const name = localStorage.getItem('name')
const tel = localStorage.getItem('tel')
// const email = localStorage.getItem('email')
setUserData({ name: name, tel: tel })
}
async function getCart() {
......@@ -53,6 +50,7 @@ function Payment({ match, location }) {
console.log(response.data)
const preCart = response.data.filter((el) => el.checked === true)
setCart(preCart)
setOrder({ products: preCart })
} catch (error) {
catchErrors(error, setError)
}
......@@ -141,8 +139,8 @@ function Payment({ match, location }) {
async function kakaopay() {
let itemNames = ""
if (cart.length > 1){
itemNames = cart[0].productId.pro_name + '' + String(cart.length-1) + ''
if (cart.length > 1) {
itemNames = cart[0].productId.pro_name + '' + String(cart.length - 1) + ''
} else {
itemNames = cart[0].productId.pro_name
}
......@@ -157,7 +155,7 @@ function Payment({ match, location }) {
partner_user_id: user,
item_name: itemNames,
quantity: cart.length,
total_amount: finalPrice+2500,
total_amount: finalPrice + 2500,
vat_amount: 200,
tax_free_amount: 0,
approval_url: 'http://localhost:3000/payment',
......@@ -172,20 +170,31 @@ function Payment({ match, location }) {
}
async function paymentCompleted() {
console.log(user)
console.log(order)
console.log(finalPrice)
const cartIds = []
order.products.map((el) => {
cartIds.push(el._id)
})
try {
const response = await axios.post(`/api/order/addorder`, {
userId: user,
...order,
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)
alert("주문이 완료되었습니다.")
return <Redirect to={'/account'} />
} catch (error) {
catchErrors(error, setError)
alert("주문에 실패하셨습니다. 다시 확인해주세요.")
}
alert("주문이 완료되었습니다.")
}
if (redirect) {
......@@ -280,14 +289,14 @@ function Payment({ match, location }) {
<div>
<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>
<input type="image" alt="카카오페이결제" src="icon/payment_icon_yellow_small.png" onClick={kakaopay} />
</div>
{paymentWay}
</div>
<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>
</Container>
</div>
......
......@@ -14,6 +14,7 @@ function Product({ match, location }) {
const [selected, setSelected] = useState({ sizes: false, colors: false })
const [count, setCount] = useState(1)
const [price, setPrice] = useState(0)
// let price = 0
useEffect(() => {
if (size && color) {
......@@ -22,16 +23,16 @@ function Product({ match, location }) {
}
}, [size, color])
function handleClick(e) {
const box = e.target.parentNode.parentNode
box.style.display = "none"
}
function pushOptions() {
setCart([...cart, { color, size, productId: product.id }])
setCart([...cart, { color, size, productId: product.id, count:1 }])
selected.sizes = false
selected.colors = false
console.log(product)
setColor("")
setSize("")
setPrice(product.price + price)
......@@ -50,19 +51,28 @@ function Product({ match, location }) {
function deleteOption(e) {
e.preventDefault()
let preprice = 0
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)
setPrice(Number(preprice))
}
function handleCount(e) {
e.preventDefault()
const addCount = cart.map((el)=>{
if(el.color !== e.target.id || el.size !== e.target.name){
return {el}
const addCount = cart.map((el) => {
if (el.color !== e.target.id || el.size !== e.target.name) {
return { ...el }
} 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)
setCount(e.value)
}
......@@ -90,7 +100,7 @@ function Product({ match, location }) {
return (
<div>
{/* {console.log("match=", match.params, "location=", location.state, "product=", product)} */}
{console.log(cart)}
<style type="text/css">
{`
.btn {
......@@ -129,14 +139,15 @@ function Product({ match, location }) {
</Form.Control>
</Form.Group>
{cart.map((e) => (
<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">
<Row className="mx-1">
<Col xs={6}>{e.color}/{e.size}</Col>
<Col xs={4} className="text-right" >
<input type='number' id={e.color} name={e.size} onChange={handleCount} value={count} style={{ width: '3rem' }} className="text-center" />
</span>
</div>
</Col>
<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%" }}>
......
......@@ -99,7 +99,20 @@ function ProductsList({ match }) {
</Row>
<Row md={8} sm={12} className="justify-content-center m-2">
{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}`,
state: {
id: pro._id,
......@@ -111,7 +124,9 @@ function ProductsList({ match }) {
main_img: pro.main_imgUrl,
detail_imgs: pro.detail_imgUrls
}
}} />
}}>
<ListCard id={pro._id} name={pro.pro_name} price={pro.price} main_img={pro.main_imgUrl} />
</Link>
))}
</Row>
</Container>
......
......@@ -43,7 +43,6 @@ const showCart = async (req, res) => {
}
}
const deleteCart = async (req, res) => {
console.log(req.body)
const { userId, cartId } = req.body
......@@ -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) => {
try {
const cart = await Cart.findOne({ userId: id })
......@@ -79,4 +101,4 @@ const userById = async (req, res, next, id) => {
}
export default { addCart, changeCart, showCart, deleteCart, userById }
\ No newline at end of file
export default { addCart, changeCart, showCart, deleteCart,deleteCart2, userById }
\ No newline at end of file
......@@ -3,7 +3,7 @@ import Category from "../schemas/Category.js";
const getCategory = async (req, res) => {
try {
const category = await Category.find({}, { _id: 0 })
console.log("main= ", category);
// console.log("main= ", category);
res.json(category)
} catch (error) {
console.log(error)
......@@ -12,11 +12,11 @@ const getCategory = async (req, res) => {
}
const getSubCategory = async (req, res) => {
console.log("req.params=", req.params);
// console.log("req.params=", req.params);
const { sub } = req.params
try {
const subcategory = await Category.findOne({}, { _id: 0}).select(`${sub}`)
console.log("sub= ",subcategory);
// console.log("sub= ",subcategory);
res.json(subcategory);
} catch (error) {
res.status(500).send('카테고리를 불러오지 못했습니다.')
......@@ -27,8 +27,8 @@ const getToHome = async (res, req) => {
try {
const bestProduct = await Product.find({}).sort({ purchase: 1 }).limit(6)
const newProduct = await Product.find({}).sort({ createdAt: -1 }).limit(6)
console.log("best=", bestProduct)
console.log("new=", newProduct)
// console.log("best=", bestProduct)
// console.log("new=", newProduct)
res.json(bestProduct, newProduct)
} catch {
res.status(500).send('상품을 불러오지 못했습니다.')
......
......@@ -33,8 +33,8 @@ const getToHome = async (req, res) => {
try {
const bestProduct = await Product.find({}).sort({ purchase: -1 }).limit(6)
const newProduct = await Product.find({}).sort({ createdAt: -1 }).limit(6)
console.log("best=", bestProduct)
console.log("new=", newProduct)
// console.log("best=", bestProduct)
// console.log("new=", newProduct)
res.json({ bestProduct, newProduct })
} catch {
res.status(500).send('상품을 불러오지 못했습니다.')
......@@ -92,4 +92,26 @@ const subcategoryId = async (req, res, next, subcategory) => {
}
}
export default { imageUpload, regist, getToHome, getAll, categoryId, getlist, subcategoryId, subgetlist }
\ No newline at end of file
const plusPurchase = async (req, res) => {
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) => {
password: hash,
tel,
}).save()
await new Cart({ userId: newUser._id, role }).save()
await new Cart({ userId: newUser._id }).save()
console.log(newUser)
res.json(newUser)
......
......@@ -16,6 +16,8 @@ router.route('/changecart')
router.route('/deletecart')
.post(cartCtrl.deleteCart)
router.route('/deletecart2')
.post(cartCtrl.deleteCart2)
router.param('userId', cartCtrl.userById)
......
......@@ -19,8 +19,10 @@ router.route('/getproduct/:category')
router.route('/getproduct/:subcategory')
.get(productCtrl.subgetlist)
router.param('category', productCtrl.categoryId)
router.route('/pluspurchase')
.post(productCtrl.plusPurchase)
router.param('category', productCtrl.categoryId)
router.param('subcategory',productCtrl.subcategoryId)
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