Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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