Commit a73da7bd authored by Jiwon Yoon's avatar Jiwon Yoon
Browse files

오류 수정 및 결제완료 후 페이지 추가

parent 78ae2a96
......@@ -9,6 +9,7 @@ import Admin from './Pages/Admin';
import ProductRegist from './Pages/ProductRegist';
import ShoppingCart from './Pages/ShoppingCart';
import Payment from './Pages/Payment';
import PaymentCompleted from './Pages/PaymentCompleted';
import Account from './Pages/Account';
import MainNav from './Components/MainNav';
import SubNav from './Components/SubNav';
......@@ -30,6 +31,7 @@ function App() {
<Route path="/regist" component={ProductRegist} />
<Route path="/shoppingcart" component={ShoppingCart} />
<Route path="/payment" component={Payment} />
<Route path="/paymentcompleted" component={PaymentCompleted} />
<Route path="/account" component={Account} />
<Route path='/kakao' component={() => { window.location.href = 'https://compmath.korea.ac.kr'; return null; }} />
<Redirect path="/" to="/" />
......
......@@ -18,9 +18,9 @@ function CartCard(props) {
<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} />
<Card.Title className="font-weight-bold mt-3">{e.productId.pro_name}</Card.Title>
<Card.Text>가격: {e.productId.price}</Card.Text>
<Card.Text>옵션: {e.size}/{e.color}</Card.Text>
<Card.Text>수량</Card.Text>
<Card.Text className="mb-0">가격: {e.productId.price}</Card.Text>
<Card.Text className="mb-0">옵션: {e.size}/{e.color}</Card.Text>
<Card.Text >수량</Card.Text>
<div>
<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="number" style={{ width: '30px' }} className="text-center align-middle mx-1" placeholder={e.count} value={e.count} readOnly></input>
......
......@@ -6,22 +6,23 @@ function PaymentCard(props) {
return (
<>
{props.cart.map((e) => (
<Card>
<Row className="mx-1">
<Col className="text-center">
<Card.Img className="img-fluid" variant="top" src={e.productId.main_imgUrl && `/images/${e.productId.main_imgUrl}`} style={{ width: '20rem' }} />
</Col>
<Col md={6} className="p-2">
<Card.Body>
<Card.Title className="font-weight-bold mt-3">{e.productId.pro_name}</Card.Title>
<Card.Text>가격: {e.productId.price}</Card.Text>
<Card.Text>옵션: {e.size}/{e.color}</Card.Text>
<Card.Text>수량: {e.count}</Card.Text>
</Card.Body>
</Col>
</Row>
</Card>
))
<Card>
<Row className="mx-1">
<Col className="text-center">
<Card.Img className="img-fluid" variant="top" src={e.productId.main_imgUrl && `/images/${e.productId.main_imgUrl}`} style={{ width: '20rem' }} />
</Col>
<Col md={6} className="p-2">
<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.deleteOrder} />
<Card.Title className="font-weight-bold mt-3">{e.productId.pro_name}</Card.Title>
<Card.Text>가격: {e.productId.price}</Card.Text>
<Card.Text>옵션: {e.size}/{e.color}</Card.Text>
<Card.Text>수량: {e.count}</Card.Text>
</Card.Body>
</Col>
</Row>
</Card>
))
}
</>
)
......
......@@ -2,7 +2,7 @@ import axios from 'axios';
import React, { useState, useEffect, useRef } from 'react';
import DaumPostcode from "react-daum-postcode";
import { Container, Card, Row, Col, Button, Form, FormGroup } from 'react-bootstrap';
import { Redirect, Link } from 'react-router-dom';
import { Redirect, Link, useHistory } from 'react-router-dom';
import PaymentCard from '../Components/PaymentCard';
import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors';
......@@ -20,6 +20,7 @@ function Payment({ match, location }) {
const [finalPrice, setFinalPrice] = useState(0)
const [completeState, setCompleteState] = useState(false)
const user = isAuthenticated()
let history = useHistory();
const preCart = []
useEffect(() => {
......@@ -39,19 +40,37 @@ function Payment({ match, location }) {
const name = localStorage.getItem('name')
const tel = localStorage.getItem('tel')
const email = localStorage.getItem('email')
setUserData({ name: name, tel: tel, email:email })
setUserData({ name: name, tel: tel, email: email })
}
async function getCart() {
try {
setError('')
const response = await axios.get(`/api/cart/showcart/${user}`)
console.log(response.data)
if(response.data[0].checked){
const preCart = response.data.filter((el) => el.checked === true)
const preCart = response.data.filter((el) => el.checked === true)
if (preCart.length) {
setCart(preCart)
setOrder({ products: preCart })
} else {
setCart(response.data)
alert("주문하실 상품이 없습니다.")
history.push("/home")
}
} catch (error) {
catchErrors(error, setError)
}
}
async function deleteOrder(e) {
try {
setError('')
const response = await axios.post('/api/cart/deletecart', {
userId: user,
cartId: e.target.name
})
console.log(response.data)
const preCart = response.data.products.filter((el) => el.checked === true)
setCart(preCart)
setOrder({ products: preCart })
} catch (error) {
catchErrors(error, setError)
......@@ -162,13 +181,13 @@ function Payment({ match, location }) {
total_amount: finalPrice + 2500,
vat_amount: 200,
tax_free_amount: 0,
approval_url: 'http://localhost:3000/payment',
fail_url: 'http://localhost:3000/payment',
cancel_url: 'http://localhost:3000/payment',
approval_url: 'http://localhost:3000/paymentcompleted',
fail_url: 'http://localhost:3000/shoppingcart',
cancel_url: 'http://localhost:3000/shoppingcart',
})
})
const data = await response.json()
if(data) {
if (data) {
setCompleteState(true)
}
window.location.href = data.redirect_url
......@@ -182,6 +201,7 @@ function Payment({ match, location }) {
cartIds.push(el._id)
})
try {
setError('')
const response = await axios.post(`/api/order/addorder`, {
userId: user,
...order,
......@@ -195,7 +215,10 @@ function Payment({ match, location }) {
products: order.products
})
console.log(response.data)
console.log(response2.data)
console.log(response3.data)
alert("주문이 완료되었습니다.")
history.push('/paymentcompleted')
} catch (error) {
catchErrors(error, setError)
alert("주문에 실패하셨습니다. 다시 확인해주세요.")
......@@ -204,7 +227,7 @@ function Payment({ match, location }) {
return (
<div>
{console.log(completeState)}
{/* {console.log(completeState)} */}
<Container>
<h3 className="my-5 font-weight-bold text-center">주문/결제</h3>
<div>
......@@ -268,7 +291,7 @@ function Payment({ match, location }) {
<div>
<h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h5>
<PaymentCard cart={cart} />
<PaymentCard cart={cart} deleteOrder={deleteOrder} />
</div>
<div className="p-5 m-3" style={{ background: '#F7F3F3' }}>
......@@ -296,7 +319,7 @@ function Payment({ match, location }) {
{paymentWay}
</div>
<div className="text-center">
<Button type="button" onClick={paymentCompleted} disabled={!completeState} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} block>결제완료</Button>
<Button type="button" onClick={paymentCompleted} disabled={!completeState} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} block>결제완료</Button>
</div>
</Container>
</div>
......
import React, { useState, useEffect } from 'react'
import axios from 'axios';
import { isAuthenticated } from '../utils/auth'
import catchErrors from '../utils/catchErrors';
import { Card, Row, Col, Button, Alert } from 'react-bootstrap';
import { Link } from 'react-router-dom';
function PaymentCompleted() {
const [order, setOrder] = useState([])
const user = isAuthenticated()
const [error, setError] = useState()
const [total, setTotal] = useState(0)
useEffect(() => {
getOrder()
}, [user])
async function getOrder() {
try {
setError('')
const response = await axios.get(`/api/order/showorder/${user}`)
console.log(response.data)
setOrder(response.data.products)
setTotal(response.data.total)
} catch (error) {
catchErrors(error, setError)
}
}
return (
<div>
<div className="mx-3 my-5 text-center px-3 py-4 border">
<div className="mb-1">
<h5 className=" font-weight-bold" style={{ display: 'inline' }}>고객님의 </h5>
<h5 className=" font-weight-bold text-danger" style={{ display: 'inline' }}>주문이 완료</h5>
<h5 className=" font-weight-bold " style={{ display: 'inline' }}>되었습니다!</h5>
</div>
<div className="mb-0">주문내역 확인은 마이페이지의 </div>
<div> "주문/배송조회"에서 하실 있습니다.</div>
</div>
<h3 className="text-center font-weight-bold my-3">주문내역</h3>
<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>
{order.map((e) => (
<Card>
<Row className="mx-1">
<Col className="text-center">
<Card.Img className="img-fluid" variant="top" src={e.productId.main_imgUrl && `/images/${e.productId.main_imgUrl}`} style={{ width: '20rem' }} />
</Col>
<Col md={6} className="p-2">
<Card.Body>
<Card.Title className="font-weight-bold mt-3">{e.productId.pro_name}</Card.Title>
<Card.Text className="mb-0">가격: {e.productId.price}</Card.Text>
<Card.Text className="mb-0">옵션: {e.size}/{e.color}</Card.Text>
<Card.Text>수량: {e.count}</Card.Text>
</Card.Body>
</Col>
</Row>
</Card>
))
}
<div className="text-center my-3">
<Button href="/" className="mx-1" style={{ background: "#91877F", borderColor: '#91877F', width: "7rem" }}>홈으로</Button>
<Button href="/account" className="mx-1" style={{ background: "#91877F", borderColor: '#91877F', width: "7rem" }}>마이페이지</Button>
</div>
</div>
)
}
export default PaymentCompleted
......@@ -50,7 +50,7 @@ function Product({ match, location }) {
} else {
selected.sizes = false
selected.colors = false
setCart([...cart, { color, size, productId: product.id, count: 1 }])
setCart([...cart, { color, size, productId: product.id, count: 1 , checked:false}])
setColor("")
setSize("")
setPrice(product.price + price)
......@@ -119,6 +119,9 @@ function Product({ match, location }) {
} else {
try {
setError('')
cart.map((el)=>{
el.checked = true
})
const response = await axios.put('/api/cart/addcart', {
userId: localStorage.getItem('id'),
products: cart
......
......@@ -15,7 +15,7 @@ function ShoppingCart() {
useEffect(() => {
getCart()
console.log(cart)
// console.log(cart)
}, [user])
function plusNum(e) {
......@@ -59,7 +59,7 @@ function ShoppingCart() {
async function deleteCart(e) {
//장바구니 DB에서 해당 항목 삭제
console.log(e.target.name)
// console.log(e.target.name)
try {
const response = await axios.post('/api/cart/deletecart', {
userId: user,
......@@ -70,7 +70,7 @@ function ShoppingCart() {
} catch (error) {
catchErrors(error, setError)
}
console.log('카트에 담긴 항목을 삭제했습니다.')
// console.log('카트에 담긴 항목을 삭제했습니다.')
}
async function getCart() {
......@@ -102,7 +102,7 @@ function ShoppingCart() {
return (
<div>
{console.log(cart)}
{/* {console.log(cart)} */}
<Container className="justify-content-center">
<h1 className="my-5 font-weight-bold text-center">장바구니</h1>
<div>
......
......@@ -55,7 +55,6 @@ const deleteCart = async (req, res) => {
path: 'products.productId',
model: 'Product'
})
// res.send("삭제완료")
res.json(cart)
} catch (error) {
console.log(error)
......@@ -77,7 +76,7 @@ const deleteCart2 = async (req, res) => {
model: 'Product'
})
}
res.send("주문완료 쇼핑카트 삭제")
res.send("주문완료 쇼핑카트에서 삭제")
// res.json(cart)
} catch (error) {
console.log(error)
......
import Order from "../schemas/Order.js";
import User from "../schemas/User.js";
const addorder = async (req, res) => {
const { userId, products, receiverInfo, total } = req.body
......@@ -15,11 +16,12 @@ const addorder = async (req, res) => {
const showorder = async (req, res) => {
try {
const order = await Order.findOne({ userId: req.id }).populate({
const order = await Order.find({ userId: req.userId }).sort({_id:-1}).limit(1).populate({
path: 'products.productId',
model: 'Product'
})
res.status(200).json(order.products)
console.log(order)
res.status(200).json(order[0])
} catch (error) {
console.log(error)
res.status(500).send('쇼핑카트를 불러오지 못했습니다.')
......@@ -27,7 +29,19 @@ const showorder = async (req, res) => {
}
const orderById = async (req, res, next, id) => {
try {
const user = await User.findById(id)
if (!user) {
res.status(404).send('사용자를 찾을 수 없습니다')
}
req.userId = user
next()
} catch (error) {
console.log(error);
res.status(500).send('사용자 아이디 검색 실패')
}
}
export default { addorder, showorder }
\ No newline at end of file
export default { addorder, showorder, orderById }
\ No newline at end of file
......@@ -99,16 +99,22 @@ const plusPurchase = async (req, res) => {
for (let i = 0; i < products.length; i++) {
const count = products[i].count
const product = await Product.findOne(
{_id: products[i].productId._id }
{ _id: products[i].productId._id }
)
const purchase = product.purchase
const stock = product.stock
await Product.updateOne(
{ _id: products[i].productId._id },
{ $set: { purchase: count + purchase } }
{ $set:
{
purchase: count + purchase,
stock: stock - count
}
}
)
// console.log("i=", i)
}
res.send("구매수 늘리기 성공")
res.send("구매수 늘리기, 재고수 줄이기 성공")
} catch (error) {
res.status(500).send('구매숫자를 늘리지 못함')
}
......
......@@ -11,5 +11,6 @@ router.route('/addorder')
router.route('/showorder/:userId')
.get(orderCtrl.showorder)
router.param('userId', orderCtrl.orderById)
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