Commit 78f4f056 authored by Jiwon Yoon's avatar Jiwon Yoon
Browse files

productRegist 병합(DB에 안들어감)

parent afcd633d
import axios from 'axios';
import React, { useState, useEffect, useRef } from 'react';
import { Row, Col, Form, Card, Button } from 'react-bootstrap';
import catchErrors from '../utils/catchErrors';
function Product() {
const [select, setSelect] = useState({ color: "", size: ""})
const [select, setSelect] = useState({ color: "", size: "" })
const [cart, setCart] = useState()
const [error, setError] = useState('')
function handleClick(e) {
const box = e.target.parentNode.parentNode
......@@ -22,14 +25,14 @@ function Product() {
}
function handleCreate() {
console.log("실행","cart=",cart)
console.log("실행", "cart=", cart)
if (cart !== undefined) {
if (cart.color !== "") {
const list = document.getElementById('list')
list.style.borderBottom = "1px solid"
const shopping = document.createElement('div')
shopping.className = "d-flex justify-content-between my-2"
shopping.innerHTML=`${cart.color} / ${cart.size}
shopping.innerHTML = `${cart.color} / ${cart.size}
<input type="number" min="0" max="10" value="1" style="width: 40px" />
<p style="margin-bottom: 0px">14,000원</p>`
const deleteA = document.createElement('a')
......@@ -41,9 +44,29 @@ function Product() {
}
}
async function addCart() {
// color, size, count, productObjectId(productlist에서 props), userId(로컬) 를 보내줌
try {
// setError('')
const response = await axios.post('/api/addcart', {
userId: "jiwon5393",
productObjectId: "5ff7fd63d41cae4ecce51dd1",
color: "red",
size: "free",
count: "1"
})
console.log(response)
}catch(error){
// catchErrors(error, setError)
}
alert("상품등록이 완료되었습니다.")
}
useEffect(() => {
if (Object.keys(select).length == 2) {
setCart({...select})
setCart({ ...select })
setSelect({})
}
}, [select])
......@@ -98,7 +121,7 @@ function Product() {
<Col className="text-right">14,000</Col>
</Row>
<Row className="justify-content-between mx-0 my-3" style={{ width: "100%" }}>
<Button style={{ width: "49%" }}>장바구니</Button>
<Button onClick={addCart} style={{ width: "49%" }}>장바구니</Button>
<Button style={{ width: "49%" }}>구매하기</Button>
</Row>
</Form>
......
import React, { useState, useEffect, useRef } from 'react';
import { Row, Col, Button, Form, Container } from 'react-bootstrap';
import axios from 'axios'
import catchErrors from '../utils/catchErrors';
import { Redirect } from 'react-router-dom';
let color = {}
let colors = []
let addedcolors = []
let list = []
function ProductsRegist() {
const [product, setProduct] = useState()
const INIT_PRODUCT = {
pro_name: '',
price: 0,
stock: 0,
main_category: '',
sub_category: [],
size: [],
color: [],
description: '',
main_image: [],
detail_image: []
}
const categorys = {
"DRESS": ["LONG DRESS", "SHORT DRESS", "KNIT DRESS", "SHIRT DRESS", "PATTERN DRESS", "BUSTIER DRESS", "TWO-PIECE DRESS"],
"OUTER": ["PADDED JACKET", "JACKET", "JUMPER", "COAT", "FLEECE", "CARDIGAN / VEST"],
"TOP": ["KNIT", "HOODY", "BLOUSE", "SHIRT", "SWEATSHIRT", "LONG SLEEVE SHIRT", "SHORT SLEEVE / SLEEVELESS SHIRT"],
"PANTS": ["JEANS", "SKINNY JEANS", "BANDING PANTS", "WIDE-FIT PANTS", "BOOT-CUT PANTS", "STRAIGHT-FIT PANTS", "SHORTS", "TROUSERS", "LEGGINGS", "JUMPSUIT / OVERALLS"],
"SKIRT": ["LONG SKIRT", "MIDI SKIRT", "MINI SKIRT"],
"TRAINING": [],
"SHOES": ["SNEAKERS / SLIP-ON", "FLAT / LOAFER", "HEEL / PUMP", "BOOTS", "SANDAL / SLIPPER"]
}
const [product, setProduct] = useState(INIT_PRODUCT)
const [categoryNum, setCategoryNum] = useState(0)
const [tag, setTag] = useState(0)
const [error, setError] = useState('')
const [success, setSuccess] = useState(false)
const [checked, setChecked] = useState({ "Free": false, "XL": false, "L": false, "M": false, "S": false, "XS": false })
const mainCategorys = Object.keys(categorys)
const subCategorys = Object.values(categorys)
function addCategory() {
console.log(product)
list.push(
<div>
<span i={tag}>{product["main_category"]} / {product["sub_category"][tag]}</span>
<input type="image" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right align-middle" onClick={deleteCategory} />
</div>)
setTag(tag + 1)
}
function deleteCategory(e) {
const categ = e.target.parentNode
categ.remove()
product["sub_category"].splice(e.target.parentNode.firstElementChild.getAttribute("i"), 1)
console.log(product)
}
function handleCheckBox(e) {
setChecked({ ...checked, [e.target.value]: !checked[`${e.target.value}`] })
}
function addColor() {
addedcolors.push(
<div>{color["color"]}</div>
)
if (product.color) {
setProduct({ ...product, [color]: colors })
} else {
setProduct({ ...product, "color": colors })
}
}
function handleChange(event) {
const { name, value } = event.target
console.log("file=",event.target.files)
console.log("name=",name,"value=",value)
if (event.target.name === "sub_category") {
product["sub_category"].push(event.target.value)
} else if (event.target.name === "color") {
color[event.target.name] = event.target.value
// console.log(color)
} else {
setProduct({ ...product, [name]: value })
}
if (event.target.name === "main_category") {
setCategoryNum(event.target.selectedIndex - 1)
}
}
async function handleSubmit(e) {
e.preventDefault()
const sizes = []
for (let [key, value] of Object.entries(checked)) {
if (value === true) {
sizes.push(key)
}
}
product["size"].push(sizes)
const formData = new FormData();
for (let key of Object.keys(product)) {
for (let key in product) {
formData.append(key, product[key])
}
console.log("formData=",formData)
axios.post('/api/product/regist',{data: formData}).then(function(res) {
console.log("client의 res=", res)
})
console.log("formData=", formData)
console.log(product)
try {
const response = axios.post('/api/product/regist', { data: formData })
setSuccess(true)
console.log(response)
} catch (error) {
catchErrors(error, setError)
}
}
if (success) {
return <Redirect to='/' />
}
// if (success) {
// return <Redirect to='/' />
// }
return (
<div>
<Container>
......@@ -51,25 +138,52 @@ function ProductsRegist() {
<Form.Label>분류</Form.Label>
<Row>
<Col md={4}>
<Form.Control as="select" name="main_category" placeholder="상위분류" onChange={handleChange}>
{/* {mainCategorys.map((main) => (
<Form.Control as="select" name="main_category" onChange={handleChange}>
<option value="" >상위분류</option>
{mainCategorys.map((main) => (
<option value={main}>{main}</option>
))} */}
))}
</Form.Control>
</Col>
<Col md={6}>
<Form.Control as="select" name="sub_category" placeholder="하위분류" onChange={handleChange}>
{/* {subCategorys[categoryNum].map((sub) => (
<Form.Control as="select" name="sub_category" onChange={handleChange}>
<option value="" >하위분류</option>
{subCategorys[categoryNum].map((sub) => (
<option value={sub}>{sub}</option>
))} */}
))}
</Form.Control>
</Col>
{/* <Col md={2}>
<Button style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addCategory}>추가</Button>
</Col> */}
<Col >
<Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addCategory}>추가</Button>
</Col>
</Row>
{list.map((element) => element)}
</Form.Group>
<Form.Group>
<Form.Label>사이즈</Form.Label>
{/* {console.log(checked)} */}
<Form.Check type="checkbox" name="size" label="Free" value="Free" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="XL" value="XL" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="L" value="L" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="M" value="M" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="S" value="S" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="XS" value="XS" onChange={handleCheckBox} />
</Form.Group>
<Form.Group>
<Form.Label>색상</Form.Label>
<Row>
<Col md={10}>
<Form.Control as="textarea" rows={1} name="color" placeholder="색상" onChange={handleChange} />
</Col>
<Col>
<Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addColor}>추가</Button>
</Col>
</Row>
{addedcolors.map((element) => element)}
</Form.Group>
<Form.Group controlId="productDescriptionform">
<Form.Label>상품설명</Form.Label>
<Form.Control as="textarea" name="description" rows={3} placeholder="상품을 설명해주세요" onChange={handleChange} />
......
import React, { useState, useEffect, useRef } from 'react';
import { Redirect } from 'react-router-dom';
import { Card, Button, Container, Row, Col } from 'react-bootstrap';
import axios from 'axios';
function ShoppingCart() {
......@@ -23,8 +24,13 @@ function ShoppingCart() {
console.log('카트에 담긴 항목을 삭제했습니다.')
}
// async function getCart(){
// const response = await axios.get('/')
// }
return (
<div>
{/* {getCart} */}
<Container className="justify-content-center">
<h3 className="my-5 font-weight-bold text-center">장바구니</h3>
<div>
......
// import React from 'react'
function catchErrors(error, displayError) {
let errorMsg
if (error.response){
errorMsg = error.response.data
console.log(errorMsg)
}
else if (error.request){
errorMsg = error.request
console.log(errorMsg)
}
else {
errorMsg = error.message
console.log(errorMsg)
}
displayError(errorMsg)
}
export default catchErrors
......@@ -3,6 +3,7 @@ import express from 'express';
import connectDb from './schemas/index.js'
import userRouter from "./routes/user.routes.js";
import productRouter from './routes/product.routes.js';
import cartRouter from './routes/cart.routes.js';
import path from 'path'
import kakaopayRoutes from './routes/kakaopay.routes.js'
import config from './config.js'
......@@ -23,6 +24,7 @@ app.use(express.static(path.join(process.cwd(), 'dist')))
app.use('/', kakaopayRoutes)
app.use('/api/users',userRouter)
app.use('/api/product', productRouter)
app.use('/api/addcart', cartRouter)
app.listen(config.port, () => {
console.info('Server started on port %s.', config.port)
......
import Cart from "../schemas/Cart.js";
import Product from '../schemas/Product.js'
const cart = async (req, res) => {
const { userId, productObjectId, color, size, count } = req.body
// console.log('req.body=', req.body)
// const {userId, productObjectId, }
// const { user, pro_name, price, main_image } = req.body
// color, size, count, productObjectId(productlist에서 props), userId(로컬)
try {
const product = await Product.find({ _id: productObjectId })
if (product) {
// console.log(product)
const { pro_name, price, main_image } = product[0]
const products = { productObjectId, color, size, count, pro_name, price, main_image }
// console.log(products)
const newCart = await new Cart({
userId, products
}).save()
console.log(newCart)
res.json(newCart)
}
// const newCart = await new Cart({
// user, pro_name, price, stock, main_category, sub_category, main_image
// }).save()
// const asdf = await Cart.find({ user })
// console.log(newCart)
// res.json(newCart)
} catch (error) {
console.log(error)
res.status(500).send('죄송합니다. 다시 입력해 주십시오.')
}
// try {
// const user = await
// User.findById(id)
// if (!user) {
// console.log(error)
// res.status(404).send('사용자를 찾을 수 없습니다')
// }
// req.profile = user
// next()
// } catch (error) {
// console.log(error)
// res.status(500).send('사용자 아이디 실패')
// }
}
export default { cart }
\ No newline at end of file
......@@ -2,14 +2,11 @@ import Product from "../schemas/Product.js";
const regist = async (req, res) => {
console.log('req.body=', req.body)
console.log('req.data=', req.data)
console.log('req.body.data=', req.body.data)
const { pro_name, price, stock, main_category, sub_category, description, main_image, detail_image } = req.body
try {
const newProduct = await new Product ({
pro_name, price, stock, main_category, sub_category, description, main_image, detail_image
}).save()
console.log(newProduct)
res.json(newProduct)
} catch (error) {
console.log(error)
......
import express from "express";
import cartCtrl from '../controllers/cart.controller.js';
const router = express.Router()
router.route('/')
.post(cartCtrl.cart)
// .get()
export default router
\ No newline at end of file
......@@ -2,11 +2,22 @@ import express from "express";
import path from 'path';
import multer from 'multer';
import productCtrl from '../controllers/product.controller.js';
import fs from 'fs'
// process.cwd() + '/client/public/image'
const router = express.Router()
fs.readdir('uploads', (error, data) => {
if (error) {
fs.mkdirSync('uploads');
if (data == undefined) {
fs.mkdirSync('/main')
fs.mkdirSync('/detail')
}
} else console.log("else data",data)
})
const upload = multer({
storage: multer.diskStorage({
destination(req, file, cb) {
......
import mongoose from 'mongoose'
const { String, Number, Array } = mongoose.Schema.Types
const CartSchema = new mongoose.Schema({
const { String, Number, Array, ObjectId } = mongoose.Schema.Types
const productschema = new mongoose.Schema ({
pro_name: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
required: true
},
stock: {
price:{
type: Number,
required: true
},
purchase: {
type: Number,
required: true,
default: 0
main_image: {
type: String,
required: true
},
main_category: {
color:{
type: String,
required: true,
required: true
},
sub_category: {
type: Array,
required: true,
size:{
type: String,
required: true
},
main_image: {
productObjectId: {
type: ObjectId,
required: true
}
})
const CartSchema = new mongoose.Schema({
userId: {
type: String,
required: true,
// required: true
},
products : {
type: [productschema],
required: true
}
}, {
timestamps: true
})
......
......@@ -20,6 +20,14 @@ const ProductSchema = new mongoose.Schema({
required: true,
default: 0
},
size: {
type: Array,
required: true
},
color: {
type: Array,
required: true
},
main_category: {
type: String,
required: true,
......
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