Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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