Proyectos de Subversion LeadersLinked - SPA

Rev

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

Rev Autor Línea Nro. Línea
813 stevensc 1
import React, { useEffect, useRef, useState } from 'react'
2
import { axios } from '../../utils'
3
import { useForm } from 'react-hook-form'
4
import { connect } from 'react-redux'
5 stevensc 5
 
813 stevensc 6
import { updateFeed } from '../../redux/feed/feed.actions'
7
import { addNotification } from '../../redux/notification/notification.actions'
5 stevensc 8
 
813 stevensc 9
import LockClockIcon from '@mui/icons-material/LockClock'
10
import PublicIcon from '@mui/icons-material/Public'
5 stevensc 11
 
813 stevensc 12
import styles from './survey.module.scss'
13
import styled, { css } from 'styled-components'
5 stevensc 14
 
15
const RadioButton = styled.div`
16
  display: flex;
17
  align-items: center;
18
  gap: 0.5rem;
19
  padding: 0.5rem 1rem;
20
  border: 2px solid var(--border-primary);
21
  border-radius: 50px;
22
  cursor: pointer;
23
  transition: all 200ms ease;
24
  position: relative;
25
  overflow: hidden;
26
  margin-bottom: 0.5rem;
27
  input {
28
    margin: 0 !important;
29
  }
30
  label {
31
    color: var(--font-color);
32
    font-weight: 500;
33
  }
34
  &::before {
813 stevensc 35
    content: '';
5 stevensc 36
    position: absolute;
37
    left: 0;
38
    top: 0;
39
    height: 100%;
813 stevensc 40
    width: ${(props) => (props.porcentage ? `${props.porcentage}%` : '0%')};
5 stevensc 41
    background-color: #0002;
42
    z-index: 4;
43
  }
44
  &:hover {
45
    border-color: var(--font-color);
46
    text-shadow: 0 0 1px var(--font-color);
47
  }
48
  ${(props) =>
49
    props.disabled &&
50
    css`
51
      background-color: #9992;
52
      cursor: auto;
53
 
54
      label {
55
        color: gray;
56
      }
57
 
58
      &:hover {
59
        border-color: var(--border-primary);
60
        text-shadow: none;
61
      }
62
    `}
813 stevensc 63
`
5 stevensc 64
 
65
const VoteTag = styled.span`
66
  position: absolute;
67
  bottom: 1rem;
68
  right: 1rem;
69
  color: var(--font-color) !important;
70
  font-weight: 600;
813 stevensc 71
`
5 stevensc 72
 
