Proyectos de Subversion LeadersLinked - SPA

Rev

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

Rev Autor Línea Nro. Línea
2970 stevensc 1
import React, { useEffect, useMemo, useRef, useState } from 'react'
813 stevensc 2
import { useForm } from 'react-hook-form'
2970 stevensc 3
import { styled } from '@mui/material'
4
import { Public, LockClock } from '@mui/icons-material'
5 stevensc 5
 
2969 stevensc 6
import { axios } from '@utils'
2970 stevensc 7
import { updateFeed } from '@store/feed/feed.actions'
2969 stevensc 8
import { addNotification } from '@store/notification/notification.actions'
5 stevensc 9
 
2970 stevensc 10
import styles from './survey.module.scss'
11
 
2969 stevensc 12
const RadioButton = styled('div')`
5 stevensc 13
  display: flex;
14
  align-items: center;
15
  gap: 0.5rem;
16
  padding: 0.5rem 1rem;
17
  border: 2px solid var(--border-primary);
18
  border-radius: 50px;
19
  cursor: pointer;
20
  transition: all 200ms ease;
21
  position: relative;
22
  overflow: hidden;
23
  margin-bottom: 0.5rem;
24
  input {
25
    margin: 0 !important;
26
  }
27
  label {
28
    color: var(--font-color);
29
    font-weight: 500;
30
  }
31
  &::before {
813 stevensc 32
    content: '';
5 stevensc 33
    position: absolute;
34
    left: 0;
35
    top: 0;
36
    height: 100%;
813 stevensc 37
    width: ${(props) => (props.porcentage ? `${props.porcentage}%` : '0%')};
5 stevensc 38
    background-color: #0002;
39
    z-index: 4;
40
  }
41
  &:hover {
42
    border-color: var(--font-color);
43
    text-shadow: 0 0 1px var(--font-color);
44
  }
813 stevensc 45
`
5 stevensc 46
 
2969 stevensc 47
const VoteTag = styled('span')`
5 stevensc 48
  position: absolute;
49
  bottom: 1rem;
50
  right: 1rem;
51
  color: var(--font-color) !important;
52
  font-weight: 600;
813 stevensc 53
`
5 stevensc 54
 
3015 stevensc 55
const SurveyForm = (props) => {
56
  const {
57
    active = 0,
58
    question = '¿Cómo consideras el ambiente laboral?',
59
    answers = ['Excelente', 'Regular', null, null, null],
60
    votes = [null, null, null, null, null],
61
    time = 0,
62
    voteUrl = '/feed/vote/d454717c-ba6f-485c-b94c-4fbb5f5bed94',
63
    resultType = 'pu',
64
    voted = 0
65
  } = props
813 stevensc 66
  const [remainingTime, setRemainingTime] = useState('00:00:00')
67
  const [isActive, setIsActive] = useState(true)
68
  const timeRef = useRef(time)
2970 stevensc 69
 
813 stevensc 70
  const { register, handleSubmit } = useForm()
5 stevensc 71
 
3015 stevensc 72
  console.log(props)
73
 
2970 stevensc 74
  const totalVotes = useMemo(
75
    () =>
76
      votes.reduce((curr, next) => {
3016 stevensc 77
        if (!next) return curr
2970 stevensc 78
        return curr + next
79
      }, 0),
80
    [votes]
81
  )
82
 
3014 stevensc 83
  const sendVote = handleSubmit(({ vote }) => {
84
    setIsActive(false)
85
 
86
    const formData = new FormData()
87
    formData.append('vote', vote)
88
 
89
    axios
90
      .post(voteUrl, formData)
91
      .then(({ data: response }) => {
92
        const { success, data } = response
93
 
94
        if (!success) {
95
          const errorMessage =
96
            typeof data === 'string'
97
              ? data
98
              : 'Error interno, por favor intente mas tarde.'
99
          throw new Error(errorMessage)
100
        }
101
 
102
        updateFeed({ feed: data, uuid: data.feed_uuid })
103
        addNotification({ style: 'success', msg: 'Voto emitido con exito' })
104
      })
105
      .catch((err) => {
106
        setIsActive(true)
107
        addNotification({ style: 'danger', msg: err.message })
108
      })
109
  })
110
 
111
  function getTimeDiff(segundos) {
112
    const currentDate = new Date()
113
    const futureDate = new Date(currentDate.getTime() + segundos * 1000)
114
    const diff = futureDate - currentDate
115
 
116
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
117
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
118
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
119
 
120
    return `${addZero(days)}d ${addZero(hours)}h ${addZero(minutes)}m`
121
  }
122
 
123
  function addZero(unit) {
124
    return String(unit).padStart(2, '0')
125
  }
126
 
127
  function getPorcentage(n, total) {
128
    return (n / total) * 100
129
  }
130
 
131
  useEffect(() => {
132
    setIsActive(!!active)
133
  }, [active])
134
 
5 stevensc 135
  return (
3014 stevensc 136
    <form onChange={sendVote} className={styles.survey_form}>
5 stevensc 137
      <h3>{question}</h3>
813 stevensc 138
      {resultType === 'pu' && (
5 stevensc 139
        <span
813 stevensc 140
          className='mb-2'
141
          title='El número de votos es visible para todos los usuarios'
5 stevensc 142
        >
2969 stevensc 143
          <Public /> Público
5 stevensc 144
        </span>
145
      )}
813 stevensc 146
      {resultType === 'pr' && (
5 stevensc 147
        <span
813 stevensc 148
          className='mb-2'
149
          title='Los resultados de la votación son privados'
5 stevensc 150
        >
2969 stevensc 151
          <LockClock /> Privado
5 stevensc 152
        </span>
153
      )}
3015 stevensc 154
      {answers.map((answer, index) => {
155
        if (answer === null) return null
156
 
157
        return (
158
          <RadioButton key={answer}>
159
            <input
160
              type='radio'
161
              name='vote'
162
              ref={register({ required: true })}
163
              value={index + 1}
164
            />
165
            <label htmlFor={`vote-${index + 1}`}>{answer}</label>
166
            {/*  {!!totalVotes && (
167
              <span className='mb-0'>
168
                {getPorcentage(votes[index], totalVotes)}%
169
              </span>
170
            )} */}
171
          </RadioButton>
172
        )
173
      })}
174
      <span>Tiempo restante: </span>
5 stevensc 175
      {!isActive && <VoteTag>Tu voto ya fue emitido</VoteTag>}
176
    </form>
813 stevensc 177
  )
178
}
5 stevensc 179
 
2969 stevensc 180
export default SurveyForm