Commit 4ae42d2f authored by Jiwon Yoon's avatar Jiwon Yoon
Browse files

orderDB저장

parent 8258442f
import React from 'react'
import { Card, Button, Container, Row, Col } from 'react-bootstrap';
import { Card, Row, Col } from 'react-bootstrap';
function CartCard(props) {
console.log(props)
return (
<>
{props.cart.map((e) => (
<Card>
<Row className="mx-1">
<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 className="text-center">
<Card.Img className="img-fluid" variant="top" src={e.productId.main_imgUrl && `/images/${e.productId.main_imgUrl}`} style={{ width: '20rem' }} />
......@@ -17,13 +18,13 @@ 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.productId.price}</Card.Text>
<Card.Text>옵션: {e.size}/{e.color}</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={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="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/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>
<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>
</Card.Body>
</Col>
......
import React from 'react'
import { Card, Row, Col } from 'react-bootstrap';
function PaymentCard() {
function PaymentCard(props) {
return (
<Card >
<>
{props.cart.map((e) => (
<Card>
<Row className="mx-1">
<Col className="text-center">
<Card.Img className="img-fluid" variant="top" src="img/asd.jpg" 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 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.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>
))
}
</>
)
}
......
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 } 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 [isAddress, setIsAddress] = useState("");
const [isZoneCode, setIsZoneCode] = useState();
const [isPostOpen, setIsPostOpen] = useState();
// const [isAddress, setIsAddress] = useState("");
// const [isZoneCode, setIsZoneCode] = useState();
// const [isPostOpen, setIsPostOpen] = useState();
const [post, setPost] = useState([])
const [redirect, setRedirect] = useState(null)
const [address, setAddress] = useState("")
const [finalPrice, setFinalPrice] = 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() {
if (post.length !== 0) {
......@@ -42,8 +77,8 @@ function Payment() {
}
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);
}
......@@ -89,12 +124,6 @@ function Payment() {
}
}
function handleClick2() {
if (paymentWay.length !== 0) {
setPaymentWay([])
}
}
async function kakaopay() {
const response = await fetch('/api/kakaopay/test/single', {
method: "POST",
......@@ -121,21 +150,20 @@ function Payment() {
// setRedirect(data.redirect_url)
}
function plusNum() {
setNum(num + 1)
}
function minusNum() {
if (num === 0) {
setNum(0)
}
else {
setNum(num - 1)
}
async function paymentCompleted(){
console.log(user)
console.log(order)
console.log(finalPrice)
try {
const response = await axios.post(`/api/order/addorder`, {
userId : user,
...order,
total : finalPrice+2500
})
console.log(response.data)
} catch (error) {
catchErrors(error, setError)
}
function deleteCart() {
//장바구니 DB에서 해당 항목 삭제
console.log('카트에 담긴 항목을 삭제했습니다.')
}
if (redirect) {
......@@ -145,6 +173,7 @@ function Payment() {
return (
<div>
{/* {console.log(order)} */}
<Container>
<h3 className="my-5 font-weight-bold text-center">주문/결제</h3>
<div>
......@@ -154,15 +183,15 @@ function Payment() {
<Form>
<Form.Group controlId="formBasicName">
<Form.Label>이름</Form.Label>
<Form.Control type="text" placeholder="윤지원" />
</Form.Group>
<Form.Group controlId="formBasicEmail">
<Form.Label>이메일</Form.Label>
<Form.Control type="email" placeholder="jiwon5393@naver.com" />
<Form.Control type="text" value={userData.name} readOnly />
</Form.Group>
<Form.Group controlId="formBasicTel">
<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>
</Col>
......@@ -176,13 +205,17 @@ function Payment() {
<Form>
<Form.Group>
<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 controlId="formBasicAdd">
<Form.Label>주소</Form.Label>
<Form.Row>
<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 >
<Button style={{ background: '#91877F', borderColor: '#91877F' }} className="mx-1" onClick={postClick}>우편번호</Button>
......@@ -191,16 +224,12 @@ function Payment() {
</Form.Row>
<Form.Row>
<Col>
<Form.Control type="text" id="add1" value={address.full} disabled={(address.zone == null) ? false : true} placeholder="주소" required></Form.Control>
<Form.Control type="text" id="add2" 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" name="address2" id="add2" onChange={handleReceiverInfo} placeholder="상세주소" required></Form.Control>
<Form.Control.Feedback type="invalid" > 상세 주소를 입력하세요. </Form.Control.Feedback>
</Col>
</Form.Row>
</Form.Group>
<Form.Group>
<Form.Label>휴대전화</Form.Label>
<Form.Control></Form.Control>
</Form.Group>
</Form>
</Col>
</Row>
......@@ -208,42 +237,22 @@ function Payment() {
<div>
<h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h5>
<Card >
<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>
<PaymentCard cart={cart} />
</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' }}>
<li>
<span className="text-secondary"> 상품금액</span>
<span className="text-secondary float-right">12,000</span>
<span className="text-secondary float-right">{finalPrice}</span>
</li>
<li>
<span className="text-secondary">배송비</span>
<span className="text-secondary float-right">2,500</span>
<span className="text-secondary float-right">2500</span>
</li>
</ul>
<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>
......@@ -256,7 +265,7 @@ function Payment() {
{paymentWay}
</div>
<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>
</Container>
</div>
......
......@@ -40,11 +40,9 @@ function Product({ match, location }) {
function handleChange(e) {
const { name, value } = e.target
if (name === "sizes") {
// setPreCart({ ...preCart, [name]: value })
setSize(value)
selected.sizes = true
} else if (name === "colors") {
// setPreCart({ ...preCart, [name]: value })
setColor(value)
selected.colors = true
}
......@@ -58,17 +56,14 @@ function Product({ match, location }) {
function handleCount(e) {
e.preventDefault()
// const asd = cart.filter((el) => el.color !== e.target.id || el.size !== e.target.name)
const asd= cart.map((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}
}
})
// const index = product["sub_category"].findIndex((item)=>{return item === e.target.name})
// product["sub_category"].splice(index, 1)
setCart(asd)
setCart(addCount)
setCount(e.value)
}
......@@ -80,7 +75,6 @@ function Product({ match, location }) {
setError('')
const response = await axios.put('/api/cart/addcart', {
userId: localStorage.getItem('id'),
// productId: product.id,
products: cart
})
console.log(response)
......
......@@ -124,7 +124,6 @@ function ProductsRegist() {
const formData = new FormData();
for (let key in product) {
if (key === "main_image" ||key === "detail_image") {
// console.log(product[key][0])
formData.append(key, product[key][0])
} else if(key === "sizes" || key === "colors"){
for (let i = 0; i < product[key].length ; i++){
......@@ -135,7 +134,6 @@ function ProductsRegist() {
formData.append(key, product[key])
}
}
// console.log(formData)
try {
const response = await axios.post('/api/product/regist', formData)
console.log(response)
......
......@@ -7,53 +7,80 @@ import { isAuthenticated } from '../utils/auth'
import CartCard from '../Components/CartCard';
function ShoppingCart() {
const [num, setNum] = useState()
const [error, setError] = useState('')
const [cart, setCart] = useState([])
const [finalCart, setFinalCart] = useState([])
const [finalPrice, setFinalPrice] = useState(0)
const user = isAuthenticated()
useEffect(() => {
getCart()
console.log(cart)
}, [user])
function plusNum() {
num = num + 1
setNum(num + 1)
function plusNum(e) {
const addCount = cart.map((el) => {
if (el._id === e.target.name) {
return { ...el, count: el.count+1}
} else {
return { ...el }
}
function minusNum() {
if (num === 0) {
setNum(0)
})
setCart(addCount)
}
function minusNum(e) {
const addCount = cart.map((el) => {
if (el._id === e.target.name) {
return { ...el, count: el.count-1 }
} else {
return { ...el }
}
else {
setNum(num - 1)
})
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) {
//장바구니 DB에서 해당 항목 삭제
console.log(e.target.name)
try {
const response = await axios.post('/api/cart/deletecart', {
userId : user,
cartId: e.target.name })
userId: user,
cartId: e.target.name
})
console.log(response.data)
setCart(response.data.products)
} catch (error) {
catchErrors(error, setError)
}
console.log('카트에 담긴 항목을 삭제했습니다.')
}
async function getCart() {
try {
const response = await axios.get(`/api/cart/showcart/${user}`)
console.log(response.data)
setCart(response.data)
const finalPrices = response.data.map((e) => {
return e.count * e.productId.price
const addChecked = response.data.map((el) => {
return { ...el, checked: false }
})
setFinalPrice(finalPrices.reduce((a, b) => (a + b)))
console.log("addchecked=",addChecked)
setCart(addChecked)
} catch (error) {
catchErrors(error, setError)
}
......@@ -65,8 +92,8 @@ function ShoppingCart() {
<h1 className="my-5 font-weight-bold text-center">장바구니</h1>
<div>
<h4 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h4>
{cart.length >0
? <CartCard cart={cart} deleteCart={deleteCart} minusNum={minusNum} plusNum={plusNum} num={num} />
{cart.length > 0
? <CartCard cart={cart} deleteCart={deleteCart} minusNum={minusNum} plusNum={plusNum} checkedCart={checkedCart} />
: <div className="text-center my-5">장바구니에 담긴 상품이 없습니다.</div>}
</div>
......@@ -88,7 +115,7 @@ function ShoppingCart() {
<div className="text-center">
<Button as={Link} to={{
pathname: `/payment`,
state: { cart }
state: finalCart
}} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} block>결제하기</Button>
</div>
</Container>
......
......@@ -9,6 +9,7 @@ import path from 'path'
import kakaopayRoutes from './routes/kakaopay.routes.js'
import config from './config.js'
import authRouter from './routes/auth.routes.js'
import orderRouter from './routes/order.routes.js'
import cors from 'cors'
fs.readdir('uploads', (error) => {
......@@ -33,6 +34,7 @@ app.use('/api/users',userRouter)
app.use('/api/auth',authRouter)
app.use('/api/product', productRouter)
app.use('/api/cart', cartRouter)
app.use('/api/order', orderRouter)
app.listen(config.port, () => {
console.info('Server started on port %s.', config.port)
......
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
......@@ -6,6 +6,15 @@ import multer from "multer";
const uploadimg = multer({ dest: 'uploads/' });
const getUser = async (req, res) => {
try {
const user = await User.findOne({ _id: req.id })
res.json(user)
} catch (error) {
res.status(500).send('사용자 정보를 불러올 수 없습니다.')
}
}
const imgUpload = uploadimg.fields([
{ name: 'avatar', maxCount: 1 }
])
......@@ -22,6 +31,7 @@ const userById = async (req, res, next, id) => {
res.status(404).send('사용자를 찾을 수 없습니다')
}
req.account = user
req.id = id
next()
} catch (error) {
console.log(error);
......@@ -54,7 +64,7 @@ const signup = async (req, res) => {
password: hash,
tel,
}).save()
await new Cart({ userId: newUser._id,role}).save()
await new Cart({ userId: newUser._id, role }).save()
console.log(newUser)
res.json(newUser)
......@@ -86,4 +96,4 @@ const update = async (req, res) => {
}
}
export default { signup, username, imgUpload, userById, update }
\ No newline at end of file
export default { getUser, signup, username, imgUpload, userById, update }
\ No newline at end of file
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,6 +10,8 @@ router.route('/account/:userId')
.get(userCtrl.username)
.put(userCtrl.imgUpload, userCtrl.update)
router.route('/getuser/:userId')
.get(userCtrl.getUser)
router.param('userId', userCtrl.userById)
......
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
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