Untitled

 avatar
unknown
plain_text
5 months ago
24 kB
2
Indexable
import React, { Fragment, useEffect, useState } from 'react'
import { Calendar, momentLocalizer, Views } from 'react-big-calendar'
import moment from 'moment'
import Grid from '@material-ui/core/Grid';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import { connect } from "react-redux";
import './calendar.css';
import { CardContent, CardHeader, Icon, Menu, MenuItem, Typography, Tab, TabContext, TabList, TabPanel } from '@material-ui/core';
import ToggleButton from '@material-ui/lab/ToggleButton';
import ToggleButtonGroup from '@material-ui/lab/ToggleButtonGroup';
import EventComponent from './EventComponent';
import TaskComponent from './TaskComponents';
import Dialog from '@material-ui/core/Dialog';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import CloseIcon from '@material-ui/icons/Close';
import { Add, Delete } from '@mui/icons-material';
import Slide from '@material-ui/core/Slide';
import AddEvent from './AddEvent';
import { deleteEventCalender, getAll, getAllTasks } from '../../api/events';
import Button from '@mui/material/Button';
import Stack from '@mui/material/Stack';
import { deleteCalenderEvents } from '../../api/auth';
import ViewCozyIcon from '@mui/icons-material/ViewCozy';
import ViewWeekIcon from '@mui/icons-material/ViewWeek';
import ViewDayIcon from '@mui/icons-material/ViewDay';
import CalendarViewMonthIcon from '@mui/icons-material/CalendarViewMonth';
import Tooltip from '@mui/material/Tooltip';
import KeyboardArrowLeftIcon from '@mui/icons-material/KeyboardArrowLeft';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';
import Form from 'react-bootstrap/Form';
import Addtaskcalendar from './Addtaskcalendar';




const localizer = momentLocalizer(moment)

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
  },
  paper: {
    height: 140,
    width: 100,
  },
  control: {
    padding: theme.spacing(1),
  },
  appBar: {
    position: 'relative',
    background: '#fafafa',
    color: '#111110',
    paddingRight: '0px !important',
    boxShadow: '0px 1px 6px 0px rgba(142, 142, 142, 0.2), 0px 1px 1px 0px rgba(243, 243, 243, 0.14), 0px 2px 1px -1px rgba(204, 204, 204, 0.12)',
  },
  title: {
    marginLeft: theme.spacing(0),
    flex: 1,
    fontSize: '13px',
    fontWeight: 'bold',
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
  },
  bttncolor:
  {
    backgroundColor: "#333333"
  },
}));

const Transition = React.forwardRef((props, ref) => <Slide direction="left" ref={ref} {...props} />);

const ITEM_HEIGHT = 48;

const backgrounds = ['bg-primary', 'bg-info', 'bg-success', 'bg-warning', 'bg-danger', 'bg-secondary'];

