ProductRegist.js 12.8 KB
Newer Older
Kim, Subin's avatar
Kim, Subin committed
1
import React, { useState, useEffect, useRef } from 'react';
2
import { Redirect } from 'react-router-dom';
kusang96's avatar
kusang96 committed
3
import { Row, Col, Button, Form, Container, Alert, Spinner } from 'react-bootstrap';
kusang96's avatar
kusang96 committed
4
import axios from 'axios';
5
import catchErrors from '../utils/catchErrors';
Jiwon Yoon's avatar
Jiwon Yoon committed
6

Kim, Subin's avatar
Kim, Subin committed
7
function ProductsRegist() {
8
9
10
11
12
13
    const INIT_PRODUCT = {
        pro_name: '',
        price: 0,
        stock: 0,
        main_category: '',
        sub_category: [],
Jiwon Yoon's avatar
Jiwon Yoon committed
14
15
        sizes: [],
        colors: [],
16
17
18
19
        description: '',
        main_image: [],
        detail_image: []
    }
20
    const [preColors, setPreColors] = useState([])
Jiwon Yoon's avatar
Jiwon Yoon committed
21
    const [categories, setCategories] = useState({ 0: [], 1: [[]] })
22
    const [product, setProduct] = useState(INIT_PRODUCT)
kusang96's avatar
kusang96 committed
23
    const [categoryNum, setCategoryNum] = useState('')
24
    const [tag, setTag] = useState(0)
25
26
    const [subCate, setSubCate] = useState([])
    const [cateList, setCateList] = useState([])
Jiwon Yoon's avatar
Jiwon Yoon committed
27
    const [color, setColor] = useState({})
kusang96's avatar
dd    
kusang96 committed
28
    const [error, setError] = useState('')
29
30
    const [success, setSuccess] = useState(false)
    const [checked, setChecked] = useState({ "Free": false, "XL": false, "L": false, "M": false, "S": false, "XS": false })
kusang96's avatar
kusang96 committed
31
32
33
    const [loading, setLoading] = useState(false)
    const selectRef = useRef(null)
    const colorRef = useRef(null)
34

kusang96's avatar
kusang96 committed
35
36
    useEffect(async () => {
        try {
kusang96's avatar
kusang96 committed
37
            setError('')
이재연's avatar
이재연 committed
38
            const response = await axios.get('/api/categories/main')
kusang96's avatar
kusang96 committed
39
            const data = response.data[0]
Jiwon Yoon's avatar
Jiwon Yoon committed
40
            setCategories([Object.keys(data), Object.values(data)])
kusang96's avatar
kusang96 committed
41
42
43
44
        } catch (error) {
            catchErrors(error, setError)
        }
    }, [])
45
46

    function deleteCategory(e) {
47
48
49
        const pdcate = product.sub_category.filter((el) => el !== e.target.name)
        setProduct({ ...product, "sub_category": pdcate })
        setSubCate([])
Jiwon Yoon's avatar
Jiwon Yoon committed
50
    }
51

Jiwon Yoon's avatar
Jiwon Yoon committed
52
    function handleCategory(e) {
kusang96's avatar
kusang96 committed
53
54
        const { name, value, selectedIndex } = e.target
        if (name === "main_category") {
55
            setProduct({ ...product, [name]: value })
kusang96's avatar
kusang96 committed
56
            setCategoryNum(selectedIndex - 1)
Jiwon Yoon's avatar
Jiwon Yoon committed
57
        }
58
59
60
61
        else {
            subCate.push(value)
            setProduct({ ...product, [name]: subCate })
            selectRef.current.selectedIndex = 0
Jiwon Yoon's avatar
Jiwon Yoon committed
62
        }
63
    }
kusang96's avatar
kusang96 committed
64

65
66
67
    function handleCheckBox(e) {
        setChecked({ ...checked, [e.target.value]: !checked[`${e.target.value}`] })
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
68

69
    function addColor() {
kusang96's avatar
kusang96 committed
70
        colorRef.current.value = ''
71
        setProduct({ ...product, "colors":[...product.colors, color["colors"]] })
Jiwon Yoon's avatar
Jiwon Yoon committed
72
    }
73

Jiwon Yoon's avatar
Jiwon Yoon committed
74
    function deleteColor(e) {
75
76
        const pdcolors = product.colors.filter((el) => el !== e.target.name)
        setProduct({ ...product, "colors": pdcolors })
Jiwon Yoon's avatar
Jiwon Yoon committed
77
    }
78

Jiwon Yoon's avatar
Jiwon Yoon committed
79
    function handleColor(e) {
kusang96's avatar
kusang96 committed
80
        color[e.target.name] = e.target.value
81
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
82
83

    function handleChange(event) {
Jiwon Yoon's avatar
0111    
Jiwon Yoon committed
84
        const { name, value, files } = event.target
Jiwon Yoon's avatar
Jiwon Yoon committed
85
        if (files) {
kusang96's avatar
dd    
kusang96 committed
86
87
88
89
            setProduct({ ...product, [name]: files })
        } else {
            setProduct({ ...product, [name]: value })
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
90
91
    }

kusang96's avatar
dd    
kusang96 committed
92
    async function handleSubmit(e) {
Jiwon Yoon's avatar
Jiwon Yoon committed
93
        e.preventDefault()
94
95
96
97
98
99
        const sizes = []
        for (let [key, value] of Object.entries(checked)) {
            if (value === true) {
                sizes.push(key)
            }
        }
kusang96's avatar
kusang96 committed
100
        product["sizes"] = sizes
kusang96's avatar
kusang96 committed
101
        const formData = new FormData();
이재연's avatar
0113    
이재연 committed
102
        for (let key in product) {
Jiwon Yoon's avatar
Jiwon Yoon committed
103
            if (key === "main_image") {
이재연's avatar
0113    
이재연 committed
104
                formData.append(key, product[key][0])
Jiwon Yoon's avatar
Jiwon Yoon committed
105
            } else if (key === "sizes" || key === "colors" || key === "sub_category" || key === "detail_image") {
Jiwon Yoon's avatar
Jiwon Yoon committed
106
                for (let i = 0; i < product[key].length; i++) {
Jiwon Yoon's avatar
Jiwon Yoon committed
107
108
                    formData.append([key], product[key][i])
                }
Jiwon Yoon's avatar
Jiwon Yoon committed
109
            }
Jiwon Yoon's avatar
Jiwon Yoon committed
110
            else {
kusang96's avatar
dd    
kusang96 committed
111
112
113
114
                formData.append(key, product[key])
            }
        }
        try {
kusang96's avatar
kusang96 committed
115
116
            setLoading(true)
            setError('')
kusang96's avatar
0115    
kusang96 committed
117
118
            const response = await axios.post('/api/product/regist', formData)
            setSuccess(true)
kusang96's avatar
dd    
kusang96 committed
119
120
        } catch (error) {
            catchErrors(error, setError)
kusang96's avatar
kusang96 committed
121
122
        } finally {
            setLoading(false)
kusang96's avatar
kusang96 committed
123
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
124
125
    }

126
    if (success) {
kusang96's avatar
kusang96 committed
127
        alert('상품 등록을 완료하였습니다.')
kusang96's avatar
0115    
kusang96 committed
128
        return <Redirect to='/admin' />
129
    }
kusang96's avatar
kusang96 committed
130

Kim, Subin's avatar
Kim, Subin committed
131
    return (
132
        <Container>
kusang96's avatar
kusang96 committed
133
134
            <Row className="justify-content-md-center">
                <Col md={8} className="border p-1" style={{ background: '#F7F3F3' }}>
135
                    {error && <Alert variant="danger" className="text-center">{error}</Alert>}
kusang96's avatar
kusang96 committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
                    <h2 className="text-center mt-5 font-weight-bold">상품등록</h2>
                    <Form className="p-5" onSubmit={handleSubmit}>
                        <Form.Group controlId="productNameform">
                            <Form.Label>상품명</Form.Label>
                            <Form.Control type="text" name="pro_name" placeholder="상품명" onChange={handleChange} />
                        </Form.Group>
                        <Form.Group controlId="productAmountform">
                            <Form.Label>재고</Form.Label>
                            <Form.Control type="text" name="stock" placeholder="숫자만 입력해주세요" onChange={handleChange} />
                        </Form.Group>
                        <Form.Group controlId="productPriceform">
                            <Form.Label>가격</Form.Label>
                            <Form.Control type="text" name="price" placeholder="숫자만 입력해주세요" onChange={handleChange} />
                        </Form.Group>
                        <Form.Group>
                            <Form.Label>분류</Form.Label>
                            <Row>
박상호's avatar
good    
박상호 committed
153
154
                                <Col md={4} className="mb-1">
                                    <Form.Control as="select" name="main_category" onChange={handleCategory} disabled={product["sub_category"].length > 0} >
kusang96's avatar
kusang96 committed
155
                                        <option value="" >상위분류</option>
Jiwon Yoon's avatar
Jiwon Yoon committed
156
                                        {categories[0].map((main) => (
kusang96's avatar
kusang96 committed
157
158
159
160
                                            <option value={main}>{main}</option>
                                        ))}
                                    </Form.Control>
                                </Col>
박상호's avatar
good    
박상호 committed
161
                                <Col md={6} className="mb-2">
kusang96's avatar
kusang96 committed
162
                                    <Form.Control as="select" ref={selectRef} name="sub_category" onChange={handleCategory}>
kusang96's avatar
kusang96 committed
163
                                        <option value="" >하위분류</option>
kusang96's avatar
kusang96 committed
164
                                        {(categoryNum === '') ? '' : (categories[1][categoryNum].map((sub) => (
kusang96's avatar
kusang96 committed
165
                                            <option value={sub}>{sub}</option>
kusang96's avatar
kusang96 committed
166
                                        )))}
kusang96's avatar
kusang96 committed
167
168
169
                                    </Form.Control>
                                </Col>
                            </Row>
170
171
172
173
174
175
176
177
                            {product.sub_category.map((el) => (
                                <div className="my-2">
                                    <p name={el} className="mb-0" style={{ display: 'inline-block'}} >{product["main_category"]} / {el} </p>
                                    <Button name={el} type="button" className="float-right p-0 btn-light" style={{ display: 'inline-block' }} onClick={deleteCategory} >
                                        <img className="align-top" name={el} alt="삭제" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" />
                                    </Button>
                                </div>
                            ))}
kusang96's avatar
kusang96 committed
178
179
180
                        </Form.Group>
                        <Form.Group>
                            <Form.Label>사이즈</Form.Label>
박상호's avatar
good    
박상호 committed
181
                            <Row className="px-3">
kusang96's avatar
kusang96 committed
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
                                <Col>
                                    <Form.Check type="checkbox" name="sizes" label="210" value="210" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="215" value="215" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="220" value="220" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="225" value="225" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="230" value="230" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="235" value="235" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="240" value="240" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="245" value="245" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="250" value="250" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="255" value="255" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="260" value="260" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="265" value="265" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="270" value="270" onChange={handleCheckBox} />
                                </Col>
                                <Col>
                                    <Form.Check type="checkbox" name="sizes" label="FREE" value="FREE" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="XL" value="XL" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="L" value="L" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="M" value="M" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="S" value="S" onChange={handleCheckBox} />
                                    <Form.Check type="checkbox" name="sizes" label="XS" value="XS" onChange={handleCheckBox} />
                                </Col>
                            </Row>
kusang96's avatar
kusang96 committed
206
207
208
209
                        </Form.Group>
                        <Form.Group>
                            <Form.Label>색상</Form.Label>
                            <Row>
210
                                <Col md={9} xs={9} className="pr-0">
211
                                    <Form.Control as="input" ref={colorRef} name="colors" placeholder="색상" onChange={handleColor} />
kusang96's avatar
kusang96 committed
212
                                </Col>
213
                                <Col className="pl-0">
kusang96's avatar
kusang96 committed
214
215
216
                                    <Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addColor}>추가</Button>
                                </Col>
                            </Row>
217
218
219
220
221
222
223
224
                            {product.colors.map((el) => (
                                <div className="my-2">
                                    <p className="mb-0"  style={{ display: 'inline-block' }}>{el}</p>
                                    <Button style={{ display: 'inline-block' }} name={el} type="button" className="float-right p-0 btn-light" onClick={deleteColor}>
                                        <img className="align-top"  name={el} alt="삭제" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" />
                                    </Button>
                                </div>
                            ))}
kusang96's avatar
kusang96 committed
225
226
227
228
229
230
231
232
233
234
235
                        </Form.Group>
                        <Form.Group controlId="productDescriptionform">
                            <Form.Label>상품설명</Form.Label>
                            <Form.Control as="textarea" name="description" rows={3} placeholder="상품을 설명해주세요" onChange={handleChange} />
                        </Form.Group>
                        <Form.Group>
                            <Form.Label>대표이미지</Form.Label>
                            <Form.File id="productImageform" name="main_image" onChange={handleChange} />
                        </Form.Group>
                        <Form.Group>
                            <Form.Label>상세이미지</Form.Label>
Jiwon Yoon's avatar
Jiwon Yoon committed
236
                            <Form.File id="productImageform" name="detail_image" onChange={handleChange} multiple />
kusang96's avatar
kusang96 committed
237
                        </Form.Group>
kusang96's avatar
kusang96 committed
238
239
240
                        <Button type="submit" style={{ background: '#91877F', borderColor: '#91877F' }} block>
                            {loading && <Spinner as='span' animation='border' size='sm' role='status' aria-hidden='true' />}{' '}등록
                        </Button>
kusang96's avatar
kusang96 committed
241
242
243
244
                    </Form>
                </Col>
            </Row>
        </Container>
Kim, Subin's avatar
Kim, Subin committed
245
246
247
248
    )
}

export default ProductsRegist