@material-ui/core#Icon JavaScript Examples

The following examples show how to use @material-ui/core#Icon. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OftadehNavLink.jsx    From oftadeh-react-admin with MIT License 6 votes vote down vote up
OftadehNavLink = props => {
  const { item } = props;
  return (
    <ListItem
      button
      component="a"
      href={item.url}
      target={item.target ? item.target : "_blank"}
    >
      {item.icon && (
        <ListItemIcon>
          <Icon>{item.icon}</Icon>
        </ListItemIcon>
      )}
      <ListItemText primary={item.title} />
      {item.badge && <OftadehNavBadge className="mr-4" badge={item.badge} />}
    </ListItem>
  );
}
Example #2
Source File: EventList.jsx    From archeage-tools with The Unlicense 6 votes vote down vote up
render() {
    const { id, name, icon, color, events, onEdit, region } = this.props;

    return (
      <Paper className="event-list">
        <AppBar position="static" className={color}>
          <Toolbar variant="dense">
            <Icon><img src={`/images/event_type/${icon}.png`} alt={name} /></Icon>
            <Typography className="title-text">{name}</Typography>
          </Toolbar>
        </AppBar>
        {events
        .map(event => (
          <EventCard
            {...event}
            key={event.name}
            onUpdateTime={this.setTime}
            type={id}
            onEdit={onEdit}
            region={region}
          />),
        )}
      </Paper>
    );
  }
