Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 7186 | Rev 7191 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
7186 stevensc 1
import React, { useEffect, useState } from 'react'
2
import { Button, Form, Modal } from 'react-bootstrap'
3
import { useDispatch, useSelector } from 'react-redux'
4
import Spinner from '../UI/Spinner'
5
import { CKEditor } from 'ckeditor4-react'
6
import { CKEDITOR_OPTIONS, axios } from '../../utils'
7
import FormErrorFeedback from '../UI/FormErrorFeedback'
8
import { useForm } from 'react-hook-form'
9
import { addNotification } from '../../redux/notification/notification.actions'
7190 stevensc 10
import TagsInput from '../../../shared/tags-input/TagsInput'
7186 stevensc 11
 
12
const QuestionModal = ({ show, url, isEdit, onClose, onComplete }) => {
13
  const [loading, setLoading] = useState(false)
7190 stevensc 14
  const [questionsCategories, setQuestionsCategories] = useState([])
15
  const [currentCategories, setCurrentCategories] = useState([])
7186 stevensc 16
  const labels = useSelector(({ intl }) => intl.labels)
17
  const dispatch = useDispatch()
18
 
19
  const { register, handleSubmit, getValues, setValue, errors } = useForm()
20
 
21
  const onSubmit = handleSubmit((data) => {
22
    setLoading(true)
23
    const formData = new FormData()
24
    Object.entries(data).map(([key, value]) => {
25
      if (['attachment', 'image'].includes(key) && value) {
26
        formData.append(key, value[0])
27
        return
28
      }
29
      formData.append(key, value)
30
    })
31
 
32
    axios
33
      .post(url, formData)
34
      .then((response) => {
35
        const { data, success } = response.data
36
        if (!success) {
37
          if (typeof data === 'string') {
38
            dispatch(addNotification({ style: 'danger', msg: data }))
39
            return
40
          }
41
 
42
          Object.entries(data).map(([key, value]) => {
43
            key in getValues() &&
44
              dispatch(
45
                addNotification({
46
                  style: 'danger',
47
                  msg: `${key}: ${Array.isArray(value) ? value[0] : value}`,
48
                })
49
              )
50
          })
51
          return
52
        }
53
 
54
        onComplete()
55
        onClose()
56
      })
57
      .finally(() => setLoading(false))
58
  })
59
 
7190 stevensc 60
  const getCategories = () => {
61
    axios
62
      .get('/my-coach', {
63
        headers: {
64
          'Content-Type': 'application/json',
65
        },
66
      })
67
      .then((response) => {
68
        const { data, success } = response.data
69
 
70
        if (!success) {
71
          const errorMessage =
72
            typeof data === 'string' ? data : labels.error_there_was_an_error
73
 
74
          dispatch(addNotification({ style: 'danger', msg: errorMessage }))
75
          return
76
        }
77
 
78
        const categories = Object.entries(data.categories).map((values) => ({
79
          name: values[1],
80
          value: values[0],
81
        }))
82
 
83
        setQuestionsCategories(categories)
84
      })
85
      .catch((error) => {
86
        dispatch(
87
          addNotification({
88
            style: 'danger',
89
            msg: labels.error_there_was_an_error,
90
          })
91
        )
92
        throw new Error(error)
93
      })
94
  }
95
 
96
  const onTagsChange = (tags) => {
97
    setValue('category_id', tags)
98
  }
99
 
7186 stevensc 100
  useEffect(() => {
101
    register('description', { required: true })
7190 stevensc 102
    register('category_id', { required: true })
7186 stevensc 103
  }, [])
104
 
105
  useEffect(() => {
106
    if (!url || !show || !isEdit) return
107
 
108
    axios.get(url).then((response) => {
109
      const { data, success } = response.data
110
 
111
      if (!success) {
112
        const errorMessage =
113
          typeof data === 'string' ? data : labels.error_there_was_an_error
114
 
115
        dispatch(
116
          addNotification({
117
            style: 'danger',
118
            msg: errorMessage,
119
          })
120
        )
121
        return
122
      }
7190 stevensc 123
      const categories = questionsCategories.map(
124
        (category) => data.category_id.includes(category.uuid) && category
125
      )
126
      setCurrentCategories(categories)
7186 stevensc 127
 
128
      setValue('title', data.title)
129
      setValue('description', data.description)
130
    })
131
  }, [url, show, isEdit])
132
 
133
  useEffect(() => {
134
    if (!show) {
135
      setValue('category_id', '')
136
      setValue('description', '')
137
      setValue('title', '')
138
      setValue('image', '')
7190 stevensc 139
    } else {
140
      getCategories()
7186 stevensc 141
    }
142
  }, [show])
143
 
144
  return (
145
    <Modal show={show}>
146
      <Modal.Header className="pb-0">
147
        <Modal.Title>
148
          {isEdit ? labels.edit : labels.add} {labels.question}
149
        </Modal.Title>
150
      </Modal.Header>
151
      <Modal.Body>
152
        {loading ? (
153
          <Spinner />
154
        ) : (
155
          <Form onSubmit={onSubmit}>
156
            <Form.Group>
157
              <Form.Label>{labels.title}</Form.Label>
158
              <Form.Control
159
                type="text"
160
                name="title"
161
                ref={register({ required: true })}
162
              />
163
              {errors.title && (
164
                <FormErrorFeedback>
165
                  {labels.error_field_empty}
166
                </FormErrorFeedback>
167
              )}
168
            </Form.Group>
169
 
170
            <CKEditor
171
              onChange={(e) => setValue('description', e.editor.getData())}
172
              onInstanceReady={(e) =>
173
                e.editor.setData(getValues('description'))
174
              }
175
              config={CKEDITOR_OPTIONS}
176
            />
177
            {errors.description && (
178
              <FormErrorFeedback>{labels.error_field_empty}</FormErrorFeedback>
179
            )}
180
 
7190 stevensc 181
            <TagsInput
182
              suggestions={currentCategories}
183
              settedTags={questionsCategories}
184
              onChange={onTagsChange}
185
            />
186
 
7186 stevensc 187
            <Button className="mt-3 mr-2" variant="primary" type="submit">
188
              {labels.accept}
189
            </Button>
190
            <Button className="btn-secondary mt-3" onClick={onClose}>
191
              {labels.cancel}
192
            </Button>
193
          </Form>
194
        )}
195
      </Modal.Body>
196
    </Modal>
197
  )
198
}
199
 
200
export default QuestionModal