Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 644 | Rev 671 | 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 { axios } from '../../utils'
import { useDispatch } from 'react-redux'
import { getBackendVars } from '../../services/backendVars'
import { addNotification } from '../../redux/notification/notification.actions'
import { Col, Container, Row } from 'react-bootstrap'
import { Link } from 'react-router-dom'
import { IconButton } from '@mui/material'
import DeleteOutline from '@mui/icons-material/DeleteOutline'

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'

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

  const { image, fullName, country, visits, connections, description } =
    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, full_name, country, visits, connections, description }) => {
          setuserInfo({
            image,
            full_name,
            country,
            visits,
            connections,
            description
          })
        }
      )
      .catch((err) => {
        console.log(err)
      })
  }, [])

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

  return (
    <>
      <Container as='main'>
        <Row>
          <Col as='aside' md='4' className='d-none d-md-flex'>
            <ProfileInfo
              image={image}
              fullName={fullName}
              description={description}
              visits={visits}
              country={country}
              connections={connections}
            />
          </Col>
          <Col as='section' md='8' className='notification-list'>
            <div className='notification-header position-relative'>
              <h2>Notificaciones</h2>
              <Options
                options={[
                  {
                    label: 'Borrar notificaciones',
                    action: toggleConfirmModal
                  }
                ]}
              />
            </div>

            {notifications.length ? (
              [...notifications].reverse().map((notification, index) => (
                <div key={index}>
                  <NotificationsPage.Item
                    onDelete={deleteNotification}
                    {...notification}
                  />
                </div>
              ))
            ) : (
              <EmptySection message='No hay notificaciones' align='center' />
            )}
          </Col>
        </Row>
      </Container>
      <ConfirmModal
        show={confirmModalShow}
        onClose={toggleConfirmModal}
        onAccept={() => {
          deleteAllNotifications()
          toggleConfirmModal()
        }}
      />
    </>
  )
}

const Item = ({ link_delete, link, message, time_elapsed, onDelete }) => {
  return (
    <div className='notification-item'>
      <div className='d-flex align-items-center justify-content-between m-0 p-0'>
        <Link to={link}>{message}</Link>
        <IconButton onClick={() => onDelete(link_delete)}>
          <DeleteOutline />
        </IconButton>
      </div>
      <span>{time_elapsed}</span>
      <hr />
    </div>
  )
}

NotificationsPage.Item = Item

export default NotificationsPage