Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

Rev Autor Línea Nro. Línea
6770 stevensc 1
import React, { useEffect, useRef } from 'react'
6769 stevensc 2
import { axios, CKEDITOR_OPTIONS } from '../../utils'
3
import { Button, Modal } from 'react-bootstrap'
4
import { useForm } from 'react-hook-form'
5
import { CKEditor } from 'ckeditor4-react'
6
import { useDispatch, useSelector } from 'react-redux'
7
import { addNotification } from '../../redux/notification/notification.actions'
8
import { getMonths, getYears } from '../../utils/dates'
6779 stevensc 9
import useFetchHelper from '../../hooks/useFetchHelper'
6769 stevensc 10
 
11
import SwitchInput from '../UI/SwitchInput'
12
import FormErrorFeedback from '../UI/FormErrorFeedback'
13
import UbicationInput from '../../../shared/ubication-input/UbicationInput'
14
 
15
const ExperienceModal = ({
16
  show = false,
17
  url = '',
18
  onClose = () => {},
19
  onComplete = () => {},
20
  isEdit = false,
21
}) => {
22
  const addressKeys = useRef([
23
    'address1',
24
    'address2',
25
    'country',
26
    'state',
27
    'city1',
28
    'city2',
29
    'postal_code',
30
    'latitude',
31
    'longitude',
32
  ])
33
  const labels = useSelector(({ intl }) => intl.labels)
34
  const dispatch = useDispatch()
6779 stevensc 35
  const { data: companySizes } = useFetchHelper('company-sizes')
6880 stevensc 36
  const { data: industries } = useFetchHelper('industries')
6769 stevensc 37
 
38
  const {
39
    register,
40
    errors,
41
    handleSubmit,
42
    setValue,
43
    clearErrors,
44
    watch,
45
    setError,
46
    reset,
47
  } = useForm()
48
 
49
  const handleModalOpen = () => {
50
    reset()
51
    onClose()
52
  }
53
 
54
  const getAddressHandler = (addresObject) => {
55
    addressKeys.current.map((addressKey) => setValue(addressKey, ''))
56
 
57
    const { address_components } = addresObject
58
 
59
    if (address_components) {
60
      address_components.map((address_component) => {
61
        const address_component_name = address_component.long_name
62
        const address_component_type = address_component.types[0]
63
        switch (address_component_type) {
64
          case 'route':
65
            setValue('address1', address_component_name)
66
            break
67
          case 'sublocality':
68
            setValue('address2', address_component_name)
69
            break
70
          case 'locality':
71
            setValue('city1', address_component_name)
72
            break
73
          case 'administrative_area_level_2':
74
            setValue('city2', address_component_name)
75
            break
76
          case 'administrative_area_level_1':
77
            setValue('state', address_component_name)
78
            break
79
          case 'country':
80
            setValue('country', address_component_name)
81
            break
82
          case 'postal_code':
83
            setValue('postal_code', address_component_name)
84
            break
85
          case 'geometry':
86
            setValue('latitude', address_component.latitude)
87
            setValue('longitude', address_component.longitude)
88
            break
89
          default:
90
            break
91
        }
92
      })
93
    }
94
 
95
    setValue('formatted_address', addresObject.formatted_address)
96
    clearErrors('formatted_address')
97
  }
98
 
99
  const onSubmit = handleSubmit((data) => {
100
    const formData = new FormData()
101
 
102
    Object.entries(data).map(([key, value]) => {
103
      if (!value) {
104
        return
105
      }
106
      formData.append(key, value)
107
    })
108
 
109
    axios.post(url, formData).then(({ data: response }) => {
110
      const { data, success } = response
111
 
112
      if (!success) {
113
        typeof data === 'string'
114
          ? dispatch(addNotification({ style: 'danger', msg: data }))
115
          : Object.entries(data).map(([key, value]) =>
116
              setError(key, { message: value[0] })
117
            )
118
        return
119
      }
120
 
121
      onComplete(data)
122
      handleModalOpen()
123
    })
124
  })
125
 
126
  useEffect(() => {
127
    addressKeys.current.map((addressKey) => register(addressKey))
128
    register('formatted_address', { required: 'Este campo es requerido' })
129
    register('description', { required: true })
130
    register('is_current', { required: true })
131
  }, [])
132
 
133
  useEffect(() => {
134
    if (!isEdit) return
135
 
136
    axios.get(url).then(({ data: response }) => {
137
      const { data, success } = response
138
 
139
      if (!success) {
140
        const errorMessage = typeof data === 'string' ? data : 'Error'
6775 stevensc 141
        dispatch(addNotification({ style: 'danger', msg: errorMessage }))
6769 stevensc 142
        return
143
      }
144
 
145
      Object.entries(data.experience).map(
146
        ([key, value]) => value && setValue(key, value)
147
      )
148
      Object.entries(data.location).map(
149
        ([key, value]) => value && setValue(key, value)
150
      )
151
    })
152
  }, [isEdit, show])
153
 
6880 stevensc 154
  useEffect(() => {
155
    console.log(errors)
156
  }, [errors])
157
 
6769 stevensc 158
  return (
159
    <Modal show={show} onHide={handleModalOpen}>
160
      <Modal.Header>
161
        <Modal.Title>
162
          {isEdit ? labels.edit : labels.add} - {labels.experience}
163
        </Modal.Title>
164
      </Modal.Header>
165
      <form onSubmit={onSubmit}>
166
        <Modal.Body>
167
          <div className="form-group">
168
            <input
169
              type="text"
170
              name="company"
171
              placeholder="Empresa"
172
              ref={register({
173
                required: 'este campo es requerido',
174
              })}
175
            />
176
            {errors.company && (
177
              <FormErrorFeedback>{errors.company.message}</FormErrorFeedback>
178
            )}
179
          </div>
6880 stevensc 180
          <div className="form-group">
6769 stevensc 181
            <select
182
              name="industry_id"
183
              id="industry_id"
184
              ref={register({
185
                required: 'este campo es requerido',
186
              })}
187
              defaultValue=""
188
            >
189
              <option value="" hidden>
190
                Industria
191
              </option>
6880 stevensc 192
              {Boolean(industries.length) &&
193
                industries.map(({ name, value }) => (
194
                  <option value={value} key={value}>
195
                    {name}
6769 stevensc 196
                  </option>
197
                ))}
198
            </select>
199
            {errors.industry_id && (
200
              <FormErrorFeedback>
201
                {errors.industry_id.message}
202
              </FormErrorFeedback>
203
            )}
6880 stevensc 204
          </div>
6769 stevensc 205
          <div className="form-group">
206
            <select
207
              name="company_size_id"
208
              id="company_size_id"
209
              ref={register({
210
                required: 'este campo es requerido',
211
              })}
212
              defaultValue=""
213
            >
214
              <option value="" hidden>
215
                Tamaño de la Empresa
216
              </option>
6871 stevensc 217
              {Boolean(companySizes.length) &&
218
                companySizes.map(({ name, value }) => (
219
                  <option value={value} key={value}>
220
                    {name}
6779 stevensc 221
                  </option>
222
                ))}
6769 stevensc 223
            </select>
224
            {errors.company_size_id && (
225
              <FormErrorFeedback>
226
                {errors.company_size_id.message}
227
              </FormErrorFeedback>
228
            )}
229
          </div>
230
          <div className="form-group">
231
            <input
232
              type="text"
233
              name="title"
234
              placeholder="Titulo"
235
              ref={register({
236
                required: 'este campo es requerido',
237
              })}
238
            />
239
            {errors.title && (
240
              <FormErrorFeedback>{errors.title.message}</FormErrorFeedback>
241
            )}
242
          </div>
243
          <div className="form-group datefm">
244
            <UbicationInput
245
              onGetAddress={getAddressHandler}
246
              settedQuery={watch('formatted_address')}
247
            />
248
            <i className="fa fa-map-marker" />
249
            {errors.formatted_address && (
250
              <FormErrorFeedback>
251
                {errors.formatted_address.message}
252
              </FormErrorFeedback>
253
            )}
254
          </div>
255
          <div className="row profile-year" style={{ gap: '.5rem' }}>
256
            <div className="input-c p-0">
257
              <div className="form-group">
258
                <select
259
                  name="from_month"
260
                  id="from_month"
261
                  ref={register({ required: 'este campo es requerido' })}
262
                  defaultValue=""
263
                >
264
                  <option value="">Mes desde</option>
265
                  {getMonths().map((month, id) => (
266
                    <option key={id} value={id + 1}>
267
                      {month}
268
                    </option>
269
                  ))}
270
                </select>
271
                {errors.from_month && (
272
                  <FormErrorFeedback>
273
                    {errors.from_month.message}
274
                  </FormErrorFeedback>
275
                )}
276
              </div>
277
            </div>
278
            <div className="input-c p-0">
279
              <div className="form-group">
280
                <select
281
                  name="from_year"
282
                  ref={register({ required: 'este campo es requerido' })}
283
                  defaultValue=""
284
                >
285
                  <option value="">Año desde</option>
286
                  {getYears().map((year) => (
287
                    <option key={year} value={year}>
288
                      {year}
289
                    </option>
290
                  ))}
291
                </select>
292
                {errors.from_year && (
293
                  <FormErrorFeedback>
294
                    {errors.from_year.message}
295
                  </FormErrorFeedback>
296
                )}
297
              </div>
298
            </div>
299
          </div>
300
          <label htmlFor="is_current"> Trabajo Actual</label>
301
          <div className="form-group">
302
            <SwitchInput
6881 stevensc 303
              isChecked={watch('is_current' === 'y')}
6769 stevensc 304
              setValue={(val) => setValue('is_current', val ? 'y' : 'n')}
305
            />
306
          </div>
307
          {!watch('is_current') && (
308
            <div className="row profile-year">
309
              <div className="input-c p-0">
310
                <div className="form-group">
311
                  <select
312
                    name="to_month"
313
                    id="to_month"
6881 stevensc 314
                    ref={register}
6769 stevensc 315
                    defaultValue=""
316
                  >
317
                    <option value="">Mes hasta</option>
318
                    {getMonths().map((month, id) => (
319
                      <option key={id} value={id + 1}>
320
                        {month}
321
                      </option>
322
                    ))}
323
                  </select>
324
                  {errors.to_month && (
325
                    <FormErrorFeedback>
326
                      {errors.to_month.message}
327
                    </FormErrorFeedback>
328
                  )}
329
                </div>
330
              </div>
331
              <div className="input-c p-0">
332
                <div className="form-group">
333
                  <select
334
                    name="to_year"
335
                    id="to_year"
6881 stevensc 336
                    ref={register}
6769 stevensc 337
                    defaultValue=""
338
                  >
339
                    <option value="">Año hasta</option>
340
                    {getYears().map((year) => (
341
                      <option key={year} value={year}>
342
                        {year}
343
                      </option>
344
                    ))}
345
                  </select>
346
                  {errors.to_year && (
347
                    <FormErrorFeedback>
348
                      {errors.to_year.message}
349
                    </FormErrorFeedback>
350
                  )}
351
                </div>
352
              </div>
353
            </div>
354
          )}
355
          <div className="form-group">
356
            <CKEditor
357
              onChange={(e) => setValue('description', e.editor.getData())}
6875 stevensc 358
              onInstanceReady={(e) => e.editor.setData(watch('description'))}
6769 stevensc 359
              config={CKEDITOR_OPTIONS}
360
            />
361
            {errors.description && (
362
              <FormErrorFeedback>Este campo es requerido</FormErrorFeedback>
363
            )}
364
          </div>
365
        </Modal.Body>
366
        <Modal.Footer>
367
          <Button size="sm" type="submit">
368
            {labels.accept}
369
          </Button>
370
          <Button size="sm" variant="danger" onClick={handleModalOpen}>
371
            {labels.cancel}
372
          </Button>
373
        </Modal.Footer>
374
      </form>
375
    </Modal>
376
  )
377
}
378
 
379
export default ExperienceModal