Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

Rev Autor Línea Nro. Línea
5475 stevensc 1
/* eslint-disable camelcase */
2
/* eslint-disable react/prop-types */
3
import { CKEditor } from 'ckeditor4-react'
4
import React, { useEffect, useRef } from 'react'
5
import { Button, Modal } from 'react-bootstrap'
6
import { useForm } from 'react-hook-form'
7
import { useDispatch } from 'react-redux'
8
import styled from 'styled-components'
9
 
10
import { addNotification } from '../../../redux/notification/notification.actions'
11
import FormErrorFeedback from '../../../shared/form-error-feedback/FormErrorFeedback'
12
import UbicationInput from '../../../shared/ubication-input/UbicationInput'
13
import { axios, CKEDITOR_OPTIONS } from '../../../utils'
14
 
15
const StyledSwitch = styled.label`
16
  position: relative;
17
  display: inline-block;
18
  width: 60px;
19
  height: 34px;
20
  input {
21
    opacity: 0;
22
    width: 0;
23
    height: 0;
24
  }
25
  .slider {
26
    position: absolute;
27
    cursor: pointer;
28
    top: 0;
29
    left: 0;
30
    right: 0;
31
    bottom: 0;
32
    background-color: #ccc;
33
    -webkit-transition: 0.4s;
34
    transition: 0.4s;
35
  }
36
  .slider:before {
37
    position: absolute;
38
    content: '';
39
    height: 26px;
40
    width: 26px;
41
    left: 4px;
42
    bottom: 4px;
43
    background-color: white;
44
    -webkit-transition: 0.4s;
45
    transition: 0.4s;
46
  }
47
  input:checked + .slider {
48
    background-color: #2196f3;
49
  }
50
  input:focus + .slider {
51
    box-shadow: 0 0 1px #2196f3;
52
  }
53
  input:checked + .slider:before {
54
    -webkit-transform: translateX(26px);
55
    -ms-transform: translateX(26px);
56
    transform: translateX(26px);
57
  }
58
  .slider.round {
59
    border-radius: 34px;
60
  }
61
 
62
  .slider.round:before {
63
    border-radius: 50%;
64
  }
65
`
66
 
