Untitled

 avatar
unknown
plain_text
5 months ago
16 kB
2
Indexable
import React, { Fragment, useContext, 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 './calendar.css';
import { CardContent, CardHeader, Icon, Menu, MenuItem, Typography } from '@material-ui/core';
import ToggleButton from '@material-ui/lab/ToggleButton';
import ToggleButtonGroup from '@material-ui/lab/ToggleButtonGroup';
import EventComponent from './EventComponent';
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 Slide from '@material-ui/core/Slide';
import AddEvent from './AddEvent';
import { connect } from 'react-redux';
import { getAllByClient, googleCalendarEvents } from '../../api/events';
// import { getAll } from '../../api/events';
import ClientContext from '../../containers/Pages/Client/clientContext';
import AddEventclient from './AddEventclient';
import { Add, Delete } from '@mui/icons-material';
import { deleteCalenderEvents } from '../../api/auth';
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';
import Button from '@mui/material/Button';
import { useParams } from 'react-router';
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: '#ffffff',
    color: '#666',
    paddingRight: '0px !important'
  },
  title: {
    marginLeft: theme.spacing(0),
    flex: 1,
    fontSize: '16px',
    fontWeight: 'bold',
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
  },
}));

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 UserCalendar(props) {

  const client = useContext(ClientContext);


  

  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 handleClickOpt = event => {
    setAchorElOpt(event.currentTarget);
  };

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

  const handleClickOpenModel = () => {
    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';
  }

  useEffect(() => {
    calendarData();
    googlecalendarData();
  }, [client])

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

  const [eventgoogle, setEventsgoogle] = useState({
    data:[],
     users :[]
  });


  

  const calendarData = async () => {
    const _events = client ? await getAllByClient(client.oid, 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 googlecalendarData = async () => {

    if (client === null) {
      return;
    }

    const _gevents = await googleCalendarEvents(client.oid);
    const events = _gevents.items;
    const _events = events.map((e) => ({
      id: e.id,
      title: e.summary,
      description: e.description,
      location: e.location,
      start: e.start.dateTime === null ? new Date() : new Date(e.start.dateTime),
      end: e.end.dateTime === null ? new Date() : new Date(e.end.dateTime),
      link: e.htmlLink,
      status: e.status,
      creator: e.creator
    }))

    const eData = {
      data: _events,
    }

    setEventsgoogle(eData);
  }


// Filter out the matched data from googleData
const unmatchedData = Array.isArray(eventgoogle.data) ? eventgoogle.data.filter(data => !events.data.some(event => event.gcal_event_id === data.id)) : [];

console.log('Unmatched Data:', unmatchedData);



  


  


  const refreshData = async () => {
    await calendarData();
    await googlecalendarData()
  }


  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);
    }
  }
  // console.log("events",events,eventgoole);
  return (
    <Fragment>
      

      <Grid container className={classes.root} spacing={1}>
        <Grid item lg={12} xs={12}>
          
          <Card>
          {/* <div className='filter_button_user'>
           
            <Button variant='contained' className='filter_button_cale' color='primary'>Business</Button>
            <Button variant='contained' className='filter_button_cale' color='primary'>Health</Button>
            <Button variant='contained' className='filter_button_cale' color='primary'>Tasks</Button>
            <Button variant='contained' className='filter_button_cale' color='primary'>Chlidren</Button>
            <Button variant='contained' className='filter_button_cale' color='primary'>Financial</Button>
            <Button variant='contained' className='filter_button_cale' color='primary'>Goals</Button>
            <Button variant='contained' className='filter_button_cale' color='primary'>Travel</Button>
         

        </div> */}
            <CardHeader className='mycalendar-header' style={{ margin: "-10px 0px -24px 0px" }}
              // action={
              //   <IconButton className='calendar-views' color='primary' aria-label="Views" onClick={handleClickOpt} >
              //     <Icon>{getIcon()}</Icon> <span>&nbsp; {getView()} </span> <Icon>arrow_drop_down</Icon>
              //   </IconButton>
              // }
              title={
                <>
                    <div>
                      <ToggleButtonGroup exclusive id='userCalendar'>
                        <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" style={{marginRight:12}} >
                          <IconButton aria-label="Month" onClick={(e) => _setViewMode(Views.MONTH)}>
                            <CalendarViewMonthIcon />
                          </IconButton>
                        </Tooltip>
                        <Tooltip title="Week" style={{marginRight:12}} >
                          <IconButton aria-label="Week" onClick={(e) => _setViewMode(Views.WEEK)}>
                            <ViewWeekIcon />
                          </IconButton>
                        </Tooltip>
                        <Tooltip title="Day" style={{marginRight:12}} >
                          <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 color='success' variant='contained' style={{margin: 12, height:30,borderRadius: 100, fontSize: 13, textTransform: "capitalize", fontWeight: 600 }} size='small'>
                        <Add /> Schedule a meeting
                      </Button>
                    </div>
                    <div style={{ display: "flex", marginLeft: "-4px", marginBottom:10 }}>
                      <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'
                      />
                      <Form.Select aria-label="Default select example" className='select_filter'>
                        <option value="" selected disabled hidden> Priority</option>
                        <option value="1">Low</option>
                        <option value="2">Medium</option>
                        <option value="3">High</option>
                        <option value="4">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={[...events.data, ...unmatchedData]}
                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: EventComponent
                }}
                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>

      {/* Event Dialog */}

      <Dialog disableEnforceFocus id="right-dialog" className='add_event_model' fullScreen open={openModel} onClose={handleCloseModel} TransitionComponent={Transition}>
        <AppBar className={classes.appBar}>
          <Toolbar>
            <Typography variant="h6" className={classes.title}>
              {eventItem && eventItem.title || ''}
            </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>
        <AddEventclient event={eventItem} onClose={handleCloseModel} refresh={refreshData} client={client}/>
        {/* <AddEvent event={eventItem} onClose={handleCloseModel} refresh={refreshData} client={client} /> */}
      </Dialog>
    </Fragment>
  )

}

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

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