Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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 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, full_name, country, visits, connections, description } =
    userInfo

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

        if (!success) {
          const errorMessage =
            typeof data === 'string'
              ? data
              : 'Ha ocurrido un error, por favor intente más tarde'
          dispatch(addNotification({ style: 'danger', msg: errorMessage }))
          return
        }

        setNotifications(data)
      })
      .catch((error) => {
        console.log('>>: error > ', error)
      })
  }

  const deleteAllNotifications = () => {
    axios
      .post('/notifications/clear')
      .then((response) => {
        const { data, success } = response.data
        if (!success) {
          dispatch(addNotification({ style: 'danger', msg: data }))
          return
        }

        dispatch(addNotification({ style: 'success', msg: data }))
        setNotifications([])
      })
      .catch((err) => {
        dispatch(addNotification({ style: 'danger', msg: `Error: ${err}` }))
        throw new Error(err)
      })
  }

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

        if (!success) {
          dispatch(addNotification({ style: 'danger', msg: data }))
          return
        }

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

        setNotifications(newNotifications)
        dispatch(addNotification({ style: 'success', msg: data }))
      })
      .catch((err) => {
        dispatch(addNotification({ style: 'danger', msg: `Error: ${err}` }))
        throw new Error(err)
      })
  }

  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)
        throw new Error(err)
      })
  }, [])

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

  return (
    <>
      <Container as="main">
        <Row>
          <Col as="aside" md="4" className="d-none d-md-flex">
            <ProfileInfo
              image={image}
              fullName={full_name}
              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>
            <ul>
              {notifications.length ? (
                [...notifications].reverse().map((notification, index) => (
                  <li key={index}>
                    <NotificationsPage.Item
                      onDelete={deleteNotification}
                      {...notification}
                    />
                  </li>
                ))
              ) : (
                <EmptySection message="No hay notificaciones" align="center" />
              )}
            </ul>
          </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 gap-2">
        <a href={link}>{message}</a>
        <DeleteOutline
          className="cursor-pointer"
          onClick={() => onDelete(link_delete)}
        />
      </div>
      <span>{time_elapsed}</span>
    </div>
  )
}

NotificationsPage.Item = Item

export default NotificationsPage