67
const ExperienceModal = ({
68
  show = false,
69
  closeModal = () => {},
70
  setUserExperiences = () => {},
71
  postUrl = '',
72
  settedDescription = '',
73
  industriesOptions = [],
74
  companySizesOptions = [],
75
  months = [],
76
}) => {
77
  const {
78
    register,
79
    errors,
80
    handleSubmit,
81
    setValue,
82
    clearErrors,
83
    getValues,
84
    watch,
85
  } = useForm()
86
  const dispatch = useDispatch()
87
  const isAddressEmpty = useRef(true)
88
  const addressKeys = useRef([
89
    'address1',
90
    'address2',
91
    'country',
92
    'state',
93
    'city1',
94
    'city2',
95
    'postal_code',
96
    'latitude',
97
    'longitude',
98
  ])
99
 
100
  const handleModalOpen = () => {
101
    Object.keys(getValues()).map(([key]) => setValue(key, ''))
102
    closeModal()
103
  }
104
 
105
  const getAddressHandler = (addresObject) => {
106
    addressKeys.current.map((addressKey) => setValue(addressKey, ''))
107
 
108
    const { address_components } = addresObject
109
 
110
    if (address_components) {
111
      address_components.map((address_component) => {
112
        const address_component_name = address_component.long_name
113
        const address_component_type = address_component.types[0]
114
        switch (address_component_type) {
115
          case 'route':
116
            setValue('address1', address_component_name)
117
            break
118
          case 'sublocality':
119
            setValue('address2', address_component_name)
120
            break
121
          case 'locality':
122
            setValue('city1', address_component_name)
123
            break
124
          case 'administrative_area_level_2':
125
            setValue('city2', address_component_name)
126
            break
127
          case 'administrative_area_level_1':
128
            setValue('state', address_component_name)
129
            break
130
          case 'country':
131
            setValue('country', address_component_name)
132
            break
133
          case 'postal_code':
134
            setValue('postal_code', address_component_name)
135
            break
136
          case 'geometry':
137
            setValue('latitude', address_component.latitude)
138
            setValue('longitude', address_component.longitude)
139
            break
140
          default:
141
            break
142
        }
143
      })
144
      isAddressEmpty.current = false
145
    } else {
146
      isAddressEmpty.current = true
147
    }
148
    setValue('formatted_address', addresObject.formatted_address)
149
    clearErrors('formatted_address')
150
  }
151
 
152
  const getYears = () => {
153
    const date = new Date()
154
    const currentYear = date.getFullYear()
155
    let years = []
156
    for (let index = currentYear; index > currentYear - 100; index--) {
157
      years = [...years, index]
158
    }
159
    return years
160
  }
161
 
162
  const onSubmitHandler = async (data) => {
163
    const formData = new FormData()
164
    Object.entries(data).map(([key, value]) => {
165
      if (!value) return null
166
      return formData.append(key, value)
167
    })
168
 
169
    await axios.post(postUrl, formData).then(({ data: response }) => {
170
      if (!response.success) {
171
        typeof response.data === 'string'
172
          ? dispatch(addNotification({ style: 'danger', msg: response.data }))
173
          : Object.entries(response.data).map(([key, value]) => {
174
              if (key in getValues())
175
                dispatch(
176
                  addNotification({
177
                    style: 'danger',
178
                    msg: `${key}: ${Array.isArray(value) ? value[0] : value}`,
179
                  })
180
                )
181
              return null
182
            })
183
        return
184
      }
185
 
186
      setUserExperiences(response.data)
187
      handleModalOpen()
188
    })
189
  }
190
 
191
  useEffect(() => {
192
    addressKeys.current.map((addressKey) => register(addressKey))
193
    register('formatted_address', {
194
      required: 'Este campo es requerido',
195
    })
196
    register('description', { required: true })
197
  }, [])
198
 
199
  useEffect(async () => {
200
    if (settedDescription) {
201
      const { data } = await axios.get(postUrl)
202
      if (!data.success) {
203
        addNotification({
204
          style: 'danger',
205
          msg:
206
            typeof data.data === 'string' ? data.data : 'Ha ocurrido un error',
207
        })
208
        return
209
      }
210
      Object.entries(data.data.experience).map(
211
        ([key, value]) => value && setValue(key, value)
212
      )
213
      Object.entries(data.data.location).map(
214
        ([key, value]) => value && setValue(key, value)
215
      )
216
    }
217
  }, [show])
218
 
219
  return (
220
    <Modal show={show} onHide={handleModalOpen}>
221
      <Modal.Header>
222
        <Modal.Title>Experiencia</Modal.Title>
223
      </Modal.Header>
224
      <form onSubmit={handleSubmit(onSubmitHandler)}>
225
        <Modal.Body>
226
          <div className="form-group">
227
            <input
228
              type="text"
229
              name="company"
230
              placeholder="Empresa"
231
              ref={register({
232
                required: 'este campo es requerido',
233
              })}
234
            />
235
            {errors.company && (
236
              <FormErrorFeedback>{errors.company.message}</FormErrorFeedback>
237
            )}
238
          </div>
239
          <div className="form-group">
240
            <select
241
              name="industry_id"
242
              id="industry_id"
243
              ref={register({
244
                required: 'este campo es requerido',
245
              })}
246
              defaultValue=""
247
            >
248
              <option value="" hidden>
249
                Industria
250
              </option>
5479 stevensc 251
              {industriesOptions &&
252
                Object.entries(industriesOptions).map(([key, value]) => (
253
                  <option value={key} key={key}>
254
                    {value}
255
                  </option>
256
                ))}
5475 stevensc 257
            </select>
258
            {errors.industry_id && (
259
              <FormErrorFeedback>
260
                {errors.industry_id.message}
261
              </FormErrorFeedback>
262
            )}
263
          </div>
264
          <div className="form-group">
265
            <select
266
              name="company_size_id"
267
              id="company_size_id"
268
              ref={register({
269
                required: 'este campo es requerido',
270
              })}
271
              defaultValue=""
272
            >
273
              <option value="" hidden>
274
                Tamaño de la Empresa
275
              </option>
5479 stevensc 276
              {companySizesOptions &&
277
                Object.entries(companySizesOptions).map(([key, value]) => (
278
                  <option value={key} key={key}>
279
                    {value}
280
                  </option>
281
                ))}
5475 stevensc 282
            </select>
283
            {errors.company_size_id && (
284
              <FormErrorFeedback>
285
                {errors.company_size_id.message}
286
              </FormErrorFeedback>
287
            )}
288
          </div>
289
          <div className="form-group">
290
            <input
291
              type="text"
292
              name="title"
293
              placeholder="Titulo"
294
              ref={register({
295
                required: 'este campo es requerido',
296
              })}
297
            />
298
            {errors.title && (
299
              <FormErrorFeedback>{errors.title.message}</FormErrorFeedback>
300
            )}
301
          </div>
302
          <div className="form-group datefm">
303
            <UbicationInput
304
              onGetAddress={getAddressHandler}
305
              settedQuery={watch('formatted_address')}
306
            />
307
            <i className="fa fa-map-marker" />
308
            {errors.formatted_address && (
309
              <FormErrorFeedback>
310
                {errors.formatted_address.message}
311
              </FormErrorFeedback>
312
            )}
313
          </div>
314
          <div className="row profile-year" style={{ gap: '.5rem' }}>
315
            <div className="input-c p-0">
316
              <div className="form-group">
317
                <select
318
                  name="from_month"
319
                  id="from_month"
320
                  ref={register({ required: 'este campo es requerido' })}
321
                  defaultValue=""
322
                >
323
                  <option value="">Mes desde</option>
324
                  {months.map((month, id) => (
325
                    <option key={id} value={id + 1}>
326
                      {month}
327
                    </option>
328
                  ))}
329
                </select>
330
                {errors.from_month && (
331
                  <FormErrorFeedback>
332
                    {errors.from_month.message}
333
                  </FormErrorFeedback>
334
                )}
335
              </div>
336
            </div>
337
            <div className="input-c p-0">
338
              <div className="form-group">
339
                <select
340
                  name="from_year"
341
                  ref={register({ required: 'este campo es requerido' })}
342
                  defaultValue=""
343
                >
344
                  <option value="">Año desde</option>
345
                  {getYears().map((year) => (
346
                    <option key={year} value={year}>
347
                      {year}
348
                    </option>
349
                  ))}
350
                </select>
351
                {errors.from_year && (
352
                  <FormErrorFeedback>
353
                    {errors.from_year.message}
354
                  </FormErrorFeedback>
355
                )}
356
              </div>
357
            </div>
358
          </div>
359
          <label htmlFor="is_current"> Trabajo Actual</label>
360
          <div className="form-group">
361
            <StyledSwitch className="switch">
362
              <input
363
                type="checkbox"
364
                name="is_current"
365
                id="is_current"
366
                value="y"
367
                ref={register}
368
              />
369
              <span className="slider round"></span>
370
            </StyledSwitch>
371
          </div>
372
          {!watch('is_current') && (
373
            <div className="row profile-year">
374
              <div className="input-c p-0">
375
                <div className="form-group">
376
                  <select
377
                    name="to_month"
378
                    id="to_month"
379
                    ref={register({
380
                      required: 'este campo es requerido',
381
                    })}
382
                    defaultValue=""
383
                  >
384
                    <option value="">Mes hasta</option>
385
                    {months.map((month, id) => (
386
                      <option key={id} value={id + 1}>
387
                        {month}
388
                      </option>
389
                    ))}
390
                  </select>
391
                  {errors.to_month && (
392
                    <FormErrorFeedback>
393
                      {errors.to_month.message}
394
                    </FormErrorFeedback>
395
                  )}
396
                </div>
397
              </div>
398
              <div className="input-c p-0">
399
                <div className="form-group">
400
                  <select
401
                    name="to_year"
402
                    id="to_year"
403
                    ref={register({
404
                      required: 'este campo es requerido',
405
                    })}
406
                    defaultValue=""
407
                  >
408
                    <option value="">Año hasta</option>
409
                    {getYears().map((year) => (
410
                      <option key={year} value={year}>
411
                        {year}
412
                      </option>
413
                    ))}
414
                  </select>
415
                  {errors.to_year && (
416
                    <FormErrorFeedback>
417
                      {errors.to_year.message}
418
                    </FormErrorFeedback>
419
                  )}
420
                </div>
421
              </div>
422
            </div>
423
          )}
424
          <div className="form-group">
425
            <CKEditor
426
              onChange={(e) => setValue('description', e.editor.getData())}
427
              onInstanceReady={(e) => e.editor.setData(settedDescription)}
428
              config={CKEDITOR_OPTIONS}
429
            />
430
            {errors.description && (
431
              <FormErrorFeedback>Este campo es requerido</FormErrorFeedback>
432
            )}
433
          </div>
434
        </Modal.Body>
435
        <Modal.Footer>
436
          <Button size="sm" type="submit">
437
            Enviar
438
          </Button>
439
          <Button size="sm" variant="danger" onClick={handleModalOpen}>
440
            Cancelar
441
          </Button>
442
        </Modal.Footer>
443
      </form>
444
    </Modal>
445
  )
446
}
447
 
448
export default ExperienceModal