Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 7190 | Rev 7192 | 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) => {
7191 stevensc 97
    const categories = tags.map((tag) => tag.value)
98
    setValue('category_id', categories)
7190 stevensc 99
  }
100
 
7186 stevensc 101
  useEffect(() => {
102
    register('description', { required: true })
7190 stevensc 103
    register('category_id', { required: true })
7186 stevensc 104
  }, [])
105
 
106
  useEffect(() => {
107
    if (!url || !show || !isEdit) return
108
 
109
    axios.get(url).then((response) => {
110
      const { data, success } = response.data
111
 
112
      if (!success) {
113
        const errorMessage =
114
          typeof data === 'string' ? data : labels.error_there_was_an_error
115
 
116
        dispatch(
117
          addNotification({
118
            style: 'danger',
119
            msg: errorMessage,
120
          })
121
        )
122
        return
123
      }
7190 stevensc 124
      const categories = questionsCategories.map(
125
        (category) => data.category_id.includes(category.uuid) && category
126
      )
127
      setCurrentCategories(categories)
7186 stevensc 128
 
129
      setValue('title', data.title)
130
      setValue('description', data.description)
131
    })
132
  }, [url, show, isEdit])
133
 
134
  useEffect(() => {
135
    if (!show) {
136
      setValue('category_id', '')
137
      setValue('description', '')
138
      setValue('title', '')
139
      setValue('image', '')
7190 stevensc 140
    } else {
141
      getCategories()
7186 stevensc 142
    }
143
  }, [show])
144
 
145
  return (
146
    <Modal show={show}>
147
      <Modal.Header className="pb-0">
148
        <Modal.Title>
149
          {isEdit ? labels.edit : labels.add} {labels.question}
150
        </Modal.Title>
151
      </Modal.Header>
152
      <Modal.Body>
153
        {loading ? (
154
          <Spinner />
155
        ) : (
156
          <Form onSubmit={onSubmit}>
157
            <Form.Group>
158
              <Form.Label>{labels.title}</Form.Label>
159
              <Form.Control
160
                type="text"
161
                name="title"
162
                ref={register({ required: true })}
163
              />
164
              {errors.title && (
165
                <FormErrorFeedback>
166
                  {labels.error_field_empty}
167
                </FormErrorFeedback>
168
              )}
169
            </Form.Group>
170
 
171
            <CKEditor
172
              onChange={(e) => setValue('description', e.editor.getData())}
173
              onInstanceReady={(e) =>
174
                e.editor.setData(getValues('description'))
175
              }
176
              config={CKEDITOR_OPTIONS}
177
            />
178
            {errors.description && (
179
              <FormErrorFeedback>{labels.error_field_empty}</FormErrorFeedback>
180
            )}
181
 
7190 stevensc 182
            <TagsInput
7191 stevensc 183
              suggestions={questionsCategories}
184
              settedTags={currentCategories}
7190 stevensc 185
              onChange={onTagsChange}
186
            />
187
 
7186 stevensc 188
            <Button className="mt-3 mr-2" variant="primary" type="submit">
189
              {labels.accept}
190
            </Button>
191
            <Button className="btn-secondary mt-3" onClick={onClose}>
192
              {labels.cancel}
193
            </Button>
194
          </Form>
195
        )}
196
      </Modal.Body>
197
    </Modal>
198
  )
199
}
200
 
201
export default QuestionModal