73
const SurveyForm = ({
814 stevensc 74
  active = false,
5 stevensc 75
  question,
76
  answers = [],
77
  votes,
78
  time,
79
  resultType,
80
  voteUrl,
81
  addNotification, // Redux action
813 stevensc 82
  updateFeed // Redux action
5 stevensc 83
}) => {
813 stevensc 84
  const [remainingTime, setRemainingTime] = useState('00:00:00')
85
  const [isActive, setIsActive] = useState(true)
86
  const [totalVotes, setTotalVotes] = useState(0)
87
  const timeRef = useRef(time)
88
  const { register, handleSubmit } = useForm()
5 stevensc 89
 
90
  const sendVote = handleSubmit(({ vote }) => {
813 stevensc 91
    setIsActive(false)
5 stevensc 92
 
93
    axios
1978 stevensc 94
      .post(voteUrl, { vote })
5 stevensc 95
      .then(({ data: response }) => {
813 stevensc 96
        const { success, data } = response
97
 
5 stevensc 98
        if (!success) {
814 stevensc 99
          const errorMessage =
100
            typeof data === 'string'
101
              ? data
102
              : 'Error interno, por favor intente mas tarde.'
103
          throw new Error(errorMessage)
5 stevensc 104
        }
105
 
813 stevensc 106
        updateFeed({ feed: data, uuid: data.feed_uuid })
107
        addNotification({ style: 'success', msg: 'Voto emitido con exito' })
5 stevensc 108
      })
109
      .catch((err) => {
813 stevensc 110
        setIsActive(true)
814 stevensc 111
        addNotification({ style: 'danger', msg: err.message })
813 stevensc 112
      })
113
  })
5 stevensc 114
 
115
  function getTimeDiff(segundos) {
813 stevensc 116
    const currentDate = new Date()
117
    const futureDate = new Date(currentDate.getTime() + segundos * 1000)
118
    const diff = futureDate - currentDate
5 stevensc 119
 
813 stevensc 120
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
121
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
122
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
5 stevensc 123
 
813 stevensc 124
    return `${addZero(days)}d ${addZero(hours)}h ${addZero(minutes)}m`
5 stevensc 125
  }
126
 
127
  function addZero(unit) {
813 stevensc 128
    return String(unit).padStart(2, '0')
5 stevensc 129
  }
130
 
131
  function getPorcentage(n, total) {
813 stevensc 132
    return (n / total) * 100
5 stevensc 133
  }
134
 
135
  useEffect(() => {
813 stevensc 136
    setRemainingTime(getTimeDiff(time))
5 stevensc 137
 
813 stevensc 138
    if (!time) return
5 stevensc 139
 
140
    const interval = setInterval(() => {
141
      if (!timeRef.current) {
813 stevensc 142
        setRemainingTime(() => getTimeDiff(0))
143
        setIsActive(false)
144
        return
5 stevensc 145
      }
146
 
147
      if (!timeRef.current <= 60) {
813 stevensc 148
        timeRef.current -= 1
149
        setRemainingTime(() => getTimeDiff(timeRef.current))
150
        return
5 stevensc 151
      }
152
 
813 stevensc 153
      timeRef.current -= 60
154
      setRemainingTime(() => getTimeDiff(timeRef.current))
155
    }, 60000)
5 stevensc 156
 
157
    return () => {
813 stevensc 158
      clearInterval(interval)
159
    }
160
  }, [])
5 stevensc 161
 
162
  useEffect(() => {
814 stevensc 163
    const total = votes.reduce((acum, current) => {
164
      if (!current) {
165
        return acum
166
      }
167
 
168
      return acum + Number(current)
169
    }, 0)
170
 
813 stevensc 171
    setTotalVotes(total)
172
  }, [votes])
5 stevensc 173
 
174
  useEffect(() => {
814 stevensc 175
    setIsActive(!!active)
813 stevensc 176
  }, [active])
5 stevensc 177
 
178
  return (
179
    <form onChange={sendVote} className={styles.survey_form}>
180
      <h3>{question}</h3>
813 stevensc 181
      {resultType === 'pu' && (
5 stevensc 182
        <span
813 stevensc 183
          className='mb-2'
184
          title='El número de votos es visible para todos los usuarios'
5 stevensc 185
        >
186
          <PublicIcon /> Público
187
        </span>
188
      )}
813 stevensc 189
      {resultType === 'pr' && (
5 stevensc 190
        <span
813 stevensc 191
          className='mb-2'
192
          title='Los resultados de la votación son privados'
5 stevensc 193
        >
194
          <LockClockIcon /> Privado
195
        </span>
196
      )}
197
      {answers.map(
198
        (option, index) =>
199
          option && (
200
            <RadioButton
201
              disabled={!isActive}
202
              porcentage={
203
                !!totalVotes && getPorcentage(votes[index], totalVotes)
204
              }
205
              key={index}
206
            >
207
              <input
813 stevensc 208
                type='radio'
209
                name='vote'
5 stevensc 210
                id={`vote-${index + 1}`}
211
                disabled={!isActive}
212
                ref={register({ required: true })}
213
                value={index + 1}
214
              />
215
              <label htmlFor={`vote-${index + 1}`}>{option}</label>
216
              {!!totalVotes && (
813 stevensc 217
                <span className='mb-0'>
5 stevensc 218
                  {getPorcentage(votes[index], totalVotes)}%
219
                </span>
220
              )}
221
            </RadioButton>
222
          )
223
      )}
224
      <span>Tiempo restante: {remainingTime}</span>
225
      {!isActive && <VoteTag>Tu voto ya fue emitido</VoteTag>}
226
    </form>
813 stevensc 227
  )
228
}
5 stevensc 229
 
230
const mapDispatchToProps = {
231
  addNotification: (notification) => addNotification(notification),
813 stevensc 232
  updateFeed: (payload) => updateFeed(payload)
233
}
5 stevensc 234
 
813 stevensc 235
export default connect(null, mapDispatchToProps)(SurveyForm)