Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 1507 | Rev 2139 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import React, { useState, useLayoutEffect, useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { Container, Grid } from '@mui/material'
import styled from 'styled-components'

import { axios } from '../../utils'
import { getBackendVars } from '../../services/backendVars'
import { addNotification } from '../../redux/notification/notification.actions'

import Options from '../../components/UI/Option'
import ConfirmModal from '../../components/modals/ConfirmModal'
import EmptySection from '../../components/UI/EmptySection'
import ProfileInfo from '../../components/widgets/default/ProfileWidget'
import WidgetWrapper from '../../components/widgets/WidgetLayout'

const StyledNotificationList = styled(WidgetWrapper.Body)`
  max-height: 60vh;
  overflow: auto;
`

const NotificationsPage = () => {
  const [userInfo, setuserInfo] = useState({})
  const [notifications, setNotifications] = useState([])
  const [confirmModalShow, setConfirmModalShow] = useState(false)
  const dispatch = useDispatch()

  const { image, fullName, country, visits, connections } = userInfo

  const getNotifications = async () => {
    axios
      .get('/notifications')
      .then(({ data: responseData }) => {
        const { data, success } = responseData

        if (!success) {
          const errorMessage =
            typeof data === 'string'
              ? data
              : 'Ha ocurrido un error, por favor intente más tarde'
          throw new Error(errorMessage)
        }

        setNotifications(data)
      })
      .catch((err) => {
        dispatch(addNotification({ style: 'danger', msg: err.message }))
      })
  }

  const deleteAllNotifications = () => {
    axios
      .post('/notifications/clear')
      .then(({ data: responseData }) => {
        const { data, success } = responseData

        if (!success) {
          throw new Error(data)
        }

        dispatch(addNotification({ style: 'success', msg: data }))
        setNotifications([])
      })
      .catch((err) => {
        dispatch(addNotification({ style: 'danger', msg: err.message }))
      })
  }

  const deleteNotification = (url) => {
    axios
      .post(url)
      .then(({ data: responseData }) => {
        const { data, success } = responseData

        if (!success) {
          throw new Error(data)
        }

        const newNotifications = notifications.filter(
          ({ link_delete }) => link_delete !== url
        )

        setNotifications(newNotifications)
        dispatch(addNotification({ style: 'success', msg: data }))
      })
      .catch((err) => {
        dispatch(addNotification({ style: 'danger', msg: err.message }))
      })
  }

  const readAllNotification = () => {
    axios
      .post('notifications/mark-all-read')
      .then(({ data: responseData }) => {
        const { data, success } = responseData

        if (!success) {
          throw new Error(data)
        }
      })
      .catch((err) => {
        dispatch(addNotification({ style: 'danger', msg: err.message }))
      })
  }

  const toggleConfirmModal = () => {
    setConfirmModalShow(!confirmModalShow)
  }

  useEffect(() => {
    getBackendVars('/helpers/menu')
      .then(
        ({ image, fullName, country, visits, connections, description }) => {
          setuserInfo({
            image,
            fullName,
            country,
            visits,
            connections
          })
        }
      )
      .catch((err) => {
        console.log(err)
      })
  }, [])

  useLayoutEffect(() => {
    getNotifications()
    readAllNotification()
  }, [])

  return (
    <>
      <Container>
        <Grid container spacing={2}>
          <Grid item xs={12} md={4}>
            <ProfileInfo
              image={image}
              name={fullName}
              visits={visits}
              country={country}
              connections={connections}
            />
          </Grid>
          <Grid item xs={12} md={8}>
            <WidgetWrapper>
              <WidgetWrapper.Header title='Notificaciones'>
                <Options
                  options={[
                    {
                      label: 'Borrar notificaciones',
                      action: toggleConfirmModal
                    }
                  ]}
                />
              </WidgetWrapper.Header>

              <StyledNotificationList>
                {notifications.length ? (
                  [...notifications].reverse().map((notification, index) => (
                    <div key={index}>
                      <NotificationsPage.Item
                        onDelete={deleteNotification}
                        {...notification}
                      />
                    </div>
                  ))
                ) : (
                  <EmptySection
                    message='No hay notificaciones'
                    align='center'
                  />
                )}
              </StyledNotificationList>
            </WidgetWrapper>
          </Grid>
        </Grid>
      </Container>

      <ConfirmModal
        show={confirmModalShow}
        onClose={toggleConfirmModal}
        onAccept={() => {
          deleteAllNotifications()
          toggleConfirmModal()
        }}
      />
    </>
  )
}

export default NotificationsPage