function TaskCalendar(props) {

  const { user } = props;

  const [spacing, setSpacing] = useState(2);
  const classes = useStyles();
  const [currentDate, setCurrentDate] = useState(new Date());
  const [viewMode, setViewMode] = useState(Views.MONTH);
  const [anchorElOpt, setAchorElOpt] = useState(null);
  const [openModel, setOpenModel] = useState(false);
  const [eventItem, setEventItem] = useState();



  const [value, setValue] = React.useState('1');


  const handleChange = (event, newValue) => {
    setValue(newValue);
  }
  const handleClickOpt = event => {
    setAchorElOpt(event.currentTarget);
  };

  const handleCloseOpt = () => {
    setAchorElOpt(null);
  }

  const handleClickOpenModel = () => {
    setEventItem({ id: null, title: null, description: null, location: null, start_time: new Date(), end_time: new Date(), user: { name: '' }, participants: [], users: events.users, comment: null });
    setOpenModel(true);
    setOpenModel(true);
  };

  const handleCloseModel = () => {
    setOpenModel(false);
  };

  const handleViewMode = (e) => {
    setCurrentDate(moment(e)._d);
    setViewMode(Views.DAY);
  }

  const _setViewMode = (view) => {
    setViewMode(view);
    setAchorElOpt(null);
  }

  const todayLabel = () => {
    if (viewMode === 'day') {
      return 'Today';
    }
    if (viewMode === 'week') {
      return 'This Week';
    }

    return 'This Month';
  }

  const getIcon = () => {
    if (viewMode === 'day') {
      return 'view_day';
    }
    if (viewMode === 'week') {
      return 'view_week';
    }
    return 'view_comfy';
  }

  const getView = () => {
    if (viewMode === 'day') {
      return 'Day';
    }
    if (viewMode === 'week') {
      return 'Week';
    }
    return 'Month';
  }


  const [events, setEvents] = useState({
    data: [],
    users: []
  });


  const deleteEvents = async (eventItem) => {
    try {
      const response = await deleteCalenderEvents(eventItem.id);
      console.log(response);
      setOpenModel(false);
      await refreshData(); // Refresh data after deletion
    } catch (error) {
      console.error("Failed to delete event:", error);
    }
  }



  const calendarData = async () => {
    const _events = await getAll(false);
    const ids = [];
    const users = [];
    const _myevents = [];
    _events.forEach(event => {
      if (!ids.includes(event.user.id)) {
        users.push(event.user);
        ids.push(event.user.id);
      }
      const start = new Date(event.start_time + 'Z')
      const end = new Date(event.end_time + 'Z')
      event['start'] = start
      event['end'] = end
      _myevents.push(event)

    });
    const eData = {
      data: _myevents,
      users: users
    }

    setEvents(eData);
  }

  const refreshData = async () => {
    await calendarData()
  }
  useEffect(() => {
    const fetchData = async () => {
      if (props.tabType === "task" || props.tabType === "recommendation") {

        setEvents({ data: [], users: [] });
        setOpenModel(false);
      } else {
        // For other tabs, fetch the events data
        await calendarData();
      }
    };

    fetchData();
  }, [props.tabType]);

  const [taskevents, setTaskEvents] = useState({
    data: [],
    users: [],
  });
  const user_id = user && user.id;
  useEffect(() => {
    const fetchTaskData = async () => {
      await tasksData();
    };

    fetchTaskData();
  }, []); 

  const tasksData = async () => {
    try {
      const _tasks = await getAllTasks(user_id);
      const ids = [];
      const users = [];
      const _mytasks = [];
      _tasks.forEach((task) => {
        if (!ids.includes(task.assign_to.id)) {
          users.push(task.assign_to);
          ids.push(task.assign_to.id);
        }
        const start = new Date(task.start_time + 'Z');
        const end = new Date(task.end_time + 'Z');
        task['start'] = start;
        task['end'] = end;
        _mytasks.push(task);
      });
      const tData = {
        data: _mytasks,
        users: users,
      };

      setTaskEvents(tData);
    } catch (error) {
      console.error('Error fetching tasks:', error.message);
    }
  };





  // filetr button ------------------------------------------------

  const [selectedButtons, setSelectedButtons] = useState(new Set());
  const [selectedPriority, setSelectedPriority] = useState('');
  const [selectedDate, setSelectedDate] = useState(null);


  const handleButtonClick = (buttonName) => {
    const updatedButtons = new Set(selectedButtons);
    if (updatedButtons.has(buttonName)) {
      updatedButtons.delete(buttonName); // Deselect the button if already selected
    } else {
      updatedButtons.add(buttonName);
      // Select the button if not selected
    }
    setSelectedButtons(updatedButtons);
  }

  const getButtonClass = (buttonName) => {
    return selectedButtons.has(buttonName) ? 'selected-button' : 'filter_button_cale';
  }
  const filteredEvents = taskevents.data.filter(event => {

    if (
      (selectedButtons.size === 0 || selectedButtons.has('All')) &&
      (!selectedPriority ||selectedPriority === null || event.priority === selectedPriority) &&
      (!selectedDate || new Date(event.start_time).toLocaleDateString('en-GB') === new Date(selectedDate).toLocaleDateString('en-GB')) // Filter by selected date
    ) {
      return true; 
    } else if (
      selectedButtons.has(event.req_type) &&
      (!selectedPriority ||selectedPriority === null || event.priority === selectedPriority) &&
      (!selectedDate || new Date(event.start_time).toLocaleDateString('en-GB') === new Date(selectedDate).toLocaleDateString('en-GB')) // Filter by selected date
    ) {
      return true; 
    }

    return false;
  });


console.log("taskevents",taskevents);


  return (
    <Fragment>
      <div>
        <div className='filter_button'>
          {props.tabType === "task" ? <>
            <Button variant='contained' className={getButtonClass('Business')} color='primary' onClick={() => handleButtonClick('Business')}>Business</Button>
            <Button variant='contained' className={getButtonClass('Physical')} color='primary' onClick={() => handleButtonClick('Physical')}>Physical</Button>
            <Button variant='contained' className={getButtonClass('Education')} color='primary' onClick={() => handleButtonClick('Education')}>Education</Button>
            <Button variant='contained' className={getButtonClass('Residence')} color='primary' onClick={() => handleButtonClick('Residence')}>Residence</Button>
            <Button variant='contained' className={getButtonClass('Personal & Family')} color='primary' onClick={() => handleButtonClick('Personal & Family')}>Personal & Family</Button>
          </> : <>
            <Button variant='contained' value='business' className={getButtonClass('business')} color='primary' onClick={() => handleButtonClick('business')}>Business</Button>
            <Button variant='contained' value='health' className={getButtonClass('health')} color='primary' onClick={() => handleButtonClick('health')}>Health</Button>
            <Button variant='contained' value='tasks' className={getButtonClass('tasks')} color='primary' onClick={() => handleButtonClick('tasks')}>Tasks</Button>
            <Button variant='contained' value='children' className={getButtonClass('children')} color='primary' onClick={() => handleButtonClick('children')}>Children</Button>
            <Button variant='contained' value='finance' className={getButtonClass('finance')} color='primary' onClick={() => handleButtonClick('finance')}>Financial</Button>
            <Button variant='contained' value='goals' className={getButtonClass('goals')} color='primary' onClick={() => handleButtonClick('goals')}>Goals</Button>
            <Button variant='contained' value='travel' className={getButtonClass('travel')} color='primary' onClick={() => handleButtonClick('travel')}>Travel</Button> </>}

        </div>

        <div className='roww mt-1 mb-2 p-0 connected-users'>
          {events.users.map((user, i) => {
            const id = "mouse-over-popover-" + i
            return (
              <div key={id} className='col-auto p-0'>
                <div className='position-relative'>
                  <img width="48" height="48" className='avatar rounded-circle border border-4 border-info bg-l25-primary cursor-pointer has-popover' src={user.avatar} />
                  <div className='popover'>
                    <span className='title'>{user.name}</span>
                    <p>Appointments: 1</p>
                  </div>
                </div>
              </div>
            )
          })}
        </div>
        <Grid container className={classes.root} spacing={2}>
          <Grid item lg={9} xs={12}>
            <Card>
              <CardHeader className='mycalendar-header' style={{ margin: "-10px 0px -24px 0px" }}

                title={
                  <>
                    <div>
                      <ToggleButtonGroup exclusive id='dafhghjg'>
                        <ToggleButton onClick={(e) => setCurrentDate(moment(currentDate).add(-1, viewMode)._d)} value="left">
                          <KeyboardArrowLeftIcon />
                        </ToggleButton>
                        <Typography style={{ fontSize: 17, fontWeight: 600, color: "#000" }} value="center">
                          {moment(currentDate).format('MMMM YYYY')}
                        </Typography>
                        <ToggleButton onClick={(e) => setCurrentDate(moment(currentDate).add(1, viewMode)._d)} value="right">
                          <KeyboardArrowRightIcon />
                        </ToggleButton>
                      </ToggleButtonGroup>
                    </div>
                    <div className={classes.toggleContainer} style={{ display: 'flex', justifyContent: "space-between" }}>
                      <div style={{ marginLeft: "-12px" }} >
                        <Tooltip title="Month" >
                          <IconButton aria-label="Month" onClick={(e) => _setViewMode(Views.MONTH)}>
                            <CalendarViewMonthIcon />
                          </IconButton>
                        </Tooltip>
                        <Tooltip title="Week">
                          <IconButton aria-label="Week" onClick={(e) => _setViewMode(Views.WEEK)}>
                            <ViewWeekIcon />
                          </IconButton>
                        </Tooltip>
                        <Tooltip title="Day">
                          <IconButton aria-label="Day" onClick={(e) => _setViewMode(Views.DAY)}>
                            <ViewDayIcon />
                          </IconButton>
                        </Tooltip>
                        <Button size="small" onClick={(e) => setCurrentDate(moment()._d)} style={{ margin: 12, borderRadius: 10, fontSize: 13, textTransform: "capitalize", fontWeight: 600 }} variant="outlined" color="success">
                          Today
                        </Button>
                      </div>
                      <Button onClick={handleClickOpenModel} variant='contained' style={{background:"#f1d089d9",color:"#122620", margin: 12, borderRadius: 100, fontSize: 12, textTransform: "capitalize", fontWeight: 600 }} size='small'>
                        <Add /> Schedule a meeting
                      </Button>
                    </div>
                    <div style={{ display: "flex", marginLeft: "-4px" }}>
                      <Form.Select aria-label="Default select example" className='select_filter'>
                        <option className='select_item' value="" selected disabled hidden>Calendar</option>
                        <option className='select_item' value="1">Personal Calendar</option>
                        <option className='select_item' value="2">Family Calendar</option>
                        <option className='select_item' value="3">Work Calendar</option>
                        <option className='select_item' value="4">Bills Calendar</option>
                      </Form.Select>
                      <Form.Control
                        type="date"
                        className='select_filter'
                        value={selectedDate ? selectedDate.toISOString().slice(0, 10) : ''} // Set value to selectedDate if available
                        onChange={(e) => {
                          const selectedDateString = e.target.value;
                          const newSelectedDate = selectedDateString ? new Date(selectedDateString) : null;
                          setSelectedDate(newSelectedDate);
                        }}

                      />
                      <Form.Select aria-label="Default select example" className='select_filter' value={selectedPriority}
                        onChange={(e) => setSelectedPriority(e.target.value)}
                      >
                        <option value="" selected disabled hidden> Priority</option>
                        <option value="">Select</option>
                        <option value="low">Low</option>
                        <option value="medium">Medium</option>
                        <option value="high">High</option>
                        <option value="critical">Critical</option>
                      </Form.Select>
                    </div>

                  </>
                }
              />
              <Menu
                id='veiw-type'
                anchorEl={anchorElOpt}
                open={Boolean(anchorElOpt)}
                onClose={handleCloseOpt}
                PaperProps={{
                  style: {
                    maxHeight: ITEM_HEIGHT * 4.5,
                    width: 200,
                  },
                }}
              >
                <MenuItem onClick={(e) => _setViewMode(Views.MONTH)}><Icon>view_comfy</Icon> Month</MenuItem>
                <MenuItem onClick={(e) => _setViewMode(Views.WEEK)}><Icon>view_week</Icon> Week</MenuItem>
                <MenuItem onClick={(e) => _setViewMode(Views.DAY)}><Icon>view_day</Icon> Day</MenuItem>
              </Menu>
              <CardContent>
                <Calendar
                  selectable
                  date={currentDate}
                  onNavigate={(_date) => setCurrentDate(_date)}
                  defaultDate={new Date()}
                  toolbar={false}
                  localizer={localizer}
                  events={filteredEvents}
                  defaultView={Views.MONTH}
                  scrollToTime={new Date(1970, 1, 1, 6)}
                  views={Object.keys(Views).map((k) => Views[k])}
                  view={viewMode}
                  startAccessor="start"
                  endAccessor="end"
                  style={{ height: 600 }}
                  components={{
                    event: TaskComponent
                  }}
                  eventPropGetter={
                    (event, start, end, isSelected) => {
                      const index = event.id % 6;
                      return {
                        className: `${backgrounds[index]}`
                      }
                    }
                  }
                  onSelectEvent={(event) => {
                    setOpenModel(true)
                    setEventItem(event)
                  }}
                  onSelectSlot={({ start, end }) => {
                    setEventItem({ id: null, title: null, description: null, location: null, start_time: start, end_time: end, user: { name: '' }, participants: [], users: events.users, comment: null })
                    setOpenModel(true)
                  }}
                  onView={handleViewMode}
                  onDrillDown={handleViewMode}
                />
              </CardContent>
            </Card>
          </Grid>
          <Grid item lg={3} xs={12}>
            <Card>
              <CardHeader className='mycalendar-header'
                title={
                  <div className='today-event'>
                    <Icon>event</Icon>
                    <span className='event-date'>{moment(currentDate).format('MMMM Do YYYY')} </span>
                  </div>
                }
                action={
                  <>
                    <div className={classes.toggleContainer}>
                      <ToggleButtonGroup exclusive>
                        <ToggleButton onClick={(e) => setCurrentDate(moment(currentDate).add(-1, 'day')._d)} value="left">
                          <Icon>chevron_left</Icon>
                        </ToggleButton>
                        <ToggleButton onClick={(e) => setCurrentDate(moment()._d)} value="center">
                          {'Today'}
                        </ToggleButton>
                        <ToggleButton onClick={(e) => setCurrentDate(moment(currentDate).add(1, 'day')._d)} value="right">
                          <Icon>chevron_right</Icon>
                        </ToggleButton>
                      </ToggleButtonGroup>
                    </div>
                  </>
                }
              />
              <CardContent>
                <Calendar
                  selectable
                  localizer={localizer}
                  toolbar={false}
                  defaultDate={new Date()}
                  scrollToTime={new Date(1970, 1, 1, 6)}
                  onNavigate={(_date) => setCurrentDate(_date)}
                  defaultView={Views.WEEK}
                  views={Object.keys(Views).map((k) => Views[k])}
                  view={Views.DAY}
                  date={currentDate}
                  events={taskevents.data}
                  startAccessor="start"
                  endAccessor="end"
                  style={{ height: 585 }}
                  components={{
                    event: TaskComponent
                  }}
                  eventPropGetter={
                    (event, start, end, isSelected) => {
                      const index = event.id % 6;
                      return {
                        className: `${backgrounds[index]}`
                      }
                    }
                  }
                  onView={handleViewMode}
                  onDrillDown={handleViewMode}
                  onSelectEvent={(event) => {
                    setEventItem(event)
                    setOpenModel(true)
                  }}
                  onSelectSlot={({ start, end }) => {
                    setEventItem({ id: null, title: null, description: null, location: null, start, start_time: start, end, end_time: end, user: { name: '' }, participants: [], users: events.users, comment: null })
                    setOpenModel(true)
                  }}
                />
              </CardContent>
            </Card>
          </Grid>
        </Grid>
        {/* Event Dialog */}
        <div className='add_event_section'>
          {!(props.tabType === "task" || props.tabType === "recommendation") && (
            <Dialog disableEnforceFocus id="right-dialog" className='add_event_model' fullScreen open={openModel} onClose={handleCloseModel} TransitionComponent={Transition}>
              <AppBar className={classes.appBar}>
                <Toolbar className='events_title'>
                  <Typography variant="h6" className={classes.title}>
                    {eventItem && eventItem.title || 'Add Event'}
                  </Typography>
                  {eventItem && eventItem.title !== null ? <Delete onClick={() => deleteEvents(eventItem)} style={{ marginRight: 20, color: "red", cursor: "pointer" }} /> : null}

                  <IconButton edge="start" color="inherit" onClick={handleCloseModel} aria-label="close">

                    <CloseIcon />
                  </IconButton>
                </Toolbar>
              </AppBar>
              <Addtaskcalendar event={eventItem} onClose={handleCloseModel} refresh={refreshData} />
            </Dialog>
          )}
        </div>
        {props.user && props.user.role === "ADVISOR" ? (
          <Grid style={{ height: "50px" }} item lg={12}></Grid>
        ) : (
          ""
        )}
      </div>
    </Fragment>
  )

}

const mapStateToProps = (state) => ({
  counters: state.dashboardReducer.data,
  user: state.authReducer.user,
});

export default connect(
  mapStateToProps,
)((TaskCalendar));
Editor is loading...
Leave a Comment