Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 1978 | Rev 2969 | 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
 
1979 stevensc 93
    const formData = new FormData()
94
    formData.append('vote', vote)
95
 
5 stevensc 96
    axios
1979 stevensc 97
      .post(voteUrl, formData)
5 stevensc 98
      .then(({ data: response }) => {
813 stevensc 99
        const { success, data } = response
100
 
5 stevensc 101
        if (!success) {
814 stevensc 102
          const errorMessage =
103
            typeof data === 'string'
104
              ? data
105
              : 'Error interno, por favor intente mas tarde.'
106
          throw new Error(errorMessage)
5 stevensc 107
        }
108
 
813 stevensc 109
        updateFeed({ feed: data, uuid: data.feed_uuid })
110
        addNotification({ style: 'success', msg: 'Voto emitido con exito' })
5 stevensc 111
      })
112
      .catch((err) => {
813 stevensc 113
        setIsActive(true)
814 stevensc 114
        addNotification({ style: 'danger', msg: err.message })
813 stevensc 115
      })
116
  })
5 stevensc 117
 
118
  function getTimeDiff(segundos) {
813 stevensc 119
    const currentDate = new Date()
120
    const futureDate = new Date(currentDate.getTime() + segundos * 1000)
121
    const diff = futureDate - currentDate
5 stevensc 122
 
813 stevensc 123
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
124
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
125
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
5 stevensc 126
 
813 stevensc 127
    return `${addZero(days)}d ${addZero(hours)}h ${addZero(minutes)}m`
5 stevensc 128
  }
129
 
130
  function addZero(unit) {
813 stevensc 131
    return String(unit).padStart(2, '0')
5 stevensc 132
  }
133
 
134
  function getPorcentage(n, total) {
813 stevensc 135
    return (n / total) * 100
5 stevensc 136
  }
137
 
138
  useEffect(() => {
813 stevensc 139
    setRemainingTime(getTimeDiff(time))
5 stevensc 140
 
813 stevensc 141
    if (!time) return
5 stevensc 142
 
143
    const interval = setInterval(() => {
144
      if (!timeRef.current) {
813 stevensc 145
        setRemainingTime(() => getTimeDiff(0))
146
        setIsActive(false)
147
        return
5 stevensc 148
      }
149
 
150
      if (!timeRef.current <= 60) {
813 stevensc 151
        timeRef.current -= 1
152
        setRemainingTime(() => getTimeDiff(timeRef.current))
153
        return
5 stevensc 154
      }
155
 
813 stevensc 156
      timeRef.current -= 60
157
      setRemainingTime(() => getTimeDiff(timeRef.current))
158
    }, 60000)
5 stevensc 159
 
160
    return () => {
813 stevensc 161
      clearInterval(interval)
162
    }
163
  }, [])
5 stevensc 164
 
165
  useEffect(() => {
814 stevensc 166
    const total = votes.reduce((acum, current) => {
167
      if (!current) {
168
        return acum
169
      }
170
 
171
      return acum + Number(current)
172
    }, 0)
173
 
813 stevensc 174
    setTotalVotes(total)
175
  }, [votes])
5 stevensc 176
 
177
  useEffect(() => {
814 stevensc 178
    setIsActive(!!active)
813 stevensc 179
  }, [active])
5 stevensc 180
 
181
  return (
182
    <form onChange={sendVote} className={styles.survey_form}>
183
      <h3>{question}</h3>
813 stevensc 184
      {resultType === 'pu' && (
5 stevensc 185
        <span
813 stevensc 186
          className='mb-2'
187
          title='El número de votos es visible para todos los usuarios'
5 stevensc 188
        >
189
          <PublicIcon /> Público
190
        </span>
191
      )}
813 stevensc 192
      {resultType === 'pr' && (
5 stevensc 193
        <span
813 stevensc 194
          className='mb-2'
195
          title='Los resultados de la votación son privados'
5 stevensc 196
        >
197
          <LockClockIcon /> Privado
198
        </span>
199
      )}
200
      {answers.map(
201
        (option, index) =>
202
          option && (
203
            <RadioButton
204
              disabled={!isActive}
205
              porcentage={
206
                !!totalVotes && getPorcentage(votes[index], totalVotes)
207
              }
208
              key={index}
209
            >
210
              <input
813 stevensc 211
                type='radio'
212
                name='vote'
5 stevensc 213
                id={`vote-${index + 1}`}
214
                disabled={!isActive}
215
                ref={register({ required: true })}
216
                value={index + 1}
217
              />
218
              <label htmlFor={`vote-${index + 1}`}>{option}</label>
219
              {!!totalVotes && (
813 stevensc 220
                <span className='mb-0'>
5 stevensc 221
                  {getPorcentage(votes[index], totalVotes)}%
222
                </span>
223
              )}
224
            </RadioButton>
225
          )
226
      )}
227
      <span>Tiempo restante: {remainingTime}</span>
228
      {!isActive && <VoteTag>Tu voto ya fue emitido</VoteTag>}
229
    </form>
813 stevensc 230
  )
231
}
5 stevensc 232
 
233
const mapDispatchToProps = {
234
  addNotification: (notification) => addNotification(notification),
813 stevensc 235
  updateFeed: (payload) => updateFeed(payload)
236
}
5 stevensc 237
 
813 stevensc 238
export default connect(null, mapDispatchToProps)(SurveyForm)