Example #3
Source File: OftadehNavItem.jsx    From oftadeh-react-admin with MIT License 6 votes vote down vote up
OftadehNavItem = props => {
  const classes = useStyles();
  const { item } = props;

  return (
    <ListItem
      button
      component={NavLinkAdapter}
      to={item.url}
      activeClassName={classes.active}
      exact={item.exact}
    >
      {item.icon && (
        <ListItemIcon>
          <Icon>{item.icon}</Icon>
        </ListItemIcon>
      )}
      <ListItemText primary={item.title} />
      {item.badge && <OftadehNavBadge className="mr-4" badge={item.badge} />}
    </ListItem>
  );
}
Example #4
Source File: Header.js    From Dog-Book with MIT License 6 votes vote down vote up
Header = () => {
  return (
    <AppBar position="static" style={{ backgroundColor: "darkred" }}>
      <Toolbar>
        <Icon>
          <Pets />
        </Icon>
        <Typography variant="h6" style={{ marginLeft: "1rem" }}>
          Dog Book
        </Typography>
      </Toolbar>
    </AppBar>
  );
}
Example #5
Source File: index.js    From Edlib with GNU General Public License v3.0 6 votes vote down vote up
function LoadingModal(props) {
    const {
        open,
        classes,
        contentIcon,
        contentTitle,
        contentText,
    } = props;

    return (
        <Modal
            open={open}
            classes={classes.root}
        >
            <div
                className={classes.paper}
            >
                <Icon className={classes.icon}>sync</Icon>
                <p>{contentText}</p>
                <img src={contentIcon} alt="image" className={classes.image} />
                <span className={classes.title}>
                    {contentTitle}
                </span>
            </div>
        </Modal>
    );
}
Example #6
Source File: WebContactsHeaderView.js    From WhatsApp-Clone with MIT License 6 votes vote down vote up
WebContactsHeaderView = ({ item, onChatCloseClick }) => {
  return (
    <div style={styles.parentView}>
      <div
        onClick={() => { 
          onChatCloseClick();
        }}
        style={{ alignSelf: "center", justifyContent: "center",cursor:'pointer' }}
      >
        <ArrowBack style={styles.backIcon} />
      </div>
      <div
        style={{
          flexDirection: "column",
          marginLeft: 7,
          justifyContent: "center",
          fontSize: 24,
          alignSelf: "center"
        }}
      >
        <Typography numberOfLines={1} style={styles.userName}>
          Select contact
        </Typography>
        <Typography numberOfLines={2} style={styles.userMessage}>
          {item} contacts
        </Typography>
      </div>
      <div style={{ flexDirection: "row", justifyContent: "space-evenly" }}>
        <Icon
          name="dots-vertical"
          type="MaterialCommunityIcons"
          style={styles.menuIcons}
        />
      </div>
    </div>
  );
}
Example #7
Source File: JoinMenu.jsx    From frontend with MIT License 6 votes vote down vote up
JoinMenu = () => {
  const [anchorEl, setAnchorEl] = React.useState(null);

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };
  return (
    <div>
      <Button onClick={handleClick} className="join-button">
        {plusIcon}
        <span className="text">Долучитися</span>
        <ArrowDropDownIcon />
      </Button>
      <Menu
        id="join-menu"
        className="join-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleClose}
      >
        <MenuItem onClick={handleClose} className="join-menu-item">
          <Icon style={{ color: '#1540A4' }}>store</Icon>
          <span>Як Організація</span>
        </MenuItem>
        <MenuItem onClick={handleClose} className="join-menu-item">
          <Icon style={{ color: '#1540A4' }}>person</Icon>
          <span>Як Волонтер</span>
        </MenuItem>
      </Menu>
    </div>
  );
}
Example #8
Source File: OftadehListItemIcon.jsx    From oftadeh-react-admin with MIT License 6 votes vote down vote up
OftadehListItemIcon = ({ item }) => (
  <>
    <ListItemAvatar>
      <ListItemIcon>
        <Avatar>
          <Icon color={item.color}>{item.icon}</Icon>
        </Avatar>
      </ListItemIcon>
    </ListItemAvatar>
    <ListItemText primary={item.title} secondary={item.subTitle} />
  </>
)
Example #9
Source File: Appbar.js    From quizdom with MIT License 6 votes vote down vote up
Appbar = ({ user, setUser }) => {
	return (
		<div className='appbar'>
			<div className='slider'>
				<Sidebar />
				<Link to='/' className='home'>
					<b>Quiz</b>dom
				</Link>
			</div>
			<div className='appbar-user'>
				<Icon>
					<AccountCircle />
				</Icon>
				<p>{user.name}</p>
			</div>
		</div>
	)
}
Example #10
Source File: ApplicationListPage.jsx    From frontend with MIT License 5 votes vote down vote up
ApplicationPage = () => {
  const classes = useStyles();
  const [handlePageChange,
    handleChangeRowsPerPage,
    pagination, paginateData] = usePaginateHandlers(applications);
  return (
    <>
      <Box mb={2}>
        <Typography variant="h4">Applications</Typography>
      </Box>
      <Box>
        <Paper elevation={2}>
          <Table>
            <TableHead>
              <TableRow>
                {columns.map((c) => <TableCell key={c.label}>{c.label}</TableCell>)}
              </TableRow>
            </TableHead>
            <TableBody>
              {paginateData.map((x) => (
                <TableRow key={x.id}>
                  <TableCell>
                    {x.requestId}
                  </TableCell>
                  <TableCell>{x.firstName}</TableCell>
                  <TableCell>{x.lastName}</TableCell>
                  <TableCell>{x.phone}</TableCell>
                  <TableCell>{x.help}</TableCell>
                  <TableCell>
                    {x.status
                      ? (
                        <Select
                          value={x.status}
                          classes={{ root: classes[x.status], select: classes[x.status] }}
                        >
                          <MenuItem value="on_hold">On hold</MenuItem>
                          <MenuItem value="in_progress">In progress</MenuItem>
                          <MenuItem value="receieved">Received</MenuItem>
                          <MenuItem value="closed">Closed</MenuItem>
                        </Select>
                      ) : 'Pending'}
                  </TableCell>
                  <TableCell align="right">
                    {!x.approved && (
                    <>
                      <IconButton color="primary">
                        <Icon>check</Icon>
                      </IconButton>
                      <IconButton color="secondary">
                        <Icon>clear</Icon>
                      </IconButton>
                    </>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
            <TableFooter>
              <TableRow>
                <TablePagination
                  count={applications.length}
                  onChangePage={handlePageChange}
                  page={pagination.page}
                  rowsPerPage={pagination.limit}
                  onChangeRowsPerPage={handleChangeRowsPerPage}
                />
              </TableRow>
            </TableFooter>
          </Table>
        </Paper>
      </Box>
    </>
  );
}
Example #11
Source File: OftadehNavCollapse.jsx    From oftadeh-react-admin with MIT License 5 votes vote down vote up
OftadehNavCollapse = props => {
  const { item, location } = props;
  const classes = useStyles(props);
  const [open, setOpen] = React.useState(() =>
    persistCollapseOpen(location, item)
  );
  // const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    if (persistCollapseOpen(location, item)) {
      setOpen(true);
    }
  }, [location, item]);

  const handleClick = () => {
    setOpen(!open);
  };

  return (
    <ul className={classes.root}>
      <ListItem button onClick={handleClick}>
        {item.icon && (
          <ListItemIcon>
            <Icon>{item.icon}</Icon>
          </ListItemIcon>
        )}
        <ListItemText primary={item.title} />
        {item.badge && <OftadehNavBadge className="mr-4" badge={item.badge} />}
        {open ? <ExpandLess /> : <ExpandMore />}
      </ListItem>
      {item.children && (
        <Collapse in={open} timeout="auto" unmountOnExit>
          {item.children.map(item => (
            <React.Fragment key={item.id}>
              {item.type === "group" && <OftadehNavGroup item={item} />}

              {item.type === "collapse" && <NavCollapse item={item} />}

              {item.type === "item" && <OftadehNavItem item={item} />}

              {item.type === "link" && <OftadehNavLink item={item} />}
            </React.Fragment>
          ))}
        </Collapse>
      )}
    </ul>
  );
}
Example #12
Source File: Sidebar.js    From quizdom with MIT License 5 votes vote down vote up
function Sidebar() {
	const [signOut, setSignOut] = useState(false)
	const SidedbarData = [
		{
			title: 'Dashboard',
			path: '/dashboard',
			icon: <Dashboard />,
			CName: 'nav-text',
		},
		{
			title: 'Join Quiz',
			path: '/join-quiz',
			icon: <MeetingRoom />,
			CName: 'nav-text',
		},
		{
			title: 'Create Quiz',
			path: '/create-quiz',
			icon: <CreateNewFolder />,
			CName: 'nav-text',
		},
	]
	const [sidebar, setSidebar] = useState(false)
	const showSidebar = () => setSidebar(!sidebar)
	if (signOut) return <Redirect to='/' />

	return (
		<div>
			<Icon className='menu-bars' onClick={showSidebar}>
				<MenuRounded />
			</Icon>
			{/* <FaIcons.FaBars  onClick={} /> */}
			<nav className={sidebar ? 'nav-menu active' : 'nav-menu'}>
				<ul className='nav-menu-items' onClick={showSidebar}>
					<li className='navbar-toggle'>
						<Icon>
							<MenuOpenRounded fontSize='large' />
						</Icon>
					</li>
					{SidedbarData.map((item, index) => {
						return (
							<li key={index} className='nav-text'>
								<Link to={item.path}>
									<Icon>{item.icon}</Icon>
									<span className='nav-item-title'>{item.title}</span>
								</Link>
							</li>
						)
					})}
					{/* Sign Out Button */}
					<li className='nav-text sign-out'>
						<button
							onClick={() => {
								console.log('clicked')
								// setUser({})
								firebase.auth().signOut()
								setSignOut(true)
							}}
						>
							<Icon>
								<ExitToApp />
							</Icon>
							<span className='nav-item-title'>{'SignOut'}</span>
						</button>
					</li>
				</ul>
			</nav>
		</div>
	)
}
Example #13
Source File: InGameTime.jsx    From archeage-tools with The Unlicense 5 votes vote down vote up
render() {
    const { mobile } = this.props;
    const { time } = this.state;

    if (mobile) {
      return (
        <Paper className="event-list">
          <AppBar position="static">
            <Toolbar variant="dense">
              <Icon>
                <div className="clock-icon" />
              </Icon>
              <Typography>In-Game Time: {time}</Typography>
            </Toolbar>
          </AppBar>
        </Paper>
      );
    }

    return (
      <Typography>
        <Tooltip title={
          <>
            <Typography>In-Game Time</Typography>
            <Typography variant="caption" component="p">In-Game Time estimation is approximate. All servers may vary
              by a minute or so.</Typography>
            <Typography variant="caption" component="p">Each in-game hour spans 10 minutes of real-life time, with a
              full in-game day occurring in 4 hours of real-life time.</Typography>
            <Typography variant="caption" component="p">Events and bosses spawn at the specified time, but may be
              completed or killed by other players before the timer&apos;s in-progress duration is over.</Typography>
          </>
        }>
          <span>
            <span className="clock-icon" />
            {time}
          </span>
        </Tooltip>
      </Typography>
    );
  }
Example #14
Source File: Requestotp.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
RequestOtp = props => {
  let history = useHistory();

  const [contactNumber, setContactNumber] = useState("");
  const [error, setError] = useState("");
  const { loaderStatus, setLoaderStatus } = useContext(LoaderContext);

  const classes = useStyles();
  const { layout: Layout } = props;
  const validate = () => {
    setLoaderStatus(true);
    const error = validateInput(
      contactNumber,
      form["contactNumber"]["validations"]
    );
    console.log(error);
    if (error[0]) setError(error);
    else {
      postCall();
    }
  };

  const postCall = () => {
    axios
      .post(
        strapiApiConstants.STRAPI_DB_URL +
          strapiApiConstants.STRAPI_REQUEST_STUDENT_OTP,
        { contact_number: contactNumber }
      )
      .then(res => {
        history.push("/verifyotp", { contactNumber: contactNumber });
        setLoaderStatus(false);
      })
      .catch(err => {
        console.log(err);
        setLoaderStatus(false);
      });
  };

  return (
    <Layout>
      <div className={classes.masterlogin2}>
        <div className={classes.masterlogin1}>
          <div className={classes.masterlogin}>
            <Paper className={classes.rootDesktop}>
              <CardContent>
                <CssBaseline />
                <div className={classes.paper}>
                  <div className={classes.signin_header}>
                    <div className={classes.loginlock}>
                      <CardIcon>
                        <Icon>lock</Icon>
                      </CardIcon>
                    </div>
                    <Typography
                      className={classes.signin}
                      component="h1"
                      variant="h5"
                      style={{ fontWeight: "700" }}
                    >
                      {authPageConstants.REGISTER}
                    </Typography>
                  </div>

                  <React.Fragment>
                    <Typography
                      component="h5"
                      variant="subtitle2"
                      style={{ marginTop: ".9rem", marginBottom: ".9rem" }}
                    >
                      {authPageConstants.MOBILE_NUMBER_ALERT}
                    </Typography>
                    <TextField
                      label="Contact Number"
                      name="contactnumber"
                      value={contactNumber}
                      variant="outlined"
                      fullWidth
                      error={error[0] ? true : false}
                      required
                      helperText={error ? error : null}
                      onChange={event => {
                        if (contactNumber.length === 9) setError("");
                        setContactNumber(event.target.value);
                      }}
                    />
                    <Button
                      color="primary"
                      type="submit"
                      fullWidth
                      variant="contained"
                      className={classes.submit}
                      onClick={() => {
                        validate();
                      }}
                    >
                      {authPageConstants.SEND_OTP_BUTTON}
                    </Button>
                  </React.Fragment>
                  <Grid container>
                    <Grid item xs={12} style={{ textAlign: "center" }}>
                      <Link
                        href={routeConstants.SIGN_IN_URL}
                        variant="body2"
                        className={classes.linkColor}
                      >
                        {authPageConstants.BACK_TO_LOGIN_TEXT}
                      </Link>
                    </Grid>
                  </Grid>
                </div>
              </CardContent>

              <Hidden mdDown>
                <CardMedia
                  className={classes.cover}
                  image={image}
                  title="UPSTPC"
                />
              </Hidden>
            </Paper>
          </div>
        </div>
      </div>
    </Layout>
  );
}
Example #15
Source File: ViewEvent.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
ViewEvent = props => {
  const history = useHistory();
  const classes = useStyles();
  const [formState, setFormState] = useState({
    eventDetails: {},
    greenButtonChecker: true,
    registeredEventsIds: [],
    registeredForEvent: false,
    isReadAllTerms: false,
    showRegisterModel: false
  });
  useEffect(() => {
    getEventDetails();
    getRegisteredEvents();
  }, []);

  /** Check if a student is registered for a event */
  const getRegisteredEvents = async () => {
    if (auth.getUserInfo().role.name === roleConstants.STUDENT) {
      const apiToCheckStudentRegistration =
        strapiConstants.STRAPI_DB_URL +
        strapiConstants.STRAPI_CONTACT_URL +
        "/" +
        auth.getUserInfo().studentInfo.contact.id +
        "/get-individual-registered-events";
      await serviceProviders
        .serviceProviderForGetRequest(apiToCheckStudentRegistration)
        .then(res => {
          let registeredEvents = [];
          res.data.result.map(data => {
            registeredEvents.push(data.event.id);
          });
          let isEventRegistered = checkEventRegistered(registeredEvents);
          setFormState(formState => ({
            ...formState,
            registeredEventsIds: registeredEvents,
            registeredForEvent: isEventRegistered
          }));
        })
        .catch(error => {
          console.log("error", error);
        });
    }
  };

  async function getEventDetails() {
    let paramsForEvent = null;
    if (auth.getUserInfo() && auth.getUserInfo().role) {
      if (
        auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
        auth.getUserInfo().role.name === roleConstants.STUDENT ||
        auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
      ) {
        paramsForEvent = props["location"]["dataForView"];
      }
      if (paramsForEvent !== null && paramsForEvent !== undefined) {
        await serviceProviders
          .serviceProviderForGetOneRequest(EVENTS_URL, paramsForEvent)
          .then(res => {
            let viewData = res.data.result;
            setFormState(formState => ({
              ...formState,
              eventDetails: viewData
            }));
          })
          .catch(error => {
            console.log("error", error);
          });
      } else {
        if (auth.getUserInfo().role.name === roleConstants.MEDHAADMIN) {
          history.push({
            pathname: routeConstants.MANAGE_EVENT
          });
        } else if (auth.getUserInfo().role.name === roleConstants.STUDENT) {
          history.push({
            pathname: routeConstants.ELIGIBLE_EVENT
          });
        } else {
          history.push({
            pathname: routeConstants.DASHBOARD_URL
          });
        }
      }
    } else {
      auth.clearAppStorage();
      history.push({
        pathname: routeConstants.SIGN_IN_URL
      });
    }
  }

  const route = () => {
    if (auth.getUserInfo().role.name === roleConstants.STUDENT) {
      history.push({
        pathname: routeConstants.ELIGIBLE_EVENT
      });
    } else if (
      auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
    ) {
      history.push({
        pathname: routeConstants.MANAGE_EVENT
      });
    } else {
      auth.clearToken();
      auth.clearUserInfo();
      history.push({
        pathname: routeConstants.SIGN_IN_URL
      });
    }
  };

  /** Gives formatted time */
  const getTime = () => {
    let startTime = new Date(formState.eventDetails["start_date_time"]);
    if (
      formState.eventDetails["start_date_time"] &&
      formState.eventDetails["end_date_time"]
    ) {
      let endTime = new Date(formState.eventDetails["end_date_time"]);
      return (
        startTime.toLocaleTimeString() + " to " + endTime.toLocaleTimeString()
      );
    } else {
      startTime = new Date(formState.eventDetails["start_date_time"]);
      return startTime.toLocaleTimeString();
    }
  };

  /** Gives formatted date */
  const getDate = () => {
    let startDate = new Date(formState.eventDetails["start_date_time"]);
    if (
      formState.eventDetails["start_date_time"] &&
      formState.eventDetails["end_date_time"]
    ) {
      let endDate = new Date(formState.eventDetails["end_date_time"]);
      return startDate.toDateString() + " to " + endDate.toDateString();
    } else {
      startDate = new Date(formState.eventDetails["start_date_time"]);
      return startDate.toDateString();
    }
  };

  /** Gets event venue */
  const getVenue = () => {
    return formState.eventDetails["address"];
  };

  /** Registers a student for a particular event */
  const register = event => {
    setFormState(formState => ({
      ...formState,
      showRegisterModel: true
    }));
  };

  const checkEventRegistered = registeredEvents => {
    if (registeredEvents.indexOf(props["location"]["dataForView"]) !== -1) {
      return true;
    } else {
      return false;
    }
  };

  const handleCheckBoxChange = () => {
    setFormState(formState => ({
      ...formState,
      isReadAllTerms: !formState.isReadAllTerms
    }));
  };

  const modalClose = () => {
    setFormState(formState => ({
      ...formState,
      showRegisterModel: false
    }));
  };

  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        <Typography variant="h4" gutterBottom>
          View Event
        </Typography>
        <GreenButton
          variant="contained"
          color="primary"
          disableElevation
          onClick={route}
          to={routeConstants.MANAGE_EVENT}
          startIcon={<Icon>keyboard_arrow_left</Icon>}
          greenButtonChecker={formState.greenButtonChecker}
        >
          Back to listing
        </GreenButton>
      </Grid>
      <Grid item xs={12} className={classes.formgrid}>
        <Card>
          <CardContent>
            <Grid container spacing={3} className={classes.formgrid}>
              <Grid item md={12} xs={12}>
                {!formUtilities.checkEmpty(formState.eventDetails) ? (
                  <React.Fragment>
                    <Grid item md={12} xs={12} className={classes.title}>
                      <Typography
                        variant="h4"
                        gutterBottom
                        color="textSecondary"
                      >
                        {formState.eventDetails["title"]}
                      </Typography>
                    </Grid>
                    <Divider />
                    <Grid
                      container
                      spacing={2}
                      className={classes.defaultMargin}
                    >
                      <Grid item md={4} xs={12}>
                        <Grid
                          item
                          className={classes.defaultMargin}
                          spacing={4}
                        >
                          <Box>
                            {formState.eventDetails["upload_logo"] !== null &&
                            formState.eventDetails["upload_logo"] !==
                              undefined &&
                            formState.eventDetails["upload_logo"] !== {} ? (
                              <CardMedia
                                image={
                                  strapiConstants.STRAPI_DB_URL_WITHOUT_HASH +
                                  formState.eventDetails["upload_logo"]["url"]
                                }
                                className={classes.ViewEventImageStyling}
                              />
                            ) : (
                              <CardMedia
                                image={noImage}
                                className={classes.NoEventsStyling}
                              />
                            )}

                            <Box className={classes.MarginTop}>
                              <Grid container spacing={1} justify="center">
                                <Grid item md={3} xs={3}>
                                  <Typography variant="h5" color="textPrimary">
                                    Date
                                  </Typography>
                                </Grid>
                                <Grid item md={9} xs={9}>
                                  <Typography color="textSecondary">
                                    {getDate()}
                                  </Typography>
                                </Grid>
                                <Grid item md={3} xs={3}>
                                  <Typography variant="h5" color="textPrimary">
                                    Time
                                  </Typography>
                                </Grid>
                                <Grid item md={9} xs={9}>
                                  <Typography color="textSecondary">
                                    {getTime()}
                                  </Typography>
                                </Grid>
                                <Grid item md={3} xs={3}>
                                  <Typography variant="h5" color="textPrimary">
                                    Venue
                                  </Typography>
                                </Grid>
                                <Grid item md={9} xs={9}>
                                  <Typography color="textSecondary">
                                    {getVenue()}
                                  </Typography>
                                </Grid>
                              </Grid>
                            </Box>
                          </Box>
                        </Grid>

                        <Divider />
                      </Grid>
                      <Grid item md={8} xs={12}>
                        {ReactHtmlParser(formState.eventDetails["description"])}
                      </Grid>
                    </Grid>
                    {auth.getUserInfo().role.name === roleConstants.STUDENT ? (
                      <Grid spacing={2} className={classes.defaultMargin}>
                        <FormControlLabel
                          control={
                            <Checkbox
                              disabled={formState.registeredForEvent}
                              checked={
                                formState.registeredForEvent
                                  ? true
                                  : formState.isReadAllTerms
                              }
                              onChange={handleCheckBoxChange}
                              name="checkedB"
                              color="primary"
                            />
                          }
                          label={genericConstants.EVENT_CONFIRMATION}
                        />
                      </Grid>
                    ) : null}
                    <Grid>
                      {auth.getUserInfo().role.name ===
                      roleConstants.STUDENT ? (
                        <Grid item md={12} xs={12}>
                          <CardActions className={classes.btnspace}>
                            <GreenButton
                              variant="contained"
                              color="primary"
                              buttonDisabled={!formState.isReadAllTerms}
                              disableElevation
                              onClick={register}
                              to={routeConstants.MANAGE_EVENT}
                              greenButtonChecker={formState.greenButtonChecker}
                            >
                              {formState.registeredForEvent
                                ? genericConstants.EVENT_REGISTERED
                                : genericConstants.EVENT_REGISTRATION}
                            </GreenButton>
                          </CardActions>
                        </Grid>
                      ) : null}
                    </Grid>
                  </React.Fragment>
                ) : (
                  <Spinner />
                )}
              </Grid>
            </Grid>
          </CardContent>
        </Card>
      </Grid>
      {auth.getUserInfo().role.name === roleConstants.STUDENT ? (
        <RegisterEvent
          showModal={formState.showRegisterModel}
          modalClose={modalClose}
          eventId={props["location"]["dataForView"]}
          eventTitle={formState.eventDetails["title"]}
          userId={auth.getUserInfo().studentInfo.contact.id}
        />
      ) : null}
    </Grid>
  );
}
Example #16
Source File: Verifyotp.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
VerifyOtp = props => {
  let history = useHistory();

  const { loaderStatus, setLoaderStatus } = useContext(LoaderContext);

  const [otp, setotp] = useState("");
  const classes = useStyles();
  const [error, setError] = useState("");
  const { layout: Layout } = props;

  const validate = () => {
    setLoaderStatus(true);
    const error = validateInput(otp, form["otp"]["validations"]);
    console.log(error);
    if (error[0]) {
      setError(error);
      setLoaderStatus(false);
    } else {
      axios
        .post(
          strapiApiConstants.STRAPI_DB_URL +
            strapiApiConstants.STRAPI_CHECK_OTP,
          { otp: otp, contact_number: props.location.state.contactNumber }
        )
        .then(res => {
          history.push(routeConstants.NEW_REGISTRATION_URL, {
            otp: otp,
            contactNumber: props.location.state.contactNumber,
            from: routeConstants.VERIFY_OTP
          });
          setLoaderStatus(false);
        })
        .catch(err => {
          if (err.response.data.message === "User already registered") {
            setError("User Already Registered");
          } else if (err.response.data.message === "OTP is invalid")
            setError("Invalid OTP");

          setLoaderStatus(false);
        });
    }
  };

  const requestOtpAgain = () => {
    setLoaderStatus(true);
    axios
      .post(
        strapiApiConstants.STRAPI_DB_URL +
          strapiApiConstants.STRAPI_REQUEST_STUDENT_OTP,
        { contact_number: props.location.state.contactNumber }
      )
      .then(res => {
        setLoaderStatus(false);
      })
      .catch(err => {
        console.log(err);
        setLoaderStatus(false);
      });
  };
  if (!props.location.state) {
    return (
      <Redirect
        to={{
          pathname: routeConstants.SIGN_IN_URL
        }}
      />
    );
  } else {
    return (
      <Layout>
        <div className={classes.masterlogin2}>
          <div className={classes.masterlogin1}>
            <div className={classes.masterlogin}>
              <Paper className={classes.rootDesktop}>
                <CardContent>
                  <CssBaseline />
                  <div className={classes.paper}>
                    <div className={classes.signin_header}>
                      <div className={classes.loginlock}>
                        <CardIcon>
                          <Icon>lock</Icon>
                        </CardIcon>
                      </div>
                      <Typography
                        className={classes.signin}
                        component="h1"
                        variant="h5"
                        style={{ fontWeight: "700" }}
                      >
                        {authPageConstants.REGISTER}
                      </Typography>
                    </div>

                    <React.Fragment>
                      <Typography
                        component="h5"
                        variant="subtitle2"
                        style={{ marginTop: ".9rem", marginBottom: ".9rem" }}
                      >
                        {authPageConstants.OTP_ALERT}{" "}
                        {props.location.state.contactNumber}
                      </Typography>
                      <TextField
                        label="One Time Password"
                        name="otp"
                        value={otp}
                        style={{ marginRight: "175px" }}
                        error={error[0] ? true : false}
                        variant="outlined"
                        fullWidth
                        helperText={error ? error : null}
                        onChange={event => {
                          if (otp.length > 0) setError("");
                          setotp(event.target.value);
                        }}
                      />
                      <Link
                        href="javascript:void(0);"
                        variant="body2"
                        className={classes.linkColor}
                        onClick={requestOtpAgain}
                      >
                        {authPageConstants.RESEND_OTP_BUTTON}
                      </Link>

                      <Button
                        color="primary"
                        type="submit"
                        fullWidth
                        variant="contained"
                        className={classes.submit}
                        onClick={() => {
                          validate();
                        }}
                      >
                        Verify OTP
                      </Button>
                    </React.Fragment>
                    <Grid container>
                      <Grid item xs={12} style={{ textAlign: "center" }}>
                        <Link
                          href={routeConstants.SIGN_IN_URL}
                          variant="body2"
                          className={classes.linkColor}
                        >
                          {authPageConstants.BACK_TO_LOGIN_TEXT}
                        </Link>
                      </Grid>
                    </Grid>
                  </div>
                </CardContent>
                <Hidden mdDown>
                  <CardMedia
                    className={classes.cover}
                    image={image}
                    title="Live from space album cover"
                  />
                </Hidden>
              </Paper>
            </div>
          </div>
        </div>
      </Layout>
    );
  }
}
Example #17
Source File: EventStudentList.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
StudentList = props => {
  const [open, setOpen] = React.useState(true);
  const history = useHistory();
  const classes = useStyles();
  const [streams, setStreams] = useState([]);
  const { setLoaderStatus } = useContext(LoaderContext);
  /** Value to set for event filter */
  const [value, setValue] = React.useState(null);

  const [formState, setFormState] = useState({
    students: [],
    registration: [],
    hireColor: {},
    greenButtonChecker: true,
    dataToShow: props.testDataToShow ? props.testDataToShow : [],
    tempData: [],
    eventTitle: props["location"]["eventTitle"],
    eventId: props["location"]["eventId"],
    year: new Date(),

    studentFilterData: [],
    filterDataParameters: {},
    isClearResetFilter: false,
    isFilterSearch: false,
    texttvalue: "",
    hireStudentData: [],

    /*** Hire */
    dataToHire: {},
    isHired: false,
    isUnHired: false,
    showModalHire: false,
    studentName: "",
    hireStudent: "",

    /** Pagination and sortinig data */
    isDataLoading: false,
    pageSize: "",
    totalRows: "",
    page: "",
    pageCount: "",
    sortAscending: true,

    /** Attaindance */
    markAttaindance: "",
    dataToMarkAttaindance: {},
    isPresent: false,
    isAbsent: false,
    showModalAttaindance: false
  });

  useEffect(() => {
    getStudentList(10, 1);
    getFilterData();
  }, []);

  const getStudentList = async (pageSize, page, paramsForevents = null) => {
    if (
      paramsForevents !== null &&
      !formUtilities.checkEmpty(paramsForevents)
    ) {
      let defaultParams = {};
      if (paramsForevents.hasOwnProperty(SORT_FIELD_KEY)) {
        defaultParams = {
          page: page,
          pageSize: pageSize
        };
      } else {
        defaultParams = {
          page: page,
          pageSize: pageSize,
          [SORT_FIELD_KEY]: "name:asc"
        };
      }
      Object.keys(paramsForevents).map(key => {
        defaultParams[key] = paramsForevents[key];
      });
      paramsForevents = defaultParams;
    } else {
      paramsForevents = {
        page: page,
        pageSize: pageSize,
        [SORT_FIELD_KEY]: "name:asc"
      };
    }
    setFormState(formState => ({
      ...formState,
      isDataLoading: true
    }));
    let EVENT_ID = null;
    let regStudent_url = null;
    if (
      auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
    ) {
      EVENT_ID = formState.eventId;
      regStudent_url = EVENT_URL + "/" + EVENT_ID + "/" + STUDENT_URL;
      if (auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN) {
        paramsForevents["individual.organization"] = auth.getUserInfo()[
          "studentInfo"
        ]["organization"]["id"];
      }
    }
    if (
      EVENT_ID !== undefined &&
      EVENT_ID !== null &&
      regStudent_url !== null
    ) {
      await serviceProvider
        .serviceProviderForGetRequest(regStudent_url, paramsForevents)
        .then(res => {
          formState.dataToShow = [];
          formState.tempData = [];
          let eventData = [];
          getHiredIds(res.data.result)
            .then(res1 => {
              eventData = convertEventData(res.data.result, res1);

              setFormState(formState => ({
                ...formState,
                students: res.data.result,
                pageSize: res.data.pageSize,
                totalRows: res.data.rowCount,
                page: res.data.page,
                pageCount: res.data.pageCount,
                dataToShow: eventData,
                tempData: eventData,
                isDataLoading: false
              }));
            })
            .catch(error => {});
        })
        .catch(error => {
          console.log("error", error);
        });
    } else {
      if (
        auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
        auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
      ) {
        history.push({
          pathname: routeConstants.MANAGE_EVENT
        });
      } else {
        history.push({
          pathname: routeConstants.DASHBOARD_URL
        });
      }
    }
  };

  const getHiredIds = async studentData => {
    let studentEventData = [];
    for (let data in studentData) {
      let paramsForHire = {
        "event.id": props["location"]["eventId"],
        "contact.id": studentData[data]["id"]
      };
      await serviceProvider
        .serviceProviderForGetRequest(REGISTRATION_URL, paramsForHire)
        .then(res => {
          for (let i in res.data.result) {
            var attaindandeAndHire = {};
            attaindandeAndHire["Attaindance"] =
              res.data.result[i]["is_attendance_verified"];
            attaindandeAndHire["HireDehire"] =
              res.data.result[i]["is_hired_at_event"];
            studentEventData.push(attaindandeAndHire);
          }
        })
        .catch(error => {
          console.log("error", error);
        });
    }
    return studentEventData;
  };

  const convertEventData = (data, hiredIds) => {
    let x = [];
    if (data.length > 0) {
      for (let i in (data, hiredIds)) {
        var eventIndividualData = {};
        let educationYear = [];
        eventIndividualData["id"] = data[i]["id"];
        eventIndividualData["studentid"] = data[i]["individual"]["id"];
        eventIndividualData["user"] = data[i]["user"]
          ? data[i]["user"]["username"]
          : "";
        eventIndividualData["name"] = data[i]["name"];
        if (data[i]["individual"]) {
        } else {
          eventIndividualData["stream"] = "";
        }
        eventIndividualData["college"] =
          data[i]["individual"] &&
          data[i]["individual"]["organization"] &&
          data[i]["individual"]["organization"]["name"]
            ? data[i]["individual"]["organization"]["name"]
            : "";

        eventIndividualData["stream"] =
          data[i]["individual"] &&
          data[i]["individual"]["stream"] &&
          data[i]["individual"]["stream"]["name"]
            ? data[i]["individual"]["stream"]["name"]
            : "";
        if (data[i]["qualifications"]) {
          for (let j in data[i]["qualifications"]) {
            if (
              data[i]["qualifications"][j]["pursuing"] &&
              data[i]["qualifications"][j]["education_year"] !== null
            ) {
              educationYear.push(
                data[i]["qualifications"][j]["education_year"]
              );
            }
          }
          eventIndividualData["educations"] = educationYear;
        } else {
          eventIndividualData["educations"] = [];
        }
        eventIndividualData["mobile"] = data[i]["phone"]
          ? data[i]["phone"]
          : "";

        eventIndividualData["attaindance"] = hiredIds[i]["Attaindance"];
        eventIndividualData["hired"] = hiredIds[i]["HireDehire"];
        x.push(eventIndividualData);
      }
      return x;
    }
  };

  const getFilterData = () => {
    let params = {
      pageSize: -1
    };

    serviceProvider
      .serviceProviderForGetRequest(STREAM_URL, params)
      .then(res => {
        setStreams(res.data.result);
      })
      .catch(error => {
        console.log("error");
      });
  };

  const modalClose = () => {
    setFormState(formState => ({
      ...formState,
      showModalHire: false,
      showModalAttaindance: false
    }));
  };

  const handleCloseHireModal = status => {
    /** This restores all the data when we close the modal */
    //restoreData();
    setOpen(true);
    setFormState(formState => ({
      ...formState,
      isStudentHired: status,
      showModalHire: false,
      fromHiredModal: true,
      isAttaindanceMarked: false,
      fromAttaindanceModal: false
    }));
    if (status) {
      getStudentList(
        formState.pageSize,
        formState.page,
        formState.filterDataParameters
      );
    }
  };

  const hiredCell = event => {
    setLoaderStatus(true);
    setFormState(formState => ({
      ...formState,
      hireStudent: event.target.getAttribute("value")
    }));
    getEventRegistrationData(event.target.id);
  };

  const getEventRegistrationData = async id => {
    let paramsForHire = {
      "contact.id": id,
      "event.id": formState.eventId
    };
    serviceProvider
      .serviceProviderForGetRequest(REGISTRATION_URL, paramsForHire)
      .then(res => {
        let registerData = res.data.result[0];
        let regUserID = registerData.id;
        if (registerData.is_hired_at_event) {
          registerCellData(regUserID, false, "");
        } else {
          registerCellData(regUserID, true, "");
        }
      })
      .catch(error => {
        console.log("error", error);
      });
  };

  const registerCellData = (id, isHired = false, studentName) => {
    if (isHired === true) {
      setFormState(formState => ({
        ...formState,
        dataToHire: id,
        isHired: true,
        isUnHired: false,
        showModalHire: true,
        fromHiredModal: false,
        isStudentHired: false
      }));
    } else {
      setFormState(formState => ({
        ...formState,
        dataToHire: id,
        isHired: false,
        isUnHired: true,
        showModalHire: true,
        messageToShow: "",
        fromHiredModal: false,
        isStudentHired: false
      }));
    }
    setLoaderStatus(false);
  };

  const handleAttaindance = event => {
    setLoaderStatus(true);
    setFormState(formState => ({
      ...formState,
      markAttaindance: event.target.getAttribute("value")
    }));
    markStudentAttaindance(event.target.id);
  };

  const markStudentAttaindance = async id => {
    let paramsForHire = {
      "contact.id": id,
      "event.id": formState.eventId
    };
    serviceProvider
      .serviceProviderForGetRequest(REGISTRATION_URL, paramsForHire)
      .then(res => {
        let registerData = res.data.result[0];
        let regUserID = registerData.id;
        if (registerData.is_attendance_verified) {
          attaindanceCellData(regUserID, false, "");
        } else {
          attaindanceCellData(regUserID, true, "");
        }
      })
      .catch(error => {
        console.log("error", error);
      });
  };

  const attaindanceCellData = (id, isPresent = false, studentName) => {
    if (isPresent === true) {
      setFormState(formState => ({
        ...formState,
        dataToMarkAttaindance: id,
        isPresent: true,
        isAbsent: false,
        showModalAttaindance: true,
        studentName: studentName
      }));
    } else {
      setFormState(formState => ({
        ...formState,
        dataToMarkAttaindance: id,
        isPresent: false,
        isAbsent: true,
        showModalAttaindance: true,
        studentName: studentName
      }));
    }
    setLoaderStatus(false);
  };

  const handleCloseAttaindanceModal = status => {
    /** This restores all the data when we close the modal */
    //restoreData();
    setOpen(true);
    setFormState(formState => ({
      ...formState,
      isAttaindanceMarked: status,
      showModalAttaindance: false,
      fromAttaindanceModal: true,
      isStudentHired: false,
      fromHiredModal: false
    }));
    if (status) {
      getStudentList(
        formState.pageSize,
        formState.page,
        formState.filterDataParameters
      );
    }
  };

  /** Pagination */
  const handlePerRowsChange = async (perPage, page) => {
    /** If we change the now of rows per page with filters supplied then the filter should by default be applied*/
    if (formUtilities.checkEmpty(formState.filterDataParameters)) {
      await getStudentList(perPage, page);
    } else {
      if (formState.isFilterSearch) {
        await searchFilter(perPage, page);
      } else {
        await getStudentList(perPage, page, formState.filterDataParameters);
      }
    }
  };

  const handlePageChange = async page => {
    if (formUtilities.checkEmpty(formState.filterDataParameters)) {
      await getStudentList(formState.pageSize, page);
    } else {
      if (formState.isFilterSearch) {
        await searchFilter(formState.pageSize, page);
      } else {
        await getStudentList(
          formState.pageSize,
          page,
          formState.filterDataParameters
        );
      }
    }
  };

  const handleChangeAutoComplete = (filterName, event, value) => {
    if (value === null) {
      delete formState.filterDataParameters[filterName];
    } else {
      formState.filterDataParameters[filterName] = value["id"];
      setFormState(formState => ({
        ...formState,
        isClearResetFilter: false
      }));
    }
  };

  const handleClick = event => {
    history.push({
      pathname: routeConstants.VIEW_STUDENT_PROFILE,
      dataForStudent: event.target.id,
      fromAddStudentToRecruitmentDrive: false,
      fromEventStudentList: true,
      eventId: formState.eventId,
      eventTitle: formState.eventTitle
    });
  };

  /** To make cell data hypertext */
  const CustomLink = ({ row }) => (
    <div>
      {}
      <div>
        <a href="#" id={row.studentid} onClick={handleClick}>
          {row.name}
        </a>
      </div>
    </div>
  );

  const backToManageEvent = () => {
    history.push({
      pathname: routeConstants.MANAGE_EVENT
    });
  };

  const toAddStudents = () => {
    history.push({
      pathname: routeConstants.ADD_STUDENT_DRIVE,
      eventId: formState.eventId,
      eventTitle: formState.eventTitle
    });
  };

  /** Data Export Functionality */
  const handleClickDownloadStudents = value => {
    let data = [];
    for (let i in value) {
      var eventIndividualData = {};
      eventIndividualData["Name"] = value[i]["name"];
      eventIndividualData["Mobile"] = value[i]["mobile"];
      eventIndividualData["College Name"] = value[i]["college"];
      eventIndividualData["Stream"] = value[i]["stream"];
      if (value[i]["attaindance"]) {
        eventIndividualData["Attended"] = "Yes";
      } else {
        eventIndividualData["Attended"] = "No";
      }
      if (value[i]["hired"]) {
        eventIndividualData["Hired"] = "Yes";
      } else {
        eventIndividualData["Hired"] = "No";
      }

      data.push(eventIndividualData);
    }
    return data;
  };

  /** Used for restoring data */
  const restoreData = () => {
    getStudentList(formState.pageSize, 1);
  };

  /** Filter methods and functions */
  /** This restores all the data when we clear the filters*/

  const clearFilter = () => {
    setFormState(formState => ({
      ...formState,
      isFilterSearch: false,
      /** Clear all filters */
      filterDataParameters: {},
      /** Turns on the spinner */
      isClearResetFilter: true,
      isStateClearFilter: true,
      isDataLoading: true,
      studentFilterData: []
    }));
    formState.filterDataParameters[STUDENT_FILTER] = "";
    /**Need to confirm this thing for resetting the data */
    restoreData();
  };

  const handleFilterChangeForStudentField = event => {
    setFormState(formState => ({
      ...formState,
      filterDataParameters: {
        ...formState.filterDataParameters,
        [event.target.name]: event.target.value
      }
    }));
    event.persist();
    // setRpcsFilter(event.target.value);
  };

  /** Search filter is called when we select filters and click on search button */
  const searchFilter = async (perPage = formState.pageSize, page = 1) => {
    if (!formUtilities.checkEmpty(formState.filterDataParameters)) {
      formState.isFilterSearch = true;
      await getStudentList(perPage, page, formState.filterDataParameters);
    } else {
      await getStudentList(perPage, page);
    }
  };

  const handleSort = (
    column,
    sortDirection,
    perPage = formState.pageSize,
    page = 1
  ) => {
    if (column.selector === "stream") {
      column.selector = "individual.stream.name";
    }
    formState.filterDataParameters[SORT_FIELD_KEY] =
      column.selector + ":" + sortDirection;
    getStudentList(perPage, page, formState.filterDataParameters);
  };

  /** Table Data */
  const column = [
    {
      name: "Name",
      sortable: true,
      selector: "name",
      cell: row => <CustomLink row={row} />
    },
    { name: "Stream", sortable: true, selector: "stream" },
    {
      name: "Education year",
      sortable: true,
      cell: row => (
        <Tooltip
          title={
            <React.Fragment>
              <Typography color="inherit">{`${row.educations}`}</Typography>
            </React.Fragment>
          }
          placement="top"
        >
          <div>{`${row.educations}`}</div>
        </Tooltip>
      )
    },
    { name: "Mobile", selector: "mobile" },

    {
      name: "Actions",
      cell: cell => (
        <div className={classes.DisplayFlex}>
          <div className={classes.PaddingSomeActionButton}>
            <HowToReg
              id={cell.id}
              value={cell.name}
              onClick={handleAttaindance}
              style={cell.attaindance}
            />
          </div>
          {cell.attaindance === true ? (
            <div className={classes.PaddingActionButton}>
              <ThumbIcon
                id={cell.id}
                value={cell.name}
                onClick={hiredCell}
                style={cell.hired}
              />
            </div>
          ) : null}
        </div>
      ),
      width: "20%",
      cellStyle: {
        width: "auto",
        maxWidth: "auto"
      }
    }
  ];

  return (
    <Grid>
      <Grid
        container
        spacing={3}
        justify="space-between"
        className={classes.title}
      >
        <Grid item>
          <Typography variant="h4" gutterBottom>
            Event Students List
          </Typography>
        </Grid>
        <Grid item>
          {auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN ? (
            <GreenButton
              id="addStudents"
              variant="contained"
              color="secondary"
              startIcon={<PersonAddIcon />}
              onClick={() => toAddStudents()}
              greenButtonChecker={formState.greenButtonChecker}
              style={{ margin: "2px", marginRight: "15px" }}
            >
              Add Student
            </GreenButton>
          ) : null}

          <ExportCSV
            id="exportCsv"
            csvData={handleClickDownloadStudents(formState.dataToShow)}
            fileName={formState.eventTitle}
          />
          <GreenButton
            id="backToManageEvent"
            variant="contained"
            color="primary"
            disableElevation
            onClick={() => backToManageEvent()}
            startIcon={<Icon>keyboard_arrow_left</Icon>}
            greenButtonChecker={formState.greenButtonChecker}
            style={{ margin: "2px" }}
          >
            Back to listing
          </GreenButton>
        </Grid>
      </Grid>

      {/** Error/Success messages to be shown for student */}
      {formState.fromAttaindanceModal && formState.isAttaindanceMarked ? (
        <Collapse in={open}>
          <Alert
            severity="success"
            action={
              <IconButton
                aria-label="close"
                color="inherit"
                size="small"
                onClick={() => {
                  setOpen(false);
                }}
              >
                <CloseIcon fontSize="inherit" />
              </IconButton>
            }
          >
            {formState.isPresent
              ? "The Student " +
                formState.markAttaindance +
                " has been marked as present."
              : "The Student " +
                formState.markAttaindance +
                " has been marked as absent."}
          </Alert>
        </Collapse>
      ) : null}
      {formState.fromAttaindanceModal && !formState.isAttaindanceMarked ? (
        <Collapse in={open}>
          <Alert
            severity="error"
            action={
              <IconButton
                aria-label="close"
                color="inherit"
                size="small"
                onClick={() => {
                  setOpen(false);
                }}
              >
                <CloseIcon fontSize="inherit" />
              </IconButton>
            }
          >
            {formState.isPresent
              ? "An error has occured while marking student " +
                formState.markAttaindance +
                " attaindance. Kindly, try again."
              : "An error has occured while removing student. " +
                formState.markAttaindance +
                " attaindance Kindly, try again."}
          </Alert>
        </Collapse>
      ) : null}

      {formState.fromHiredModal && formState.isStudentHired ? (
        <Collapse in={open}>
          <Alert
            severity="success"
            action={
              <IconButton
                aria-label="close"
                color="inherit"
                size="small"
                onClick={() => {
                  setOpen(false);
                }}
              >
                <CloseIcon fontSize="inherit" />
              </IconButton>
            }
          >
            {formState.isHired
              ? "The Student " +
                formState.hireStudent +
                " has been marked as hired."
              : "The Student " +
                formState.hireStudent +
                " has been marked as dehired."}
          </Alert>
        </Collapse>
      ) : null}
      {formState.fromHiredModal && !formState.isStudentHired ? (
        <Collapse in={open}>
          <Alert
            severity="error"
            action={
              <IconButton
                aria-label="close"
                color="inherit"
                size="small"
                onClick={() => {
                  setOpen(false);
                }}
              >
                <CloseIcon fontSize="inherit" />
              </IconButton>
            }
          >
            {formState.isHired
              ? "An error has occured while hiring student " +
                formState.hireStudent +
                " . Kindly, try again."
              : "An error has occured while dehiring student. " +
                formState.hireStudent +
                " Kindly, try again."}
          </Alert>
        </Collapse>
      ) : null}

      <Grid item xs={12} className={classes.formgrid}>
        <Typography variant="h5" gutterBottom color="textSecondary">
          {formState.eventTitle}
        </Typography>
      </Grid>
      <Grid item xs={12} className={classes.formgrid}>
        <Card>
          <CardContent className={classes.Cardtheming}>
            <Grid className={classes.filterOptions} container spacing={1}>
              <Grid item>
                <TextField
                  id="studentName"
                  label="Name"
                  margin="normal"
                  variant="outlined"
                  name={STUDENT_FILTER}
                  value={formState.filterDataParameters[STUDENT_FILTER] || ""}
                  placeholder="Name"
                  className={classes.autoCompleteField}
                  onChange={handleFilterChangeForStudentField}
                />
              </Grid>
              <Grid item className={classes.paddingDate}>
                <Autocomplete
                  id="streams-filter"
                  name={STREAM_FILTER}
                  options={streams}
                  className={classes.autoCompleteField}
                  getOptionLabel={option => option.name}
                  onChange={(event, value) =>
                    handleChangeAutoComplete(STREAM_FILTER, event, value)
                  }
                  value={
                    formState.isClearResetFilter
                      ? null
                      : streams[
                          streams.findIndex(function (item, i) {
                            return (
                              item.id ===
                              formState.filterDataParameters[STREAM_FILTER]
                            );
                          })
                        ] || null
                  }
                  renderInput={params => (
                    <TextField
                      {...params}
                      label="Stream"
                      placeholder="Stream"
                      className={classes.autoCompleteField}
                      variant="outlined"
                    />
                  )}
                />
              </Grid>
              <Grid item className={classes.paddingDate}>
                <Autocomplete
                  id="education-year-list"
                  options={genericConstants.EDUCATIONYEARLIST}
                  getOptionLabel={option => option.name}
                  renderInput={params => (
                    <TextField
                      {...params}
                      label="Education Year"
                      variant="outlined"
                      name="education-year"
                      placeholder="Education Year"
                      className={classes.autoCompleteField}
                    />
                  )}
                />
              </Grid>
              <Grid item>
                <TextField
                  id="mobileNumberFilter"
                  label="Mobile Number"
                  margin="normal"
                  variant="outlined"
                  name={MOBILE_NUMBER_FILTER}
                  value={
                    formState.filterDataParameters[MOBILE_NUMBER_FILTER] || ""
                  }
                  placeholder="Mobile Number"
                  className={classes.autoCompleteField}
                  onChange={handleFilterChangeForStudentField}
                />
              </Grid>

              <Grid item className={classes.filterButtonsMargin}>
                <YellowButton
                  id="submitFiter"
                  variant="contained"
                  color="primary"
                  disableElevation
                  onClick={event => {
                    event.persist();
                    searchFilter();
                  }}
                >
                  Search
                </YellowButton>
              </Grid>
              <Grid item className={classes.filterButtonsMargin}>
                <GrayButton
                  id="clearFilter"
                  variant="contained"
                  color="primary"
                  onClick={clearFilter}
                  disableElevation
                >
                  Reset
                </GrayButton>
              </Grid>
            </Grid>
          </CardContent>
        </Card>
        <Card className={classes.tabledata} variant="outlined">
          {formState.dataToShow ? (
            formState.dataToShow.length ? (
              <Table
                data={formState.dataToShow}
                column={column}
                selectableRows={false}
                defaultSortField="user.first_name"
                onSort={handleSort}
                sortServer={true}
                paginationDefaultPage={formState.page}
                paginationPerPage={formState.pageSize}
                defaultSortAsc={formState.sortAscending}
                progressPending={formState.isDataLoading}
                paginationTotalRows={formState.totalRows}
                paginationRowsPerPageOptions={[10, 20, 50]}
                onChangeRowsPerPage={handlePerRowsChange}
                onChangePage={handlePageChange}
                clearSelectedRows={formState.toggleCleared}
              />
            ) : (
              <Spinner />
            )
          ) : (
            <div className={classes.noDataMargin}>No data to show</div>
          )}
          <HireStudent
            id={formState.dataToHire}
            showModal={formState.showModalHire}
            isHired={formState.isHired}
            isUnHired={formState.isUnHired}
            //hiredSuccessfully={isStudentHiredCompleted}
            closeHireModal={handleCloseHireModal}
            modalClose={modalClose}
            studentName={formState.hireStudent}
          />
          <MarkAttaindance
            id={formState.dataToMarkAttaindance}
            showModal={formState.showModalAttaindance}
            isPresent={formState.isPresent}
            isAbsent={formState.isAbsent}
            closeAttaindanceModal={handleCloseAttaindanceModal}
            modalClose={modalClose}
            studentName={formState.markAttaindance}
          />
        </Card>
      </Grid>
    </Grid>
  );
}
Example #18
Source File: GameMetadata.js    From dipact with GNU General Public License v3.0 4 votes vote down vote up
render() {
		let cells = [];
		if (this.state.game.Properties.ChatLanguageISO639_1) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<span
						style={{
							marginRight: "8px",
							width: "24px",
							height: "24px",
						}}
					>
						<div
							style={{
								fontFamily: "cabin",
								height: "24px",
								width: "24px",
								display: "inline-flex",
								alignSelf: "flex-start",
								backgroundImage:
									'url(\'data:image/svg+xml;utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24" viewBox="0 0 24 24"><path fill="%23000000" d="M 20 2 H 4 c -1.1 0 -2 0.9 -2 2 v 18 l 4 -4 h 14 c 1.1 0 2 -0.9 2 -2 V 4 c 0 -1.1 -0.9 -2 -2 -2 Z"></path></svg>\')',
							}}
						>
							<div
								style={{
									fontSize: "12px",
									color: "#FFF",
									marginTop: "1px",
									textAlign: "center",
									width: "24px",
								}}
							>
								{this.state.game.Properties.ChatLanguageISO639_1} aaa
							</div>
						</div>
					</span>
					<Typography>
						Chat language:{" "}
						{
							helpers.iso639_1Codes.find((el) => {
								return (
									el.code === this.state.game.Properties.ChatLanguageISO639_1
								);
							}).name
						}
					</Typography>
				</div>
			);
		}
		if (this.state.game.Properties.Private) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<PrivateGameIcon style={{ marginRight: "8px" }} />
					<Typography>Private game</Typography>
				</div>
			);
		}
		if (this.props.game.Properties.GameMasterEnabled) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<GavelIcon style={{ marginRight: "8px" }} />
					<Typography>Managed by Game Master</Typography>
				</div>
			);
		}
		if (
			this.state.game.Properties.Private &&
			this.state.game.Properties.GameMasterEnabled &&
			this.state.game.Properties.RequireGameMasterInvitation
		) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<WhitelistIcon style={{ marginRight: "8px" }} />
					<Typography>Assigned players only (Whitelist)</Typography>
				</div>
			);
		}
		cells.push(
			<div
				style={{ width: "100%", display: "flex", alignItems: "center" }}
				key={cells.length}
			>
				<GameVariantIcon style={{ marginRight: "8px" }} />
				<Typography>
					Game variant: {this.state.game.Properties.Variant}
				</Typography>
			</div>
		);
		cells.push(
			<div
				style={{ width: "100%", display: "flex", alignItems: "center" }}
				key={cells.length}
			>
				<PhaseDeadlineIcon style={{ marginRight: "8px" }} />
				<Typography>
					Phase deadline{" "}
					{helpers.minutesToDuration(
						this.state.game.Properties.PhaseLengthMinutes
					)}
				</Typography>
			</div>
		);
		if (!this.state.game.Properties.SkipMuster) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<MusteringIcon style={{ marginRight: "8px" }} />
					<Typography>Get Ready Phase before start</Typography>
				</div>
			);
		}
		if (this.state.game.Properties.NonMovementPhaseLengthMinutes) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<PhaseDeadlineIcon style={{ marginRight: "8px" }} />
					<Typography>
						Non movement phase deadline{" "}
						{helpers.minutesToDuration(
							this.state.game.Properties.NonMovementPhaseLengthMinutes
						)}
					</Typography>
				</div>
			);
		}
		if (this.state.game.Properties.LastYear) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<EndsAfterThisYearIcon style={{ marginRight: "8px" }} />
					<Typography>
						Ends after year: {this.state.game.Properties.LastYear}
					</Typography>
				</div>
			);
		}
		cells.push(
			<div
				style={{ width: "100%", display: "flex", alignItems: "center" }}
				key={cells.length}
			>
				<Icon style={{ marginRight: "8px" }}>
					<SvgIcon>
						<g
							id="Artboard"
							stroke="none"
							strokeWidth="1"
							fill="none"
							fillRule="evenodd"
						>
							<g id="timelapse-24px">
								<polygon id="Path" points="0 0 24 0 24 24 0 24"></polygon>
								<path
									d="M12,6 C12.5719312,6 13.1251722,6.08002251 13.6491373,6.22948186 L12,12 Z M12,2 C6.48,2 2,6.48 2,12 C2,17.52 6.48,22 12,22 C17.52,22 22,17.52 22,12 C22,6.48 17.52,2 12,2 Z M12,20 C7.58,20 4,16.42 4,12 C4,7.58 7.58,4 12,4 C16.42,4 20,7.58 20,12 C20,16.42 16.42,20 12,20 Z"
									id="Shape"
									fill="#000000"
									fillRule="nonzero"
								></path>
							</g>
						</g>
					</SvgIcon>
				</Icon>
				<Typography>
					Created: {helpers.timeStrToDate(this.state.game.Properties.CreatedAt)}{" "}
				</Typography>
			</div>
		);
		if (this.state.game.Properties.Started) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<StartedAtIcon style={{ marginRight: "8px" }} />
					<Typography>
						Started:{" "}
						{helpers.timeStrToDate(this.state.game.Properties.StartedAt)}
					</Typography>
				</div>
			);
		}
		if (this.state.game.Properties.Finished) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<Icon style={{ marginRight: "8px" }}>
						<SvgIcon>
							<g
								id="Artboard"
								stroke="none"
								strokeWidth="1"
								fill="none"
								fillRule="evenodd"
							>
								<g id="timelapse-24px">
									<polygon id="Path" points="0 0 24 0 24 24 0 24"></polygon>
									<path
										d="M12,6 C15.3137085,6 18,8.6862915 18,12 C18,15.3137085 15.3137085,18 12,18 C8.6862915,18 6,15.3137085 6,12 C6,9.25822274 7.83903025,6.94597402 10.3508627,6.22948186 L12,12 Z M12,2 C6.48,2 2,6.48 2,12 C2,17.52 6.48,22 12,22 C17.52,22 22,17.52 22,12 C22,6.48 17.52,2 12,2 Z M12,20 C7.58,20 4,16.42 4,12 C4,7.58 7.58,4 12,4 C16.42,4 20,7.58 20,12 C20,16.42 16.42,20 12,20 Z"
										id="Shape"
										fill="#000000"
										fillRule="nonzero"
									></path>
								</g>
							</g>
						</SvgIcon>
					</Icon>
					<Typography>
						Finished:{" "}
						{helpers.timeStrToDate(this.state.game.Properties.FinishedAt)}{" "}
					</Typography>
				</div>
			);
		}
		cells.push(
			<div
				style={{ width: "100%", display: "flex", alignItems: "center" }}
				key={cells.length}
			>
				{this.state.game.Properties.NationAllocation === 1 ? (
					<NationAllocationIcon style={{ marginRight: "8px" }} />
				) : (
					<Icon style={{ marginRight: "8px" }}>
						<SvgIcon>
							<g
								id="Artboard"
								stroke="none"
								strokeWidth="1"
								fill="none"
								fillRule="evenodd"
							>
								<g id="playlist_add_check-24px-(1)">
									<rect
										id="Rectangle"
										x="0"
										y="0"
										width="24"
										height="24"
									></rect>
									<path
										d="M14,10 L2,10 L2,12 L14,12 L14,10 Z M14,6 L2,6 L2,8 L14,8 L14,6 Z M18.51,16.25 L21,18.75 L18.51,21.25 L18.51,19.5 L13,19.5 L13,18 L18.51,18 L18.51,16.25 Z M15.49,12 L15.49,13.75 L21,13.75 L21,15.25 L15.49,15.25 L15.49,17 L13,14.5 L15.49,12 Z M10,14 L10,16 L2,16 L2,14 L10,14 Z"
										id="Shape"
										fill="#000000"
										fillRule="nonzero"
									></path>
								</g>
								<g id="loop-24px">
									<polygon id="Path" points="13 12 26 12 26 25 13 25"></polygon>
									<g id="transfer_within_a_station-24px">
										<polygon id="Path" points="0 0 24 0 24 24 0 24"></polygon>
									</g>
								</g>
							</g>
						</SvgIcon>
					</Icon>
				)}

				<Typography>
					Nation selection:{" "}
					{this.state.game.Properties.NationAllocation === 1
						? "Preferences"
						: "Random"}{" "}
				</Typography>
			</div>
		);

		if (this.state.game.Properties.MinRating) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<RatingIcon style={{ marginRight: "8px" }} />
					<Typography>
						Minimum rating: {this.state.game.Properties.MinRating}{" "}
					</Typography>
				</div>
			);
		}
		if (this.state.game.Properties.MaxRating) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<RatingIcon style={{ marginRight: "8px" }} />
					<Typography>
						Maximum rating: {this.state.game.Properties.MaxRating}{" "}
					</Typography>
				</div>
			);
		}
		if (this.state.game.Properties.MinReliability) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<ReliabilityIcon style={{ marginRight: "8px" }} />
					<Typography>
						Minimum reliability: {this.state.game.Properties.MinReliability}{" "}
					</Typography>
				</div>
			);
		}
		if (this.state.game.Properties.MinQuickness) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<ReliabilityIcon style={{ marginRight: "8px" }} />
					<Typography>
						Minimum quickness: {this.state.game.Properties.MinQuickness}{" "}
					</Typography>
				</div>
			);
		}
		if (this.state.game.Properties.MaxHated) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<Icon style={{ marginRight: "8px" }}>
						<SvgIcon>
							<g
								id="Artboard"
								stroke="none"
								strokeWidth="1"
								fill="none"
								fillRule="evenodd"
							>
								<g
									id="emoticon-angry-outline"
									transform="translate(1.000000, 1.000000)"
									fill="#000000"
									fillRule="nonzero"
								>
									<path
										d="M1.05,0.08 L13.4993434,12.5296465 L13.509,12.519 L13.9296465,12.939697 L12.939697,13.9296465 L11.4291042,12.4206404 C10.184652,13.4375261 8.62132228,14 7,14 C5.14348457,14 3.36300718,13.2625021 2.05025253,11.9497475 C0.737497883,10.6369928 0,8.85651543 0,7 C0,5.31921341 0.592383418,3.77678538 1.57975754,2.57010863 L0.0703535444,1.06030304 L1.05,0.08 Z M2.5761358,3.566003 C1.83897141,4.51428911 1.4,5.70588092 1.4,7 C1.4,10.0927946 3.9072054,12.6 7,12.6 C8.29411908,12.6 9.48571089,12.1610286 10.433997,11.4238642 L9.305,10.295 L8.939,10.661 C8.624,10.15 7.875,9.8 7,9.8 C6.125,9.8 5.376,10.15 5.061,10.661 L4.067,9.667 C4.697,8.904 5.775,8.4 7,8.4 C7.14658996,8.4 7.29107491,8.40721717 7.43293907,8.42123168 L5.12607623,6.1169691 C4.95837689,6.23170489 4.75906667,6.3 4.55,6.3 C3.99,6.3 3.5,5.81 3.5,5.25 L3.5,4.49 L2.5761358,3.566003 Z M7,0 C8.85651543,0 10.6369928,0.737497883 11.9497475,2.05025253 C13.2625021,3.36300718 14,5.14348457 14,7 C14,8.14229525 13.7207968,9.25580388 13.2001824,10.2492879 L12.1507771,9.20127306 C12.4399256,8.52556954 12.6,7.78147846 12.6,7 C12.6,5.51478766 12.0100017,4.09040574 10.959798,3.04020203 C9.90959426,1.98999831 8.48521234,1.4 7,1.4 C6.21813639,1.4 5.47369701,1.56023219 4.79772792,1.84965051 L3.74828763,0.799495095 C4.71989309,0.288908589 5.82620744,0 7,0 Z M10.5,4.2 L10.5,5.25 C10.5,5.81 10.01,6.3 9.45,6.3 C8.89,6.3 8.4,5.81 8.4,5.25 L10.5,4.2 Z"
										id="Combined-Shape"
									></path>
								</g>
							</g>
						</SvgIcon>
					</Icon>
					<Typography>
						Maximum hated:
						{this.state.game.Properties.MaxHated}{" "}
					</Typography>
				</div>
			);
		}
		if (this.state.game.Properties.MaxHater) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<Icon style={{ marginRight: "8px" }}>
						<SvgIcon>
							<g
								id="Artboard"
								stroke="none"
								strokeWidth="1"
								fill="none"
								fillRule="evenodd"
							>
								<g
									id="emoticon-angry-outline"
									transform="translate(1.000000, 1.000000)"
									fill="#000000"
									fillRule="nonzero"
								>
									<path
										d="M1.05,0.08 L13.4993434,12.5296465 L13.509,12.519 L13.9296465,12.939697 L12.939697,13.9296465 L11.4291042,12.4206404 C10.184652,13.4375261 8.62132228,14 7,14 C5.14348457,14 3.36300718,13.2625021 2.05025253,11.9497475 C0.737497883,10.6369928 0,8.85651543 0,7 C0,5.31921341 0.592383418,3.77678538 1.57975754,2.57010863 L0.0703535444,1.06030304 L1.05,0.08 Z M2.5761358,3.566003 C1.83897141,4.51428911 1.4,5.70588092 1.4,7 C1.4,10.0927946 3.9072054,12.6 7,12.6 C8.29411908,12.6 9.48571089,12.1610286 10.433997,11.4238642 L9.305,10.295 L8.939,10.661 C8.624,10.15 7.875,9.8 7,9.8 C6.125,9.8 5.376,10.15 5.061,10.661 L4.067,9.667 C4.697,8.904 5.775,8.4 7,8.4 C7.14658996,8.4 7.29107491,8.40721717 7.43293907,8.42123168 L5.12607623,6.1169691 C4.95837689,6.23170489 4.75906667,6.3 4.55,6.3 C3.99,6.3 3.5,5.81 3.5,5.25 L3.5,4.49 L2.5761358,3.566003 Z M7,0 C8.85651543,0 10.6369928,0.737497883 11.9497475,2.05025253 C13.2625021,3.36300718 14,5.14348457 14,7 C14,8.14229525 13.7207968,9.25580388 13.2001824,10.2492879 L12.1507771,9.20127306 C12.4399256,8.52556954 12.6,7.78147846 12.6,7 C12.6,5.51478766 12.0100017,4.09040574 10.959798,3.04020203 C9.90959426,1.98999831 8.48521234,1.4 7,1.4 C6.21813639,1.4 5.47369701,1.56023219 4.79772792,1.84965051 L3.74828763,0.799495095 C4.71989309,0.288908589 5.82620744,0 7,0 Z M10.5,4.2 L10.5,5.25 C10.5,5.81 10.01,6.3 9.45,6.3 C8.89,6.3 8.4,5.81 8.4,5.25 L10.5,4.2 Z"
										id="Combined-Shape"
									></path>
								</g>
							</g>
						</SvgIcon>
					</Icon>
					<Typography>
						Maximum hater: {this.state.game.Properties.MaxHater}
					</Typography>
				</div>
			);
		}

		if (
			(this.state.game.Properties.Private &&
				this.state.game.Properties.Anonymous) ||
			(!this.state.game.Properties.Private &&
				this.state.game.Properties.DisableConferenceChat &&
				this.state.game.Properties.DisableGroupChat &&
				this.state.game.Properties.DisablePrivateChat)
		) {
			cells.push(
				<div
					style={{
						width: "100%",
						display: "flex",
						alignItems: "center",
					}}
					key={cells.length}
				>
					<span
						style={{
							marginRight: "8px",
							width: "24px",
							height: "24px",
						}}
					>
						<Icon style={{ marginRight: "8px" }}>
							<img
								alt="Anonymous"
								width="24"
								height="24"
								src={AnonymousSvgPath}
							/>
						</Icon>
					</span>
					<Typography>Anonymous</Typography>
				</div>
			);
		}
		if (
			this.state.game.Properties.DisableConferenceChat ||
			this.state.game.Properties.DisableGroupChat ||
			this.state.game.Properties.DisablePrivateChat
		) {
			if (
				this.state.game.Properties.DisableConferenceChat &&
				this.state.game.Properties.DisableGroupChat &&
				this.state.game.Properties.DisablePrivateChat
			) {
				// Add two columns because this is required for formatting nicely.
				cells.push(
					<div
						style={{
							width: "100%",
							display: "flex",
							alignItems: "center",
						}}
						key={cells.length}
					>
						<Icon style={{ marginRight: "8px" }}>
							<SvgIcon>
								<g
									id="Artboard"
									stroke="none"
									strokeWidth="1"
									fill="none"
									fillRule="evenodd"
								>
									<g id="message-24px">
										<polygon id="Path" points="0 0 24 0 24 24 0 24"></polygon>
										<path
											d="M2.4,2.614 L20.5847763,20.7989899 L20.598,20.784 L20.7989899,20.9842712 L19.3847763,22.3984848 L14.986,18 L6,18 L2,22 L2.008,5.022 L1,4.0137085 L2.4,2.614 Z M20,2 C21.05,2 21.9177686,2.82004132 21.9944872,3.85130541 L22,4 L22,16 C22,16.9134058 21.3794387,17.6889091 20.539101,17.925725 L16.614,14 L18,14 L18,12 L14.614,12 L13.614,11 L18,11 L18,9 L11.614,9 L10.614,8 L18,8 L18,6 L8.614,6 L4.614,2 L20,2 Z M8.987,12 L6,12 L6,14 L10.986,14 L8.987,12 Z M6,9.013 L6,11 L7.987,11 L6,9.013 Z"
											id="Combined-Shape"
											fill="#000000"
											fillRule="nonzero"
										></path>
									</g>
								</g>
							</SvgIcon>
						</Icon>
						<Typography>No chat (Gunboat)</Typography>
					</div>
				);
			} else {
				// Sort channel types by whether they're enabled or disabled.
				let allChannels = { false: [], true: [] };
				allChannels[this.state.game.Properties.DisableConferenceChat].push(
					"Conference"
				);
				allChannels[this.state.game.Properties.DisableGroupChat].push("Group");
				allChannels[this.state.game.Properties.DisablePrivateChat].push(
					"Individual"
				);
				cells.push(
					<div
						style={{
							width: "100%",
							display: "flex",
							alignItems: "center",
						}}
						key={cells.length}
					>
						<Icon style={{ marginRight: "8px" }}>
							<SvgIcon>
								<g
									id="Artboard"
									stroke="none"
									strokeWidth="1"
									fill="none"
									fillRule="evenodd"
								>
									<g id="message-24px">
										<polygon id="Path" points="0 0 24 0 24 24 0 24"></polygon>
										<path
											d="M2.4,2.614 L20.5847763,20.7989899 L20.598,20.784 L20.7989899,20.9842712 L19.3847763,22.3984848 L14.986,18 L6,18 L2,22 L2.008,5.022 L1,4.0137085 L2.4,2.614 Z M20,2 C21.05,2 21.9177686,2.82004132 21.9944872,3.85130541 L22,4 L22,16 C22,16.9134058 21.3794387,17.6889091 20.539101,17.925725 L16.614,14 L18,14 L18,12 L14.614,12 L13.614,11 L18,11 L18,9 L11.614,9 L10.614,8 L18,8 L18,6 L8.614,6 L4.614,2 L20,2 Z M8.987,12 L6,12 L6,14 L10.986,14 L8.987,12 Z M6,9.013 L6,11 L7.987,11 L6,9.013 Z"
											id="Combined-Shape"
											fill="#000000"
											fillRule="nonzero"
										></path>
									</g>
								</g>
							</SvgIcon>
						</Icon>
						<Typography> {allChannels[true].join(" & ")} chat off</Typography>
					</div>
				);
				cells.push(
					<div
						style={{
							width: "100%",
							display: "flex",
							alignItems: "center",
						}}
						key={cells.length}
					>
						<ChatIcon style={{ marginRight: "8px" }} />
						<Typography> {allChannels[false].join(" & ")} chat on </Typography>
					</div>
				);
			}
		}
		if (!this.props.noplayerlist) {
			let playerList = [];
			playerList.push(
				<Typography
					variant="subtitle2"
					style={{ color: "rgba(40, 26, 26, 0.7)", marginTop: "4px" }}
					key={playerList.length}
				>
					Players:
				</Typography>
			);

			(this.state.game.Properties.Members || []).forEach((member) => {
				if (member.Replaceable == false) {
					playerList.push(
						<div
							key={playerList.length}
							style={{
								display: "flex",
								alignItems: "center",
								marginBottom: "4px",
							}}
						>
							<UserAvatar user={member.User} />
							<Typography>
								{member.User.GivenName} {member.User.FamilyName}
							</Typography>
							{this.props.withKickButtons ? (
								this.state.game.Links.find((link) => {
									return link.Rel === "kick-" + member.User.Id;
								}) ? (
									//TODO: add confirmdialog.js before we just KICK someone (how)?
									<Button
										onClick={this.onKick(member.User.Id)}
										variant="contained"
										color="primary"
										style={{ margin: "0 0 0 auto" }}
									>
									Kick
									</Button>
								) : (
									""
								)
							) : (
								""
							)}
						</div>
					);
				} else {
					//we use createmessageicon below because it's "Add" aka a "+" icon
					//TODO: make this whole div start the Invite feature
					playerList.push(
						<div
							key={playerList.length}
							style={{
								display: "flex",
								alignItems: "center",
								marginBottom: "4px",
							}}
						>
							<UserAvatar
								user={member.User}
								style={{ border: "1px solid red" }}
							/>
							<Typography style={{ color: "red" }}>[Open position]</Typography>
							{/*

							<Button style={{ margin: "0 0 0 auto", borderColor: "red", color: "red"}} variant="outlined" >
								Invite
							</Button>*/}
						</div>
					);
				}
			});
			cells.push(
				<div
					style={{
						width: "100%",
						maxWidth: "460px",
					}}
					key={cells.length}
				>
					{playerList}
				</div>
			);
		}

		return cells;
	}
