Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 7205 | Rev 7207 | 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(() => {
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
 
7202 stevensc 128
      const categories = []
129
 
7205 stevensc 130
      for (const id of data.category_id) {
7202 stevensc 131
        const category = questionsCategories.find((c) => c.value === id)
7206 stevensc 132
        console.log(id)
133
        console.log(category)
7202 stevensc 134
        categories.concat(category)
135
      }
136
 
7206 stevensc 137
      console.log(categories)
7190 stevensc 138
      setCurrentCategories(categories)
7186 stevensc 139
 
140
      setValue('title', data.title)
141
      setValue('description', data.description)
142
    })
7204 stevensc 143
  }, [url, show, isEdit, questionsCategories])
7186 stevensc 144
 
145
  useEffect(() => {
146
    if (!show) {
147
      setValue('category_id', '')
148
      setValue('description', '')
149
      setValue('title', '')
150
      setValue('image', '')
151
    }
152
  }, [show])
153
 
154
  return (
155
    <Modal show={show}>
156
      <Modal.Header className="pb-0">
157
        <Modal.Title>
158
          {isEdit ? labels.edit : labels.add} {labels.question}
159
        </Modal.Title>
160
      </Modal.Header>
161
      <Modal.Body>
162
        {loading ? (
163
          <Spinner />
164
        ) : (
165
          <Form onSubmit={onSubmit}>
166
            <Form.Group>
167
              <Form.Label>{labels.title}</Form.Label>
168
              <Form.Control
169
                type="text"
170
                name="title"
171
                ref={register({ required: true })}
172
              />
173
              {errors.title && (
174
                <FormErrorFeedback>
175
                  {labels.error_field_empty}
176
                </FormErrorFeedback>
177
              )}
178
            </Form.Group>
179
 
180
            <CKEditor
181
              onChange={(e) => setValue('description', e.editor.getData())}
182
              onInstanceReady={(e) =>
183
                e.editor.setData(getValues('description'))
184
              }
185
              config={CKEDITOR_OPTIONS}
186
            />
187
            {errors.description && (
188
              <FormErrorFeedback>{labels.error_field_empty}</FormErrorFeedback>
189
            )}
190
 
7192 stevensc 191
            <TagsContainer>
192
              <TagsInput
193
                suggestions={questionsCategories}
194
                settedTags={currentCategories}
195
                onChange={onTagsChange}
196
              />
197
            </TagsContainer>
7190 stevensc 198
 
7186 stevensc 199
            <Button className="mt-3 mr-2" variant="primary" type="submit">
200
              {labels.accept}
201
            </Button>
202
            <Button className="btn-secondary mt-3" onClick={onClose}>
203
              {labels.cancel}
204
            </Button>
205
          </Form>
206
        )}
207
      </Modal.Body>
208
    </Modal>
209
  )
210
}
211
 
212
export default QuestionModal