Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 6488 | | Comparar con el anterior | Ultima modificación | Ver Log |

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