Example #19
Source File: RequestOTP.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
RequestOTP = props => {
  let history = useHistory();

  const [formState, setFormState] = useState({
    values: {},
    error: {},
    counter: 0,
    flag: 0
  });

  const [error, setError] = useState("");
  const { loaderStatus, setLoaderStatus } = useContext(LoaderContext);
  const [open, setOpen] = React.useState(true);
  const [ifFailure, setIfFailure] = React.useState(false);

  const [alert, setAlert] = useState({
    isOpen: false,
    message: "",
    severity: ""
  });

  const classes = useStyles();
  const { layout: Layout } = props;
  const validate = () => {
    setLoaderStatus(true);

    formState.error["contactNumber"] = validateInput(
      formState.values.contactNumber,
      form["contactNumber"]["validations"]
    );

    if (formState.flag === 1) {
      formState.error["otp"] = validateInput(
        formState.values.otp,
        form["otp"]["validations"]
      );
    }

    if (
      formState.error.contactNumber &&
      formState.error.contactNumber.length === 0
    ) {
      formState.error = Object.assign(
        {},
        _.omit(formState.error, ["contactNumber"])
      );
    }
    if (
      formState.flag === 1 &&
      formState.error.otp &&
      formState.error.otp.length === 0
    ) {
      formState.error = Object.assign({}, _.omit(formState.error, ["otp"]));
    }

    if (formState.flag === 0) {
    }
    if (formState.flag === 1) {
    }
    if (Object.keys(formState.error).length === 0 && formState.flag === 1) {
      updateCall();
    }
    if (formState.flag === 0 && Object.keys(formState.error).length === 0) {
      postCall();
    }
    setFormState(formState => ({
      ...formState,
      isValid: false
    }));
  };

  const handleChange = (name, event) => {
    event.persist();
    setFormState(formState => ({
      ...formState,

      values: {
        ...formState.values,
        [name]: event.target.value
      }
    }));
  };

  const hasError = field => (formState.error[field] ? true : false);
  if (
    props.location.state &&
    props.location.state.contactNumber &&
    formState.counter === 0
  ) {
    formState.values["contactNumber"] = props.location.state.contactNumber;
    formState.counter = 1;
    // setFormState(formState => ({
    //   ...formState,

    //   values: {
    //     ...formState.values,
    //     ["contactNumber"]: props.location.state.contactNumber,
    //     ["email"]: props.location.state.email
    //   }
    // }));
  }
  const updateCall = () => {
    const url =
      strapiApiConstants.STRAPI_DB_URL +
      strapiApiConstants.STRAPI_UPDATE_CONTACT;
    serviceProvider
      .serviceProviderForPostRequest(url, {
        old_contact_number: props.location.state.contactNumber,
        new_contact_number: formState.values.contactNumber,
        otp: formState.values.otp
      })
      .then(response => {
        history.push({ pathname: routeConstants.CHANGED_CONTACT_NUMBER });
        setLoaderStatus(false);
      })
      .catch(error => {
        setAlert(() => ({
          isOpen: true,
          message: error.response.data.message,
          severity: "error"
        }));
        setLoaderStatus(false);
      });
  };
  const postCall = () => {
    axios
      .post(
        strapiApiConstants.STRAPI_DB_URL +
          strapiApiConstants.STRAPI_REQUEST_OTP,
        { contact_number: formState.values.contactNumber }
      )
      .then(res => {
        setFormState(formState => ({
          ...formState,
          flag: 1
        }));
        setLoaderStatus(false);
      })
      .catch(err => {
        console.log(err);
        setLoaderStatus(false);
      });
  };

  const AlertAPIResponseMessage = () => {
    return (
      <Collapse in={alert.isOpen}>
        <Alert
          severity={alert.severity || "warning"}
          action={
            <IconButton
              aria-label="close"
              color="inherit"
              size="small"
              onClick={() => {
                setAlert(() => ({ isOpen: false }));
              }}
            >
              <CloseIcon fontSize="inherit" />
            </IconButton>
          }
        >
          {alert.message}
        </Alert>
      </Collapse>
    );
  };

  return (
    <div className={classes.masterlogin2}>
      <div className={classes.masterlogin1}>
        <div className={classes.masterlogin}>
          <Paper className={classes.rootDesktop}>
            <CardContent>
              <CssBaseline />
              <div className={classes.paper}>
                <div className={classes.signin_header}>
                  <div className={classes.loginlock}>
                    <CardIcon>
                      <Icon>lock</Icon>
                    </CardIcon>
                  </div>
                  <Typography
                    className={classes.signin}
                    component="h1"
                    variant="h5"
                    style={{ fontWeight: "700" }}
                  >
                    {"Change Contact Number "}
                  </Typography>
                </div>
                <AlertAPIResponseMessage />
                <React.Fragment>
                  <Typography
                    component="h5"
                    variant="subtitle2"
                    style={{ marginTop: ".9rem", marginBottom: ".9rem" }}
                  >
                    {
                      "Enter the new Contact Number to which the OTP will be sent. "
                    }{" "}
                  </Typography>
                  <TextField
                    label="Contact Number"
                    name="contactnumber"
                    value={formState.values.contactNumber}
                    variant="outlined"
                    fullWidth
                    disabled={formState.flag === 1 ? true : false}
                    style={{ marginTop: ".9rem", marginBottom: ".9rem" }}
                    error={hasError("contactNumber")}
                    helperText={
                      hasError("contactNumber")
                        ? formState.error["contactNumber"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    onChange={event => {
                      handleChange("contactNumber", event);
                    }}
                  />

                  {formState.flag == 0 ? null : (
                    <TextField
                      label="OTP"
                      name="OTP"
                      value={formState.values.OTP}
                      variant="outlined"
                      fullWidth
                      style={{ marginTop: ".9rem", marginBottom: ".9rem" }}
                      error={hasError("otp")}
                      helperText={
                        hasError("otp")
                          ? formState.error["otp"].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                      onChange={event => {
                        handleChange("otp", event);
                      }}
                    />
                  )}
                  {formState.flag == 0 ? (
                    <Button
                      color="primary"
                      type="submit"
                      fullWidth
                      variant="contained"
                      className={classes.submit}
                      onClick={() => {
                        validate();
                      }}
                    >
                      {authPageConstants.SEND_OTP_BUTTON}
                    </Button>
                  ) : (
                    <div style={{ textAlign: "center" }}>
                      <Button
                        color="primary"
                        type="submit"
                        fullWidth
                        variant="contained"
                        className={classes.submit}
                        onClick={() => {
                          validate();
                        }}
                      >
                        {"Update"}
                      </Button>
                      <Link
                        href="javascript:void(0);"
                        variant="body2"
                        className={classes.linkColor}
                        onClick={() => {
                          setFormState(formState => ({
                            ...formState,
                            flag: 0
                          }));
                        }}
                      >
                        {authPageConstants.CHANGE_CONTACT_NUMBER}
                      </Link>
                    </div>
                  )}
                  {/* <Backdrop
                        className={classes.backdrop}
                        open={openBackdrop}
                      >
                        <CircularProgress color="inherit" />
                      </Backdrop> */}
                </React.Fragment>
              </div>
            </CardContent>

            <CardMedia
              className={classes.cover}
              image={image}
              title="Live from space album cover"
            />
          </Paper>
        </div>
      </div>
    </div>
  );
}
Example #20
Source File: DailyCategory.jsx    From archeage-tools with The Unlicense 4 votes vote down vote up
render() {
    const { id, name, icon, quests, collapsed, hidden, isHidden, hideComplete, completedQuests, showHidden, instance, hiddenQuests, region, rewardTypes, questData, castles, residence, rewards } = this.props;
    const { setCollapseCategory, setHideCategory, setQuestStatus, setQuestHide, openDialog } = this.props;

    const questIds = (instance ? quests.map(q => q.id) : quests).filter(qid => {
      if (instance && !quests.find(q => q.id === qid).regions.includes(region)) {
        return false;
      }
      // filter rewards
      if (rewards.length > 0) {
        let { rewards: qRewards } = instance ? quests.find(q => q.id === qid) : (questData[qid] || { rewards: [] });
        qRewards = qRewards.filter(r => !r.region || r.region.includes(region));
        if (!qRewards.some(r => rewards.includes(r.typeId)) &&
          (!rewards.includes(REWARD_GILDA) || !qRewards.some(r => r.refId === ITEM.GILDA_STAR)) &&
          (!rewards.includes(REWARD_BSB) || !qRewards.some(r => r.refId === ITEM.BLUE_SALT_BOND))) {
          return false;
        }
      }
      if (showHidden) {
        return true;
      }
      if (id === QUEST_CATEGORY.AURORIA_TERRITORIES) {
        return questZoneCheck(qid, CASTLE_QUESTS, castles) && !hiddenQuests[qid];
      }
      if (id === QUEST_CATEGORY.ALL_IN_THE_FAMILY) {
        return questZoneCheck(qid, RESIDENCE_QUESTS, residence) && !hiddenQuests[qid];
      }
      return !hiddenQuests[qid];
    });

    const completedCount = questIds.reduce((a, b) => a + (completedQuests[b] ? 1 : 0), 0);
    const dailyQuestIds = questIds.filter(qid => showHidden || !(hideComplete && completedQuests[qid]));

    const display = (((dailyQuestIds.length > 0 || !hideComplete) && !hidden) || showHidden) && questIds.length > 0;

    return (
      <div className="daily-category" style={{ display: display ? 'block' : 'none' }}>
        <Paper className="content">
          <AppBar position="static">
            <Toolbar variant="dense">
              <IconButton onClick={() => setCollapseCategory(id, !collapsed)} size="small" color="inherit">
                {collapsed
                  ? <KeyboardArrowRightIcon />
                  : <KeyboardArrowDownIcon />}
              </IconButton>
              {icon && <Icon><img src={icon} alt={name} className="category-icon" /></Icon>}
              <Typography className="title-text">{name}</Typography>
              <Typography variant="body2">
                {completedCount}/{questIds.length}
              </Typography>
              <Tooltip title={isHidden ? 'Show Category' : 'Hide Category'}>
                <IconButton onClick={() => setHideCategory(id, !isHidden)} size="small" color="inherit">
                  {isHidden
                    ? <VisibilityIcon />
                    : <VisibilityOffIcon />}
                </IconButton>
              </Tooltip>
              {Object.values(QUEST_CATEGORY).includes(id) &&
              <Tooltip title="Modify Residence/Castle claims">
                <IconButton onClick={() => openDialog(DIALOG_MY_GAME, RESIDENCE)} size="small" color="inherit">
                  <HomeIcon />
                </IconButton>
              </Tooltip>}
            </Toolbar>
          </AppBar>
          {!collapsed &&
          <div>
            {dailyQuestIds
            .sort((aid, bid) => {
              const a = instance ? quests.find(q => q.id === aid) : questData[aid];
              const b = instance ? quests.find(q => q.id === bid) : questData[bid];
              return sortBy('name')(a, b);
            })
            .map(qid => {
              const otherProps = {
                completed: pathOr(false, [qid])(completedQuests),
                hidden: pathOr(false, [qid])(hiddenQuests),
                region,
                rewardTypes,
                setQuestStatus,
                setQuestHide,
              };
              if (instance) {
                return (
                  <DailyQuest
                    key={`instance-${qid}`}
                    {...quests.find(q => q.id === qid)}
                    {...otherProps}
                    instance
                  />
                );
              } else {
                return (
                  <DailyQuest
                    key={`quest-${qid}`}
                    {...otherProps}
                    {...pathOr({}, [qid])(questData)}
                    id={qid}
                  />
                );
              }
            })}
          </div>}
        </Paper>
      </div>
    );
  }
Example #21
Source File: Login.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
LogIn = props => {
  const [openSpinner, setOpenSpinner] = React.useState(false);
  const [open, setOpen] = React.useState(true);
  const classes = useStyles();
  const theme = useTheme();
  const history = useHistory();
  const [ifSuccess, setIfSuccess] = React.useState(false);
  const [ifFailure, setIfFailure] = React.useState(false);
  const { index, setIndex } = useContext(SetIndexContext);

  const [formState, setFormState] = useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    isSuccess: false,
    showPassword: false,
    fromPasswordChangedPage: props.from
      ? props.from.fromPasswordChangedPage
        ? true
        : false
      : false,
    dataToShow: props.from
      ? props.from.fromPasswordChangedPage
        ? props.from.dataToShow
        : ""
      : ""
  });

  function checkAllKeysPresent(obj) {
    let areFieldsValid = false;
    Object.keys(form).map(field => {
      if (form[field]["required"] === true && obj.hasOwnProperty(field)) {
        areFieldsValid = true;
      } else {
        areFieldsValid = false;
      }
    });
    return areFieldsValid;
  }

  function count(obj) {
    return !Object.keys(obj).length ? true : false;
  }

  const isDesktop = useMediaQuery(theme.breakpoints.up("lg"), {
    defaultMatches: true
  });

  useEffect(() => {
    if (formUtilities.checkAllKeysPresent(formState.values, form)) {
      Object.keys(formState.values).map(field => {
        const errors = validateInput(
          formState.values[field],
          form[field]["validations"]
        );
        setFormState(formState => ({
          ...formState,
          isValid:
            !errors.length &&
            count(formState.errors) &&
            checkAllKeysPresent(formState.values)
              ? true
              : false,
          errors: errors.length
            ? {
                ...formState.errors,
                [field]: errors
              }
            : formState.errors
        }));
        if (!errors.length && formState.errors.hasOwnProperty(field)) {
          delete formState.errors[field];
        }
      });
    } else {
      formState.values = formUtilities.getListOfKeysNotPresent(
        formState.values,
        form
      );
      Object.keys(formState.values).map(field => {
        const errors = validateInput(
          formState.values[field],
          form[field]["validations"]
        );
        setFormState(formState => ({
          ...formState,
          isValid:
            !errors.length &&
            count(formState.errors) &&
            checkAllKeysPresent(formState.values)
              ? true
              : false,
          errors: errors.length
            ? {
                ...formState.errors,
                [field]: errors
              }
            : formState.errors
        }));
        if (!errors.length && formState.errors.hasOwnProperty(field)) {
          delete formState.errors[field];
        }
      });
    }

    Object.keys(formState.values).map(field => {
      const errors = validateInput(
        formState.values[field],
        form[field]["validations"]
      );
      setFormState(formState => ({
        ...formState,
        isValid:
          !errors.length &&
          count(formState.errors) &&
          checkAllKeysPresent(formState.values)
            ? true
            : false,
        errors: errors.length
          ? {
              ...formState.errors,
              [field]: errors
            }
          : formState.errors
      }));
      if (!errors.length && formState.errors.hasOwnProperty(field)) {
        delete formState.errors[field];
      }
    });
  }, [formState.values]);

  const handleChange = e => {
    e.persist();
    setIfFailure(false);

    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [e.target.name]: e.target.value
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      }
    }));
  };

  if (ifSuccess && auth.getToken()) {
    return auth.getUserInfo().role.name === roleConstants.STUDENT ? (
      <Redirect
        to={{
          pathname: routeConstants.VIEW_PROFILE,
          state: { from: props.location }
        }}
      />
    ) : (
      <Redirect
        to={{
          pathname: routeConstants.DASHBOARD_URL,
          state: { from: props.location }
        }}
      />
    );
  }

  const handleSignIn = event => {
    event.preventDefault();
    processLogin();
  };

  const hasError = field =>
    formState.touched[field] && formState.errors[field] ? true : false;

  const setUserData = (jwt, user) => {
    auth.setToken(jwt, true);
    auth.setUserInfo(user, true);
    setIfSuccess(true);
  };

  const moveToErrorPageForBlocked = () => {
    history.push({
      pathname: routeConstants.REQUIRED_ERROR_PAGE,
      from: "login"
    });
  };

  const processLogin = async () => {
    setOpenSpinner(true);
    await axios
      .post(
        strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_LOGIN_PATH,
        {
          identifier: formState.values.identifier,
          password: formState.values.password
        }
      )
      .then(response => {
        setIndex(0);
        if (response.data.user.role.name === roleConstants.STUDENT) {
          /** This check whether the college is blocked or not then it checks whether the user is blocked or not */
          if (response.data.user.studentInfo.organization.is_blocked) {
            moveToErrorPageForBlocked();
          } else {
            if (response.data.user.blocked) {
              moveToErrorPageForBlocked();
            } else if (!response.data.user.studentInfo.is_verified) {
              history.push(routeConstants.REQUIRED_CONFORMATION);
            } else {
              setUserData(response.data.jwt, response.data.user);
            }
          }
          setOpenSpinner(false);
        } else if (
          response.data.user.role.name === roleConstants.COLLEGEADMIN
        ) {
          if (response.data.user.studentInfo.organization.is_blocked) {
            moveToErrorPageForBlocked();
          } else {
            if (response.data.user.blocked) {
              moveToErrorPageForBlocked();
            } else {
              setUserData(response.data.jwt, response.data.user);
            }
          }
          setOpenSpinner(false);
        } else if (response.data.user.role.name === roleConstants.MEDHAADMIN) {
          if (response.data.user.blocked) {
            moveToErrorPageForBlocked();
          } else {
            setUserData(response.data.jwt, response.data.user);
          }
          setOpenSpinner(false);
        } else if (
          response.data.user.role.name === roleConstants.DEPARTMENTADMIN
        ) {
          if (response.data.user.blocked) {
            moveToErrorPageForBlocked();
          } else {
            setUserData(response.data.jwt, response.data.user);
          }
          setOpenSpinner(false);
        } else if (response.data.user.role.name === roleConstants.ZONALADMIN) {
          if (response.data.user.blocked) {
            moveToErrorPageForBlocked();
          } else {
            setUserData(response.data.jwt, response.data.user);
          }
          setOpenSpinner(false);
        } else if (response.data.user.role.name === roleConstants.RPCADMIN) {
          if (response.data.user.blocked) {
            moveToErrorPageForBlocked();
          } else {
            setUserData(response.data.jwt, response.data.user);
          }
          setOpenSpinner(false);
        } else {
          moveToErrorPageForBlocked();
        }
      })
      .catch(error => {
        if (error.response) {
          if (error.response.status === 400) {
            if (error.response.data["message"]) {
              if (
                error.response.data["message"][0]["messages"][0]["id"] ===
                "Auth.form.error.blocked"
              ) {
                moveToErrorPageForBlocked();
              } else if (
                error.response.data["message"][0]["messages"][0]["id"] ===
                "Auth.form.error.invalid"
              ) {
                setOpen(true);
                setIfFailure(true);
              }
            }
          } else {
            setOpen(true);
            setIfFailure(true);
            console.log("An error occurred:", JSON.stringify(error));
          }
        }
      });
    setOpenSpinner(false);
  };

  const handleClickShowPassword = () => {
    setFormState({
      ...formState,
      showPassword: !formState.showPassword
    });
  };

  const handleMouseDownPassword = event => {
    event.preventDefault();
  };

  return (
    <div className={classes.masterlogin2}>
      <div className={classes.masterlogin1}>
        <div className={classes.masterlogin}>
          <Paper className={isDesktop ? classes.rootDesktop : classes.root}>
            <CardContent>
              <CssBaseline />
              <div className={classes.paper}>
                <div className={classes.signin_header}>
                  <div className={classes.loginlock}>
                    <CardIcon>
                      <Icon>lock</Icon>
                    </CardIcon>
                  </div>
                  <Typography
                    className={classes.signin}
                    component="h1"
                    variant="h5"
                    style={{ fontWeight: "700" }}
                  >
                    {authPageConstants.SIGN_IN_HEADER}
                  </Typography>
                </div>
                {ifFailure ? (
                  <Collapse in={open}>
                    <Alert
                      severity="error"
                      action={
                        <IconButton
                          aria-label="close"
                          color="inherit"
                          size="small"
                          onClick={() => {
                            setOpen(false);
                          }}
                        >
                          <CloseIcon fontSize="inherit" />
                        </IconButton>
                      }
                    >
                      {authPageConstants.INVALID_USER}
                    </Alert>
                  </Collapse>
                ) : formState.fromPasswordChangedPage ? (
                  <Collapse in={open}>
                    <Alert
                      severity="success"
                      action={
                        <IconButton
                          aria-label="close"
                          color="inherit"
                          size="small"
                          onClick={() => {
                            setOpen(false);
                          }}
                        >
                          <CloseIcon fontSize="inherit" />
                        </IconButton>
                      }
                    >
                      {formState.dataToShow}
                    </Alert>
                  </Collapse>
                ) : null}
                <form
                  className={classes.form}
                  noValidate
                  onSubmit={handleSignIn}
                  id="form"
                >
                  <TextField
                    id={get(form[identifier], "id")}
                    variant="outlined"
                    margin="normal"
                    error={hasError("identifier")}
                    fullWidth
                    autoFocus={get(form[identifier], "autoFocus")}
                    helperText={
                      hasError(identifier)
                        ? formState.errors[identifier].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    label={get(form[identifier], "label")}
                    name={identifier}
                    onChange={handleChange}
                    type={get(form[identifier], "type")}
                    value={formState.values[identifier] || ""}
                  />

                  <FormControl
                    fullWidth
                    className={clsx(classes.margin, classes.textField)}
                    variant="outlined"
                  >
                    <InputLabel
                      htmlFor="outlined-adornment-password"
                      fullWidth
                      error={hasError(password)}
                    >
                      Password
                    </InputLabel>
                    <OutlinedInput
                      id={get(form[password], "id")}
                      name={password}
                      type={formState.showPassword ? "text" : "password"}
                      value={formState.values[password] || ""}
                      onChange={handleChange}
                      fullWidth
                      error={hasError(password)}
                      endAdornment={
                        <InputAdornment
                          position="end"
                          error={hasError(password)}
                        >
                          <IconButton
                            aria-label="toggle password visibility"
                            onClick={handleClickShowPassword}
                            onMouseDown={handleMouseDownPassword}
                            edge="end"
                          >
                            {formState.showPassword ? (
                              <Visibility />
                            ) : (
                              <VisibilityOff />
                            )}
                          </IconButton>
                        </InputAdornment>
                      }
                      labelWidth={70}
                      InputLabelProps={{
                        classes: {
                          root: classes.cssLabel,
                          focused: classes.cssFocused
                        }
                      }}
                      InputProps={{
                        classes: {
                          root: classes.cssOutlinedInput,
                          focused: classes.cssFocused,
                          notchedOutline: classes.notchedOutline
                        }
                      }}
                    ></OutlinedInput>
                    <FormHelperText error={hasError(password)}>
                      {hasError(password)
                        ? formState.errors[password].map(error => {
                            return error + " ";
                          })
                        : null}
                    </FormHelperText>
                    <Link
                      className={classes.forgotpass}
                      href={routeConstants.FORGOT_PASSWORD_URL}
                      variant="body2"
                      className={classes.linkColor}
                    >
                      {authPageConstants.FORGOT_PASSWORD_ROUTE_TEXT}
                    </Link>
                  </FormControl>
                  <Button
                    color="primary"
                    disabled={!formState.isValid}
                    type="submit"
                    fullWidth
                    variant="contained"
                    className={classes.submit}
                  >
                    {authPageConstants.SIGN_IN_BUTTON}
                  </Button>
                  <Grid container>
                    <Grid item xs={12} style={{ textAlign: "center" }}>
                      Don't have an account? |{" "}
                      <Link
                        href={routeConstants.REQUEST_OTP}
                        variant="body2"
                        className={classes.linkColor}
                      >
                        {authPageConstants.NEW_REG_ROUTE_TEXT}
                      </Link>
                    </Grid>
                  </Grid>
                </form>
              </div>
            </CardContent>
            <Hidden mdDown>
              <CardMedia
                className={classes.cover}
                image={image}
                title="Live from space album cover"
              />
            </Hidden>
            <Backdrop className={classes.backdrop} open={openSpinner}>
              <CircularProgress color="inherit" />
            </Backdrop>
          </Paper>
        </div>
      </div>
    </div>
  );
}
Example #22
Source File: ForgotPassword.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
ForgotPassword = props => {
  const [openBackdrop, setOpenBackdrop] = React.useState(false);
  const [open, setOpen] = React.useState(true);
  const theme = useTheme();
  const history = useHistory();
  const classes = useStyles();
  const [isOtpVerificationFailed, setIsOtpVerificationFailed] = React.useState(
    false
  );

  const [formState, setFormState] = useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    otpResent: false,
    otpSent: false,
    otpVerify: false,
    passChangeSuccess: false,
    passChangeFailure: false,
    resetPasswordToken: "",
    errorsToShow: "",
    isChangePassFailed: false,
    showPassword: false,
    otpSendingFailed: false,
    formType: authPageConstants.FORM_TYPE_ENTER_MOBILE
  });

  const handleClickShowPassword = () => {
    setFormState({
      ...formState,
      showPassword: !formState.showPassword
    });
  };

  const handleMouseDownPassword = event => {
    event.preventDefault();
  };

  const handleSubmit = async evt => {
    evt.preventDefault();
    evt.persist();
    if (formState.otpSent === false) {
      sendOtp();
    } else if (
      (formState.otpSent === true || formState.otpResent === true) &&
      formState.otpVerify === false
    ) {
      await verifyOtp();
    } else if (formState.otpVerify === true) {
      await changePassword();
    }
  };

  const changePassword = async () => {
    setOpenBackdrop(true);
    setFormState(formState => ({
      ...formState,
      isChangePassFailed: false
    }));
    let postData = {
      code: formState.resetPasswordToken,
      password: formState.values[newPassword],
      passwordConfirmation: formState.values[newPassword]
    };
    let headers = {
      "Content-Type": "application/json"
    };
    await serviceProvider
      .serviceProviderForPostRequest(CHANGE_PASSWORD_URL, postData, headers)
      .then(res => {
        setOpenBackdrop(false);
        history.push({
          pathname: routeConstants.SIGN_IN_URL,
          fromPasswordChangedPage: true,
          dataToShow: "Password Changed Successfully"
        });
      })
      .catch(error => {
        setOpen(true);
        setFormState(formState => ({
          ...formState,
          isChangePassFailed: true,
          errorsToShow: "Error Changing Password"
        }));
        setOpenBackdrop(false);
      });
  };

  function checkAllKeysPresent(obj) {
    let areFieldsValid = false;

    Object.keys(form).map(field => {
      if (field === newPassword) {
        if (form[field]["required"] === true && obj.hasOwnProperty(field)) {
          areFieldsValid = true;
        } else {
          areFieldsValid = false;
        }
      }
    });
    return areFieldsValid;
  }

  function count(obj) {
    return !Object.keys(obj).length ? true : false;
  }

  useEffect(() => {
    Object.keys(formState.values).map(field => {
      const errors = validateInput(
        formState.values[field],
        form[field]["validations"]
      );
      formState.formType === authPageConstants.FORM_TYPE_CHANGE_PASS
        ? setFormState(formState => ({
            ...formState,
            isValid:
              !errors.length &&
              count(formState.errors) &&
              checkAllKeysPresent(formState.values)
                ? true
                : false,
            errors:
              errors.length && form
                ? {
                    ...formState.errors,
                    [field]: errors
                  }
                : formState.errors
          }))
        : setFormState(formState => ({
            ...formState,
            isValid: errors.length ? false : true,
            errors:
              errors.length && form
                ? {
                    ...formState.errors,
                    [field]: errors
                  }
                : formState.errors
          }));
      if (!errors.length && formState.errors.hasOwnProperty(field)) {
        delete formState.errors[field];
      }
    });
  }, [formState.values]);

  const handleChange = e => {
    e.persist();
    setIsOtpVerificationFailed(false);
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [e.target.name]: e.target.value
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      },
      isChangePassFailed: false
    }));
  };

  const sendOtp = async () => {
    await generateOtp(true, false);
  };

  const resendOtp = async () => {
    await generateOtp(false, true);
    return false;
  };

  /** Function used to generate otp */
  const generateOtp = async (sendOtp, resendOtp) => {
    /** Reset error message */
    setOpenBackdrop(true);
    setIsOtpVerificationFailed(false);
    setFormState(formState => ({
      ...formState,
      otpSendingFailed: false
    }));
    let postData = { contact_number: formState.values[mobileNumber] };
    let headers = {
      "Content-Type": "application/json"
    };
    await serviceProvider
      .serviceProviderForPostRequest(REQUEST_OTP_URL, postData, headers)
      .then(res => {
        if (res.data.result.status === "Ok") {
          if (sendOtp) {
            setFormState(formState => ({
              ...formState,
              otpSent: true,
              isValid: false,
              otpSendingFailed: false,
              errorsToShow: "",
              formType: authPageConstants.FORM_TYPE_VERIFY_OTP
            }));
          } else if (resendOtp) {
            setOpen(true);
            setFormState(formState => ({
              ...formState,
              otpSendingFailed: false,
              otpResent: true,
              isValid: false,
              errorsToShow: "OTP sent successfully"
            }));
          }
        }
        setOpenBackdrop(false);
      })
      .catch(error => {
        setOpen(true);
        setFormState(formState => ({
          ...formState,
          otpSendingFailed: true,
          errorsToShow: "Error Generating OTP"
        }));
        setOpenBackdrop(false);
      });
  };

  const verifyOtp = async () => {
    setOpenBackdrop(true);
    setIsOtpVerificationFailed(false);
    let postData = {
      contact_number: formState.values[mobileNumber],
      otp: formState.values[otp]
    };
    let headers = {
      "Content-Type": "application/json"
    };
    await serviceProvider
      .serviceProviderForPostRequest(CHECK_USER, postData, headers)
      .then(res => {
        setIsOtpVerificationFailed(true);
        setOpen(true);
        setFormState(formState => ({
          ...formState,
          errorsToShow: "User not registered"
        }));
        setOpenBackdrop(false);
      })
      .catch(async function (error) {
        let verificationError = false;
        let invalidOtp = false;
        if (error.response) {
          if (error.response.data.message === "User already registered") {
            await serviceProvider
              .serviceProviderForPostRequest(
                VALIDATE_OTP_URL,
                postData,
                headers
              )
              .then(res => {
                if (
                  res.data.statusCode === 400 &&
                  res.data.message === "OTP has expired"
                ) {
                  setOpen(true);
                  setIsOtpVerificationFailed(true);
                  setFormState(formState => ({
                    ...formState,
                    errorsToShow: "OTP has expired"
                  }));
                } else if (res.data.message === "EmptyResponse") {
                  invalidOtp = true;
                } else if (formUtilities.checkEmpty(res.data)) {
                  invalidOtp = true;
                } else if (res.data.result) {
                  /** Otp verified and reset password token genarated */
                  formState.resetPasswordToken = res.data.result;
                  setFormState(formState => ({
                    ...formState,
                    otpVerify: true,
                    isValid: false,
                    resetPasswordToken: res.data.result,
                    errorsToShow: "",
                    formType: authPageConstants.FORM_TYPE_CHANGE_PASS
                  }));
                }
                setOpenBackdrop(false);
              })
              .catch(error => {
                verificationError = true;
              });
          } else if (error.response.data.message === "Invalid OTP") {
            invalidOtp = true;
          } else {
            verificationError = true;
          }
        } else {
          verificationError = true;
        }

        if (verificationError) {
          /** Error verifying otp */
          setOpen(true);
          setIsOtpVerificationFailed(true);
          setFormState(formState => ({
            ...formState,
            errorsToShow: "Error verifying OTP"
          }));
          setOpenBackdrop(false);
        } else if (invalidOtp) {
          /** Invalid Otp message */
          setOpen(true);
          setIsOtpVerificationFailed(true);
          setFormState(formState => ({
            ...formState,
            errorsToShow: "Invalid OTP"
          }));
          setOpenBackdrop(false);
        }
        setOpenBackdrop(false);
      });
  };

  const hasError = field =>
    formState.touched[field] && formState.errors[field] ? true : false;

  const isDesktop = useMediaQuery(theme.breakpoints.up("lg"), {
    defaultMatches: true
  });

  return (
    <div className={classes.masterlogin2}>
      <div className={classes.masterlogin1}>
        <div className={classes.masterlogin}>
          <Paper className={isDesktop ? classes.rootDesktop : classes.root}>
            <CardContent>
              <CssBaseline />
              <div className={classes.paper}>
                <div className={classes.signin_header}>
                  <div className={classes.loginlock}>
                    <CardIcon>
                      <Icon>lock</Icon>
                    </CardIcon>
                  </div>
                  <Typography
                    className={classes.signin}
                    component="h1"
                    variant="h5"
                    style={{ fontWeight: "700" }}
                  >
                    {authPageConstants.FORGOT_PASSWORD_HEADER}
                  </Typography>
                </div>
                {isOtpVerificationFailed ||
                formState.isChangePassFailed ||
                formState.otpSendingFailed ? (
                  <Collapse in={open}>
                    <Alert
                      severity="error"
                      action={
                        <IconButton
                          aria-label="close"
                          color="inherit"
                          size="small"
                          onClick={() => {
                            setOpen(false);
                          }}
                        >
                          <CloseIcon fontSize="inherit" />
                        </IconButton>
                      }
                    >
                      {formState.errorsToShow}
                    </Alert>
                  </Collapse>
                ) : formState.otpResent &&
                  formState.errorsToShow === "OTP sent successfully" ? (
                  <Collapse in={open}>
                    <Alert
                      severity="success"
                      action={
                        <IconButton
                          aria-label="close"
                          color="inherit"
                          size="small"
                          onClick={() => {
                            setOpen(false);
                          }}
                        >
                          <CloseIcon fontSize="inherit" />
                        </IconButton>
                      }
                    >
                      {formState.errorsToShow}
                    </Alert>
                  </Collapse>
                ) : null}
                <form
                  className={classes.form}
                  noValidate
                  onSubmit={handleSubmit}
                >
                  {formState.otpVerify === true ? (
                    <React.Fragment>
                      <Typography
                        component="h5"
                        variant="subtitle2"
                        style={{ marginTop: ".9rem", marginBottom: ".9rem" }}
                      >
                        {authPageConstants.CONFIRM_NEW_PASS_ALERT}
                      </Typography>
                      <FormControl
                        fullWidth
                        className={clsx(classes.margin, classes.textField)}
                        variant="outlined"
                      >
                        <InputLabel
                          htmlFor="outlined-adornment-password"
                          fullWidth
                          error={hasError(newPassword)}
                        >
                          New Password
                        </InputLabel>
                        <OutlinedInput
                          id={get(form[newPassword], "id")}
                          name={newPassword}
                          type={formState.showPassword ? "text" : "password"}
                          value={formState.values[newPassword] || ""}
                          onChange={handleChange}
                          fullWidth
                          error={hasError(newPassword)}
                          endAdornment={
                            <InputAdornment
                              position="end"
                              error={hasError(newPassword)}
                            >
                              <IconButton
                                aria-label="toggle password visibility"
                                onClick={handleClickShowPassword}
                                onMouseDown={handleMouseDownPassword}
                                edge="end"
                              >
                                {formState.showPassword ? (
                                  <Visibility />
                                ) : (
                                  <VisibilityOff />
                                )}
                              </IconButton>
                            </InputAdornment>
                          }
                          labelWidth={70}
                          InputLabelProps={{
                            classes: {
                              root: classes.cssLabel,
                              focused: classes.cssFocused
                            }
                          }}
                          InputProps={{
                            classes: {
                              root: classes.cssOutlinedInput,
                              focused: classes.cssFocused,
                              notchedOutline: classes.notchedOutline
                            }
                          }}
                        ></OutlinedInput>
                        <FormHelperText error={hasError(newPassword)}>
                          {hasError(newPassword)
                            ? formState.errors[newPassword].map(error => {
                                return "\n" + error;
                              })
                            : null}
                        </FormHelperText>
                      </FormControl>
                      <Button
                        color="primary"
                        disabled={!formState.isValid}
                        type="submit"
                        fullWidth
                        variant="contained"
                        className={classes.submit}
                      >
                        {authPageConstants.RESET_PASS_BUTTON}
                      </Button>
                      <Backdrop
                        className={classes.backdrop}
                        open={openBackdrop}
                      >
                        <CircularProgress color="inherit" />
                      </Backdrop>
                    </React.Fragment>
                  ) : formState.otpSent === true ? (
                    <React.Fragment>
                      <Typography
                        component="h5"
                        variant="subtitle2"
                        style={{ marginTop: ".9rem", marginBottom: ".9rem" }}
                      >
                        {authPageConstants.OTP_ALERT}{" "}
                        {formState.values.mobileNumber}
                      </Typography>
                      <FormControl
                        fullWidth
                        className={clsx(classes.margin, classes.textField)}
                        variant="outlined"
                      >
                        <InputLabel
                          htmlFor="outlined-adornment-password"
                          fullWidth
                          error={hasError(otp)}
                        >
                          OTP
                        </InputLabel>
                        <OutlinedInput
                          id={get(form[otp], "id")}
                          name={otp}
                          type={formState.showPassword ? "text" : "password"}
                          value={formState.values[otp] || ""}
                          onChange={handleChange}
                          fullWidth
                          error={hasError(otp)}
                          endAdornment={
                            <InputAdornment
                              position="end"
                              error={hasError(otp)}
                            >
                              <IconButton
                                aria-label="toggle password visibility"
                                onClick={handleClickShowPassword}
                                onMouseDown={handleMouseDownPassword}
                                edge="end"
                              >
                                {formState.showPassword ? (
                                  <Visibility />
                                ) : (
                                  <VisibilityOff />
                                )}
                              </IconButton>
                            </InputAdornment>
                          }
                          labelWidth={70}
                          InputLabelProps={{
                            classes: {
                              root: classes.cssLabel,
                              focused: classes.cssFocused
                            }
                          }}
                          InputProps={{
                            classes: {
                              root: classes.cssOutlinedInput,
                              focused: classes.cssFocused,
                              notchedOutline: classes.notchedOutline
                            }
                          }}
                        ></OutlinedInput>
                        <FormHelperText error={hasError(otp)}>
                          {hasError(otp)
                            ? formState.errors[otp].map(error => {
                                return "\n" + error;
                              })
                            : null}
                        </FormHelperText>
                        <Link
                          href="javascript:void(0);"
                          variant="body2"
                          className={classes.linkColor}
                          onClick={resendOtp}
                        >
                          {authPageConstants.RESEND_OTP_BUTTON}
                        </Link>
                      </FormControl>
                      <Button
                        color="primary"
                        disabled={!formState.isValid}
                        type="submit"
                        fullWidth
                        variant="contained"
                        className={classes.submit}
                      >
                        {authPageConstants.VERIFY_OTP_BUTTON}
                      </Button>
                      <Backdrop
                        className={classes.backdrop}
                        open={openBackdrop}
                      >
                        <CircularProgress color="inherit" />
                      </Backdrop>
                    </React.Fragment>
                  ) : (
                    <React.Fragment>
                      <Typography
                        component="h5"
                        variant="subtitle2"
                        style={{ marginTop: ".9rem", marginBottom: ".9rem" }}
                      >
                        {authPageConstants.MOBILE_NUMBER_ALERT}
                      </Typography>
                      <TextField
                        variant="outlined"
                        margin="normal"
                        required
                        fullWidth
                        type={get(form[mobileNumber], "type")}
                        id={get(form[mobileNumber], "id")}
                        label={get(form[mobileNumber], "label")}
                        name={mobileNumber}
                        error={hasError(mobileNumber)}
                        helperText={
                          hasError(mobileNumber)
                            ? formState.errors[mobileNumber].map(error => {
                                return "\n" + error;
                              })
                            : null
                        }
                        autoFocus
                        value={formState.values[mobileNumber] || ""}
                        onChange={handleChange}
                      />
                      <Button
                        color="primary"
                        disabled={!formState.isValid}
                        type="submit"
                        fullWidth
                        variant="contained"
                        className={classes.submit}
                      >
                        {authPageConstants.SEND_OTP_BUTTON}
                      </Button>
                      <Backdrop
                        className={classes.backdrop}
                        open={openBackdrop}
                      >
                        <CircularProgress color="inherit" />
                      </Backdrop>
                    </React.Fragment>
                  )}
                  <Grid container>
                    <Grid item xs={12} style={{ textAlign: "center" }}>
                      <Link
                        href={routeConstants.SIGN_IN_URL}
                        variant="body2"
                        className={classes.linkColor}
                      >
                        {authPageConstants.BACK_TO_LOGIN_TEXT}
                      </Link>
                    </Grid>
                  </Grid>
                </form>
              </div>
            </CardContent>

            <Hidden mdDown>
              <CardMedia
                className={classes.cover}
                image={image}
                title="Live from space album cover"
              />
            </Hidden>
          </Paper>
        </div>
      </div>
    </div>
  );
}
Example #23
Source File: PastActivitiesDetails.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
PastActivitiesDetails = props => {
  const history = useHistory();
  const classes = useStyles();
  const [formState, setFormState] = useState({
    activityDetails: {},
    greenButtonChecker: true
  });
  const { setLoaderStatus } = useContext(LoaderContext);

  useEffect(() => {
    setLoaderStatus(true);
    getactivityDetails();
    setLoaderStatus(false);
  }, []);

  async function getactivityDetails() {
    let paramsForEvent = null;
    if (
      auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
    ) {
      paramsForEvent = props["location"]["dataForView"];
    } else if (auth.getUserInfo().role.name === roleConstants.STUDENT) {
      paramsForEvent = props["location"]["dataForView"];
    }
    if (
      paramsForEvent !== null &&
      paramsForEvent !== undefined &&
      (auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
        auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN)
    ) {
      await serviceProviders
        .serviceProviderForGetOneRequest(ACTIVITIES_URL, paramsForEvent)
        .then(res => {
          let viewData = res.data.result;
          setFormState(formState => ({
            ...formState,
            activityDetails: viewData
          }));
        })
        .catch(error => {
          console.log("error", error);
        });
    } else if (
      paramsForEvent !== null &&
      paramsForEvent !== undefined &&
      auth.getUserInfo().role.name === roleConstants.STUDENT
    ) {
      setFormState(formState => ({
        ...formState,
        activityDetails: props["location"]["dataForView"]
      }));
    } else {
      if (auth.getUserInfo().role.name === roleConstants.STUDENT) {
        history.push({
          pathname: routeConstants.VIEW_PAST_ACTIVITIES
        });
      } else {
        history.push({
          pathname: routeConstants.DASHBOARD_URL
        });
      }
    }
  }

  const route = () => {
    setLoaderStatus(true);
    if (auth.getUserInfo().role.name === roleConstants.STUDENT) {
      history.push({
        pathname: routeConstants.VIEW_PAST_ACTIVITIES
      });
    }
    setLoaderStatus(false);
  };

  const getTime = () => {
    let startTime = new Date(formState.activityDetails["start_date_time"]);
    if (
      formState.activityDetails["start_date_time"] &&
      formState.activityDetails["end_date_time"]
    ) {
      let endTime = new Date(formState.activityDetails["end_date_time"]);
      return (
        startTime.toLocaleTimeString() + " to " + endTime.toLocaleTimeString()
      );
    } else {
      startTime = new Date(formState.activityDetails["start_date_time"]);
      return startTime.toLocaleTimeString();
    }
  };

  const getDate = () => {
    let startDate = new Date(formState.activityDetails["start_date_time"]);
    if (
      formState.activityDetails["start_date_time"] &&
      formState.activityDetails["end_date_time"]
    ) {
      let endDate = new Date(formState.activityDetails["end_date_time"]);
      return startDate.toDateString() + " to " + endDate.toDateString();
    } else {
      startDate = new Date(formState.activityDetails["start_date_time"]);
      return startDate.toDateString();
    }
  };

  const getBatch = () => {
    return formState.activityDetails.activity_batch.name;
  };

  const getBatchTime = () => {
    if (
      formState.activityDetails.activity_batch.start_date_time &&
      formState.activityDetails.activity_batch.end_date_time
    ) {
      let startTime = moment(
        formState.activityDetails.activity_batch["start_date_time"]
      ).format("LT");
      let endTime = moment(
        formState.activityDetails.activity_batch["end_date_time"]
      ).format("LT");
      return startTime + " to " + endTime;
    } else {
      return null;
    }
  };

  const getVenue = () => {
    return formState.activityDetails["address"];
  };

  const getRemainingDays = data => {
    let currentDate = new Date();
    let startDate = new Date(
      formState.activityDetails["activity_batch"]["start_date_time"]
    );
    let remainingDays = startDate.getDay() - currentDate.getDay();
    if (remainingDays >= 1) return parseInt(remainingDays) + " Days to go";
    else return "Today";
  };

  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        <Typography variant="h4" gutterBottom>
          Activity
        </Typography>
        <GreenButton
          variant="contained"
          color="primary"
          disableElevation
          onClick={route}
          to={routeConstants.VIEW_PAST_ACTIVITIES}
          startIcon={<Icon>keyboard_arrow_left</Icon>}
          greenButtonChecker={formState.greenButtonChecker}
        >
          Back to listing
        </GreenButton>
      </Grid>
      <Grid item xs={12} className={classes.formgrid}>
        <Card>
          <CardContent>
            <Grid container spacing={3} className={classes.formgrid}>
              <Grid item md={12} xs={12}>
                {!formUtilities.checkEmpty(formState.activityDetails) ? (
                  <React.Fragment>
                    <Grid container md={12}>
                      <Grid item md={6} xs={12} className={classes.title}>
                        <Typography variant="h4" gutterBottom>
                          {formState.activityDetails["title"]}
                        </Typography>
                      </Grid>
                    </Grid>
                    <Divider />
                    <Grid
                      container
                      spacing={2}
                      className={classes.defaultMargin}
                    >
                      <Grid item md={4} xs={12}>
                        <Grid
                          item
                          className={classes.defaultMargin}
                          spacing={4}
                        >
                          {formState.activityDetails["upload_logo"] !== null &&
                          formState.activityDetails["upload_logo"] !==
                            undefined &&
                          formState.activityDetails["upload_logo"] !== {} ? (
                            <Img
                              src={
                                strapiConstants.STRAPI_DB_URL_WITHOUT_HASH +
                                formState.activityDetails["upload_logo"]["url"]
                              }
                              loader={<Spinner />}
                              width="100%"
                              height="100%"
                            />
                          ) : (
                            <Img
                              src="/images/noImage.png"
                              loader={<Spinner />}
                              width="100%"
                              height="100%"
                            />
                          )}
                        </Grid>
                        <Grid container className={classes.defaultMargin}>
                          <Grid item md={3} xs={3}>
                            <b>Date </b>
                          </Grid>
                          <Grid item md={9} xs={9}>
                            {getDate()}
                          </Grid>
                        </Grid>
                        {auth.getUserInfo().role.name ===
                          roleConstants.MEDHAADMIN ||
                        auth.getUserInfo().role.name ===
                          roleConstants.COLLEGEADMIN ? (
                          <Grid container className={classes.defaultMargin}>
                            <Grid item md={3} xs={3}>
                              <b>Time </b>
                            </Grid>
                            <Grid item md={9} xs={9}>
                              {getTime()}
                            </Grid>
                          </Grid>
                        ) : null}
                        <Grid container className={classes.defaultMargin}>
                          <Grid item md={3} xs={3}>
                            <b>Venue </b>
                          </Grid>
                          <Grid item md={9} xs={9}>
                            {getVenue()}
                          </Grid>
                        </Grid>
                        {auth.getUserInfo().role.name ===
                        roleConstants.STUDENT ? (
                          <Grid container className={classes.defaultMargin}>
                            <Grid item md={3} xs={3}>
                              <b>Batch </b>
                            </Grid>
                            <Grid item md={9} xs={9}>
                              {getBatch()}
                            </Grid>
                          </Grid>
                        ) : null}
                        {auth.getUserInfo().role.name ===
                        roleConstants.STUDENT ? (
                          <Grid container className={classes.defaultMargin}>
                            <Grid item md={3} xs={3}>
                              <b>Timing </b>
                            </Grid>
                            <Grid item md={9} xs={9}>
                              {getBatchTime()}
                            </Grid>
                          </Grid>
                        ) : null}
                        <Divider />
                      </Grid>
                      <Grid item md={6} xs={12}>
                        {ReactHtmlParser(
                          formState.activityDetails["description"]
                        )}
                      </Grid>
                    </Grid>
                    <Grid></Grid>
                  </React.Fragment>
                ) : (
                  <Spinner />
                )}
              </Grid>
            </Grid>
          </CardContent>
        </Card>
      </Grid>
    </Grid>
  );
}
Example #24
Source File: ActivityDetails.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
ActivityDetails = props => {
  const history = useHistory();
  const classes = useStyles();
  const [formState, setFormState] = useState({
    activityDetails: {},
    greenButtonChecker: true
  });
  const { setLoaderStatus } = useContext(LoaderContext);

  useEffect(() => {
    setLoaderStatus(true);
    getactivityDetails();
    setLoaderStatus(false);
  }, []);

  async function getactivityDetails() {
    let paramsForEvent = null;
    if (
      auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
    ) {
      paramsForEvent = props["location"]["dataForView"];
    } else if (auth.getUserInfo().role.name === roleConstants.STUDENT) {
      paramsForEvent = props["location"]["dataForView"];
    }
    if (
      paramsForEvent !== null &&
      paramsForEvent !== undefined &&
      (auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
        auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN)
    ) {
      await serviceProviders
        .serviceProviderForGetOneRequest(ACTIVITIES_URL, paramsForEvent)
        .then(res => {
          let viewData = res.data.result;
          setFormState(formState => ({
            ...formState,
            activityDetails: viewData
          }));
        })
        .catch(error => {
          console.log("error", error);
        });
    } else if (
      paramsForEvent !== null &&
      paramsForEvent !== undefined &&
      auth.getUserInfo().role.name === roleConstants.STUDENT
    ) {
      setFormState(formState => ({
        ...formState,
        activityDetails: props["location"]["dataForView"]
      }));
    } else {
      if (
        auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
        auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
      ) {
        history.push({
          pathname: routeConstants.MANAGE_ACTIVITY
        });
      } else if (auth.getUserInfo().role.name === roleConstants.STUDENT) {
        history.push({
          pathname: routeConstants.ELIGIBLE_ACTIVITY
        });
      } else {
        history.push({
          pathname: routeConstants.DASHBOARD_URL
        });
      }
    }
  }

  const route = () => {
    setLoaderStatus(true);
    if (auth.getUserInfo().role.name === roleConstants.STUDENT) {
      history.push({
        pathname: routeConstants.ELIGIBLE_ACTIVITY
      });
    } else if (
      auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
    ) {
      history.push({
        pathname: routeConstants.MANAGE_ACTIVITY
      });
    } else {
      auth.clearToken();
      auth.clearUserInfo();
      history.push({
        pathname: routeConstants.SIGN_IN_URL
      });
    }
    setLoaderStatus(false);
  };

  const getTime = () => {
    let startTime = new Date(formState.activityDetails["start_date_time"]);
    if (
      formState.activityDetails["start_date_time"] &&
      formState.activityDetails["end_date_time"]
    ) {
      let endTime = new Date(formState.activityDetails["end_date_time"]);
      return (
        startTime.toLocaleTimeString() + " to " + endTime.toLocaleTimeString()
      );
    } else {
      startTime = new Date(formState.activityDetails["start_date_time"]);
      return startTime.toLocaleTimeString();
    }
  };

  const getDate = () => {
    let startDate = new Date(formState.activityDetails["start_date_time"]);
    if (
      formState.activityDetails["start_date_time"] &&
      formState.activityDetails["end_date_time"]
    ) {
      let endDate = new Date(formState.activityDetails["end_date_time"]);
      return startDate.toDateString() + " to " + endDate.toDateString();
    } else {
      startDate = new Date(formState.activityDetails["start_date_time"]);
      return startDate.toDateString();
    }
  };

  const getBatch = () => {
    return formState.activityDetails.activity_batch.name;
  };

  const getBatchTime = () => {
    if (
      formState.activityDetails.activity_batch.start_date_time &&
      formState.activityDetails.activity_batch.end_date_time
    ) {
      let startTime = moment(
        formState.activityDetails.activity_batch["start_date_time"]
      ).format("LT");
      let endTime = moment(
        formState.activityDetails.activity_batch["end_date_time"]
      ).format("LT");
      return startTime + " to " + endTime;
    } else {
      return null;
    }
  };

  const getVenue = () => {
    return formState.activityDetails["address"];
  };

  const getRemainingDays = data => {
    let currentDate = new Date();
    let startDate = new Date(
      formState.activityDetails["activity_batch"]["start_date_time"]
    );
    let remainingDays = startDate.getDay() - currentDate.getDay();
    if (remainingDays >= 1) return parseInt(remainingDays) + " Days to go";
    else return "Today";
  };

  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        <Typography variant="h4" gutterBottom>
          Activity
        </Typography>
        <GreenButton
          variant="contained"
          color="primary"
          disableElevation
          onClick={route}
          to={routeConstants.MANAGE_ACTIVITY}
          startIcon={<Icon>keyboard_arrow_left</Icon>}
          greenButtonChecker={formState.greenButtonChecker}
        >
          Back to listing
        </GreenButton>
      </Grid>
      <Grid item xs={12} className={classes.formgrid}>
        <Card>
          <CardContent>
            <Grid container spacing={3} className={classes.formgrid}>
              <Grid item md={12} xs={12}>
                {!formUtilities.checkEmpty(formState.activityDetails) ? (
                  <React.Fragment>
                    <Grid container md={12}>
                      <Grid item md={6} xs={12} className={classes.title}>
                        <Typography variant="h4" gutterBottom>
                          {formState.activityDetails["title"]}
                        </Typography>
                      </Grid>
                      {auth.getUserInfo().role.name ===
                      roleConstants.STUDENT ? (
                        <Grid
                          container
                          md={6}
                          justify="flex-end"
                          alignItems="baseline"
                          className={classes.CardHeader}
                        >
                          <Grid item xs={9} style={{ textAlign: "end" }}>
                            <IconButton aria-label="is student registered">
                              <Clock style={{ color: green[500] }} />
                            </IconButton>
                          </Grid>

                          <Grid item xs={3}>
                            <Typography
                              className={classes.header}
                              style={{
                                color: green[500]
                              }}
                            >
                              {getRemainingDays()}
                            </Typography>
                          </Grid>
                        </Grid>
                      ) : null}
                    </Grid>
                    <Divider />
                    <Grid
                      container
                      spacing={2}
                      className={classes.defaultMargin}
                    >
                      <Grid item md={4} xs={12}>
                        <Grid
                          item
                          className={classes.defaultMargin}
                          spacing={4}
                        >
                          {formState.activityDetails["upload_logo"] !== null &&
                          formState.activityDetails["upload_logo"] !==
                            undefined &&
                          formState.activityDetails["upload_logo"] !== {} ? (
                            <Img
                              src={
                                strapiConstants.STRAPI_DB_URL_WITHOUT_HASH +
                                formState.activityDetails["upload_logo"]["url"]
                              }
                              loader={<Spinner />}
                              width="100%"
                              height="100%"
                            />
                          ) : (
                            <Img
                              src="/images/noImage.png"
                              loader={<Spinner />}
                              width="100%"
                              height="100%"
                            />
                          )}
                        </Grid>
                        <Grid container className={classes.defaultMargin}>
                          <Grid item md={3} xs={3}>
                            <b>Date </b>
                          </Grid>
                          <Grid item md={9} xs={9}>
                            {getDate()}
                          </Grid>
                        </Grid>
                        {auth.getUserInfo().role.name ===
                          roleConstants.MEDHAADMIN ||
                        auth.getUserInfo().role.name ===
                          roleConstants.COLLEGEADMIN ? (
                          <Grid container className={classes.defaultMargin}>
                            <Grid item md={3} xs={3}>
                              <b>Time </b>
                            </Grid>
                            <Grid item md={9} xs={9}>
                              {getTime()}
                            </Grid>
                          </Grid>
                        ) : null}
                        <Grid container className={classes.defaultMargin}>
                          <Grid item md={3} xs={3}>
                            <b>Venue </b>
                          </Grid>
                          <Grid item md={9} xs={9}>
                            {getVenue()}
                          </Grid>
                        </Grid>
                        {auth.getUserInfo().role.name ===
                        roleConstants.STUDENT ? (
                          <Grid container className={classes.defaultMargin}>
                            <Grid item md={3} xs={3}>
                              <b>Batch </b>
                            </Grid>
                            <Grid item md={9} xs={9}>
                              {getBatch()}
                            </Grid>
                          </Grid>
                        ) : null}
                        {auth.getUserInfo().role.name ===
                        roleConstants.STUDENT ? (
                          <Grid container className={classes.defaultMargin}>
                            <Grid item md={3} xs={3}>
                              <b>Timing </b>
                            </Grid>
                            <Grid item md={9} xs={9}>
                              {getBatchTime()}
                            </Grid>
                          </Grid>
                        ) : null}
                        <Divider />
                      </Grid>
                      <Grid item md={6} xs={12}>
                        {ReactHtmlParser(
                          formState.activityDetails["description"]
                        )}
                      </Grid>
                    </Grid>
                    <Grid></Grid>
                  </React.Fragment>
                ) : (
                  <Spinner />
                )}
              </Grid>
            </Grid>
          </CardContent>
        </Card>
      </Grid>
    </Grid>
  );
}
Example #25
Source File: AddQuestionModal.js    From quizdom with MIT License 4 votes vote down vote up
export default function AddQuestionModal({
	type = 'add',
	title = '',
	opType = 'radio',
	opArray,
	index = -1,
	addQuestionHandle,
}) {
	const classes = useStyles()
	const [open, setOpen] = React.useState(false)
	const [optionType, setOptionType] = useState('radio')
	const [optionsArray, setOptionsArray] = useState([])
	const [editedOption, setEditedOption] = useState(null)
	const [editOpIndex, setEditOpIndex] = useState(-1)
	const [titleField, setTitleField] = useState('')
	const optionsRef = useRef(null)
	const checkBoxRef = useRef(null)

	useEffect(() => {
		if (open) {
			setTitleField(title)
			setOptionType(opType)
			if (opArray) setOptionsArray(opArray)
		} else {
			setTitleField('')
			setOptionsArray([])
			setOptionType('radio')
		}
	}, [open, title, opType, opArray])
	const handleOpen = () => {
		setOpen(true)
	}

	const handleClose = () => {
		setOpen(false)
	}
	const addQuestionCallBack = () => {
		const tempArr = [...optionsArray]
		if (optionsRef.current.value.length !== 0) {
			// For radio options, set all other options incorrect
			if (optionType === 'radio' && checkBoxRef.current.checked)
				tempArr.forEach((op) => (op.isCorrect = false))

			tempArr.push({
				text: optionsRef.current.value,
				isCorrect: checkBoxRef.current.checked,
			})
		}
		// Error Handling
		if (!titleField.length && optionsArray.length < 2) {
			alert('Please add Question and atleast 2 options.')
			return
		} else if (!titleField.length) {
			alert('Please add Question.')
			return
		} else if (optionsArray.length < 2) {
			alert('Number of Options must be greater than 1.')
			return
		}
		const correctOp = optionsArray.filter((op) => op.isCorrect)
		if (correctOp.length < 1) {
			alert('No correct option was selected.')
			return
		}
		if (index !== -1) addQuestionHandle(titleField, optionType, tempArr, index)
		else addQuestionHandle(titleField, optionType, tempArr)

		setOpen(false)
	}

	const addOption = () => {
		if (optionsRef.current.value.length === 0) return

		const arr = [...optionsArray]
		if (
			optionsArray.findIndex((op) => op.text === optionsRef.current.value) !==
			-1
		) {
			alert('Option already exists.')
			return
		}
		if (optionType === 'radio' && checkBoxRef.current.checked)
			// For radio options, set all other options incorrect
			arr.forEach((op) => (op.isCorrect = false))

		arr.push({
			text: optionsRef.current.value,
			isCorrect: checkBoxRef.current.checked,
		})
		optionsRef.current.value = ''
		checkBoxRef.current.checked = false
		setOptionsArray(arr)
	}
	const handleTypeChange = (e) => setOptionType(e.target.value)

	const deleteHandler = (ind) => {
		const temp = [...optionsArray]
		temp.splice(ind, 1)
		setOptionsArray(temp)
		setEditOpIndex(-1)
	}

	const handleEdit = (ind) => {
		if (editOpIndex === -1) {
			setEditOpIndex(ind)
			setEditedOption(optionsArray[ind].text)
		}
	}

	const saveEdited = () => {
		const temp = [...optionsArray]
		temp[editOpIndex].text = editedOption
		setOptionsArray(temp)
		setEditOpIndex(-1)
	}

	return (
		<div className={classes.root}>
			{type === 'add' ? (
				<button className='button' onClick={handleOpen}>
					Add Question
				</button>
			) : (
				<IconButton onClick={handleOpen}>
					<EditRounded />
				</IconButton>
			)}
			<Modal
				aria-labelledby='transition-modal-title'
				aria-describedby='transition-modal-description'
				className={classes.modal}
				open={open}
				disableEnforceFocus={true}
			>
				<div className={classes.paper}>
					<div className='questionCard'>
						<div id='title'>Question:</div>
						<input
							type='text'
							autoFocus
							value={titleField}
							onChange={(e) => setTitleField(e.target.value)}
							className='input-text question'
							placeholder='Type Question Here'
						/>
						<select
							id='select'
							placeholder='Select'
							onChange={handleTypeChange}
						>
							<option className='selectOp' value='radio'>
								Single Answer
							</option>
							<option className='selectOp' value='check'>
								Multiple Answers
							</option>
						</select>

						<div className='option-div'>
							<div className='options' id='one-op'>
								{optionsArray.map((option, ind) => (
									<div className='option' key={ind}>
										<input
											type={optionType === 'radio' ? 'radio' : 'checkbox'}
											disabled={true}
											className='radio-in'
											name='option'
											checked={option.isCorrect}
										/>
										{editOpIndex === ind ? (
											<input
												value={editedOption}
												onChange={(e) => setEditedOption(e.target.value)}
											/>
										) : (
											<div className='add-op'>{option.text}</div>
										)}
										{editOpIndex === ind ? (
											<Icon className='save-icon' onClick={() => saveEdited()}>
												<SaveRounded />
											</Icon>
										) : (
											<Icon
												className='edit-icon'
												onClick={() => handleEdit(ind)}
											>
												<EditRounded />
											</Icon>
										)}
										<Icon
											className='delete-icon'
											onClick={() => {
												deleteHandler(ind)
											}}
										>
											<DeleteRounded />
										</Icon>
									</div>
								))}
							</div>
						</div>

						<div className='add-op'>
							<div>
								<input
									type={optionType === 'radio' ? 'radio' : 'checkbox'}
									ref={checkBoxRef}
									className='radio-in'
									name='option'
								/>
								<input
									type='text'
									ref={optionsRef}
									className='input-text op-text'
									placeholder={`Option ${optionsArray.length + 1}`}
								/>
							</div>
							<input
								type='submit'
								className='add-btn'
								value='+ Add'
								onClick={addOption}
							/>
						</div>
					</div>
					<div className={classes.buttons}>
						<button className='add-btn' onClick={handleClose}>
							Close
						</button>
						<button
							// disabled={!(optionsArray.length && titleField.length)}
							className='button'
							color='secondary'
							variant='contained'
							onClick={addQuestionCallBack}
						>
							{type === 'add' ? 'Add ' : 'Edit '}
							Question
						</button>
					</div>
				</div>
			</Modal>
		</div>
	)
}
Example #26
Source File: DashboardPage.jsx    From frontend with MIT License 4 votes vote down vote up
DashboardPage = () => {
  const [selectedFacilityId, setSelectedFacilityId] = useState('');
  const [selectedContactId, setSelectedContactId] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('');
  const [modalOpen, setModalOpen] = useState(false);
  const [resourceEditId, setResourceEditId] = useState(0);
  const [requests, setRequests] = useState([]);
  const [facilities, setFacilites] = useState([]);
  const [contacts, setContacts] = useState([]);
  const [categories, setCategories] = useState([]);
  const [amount, setAmount] = useState(0);
  const selectedFacility = facilities.find((x) => x.name === selectedFacilityId);
  const selectedContact = contacts.find((x) => x.name === selectedContactId);

  useEffect(() => {
    if (modalOpen) {
      setSelectedFacilityId('');
      setSelectedContactId('');
      setSelectedCategory('');
      setAmount(0);
    } else if (resourceEditId) {
      setTimeout(() => setResourceEditId(0), 50);
    }
  }, [modalOpen]);

  useEffect(() => {
    if (resourceEditId) {
      const {
        name,
        quantity,
        beneficiary,
        contactPerson,
      } = requests.find(({ id }) => id === resourceEditId);

      setSelectedFacilityId(beneficiary.name);
      setSelectedContactId(contactPerson.name);
      setSelectedCategory(name);
      setAmount(quantity);
    }
  }, [resourceEditId]);

  const getData = () => {
    fetch(`${apiUrl}/resources`)
      .then((x) => x.json())
      .then((x) => x.list.filter((a) => a.name))
      .then((x) => {
        setRequests(x);
        const facilitiesX = x
          .reduce((res, next) => res.set(next.beneficiary.name, next.beneficiary), new Map());
        setFacilites([...facilitiesX.values()]);

        const contactsX = x
          .reduce((res, next) => res.set(next.contactPerson.name, next.contactPerson), new Map());
        setContacts([...contactsX.values()]);

        const categoriesX = x
          .reduce((res, next) => res.set(next.name, next.name), new Map());
        setCategories([...categoriesX.values()]);
      });
  };
  const init = useRef(false);
  useEffect(() => {
    if (!init.current) {
      getData();
      init.current = true;
    }
  }, [init]);

  const submit = (modalClose) => {
    const req = {
      beneficiary: selectedFacility,
      contactPerson: selectedContact,
      status: 'OPEN',
      items: [{
        name: selectedCategory,
        quantity: parseInt(amount, 10),
      }],
    };

    /* if (resourceEditId) {
      fetch(`${apiUrl}/resources/${resourceEditId}`, {
        method: 'PUT',
        body: JSON.stringify(req),
      }).then((response) => {
        setRequests(requests.reduce((acc, rowData) => {
          if (rowData.id === resourceEditId) {
            acc.push(response);
          } else {
            acc.push(rowData);
          }

          return acc;
        }), []);
      }).then(() => modalClose())
        .catch((e) => console.log(e));
    } else {
      fetch(`${apiUrl}/resources`, {
        method: 'POST',
        body: JSON.stringify(req),
      }).then((x) => setRequests(x.list.filter((a) => a.name)))
        .then(() => modalClose())
        .catch((e) => console.log(e));
    } */

    // temporarily until the server is implemented
    modalClose();
  };

  return (
    <>
      <Box mb={4} display="flex" justifyContent="space-between">
        <Typography variant="h4">Dashboard</Typography>
        <Button color="primary" variant="contained" onClick={() => setModalOpen(true)}>
          <Icon>add</Icon>
          {' '}
          Create Request
        </Button>
      </Box>
      {/* <Box mb={2}>
        <Paper elevation={2}>
          <Box p={2}>
            <Typography variant="h5" gutterBottom>Filter</Typography>
            <Grid container spacing={2}>
              <Grid item xs>
                <FormControl>
                  <InputLabel>Facility</InputLabel>
                  <Input />
                </FormControl>
              </Grid>
              <Grid item xs>
                <FormControl>
                  <InputLabel>Region</InputLabel>
                  <Input />
                </FormControl>
              </Grid>
              <Grid item xs>
                <FormControl>
                  <MuiPickersUtilsProvider utils={DateFnsUtils}>
                    <KeyboardDatePicker label="Deadline" onChange={() => {}} />
                  </MuiPickersUtilsProvider>
                </FormControl>
              </Grid>
            </Grid>
          </Box>
        </Paper>
      </Box> */}
      <Paper elevation={2}>
        <Table>
          <TableHead>
            <TableRow>
              {columns.map((c) => <TableCell key={c.label}>{c.label}</TableCell>)}
            </TableRow>
          </TableHead>
          <TableBody>
            {requests.map((x) => (
              <TableRow key={x.id}>
                <TableCell>{x.beneficiary.name}</TableCell>
                <TableCell>{x.name}</TableCell>
                <TableCell>{x.quantity}</TableCell>
                <TableCell>{x.deadline}</TableCell>
                <TableCell>
                  {x.contactPerson ? x.contactPerson.name : (
                    <Button color="secondary" variant="contained">
                      Assign
                    </Button>
                  )}
                </TableCell>
                <TableCell align="right">
                  <IconButton
                    variant="icon"
                    onClick={() => {
                      setResourceEditId(x.id);
                      setModalOpen(true);
                    }}
                  >
                    <Icon>edit</Icon>
                  </IconButton>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </Paper>

      <Dialog open={modalOpen} fullWidth>
        <DialogTitle>
          {resourceEditId ? 'Update' : 'New'}
          {' '}
          Request
        </DialogTitle>
        <DialogContent>
          <Box mb={2}>
            <FormControl fullWidth>
              <InputLabel>Facility</InputLabel>
              <Select
                value={selectedFacilityId}
                fullWidth
                onChange={({ target: { value } }) => setSelectedFacilityId(value)}
              >
                {facilities.map((x) => <MenuItem key={x.name} value={x.name}>{x.name}</MenuItem>)}
              </Select>
            </FormControl>
            {
              selectedFacilityId
                ? (
                  <>
                    <Typography color="textSecondary" variant="subtitle1">{selectedFacility.name}</Typography>
                    <Typography color="textSecondary" variant="subtitle2">{selectedFacility.address}</Typography>
                  </>
                ) : null
            }
          </Box>
          <Box mb={2}>
            <FormControl fullWidth>
              <InputLabel>Contact person</InputLabel>
              <Select
                value={selectedContactId}
                fullWidth
                onChange={({ target: { value } }) => setSelectedContactId(value)}
              >
                {contacts.map((x) => <MenuItem key={x.name} value={x.name}>{x.name}</MenuItem>)}
              </Select>
            </FormControl>
            {
              selectedContactId
                ? (
                  <>
                    <Typography color="textSecondary" variant="subtitle1">{selectedContact.name}</Typography>
                    <Typography color="textSecondary" variant="subtitle2">{selectedContact.phone}</Typography>
                  </>
                ) : null
            }
          </Box>
          <Typography variant="h6">Request</Typography>
          <Box mb={2}>
            <FormControl fullWidth>
              <InputLabel>Category</InputLabel>
              <Select
                value={selectedCategory}
                fullWidth
                onChange={({ target: { value } }) => setSelectedCategory(value)}
              >
                {categories.map((x) => <MenuItem key={x} value={x}>{x}</MenuItem>)}
              </Select>
            </FormControl>
          </Box>
          <Box mb={2}>
            <FormControl fullWidth>
              <InputLabel>Amount</InputLabel>
              <Input value={amount} onChange={(({ target: { value } }) => setAmount(value))} />
            </FormControl>
          </Box>
          <Box mb={2}>
            <FormControl fullWidth>
              <MuiPickersUtilsProvider utils={DateFnsUtils}>
                <KeyboardDatePicker fullWidth label="Deadline" onChange={() => {}} />
              </MuiPickersUtilsProvider>
            </FormControl>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button
            color="secondary"
            onClick={() => {
              setModalOpen(false);
            }}
          >
            Cancel
          </Button>
          <Button
            variant="contained"
            color="primary"
            onClick={() => {
              submit(() => setModalOpen(false));
            }}
          >
            {resourceEditId ? 'Update' : 'Create'}
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
}
Example #27
Source File: AnswerLayout.js    From Edlib with GNU General Public License v3.0 4 votes vote down vote up
AnswerLayout = props => {
    const {
        onToggle,
        isCorrect,
        onAnswerChange,
        showToggle,
        additionalClass,
        answerText,
        deleteAnswer,
        canDelete,
        placeHolder,
        title,
        image,
        onImageChange,
        useImage,
        maxRows,
        multiline,
        richText,
    } = props;

    let inputType;
    if ( onAnswerChange ) {
        if ( richText ) {
            inputType = (
                <RichEditor
                    value={answerText}
                    onChange={onAnswerChange}
                />
            );
        } else {
            inputType = (
                <Input
                    name="text"
                    placeholder={placeHolder}
                    onChange={event => onAnswerChange(event.currentTarget.value)}
                    value={answerText}
                    className="answerText"
                    fullWidth={true}
                    multiline={multiline}
                    rowsMax={maxRows}
                />
            );
        }
    } else {
        inputType = (
            <HtmlContainer
                className="displayText"
                html={answerText}
                stripTags={false}
                firstParagraphFix={true}
                compactParagraphs={true}
            />
        );
    }

    return (
        <div className={'answerCard ' + additionalClass}>
            {title && (
                <div className="answerTitle">{title}</div>
            )}

            {canDelete === true && typeof deleteAnswer === 'function' && (
                <Icon
                    className="deleteButton"
                    onClick={deleteAnswer}
                >add</Icon>
            )}
            <div className="answerContainer">
                {inputType}
                {useImage === true && onImageChange && (
                    <ImageContainer
                        onChange={onImageChange}
                        readOnly={onImageChange === null}
                        image={image}
                    />
                )}
                {showToggle && onToggle && (
                    <Toggle
                        onToggle={onToggle}
                        isCorrect={isCorrect}
                        rightLabel={<FormattedMessage id="ANSWER.LABEL_CORRECT" />}
                        leftLabel={<FormattedMessage id="ANSWER.LABEL_WRONG" />}
                    />
                )}
            </div>
        </div>
    );
}
Example #28
Source File: CargoShip.jsx    From archeage-tools with The Unlicense 4 votes vote down vote up
render() {
    const { alerts, setAlert, speak, setSpeak, servers, server: serverId, mobile, openDialog } = this.props;
    const { open, setup, stepIndex, endTime, shipPosition, menu, updated } = this.state;
    const now = moment();
    let eventStepTime = moment(endTime);
    const step = CARGO_SCHEDULE[stepIndex];

    const server = servers[serverId];
    const serverName = pathOr('???', ['name'])(server);

    return [
      <Paper className="cargo-ship event-list" key="cargo-timer">
        <AppBar position="static">
          <Toolbar variant="dense">
            <Icon><img src={'/images/event_type/exploration.png'} alt="Cargo Ship" /></Icon>
            <Typography variant="subtitle1" className="title-text">[{serverName}] Cargo Ship</Typography>
            <IfPerm permission={`cargo.${serverName.toLowerCase()}`}>
              <Tooltip title={`Edit ${serverName} Timer`}>
                <IconButton onClick={this.toggleDialog} color="inherit">
                  <EditIcon />
                </IconButton>
              </Tooltip>
            </IfPerm>
            <Tooltip title="Change Server">
              <IconButton onClick={() => openDialog(DIALOG_MY_GAME, SERVER)} color="inherit">
                <HomeIcon />
              </IconButton>
            </Tooltip>
            <Tooltip title="Configure alerts">
              <IconButton
                onClick={this.handleOpenMenu}
                className="super-btn"
              >
                <NotificationsIcon
                  className={cn({ 'notif-fade': alerts.length === 0 })}
                  color="inherit"
                />
                {alerts.length > 0 &&
                <Typography className="super-text" color="primary">{alerts.length}</Typography>}
              </IconButton>
            </Tooltip>
          </Toolbar>
        </AppBar>
        <div className="cargo-slider">
          <div className="cargo-rail" />
          <Tooltip title="Solis Headlands Trade Outlet">
            <div className="cargo-icon austera" />
          </Tooltip>
          <Tooltip title="Two Crowns Trade Outlet">
            <div className="cargo-icon two-crowns" />
          </Tooltip>
          <div
            className={cn('cargo-icon ship', { moving: !step.port, reverse: step.reverse })}
            style={{ [step.reverse ? 'left' : 'right']: `${(shipPosition / step.duration) * 100}%` }}
          />
        </div>
        <div className="cargo-text">
          {!server &&
          <Typography>Select a server to see the cargo ship location.</Typography>}
          {server && !updated &&
          <Typography>The cargo ship has not been updated since the last maintenance.</Typography>}
          {server && updated &&
          <>
            <Typography>Cargo ship is {step.text}.</Typography>
            <br />
            <Table size="small" stickyHeader className="timer-table">
              <TableHead>
                <TableRow>
                  <TableCell>
                    Event
                  </TableCell>
                  <TableCell>
                    Time
                  </TableCell>
                  <TableCell align="right">
                    Countdown
                  </TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {Array.from(Array(CARGO_SCHEDULE.length).keys()).map((_, i) => {
                  const index = getNextIndex(stepIndex + i - 1);
                  const step = CARGO_SCHEDULE[index];
                  if (i > 0) {
                    eventStepTime.add(step.duration, 'seconds');
                  }
                  return (
                    <TableRow key={`cargo-${i}`}>
                      <TableCell>{step.next}</TableCell>
                      <TableCell>{eventStepTime.format('h:mm A')}</TableCell>
                      <TableCell align="right">{hhmmssFromDate(eventStepTime.diff(now))}</TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </>}
        </div>
      </Paper>,
      <Dialog
        open={open}
        key="cargo-settings"
        onClose={this.toggleDialog}
        maxWidth="sm"
      >
        <AppBar position="static">
          <Toolbar variant="dense">
            <Typography variant="subtitle1" className="title-text">Cargo Ship Setup</Typography>
            <Tooltip title="Close">
              <IconButton onClick={this.toggleDialog}>
                <CloseIcon />
              </IconButton>
            </Tooltip>
          </Toolbar>
        </AppBar>
        <DialogContent>
          <Typography>To setup the timer, the ship must currently be docked at a port.</Typography>
          <br />
          <FormControl component="fieldset">
            <FormLabel component="legend">What port is the ship at?</FormLabel>
            <RadioGroup name="port" value={Number.parseInt(setup.port)} onChange={this.handleSetupChange('port')} row>
              <FormControlLabel
                control={<Radio color="primary" />}
                label="Solis Headlands"
                value={ZONE.SOLIS_HEADLANDS}
              />
              <FormControlLabel
                control={<Radio color="primary" />}
                label="Two Crowns"
                value={ZONE.TWO_CROWNS}
              />
            </RadioGroup>
          </FormControl>
          <FormControl component="fieldset">
            <FormLabel component="legend">What is the remaining time on the &quot;Cargo Ship
              Anchored&quot; buff?</FormLabel>
            <div className="duration-pick">
              <Input
                id="mm"
                placeholder="20"
                endAdornment="m"
                inputProps={{
                  maxLength: 2,
                  ref: this.mm,
                }}
                value={setup.mm}
                onChange={this.handleTimeChange('mm')}
                onKeyPress={this.handleEnter}
              />
              <Input
                id="ss"
                placeholder="00"
                endAdornment="s"
                inputProps={{
                  maxLength: 2,
                  ref: this.ss,
                }}
                value={setup.ss}
                onChange={this.handleTimeChange('ss')}
                onKeyPress={this.handleEnter}
              />
            </div>
          </FormControl>
          <FormControl component="fieldset">
            <FormControlLabel
              control={<Checkbox color="primary" />}
              label="Don't Update Sibling Realms"
              checked={setup.noLinkedUpdate}
              onChange={this.handleNoLink}
            />
          </FormControl>
        </DialogContent>
        <DialogActions>
          <Button
            onClick={this.submitSetup}
            color="primary"
            disabled={!setup.port || (String(setup.mm).length === 0 && String(setup.ss).length === 0)}
          >
            Update
          </Button>
        </DialogActions>
      </Dialog>,
      <Menu
        id="alert-menu"
        anchorEl={menu}
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'center',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'center',
        }}
        getContentAnchorEl={null}
        open={Boolean(menu)}
        onClose={this.handleCloseMenu}
        className="alert-menu"
        autoFocus={false}
        key="alert-menu"
        variant="menu"
      >
        <ListItem tabIndex={null} dense={!mobile}>
          <ListItemText>Alert Types:</ListItemText>
        </ListItem>
        <MenuItem disabled dense={!mobile}>
          <ListItemIcon>
            <CheckBoxIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Audio Cue</ListItemText>
        </MenuItem>
        <MenuItem
          onClick={setSpeak(CARGO_ID, !speak)}
          dense={!mobile}
          disabled={!CAN_SPEAK}
          divider
        >
          <ListItemIcon>
            {speak
              ? <CheckBoxIcon fontSize="small" color="primary" />
              : <CheckBoxOutlineBlankIcon fontSize="small" />}
          </ListItemIcon>
          <ListItemText>Audio Message</ListItemText>
        </MenuItem>
        <ListItem tabIndex={null} dense={!mobile}>
          <ListItemText>Alert Times:</ListItemText>
          <ListItemSecondaryAction>
            <Tooltip title="Clear all">
                <span>
                  <IconButton size="small" onClick={setAlert(CARGO_ID, '')} disabled={alerts.length === 0}>
                    <CloseIcon fontSize="small" />
                  </IconButton>
                </span>
            </Tooltip>
          </ListItemSecondaryAction>
        </ListItem>
        {Object.entries(CARGO_ALERTS).map(([key, option]) => (
          <MenuItem
            dense={!mobile}
            onClick={setAlert(CARGO_ID, key)}
            key={`alert-opt-${randomString(16)}-${key}`}
          >
            <ListItemIcon>
              {alerts.includes(key)
                ? <CheckBoxIcon fontSize="small" color="primary" />
                : <CheckBoxOutlineBlankIcon fontSize="small" />}
            </ListItemIcon>
            <ListItemText>{option.name}</ListItemText>
          </MenuItem>
        ))}
      </Menu>,
    ];
  }