@material-ui/core#FormGroup JavaScript Examples

The following examples show how to use @material-ui/core#FormGroup. 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: CardMembers.js    From TrelloClone with MIT License 6 votes vote down vote up
CardMembers = ({ card }) => {
  const classes = useStyles();
  const boardMembers = useSelector((state) => state.board.board.members);
  const members = card.members.map((member) => member.user);
  const dispatch = useDispatch();

  return (
    <div>
      <h3 className={classes.membersTitle}>Members</h3>
      <FormControl component='fieldset'>
        <FormGroup>
          {boardMembers.map((member) => (
            <FormControlLabel
              key={member.user}
              control={
                <Checkbox
                  checked={members.indexOf(member.user) !== -1}
                  onChange={async (e) =>
                    dispatch(
                      addCardMember({
                        add: e.target.checked,
                        cardId: card._id,
                        userId: e.target.name,
                      })
                    )
                  }
                  name={member.user}
                />
              }
              label={member.name}
            />
          ))}
        </FormGroup>
      </FormControl>
    </div>
  );
}
Example #2
Source File: Checklist.js    From TrelloClone with MIT License 6 votes vote down vote up
Checklist = ({ card }) => {
  const classes = useStyles();

  return (
    <Fragment>
      <h3 className={classes.header}>Checklist</h3>
      <FormControl component='fieldset'>
        <FormGroup>
          {card.checklist.map((item) => (
            <ChecklistItem key={item._id} item={item} card={card} />
          ))}
        </FormGroup>
      </FormControl>
      <CreateChecklistItem cardId={card._id} />
    </Fragment>
  );
}
Example #3
Source File: ArmingFlagsView.js    From Nemesis with GNU General Public License v3.0 5 votes vote down vote up
render() {
    return (
      <React.Fragment>
        <Typography variant="h5">
          <FormattedMessage id="pfc.armingflags.title" />
        </Typography>
        <List>
          {this.state.armingFlags.map(flag => (
            <Chip
              onClick={flag.onClick}
              key={flag.label}
              style={{ margin: 4 }}
              label={<FormattedMessage id={flag.label} />}
            />
          ))}
        </List>
        <FormGroup component="fieldset">
          {this.state.debug && (
            <FormControlLabel
              control={
                <Switch
                  checked={this.state.showDebug}
                  onChange={(event, showDebug) => {
                    this.setState({ showDebug });
                  }}
                />
              }
              label={<FormattedMessage id="info.show-debug" />}
            />
          )}
          {this.state.showDebug && (
            <List>
              {this.state.debug.map((debugVal, index) => {
                return (
                  <ListItem className="debug-item" key={index}>
                    DEBUG {index}: {debugVal}
                  </ListItem>
                );
              })}
            </List>
          )}
        </FormGroup>
      </React.Fragment>
    );
  }
Example #4
Source File: FilterHelper.js    From theouterrim with MIT License 5 votes vote down vote up
render() {
    let { filterIndex, column } = this.props
    return (
      <Grid xs={12}>
        <InputLabel shrink>Price</InputLabel>
        <FormGroup row style={{ justifyContent: "space-between", marginTop: 16 }}>
          <Select
            style={{
              flex: "0 1 20%",
              textAlign: "center",
            }}
            value={this.state.operator}
            onChange={evt => {
              this.setState({ operator: evt.target.value })
              this.debouncedChange(
                [evt.target.value, this.state.amount],
                filterIndex,
                column
              )
            }}
          >
            <MenuItem value={PriceFilterOperator.GT}>&gt;</MenuItem>
            <MenuItem value={PriceFilterOperator.GTE}>&gt;=</MenuItem>
            <MenuItem value={PriceFilterOperator.LT}>&lt;</MenuItem>
            <MenuItem value={PriceFilterOperator.LTE}>&lt;=</MenuItem>
          </Select>
          <TextField
            style={{ flex: "0 1 75%" }}
            type="number"
            value={this.state.amount}
            onChange={evt => {
              this.setState({ amount: evt.target.value })
              this.debouncedChange(
                [this.state.operator, evt.target.value],
                filterIndex,
                column
              )
            }}
          />
        </FormGroup>
      </Grid>
    )
  }
Example #5
Source File: FilterHelper.js    From theouterrim with MIT License 5 votes vote down vote up
render() {
    let { filterIndex, column, fieldLabel } = this.props
    return (
      <Grid xs={12}>
        <InputLabel shrink>{fieldLabel}</InputLabel>
        <FormGroup row style={{ justifyContent: "space-between", marginTop: 16 }}>
          <TextField
            style={{
              flex: "0 1 45%",
            }}
            type="number"
            placeholder="Min"
            value={this.state.minVal}
            onChange={evt => {
              this.setState({ minVal: evt.target.value })
              this.debouncedChange(
                [evt.target.value, this.state.maxVal],
                filterIndex,
                column
              )
            }}
          />
          <TextField
            style={{
              flex: "0 1 45%",
            }}
            type="number"
            placeholder="Max"
            value={this.state.maxVal}
            onChange={evt => {
              this.setState({ maxVal: evt.target.value })
              this.debouncedChange(
                [this.state.minVal, evt.target.value],
                filterIndex,
                column
              )
            }}
          />
        </FormGroup>
      </Grid>
    )
  }
Example #6
Source File: Terms.js    From web with GNU General Public License v3.0 5 votes vote down vote up
Terms = ({ handleClick }) => {
  const { setFieldValue, values } = useFormikContext();

  const disabled = (() => {
    return !values[FIELD_TERM1];
  })();

  return (
    <>
      <Title>
        <T i18nKey="terms_text_1" />
      </Title>

      <Paragraph>
        <T i18nKey="terms_text_2" />
      </Paragraph>
      <Paragraph>
        <T i18nKey="terms_text_3" />
      </Paragraph>

      <FormGroup>
        <Checkbox
          checked={values[FIELD_TERM1]}
          label={
            <Annotation>
              <T i18nKey="terms_text_4" />
            </Annotation>
          }
          name={FIELD_TERM1}
          onChange={() => setFieldValue(FIELD_TERM1, !values[FIELD_TERM1])}
        />
      </FormGroup>

      <ButtonWrapper>
        <Button disabled={disabled} onClick={handleClick} label={<T i18nKey="button_next" />} />
      </ButtonWrapper>

      <Small>
        <T i18nKey="terms_text_5" />
      </Small>
    </>
  );
}
Example #7
Source File: Age.js    From web with GNU General Public License v3.0 5 votes vote down vote up
Age = ({ onBack, onNext }) => {
  const { setFieldValue, values } = useFormikContext();

  const onChange = value => {
    setFieldValue(DIAGNOSIS_FORM_FIELDS.AGE, value);
  };

  return (
    <Layout id="view-diagnosis-age" onBackClick={onBack} hideBell>
      <Title>
        <T i18nKey="age_text1" />
      </Title>
      <FormGroup>
        <Radio
          checked={values[DIAGNOSIS_FORM_FIELDS.AGE] === IS_NOT_ELDERLY}
          label={<T i18nKey="age_text2" />}
          name="age"
          onChange={() => onChange(IS_NOT_ELDERLY)}
          testId="is-not-elderly"
        />
        <Radio
          checked={values[DIAGNOSIS_FORM_FIELDS.AGE] === IS_ELDERLY}
          label={<T i18nKey="age_text3" />}
          name="age"
          onChange={() => onChange(IS_ELDERLY)}
          testId="is-elderly"
        />
        <Radio
          checked={values[DIAGNOSIS_FORM_FIELDS.AGE] === NO_DATA}
          label={<T i18nKey="age_text4" />}
          name="age"
          onChange={() => onChange(NO_DATA)}
          testId="no-data"
        />
      </FormGroup>
      <Paragraph>
        <T i18nKey="age_text5" />
      </Paragraph>
      <Actions>
        <Button
          disabled={values[DIAGNOSIS_FORM_FIELDS.AGE] === undefined}
          onClick={() => onNext()}
          label={<T i18nKey="button_next" />}
        />
      </Actions>
    </Layout>
  );
}
Example #8
Source File: Smoke.js    From web with GNU General Public License v3.0 5 votes vote down vote up
Smoke = ({ handelGoToNextStep, t }) => {
  const { setFieldValue, values } = useFormikContext();

  const options = [
    VALUE_SMOKE_NUMBER_1,
    VALUE_SMOKE_NUMBER_2,
    VALUE_SMOKE_NUMBER_3,
    VALUE_SMOKE_NUMBER_4,
    VALUE_SMOKE_NUMBER_5
  ].map(option => ({ label: t(option), value: option }));

  const isSmoking = values[FIELD_SMOKE] === t('yes');
  const noSmoking = values[FIELD_SMOKE] === t('no');

  const handleSmokeRadio = value => {
    if (value === t('yes')) {
      setFieldValue(FIELD_SMOKE, t('yes'));
      setFieldValue(FIELD_SMOKE_NUMBER, VALUE_SMOKE_NUMBER_1);
      return;
    }

    setFieldValue(FIELD_SMOKE, t('no'));
    setFieldValue(FIELD_SMOKE_NUMBER, null);
  };

  return (
    <>
      <Title>
        <T i18nKey="smoke_text1" />
      </Title>
      <Wrapper>
        <FormGroup>
          <Radio
            checked={isSmoking}
            label={
              <Label>
                <T i18nKey="smoke_text2" />
              </Label>
            }
            name={FIELD_SMOKE}
            onChange={() => handleSmokeRadio(t('yes'))}
          />
          <Radio
            checked={noSmoking}
            label={
              <Label>
                <T i18nKey="smoke_text3" />
              </Label>
            }
            name={FIELD_SMOKE}
            onChange={() => handleSmokeRadio(t('no'))}
          />
        </FormGroup>
      </Wrapper>

      {isSmoking && (
        <Styled.SelectWrapper>
          <Select
            changeHandler={setFieldValue}
            label={<T i18nKey="smoke_text4" />}
            name={FIELD_SMOKE_NUMBER}
            options={options}
            value={values[FIELD_SMOKE_NUMBER]}
          />
        </Styled.SelectWrapper>
      )}
      <Actions>
        <Button
          disabled={!values[FIELD_SMOKE]}
          onClick={handelGoToNextStep}
          label={<T i18nKey="button_next" />}
        />
      </Actions>
    </>
  );
}
Example #9
Source File: ManualCovidState.js    From web with GNU General Public License v3.0 5 votes vote down vote up
ManualCovidState = ({ handelGoToNextStep }) => {
  const { setFieldValue, values } = useFormikContext();

  const yesManualCovid = values[FIELD_MANUAL_COVID] === true;
  const noManualCovid = values[FIELD_MANUAL_COVID] === false;

  const handleManualCovidRadio = value => {
    setFieldValue(FIELD_MANUAL_COVID, value);
  };

  return (
    <>
      <Title>
        <T i18nKey="manual_covid_state_text1" />
      </Title>
      <FormGroup>
        <Radio
          checked={yesManualCovid}
          onChange={() => handleManualCovidRadio(true)}
          name={FIELD_MANUAL_COVID}
          label={
            <Label>
              <T i18nKey="manual_covid_state_text2" />
            </Label>
          }
        />
        <Radio
          checked={noManualCovid}
          onChange={() => handleManualCovidRadio(false)}
          name={FIELD_MANUAL_COVID}
          label={
            <Label>
              <T i18nKey="manual_covid_state_text3" />
            </Label>
          }
        />
      </FormGroup>

      {noManualCovid && (
        <Styled.WarningBox>
          <Styled.Icon />
          <Styled.Description>
            <Styled.Title>
              <T i18nKey="manual_covid_state_text4" />
            </Styled.Title>
            <Styled.Paragraph>
              <T i18nKey="manual_covid_state_text5" />
            </Styled.Paragraph>
          </Styled.Description>
        </Styled.WarningBox>
      )}

      <Actions>
        <Button
          disabled={values[FIELD_MANUAL_COVID] === undefined}
          onClick={handelGoToNextStep}
          label={<T i18nKey="button_next" />}
        />
      </Actions>
    </>
  );
}
Example #10
Source File: BloodGroup.js    From web with GNU General Public License v3.0 5 votes vote down vote up
BloodGroup = ({ handelGoToNextStep }) => {
  const { setFieldValue, values } = useFormikContext();

  const renderRadios = [
    {
      text: 'AB+',
      value: VALUE_BLOOD_GROUP_ABPLUS
    },
    {
      text: 'AB-',
      value: VALUE_BLOOD_GROUP_ABMINUS
    },
    {
      text: 'A+',
      value: VALUE_BLOOD_GROUP_APLUS
    },
    {
      text: 'A-',
      value: VALUE_BLOOD_GROUP_AMINUS
    },
    {
      text: 'B+',
      value: VALUE_BLOOD_GROUP_BPLUS
    },
    {
      text: 'B-',
      value: VALUE_BLOOD_GROUP_BMINUS
    },
    {
      text: '0+',
      value: VALUE_BLOOD_GROUP_0PLUS
    },
    {
      text: '0-',
      value: VALUE_BLOOD_GROUP_0MINUS
    },
    {
      text: <T i18nKey="imprint_text6" />,
      value: VALUE_BLOOD_GROUP_UNDEFINED
    }
  ].map(({ text, value }) => (
    <Radio
      key={value}
      checked={values[FIELD_BLOOD_GROUP] === value}
      label={<Label>{text}</Label>}
      name={FIELD_BLOOD_GROUP}
      onChange={() => setFieldValue(FIELD_BLOOD_GROUP, value)}
    />
  ));

  return (
    <>
      <Title>
        <T i18nKey="blood_group_text1" />
      </Title>
      <FormGroup>{renderRadios}</FormGroup>
      <Actions>
        <Button
          disabled={!values[FIELD_BLOOD_GROUP]}
          onClick={handelGoToNextStep}
          label={<T i18nKey="button_next" />}
        />
      </Actions>
    </>
  );
}
Example #11
Source File: CreateChannelDialog.js    From dipact with GNU General Public License v3.0 5 votes vote down vote up
render() {
		return (
			<Dialog
				onEntered={helpers.genOnback(this.close)}
				open={this.state.open}
				disableBackdropClick={false}
				onClose={this.close}
			>
				<DialogTitle>Create channel</DialogTitle>
				<DialogContent>
					<DialogContentText>
						Pick the participants of the new channel.
					</DialogContentText>
					<FormGroup>
						{this.variant.Properties.Nations.map((n) => {
							return (
								<FormControlLabel
									key={n}
									control={
										<Checkbox
											disabled={n === this.member.Nation}
											checked={!!this.state.members[n]}
											onChange={this.toggleMember(n)}
										/>
									}
									label={n}
								/>
							);
						})}
					</FormGroup>
				</DialogContent>
				<DialogActions>
					<Button onClick={this.close} color="primary">
						Cancel
					</Button>
					<Button
						onClick={this.createChannel}
						color="primary"
					>
						Create
					</Button>
				</DialogActions>
			</Dialog>
		);
	}
Example #12
Source File: PageWrapper.jsx    From zubhub with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @function PageWrapper View
 * @author Raymond Ndibe <[email protected]>
 *
 * @todo - describe function's signature
 */
function PageWrapper(props) {
  const backToTopEl = React.useRef(null);
  const classes = useStyles();
  const common_classes = useCommonStyles();
  const trigger = useScrollTrigger();
  const [searchType, setSearchType] = useState(
    getQueryParams(window.location.href).get('type') || SearchType.PROJECTS,
  );
  const formRef = useRef();
  const token = useSelector(state => state.auth.token);

  const [state, setState] = React.useState({
    username: null,
    anchor_el: null,
    loading: false,
    open_search_form: false,
  });

  const [options, setOptions] = useState([]);
  const [query, setQuery] = useState('');
  const [queryInput, setQueryInput] = useState('');

  const throttledFetchOptions = useMemo(
    () =>
      throttle(async (query, searchType) => {
        if (query.length === 0) {
          setOptions([]);
          return;
        }

        const api = new API();
        let completions = [];
        if (searchType === SearchType.TAGS) {
          completions = await api.autocompleteTags({ query, token });
          completions = completions.map(({ name }) => ({
            title: name,
          }));
        } else if (searchType === SearchType.PROJECTS) {
          completions = await api.autocompleteProjects({ query, token });
          completions = completions.map(({ id, title, creator, images }) => ({
            title,
            shortInfo: creator.username,
            image: images.length > 0 ? images[0].image_url : null,
            link: `/projects/${id}`,
          }));
        } else {
          completions = await api.autocompleteCreators({ query, token });
          completions = completions.map(({ username, avatar }) => ({
            title: username,
            image: avatar,
            link: `/creators/${username}`,
          }));
        }
        setOptions(completions);
      }, 2),
    [],
  );

  useEffect(() => {
    throttledFetchOptions(
      query ||
        (props.location.search &&
          getQueryParams(window.location.href).get('q')),
      searchType,
    );
  }, [query, searchType]);

  useEffect(() => {
    throttledFetchOptions.cancel();
  }, []);

  useEffect(() => {
    handleSetState({ loading: true });
    fetchHero(props)
      .then(() => {
        if (props.auth.token) {
          return props.getAuthUser(props);
        }
      })
      .finally(() => {
        handleSetState({ loading: false });
      });
  }, [props.auth.token]);

  React.useEffect(() => {
    handleSetState(handleProfileMenuClose());
  }, [trigger]);

  const handleSetState = obj => {
    if (obj) {
      Promise.resolve(obj).then(obj => {
        setState(state => ({ ...state, ...obj }));
      });
    }
  };

  const onSearchOptionClick = async (_, option) => {
    if (!option || !option.title) return;

    await new Promise(resolve => setTimeout(resolve, 100));
    if (option.link) {
      window.history.pushState({}, '', option.link);
      window.location.reload();
      return;
    }

    const queryParams = new URLSearchParams({
      type: searchType,
      q: option.title,
    });
    window.history.pushState({}, '', `/search?${queryParams}`);
    window.location.reload();
  };

  const handleSubmit = e => {
    e.preventDefault();
    const queryParams = new URLSearchParams({
      type: searchType,
      q: query,
    });

    window.history.pushState({}, '', `/search?${queryParams}`);
    window.location.reload();
  };

  const { anchor_el, loading, open_search_form } = state;
  const { t } = props;
  const { zubhub, hero } = props.projects;

  const profileMenuOpen = Boolean(anchor_el);

  return (
    <>
      <ToastContainer />
      <CssBaseline />
      <AppBar className={classes.navBarStyle}>
        <Container className={classes.mainContainerStyle}>
          <Toolbar className={classes.toolBarStyle}>
            <Box className={classes.logoStyle}>
              <Link to="/">
                <img
                  src={zubhub?.header_logo_url ? zubhub.header_logo_url : logo}
                  alt="logo"
                />
              </Link>
              <Box
                className={clsx(
                  classes.languageSelectBoxStyle,
                  common_classes.displayInlineFlex,
                  common_classes.alignCenter,
                  common_classes.addOnSmallScreen,
                )}
              >
                <TranslateIcon />
                <Select
                  className={classes.languageSelectStyle}
                  value=""
                  onChange={e => handleChangeLanguage({ e, props })}
                >
                  {Object.keys(languageMap).map((ln, index) => (
                    <MenuItem key={index} value={ln}>
                      {languageMap[ln]}
                    </MenuItem>
                  ))}
                </Select>
              </Box>
              <Box
                className={clsx(
                  classes.languageSelectBoxStyle,
                  common_classes.displayInlineFlex,
                  common_classes.alignCenter,
                  common_classes.removeOnSmallScreen,
                )}
              >
                <TranslateIcon />
                <Select
                  className={classes.languageSelectStyle}
                  value={props.i18n.language}
                  onChange={e => handleChangeLanguage({ e, props })}
                >
                  {Object.keys(languageMap).map((ln, index) => (
                    <MenuItem key={index} value={ln}>
                      {languageMap[ln]}
                    </MenuItem>
                  ))}
                </Select>
              </Box>
              <form
                action="/search"
                className={clsx(classes.searchFormStyle, classes.removeOn894)}
                role="search"
                onSubmit={handleSubmit}
                ref={formRef}
              >
                <FormControl variant="outlined">
                  <InputLabel
                    htmlFor="q"
                    className={classes.searchFormLabelStyle}
                  >
                    {t('pageWrapper.inputs.search.label')}
                  </InputLabel>
                  <FormGroup row>
                    <FormControl variant="outlined">
                      <InputSelect
                        searchType={searchType}
                        onSearchTypeChange={setSearchType}
                        name="type"
                      >
                        <MenuItem value={SearchType.PROJECTS}>
                          Projects
                        </MenuItem>
                        <MenuItem value={SearchType.CREATORS}>
                          Creators
                        </MenuItem>
                        <MenuItem value={SearchType.TAGS}>Tags</MenuItem>
                      </InputSelect>
                    </FormControl>
                    <Autocomplete
                      options={options}
                      defaultValue={{
                        title:
                          props.location.search &&
                          getQueryParams(window.location.href).get('q'),
                      }}
                      renderOption={(option, { inputValue }) => (
                        <Option
                          option={option}
                          inputValue={inputValue}
                          onOptionClick={onSearchOptionClick}
                        />
                      )}
                      onChange={onSearchOptionClick}
                    >
                      {params => (
                        <TextField
                          name="q"
                          id="q"
                          type="search"
                          variant="outlined"
                          {...params}
                          InputProps={{
                            ...params.InputProps,
                            className: clsx(
                              classes.searchFormInputStyle,
                              'search-form-input',
                            ),
                            endAdornment: (
                              <InputAdornment position="end">
                                <IconButton
                                  type="submit"
                                  className={classes.searchFormSubmitStyle}
                                  aria-label={t(
                                    'pageWrapper.inputs.search.label',
                                  )}
                                >
                                  <SearchIcon />
                                </IconButton>
                              </InputAdornment>
                            ),
                            pattern: '(.|s)*S(.|s)*',
                            defaultValue: {
                              title:
                                props.location.search &&
                                getQueryParams(window.location.href).get('q'),
                            },
                          }}
                          onChange={e => setQuery(e.target.value)}
                          placeholder={`${t(
                            'pageWrapper.inputs.search.label',
                          )}...`}
                        />
                      )}
                    </Autocomplete>
                  </FormGroup>
                </FormControl>
              </form>
            </Box>
            <div className={classes.navActionStyle}>
              {!props.auth.token ? (
                <>
                  <IconButton
                    className={clsx(
                      classes.toggleSearchFormStyle,
                      classes.addOn894,
                    )}
                    id="toggle-search"
                    aria-label="toggle search form"
                    onClick={() =>
                      handleSetState(handleToggleSearchForm(state))
                    }
                  >
                    <SearchIcon />
                  </IconButton>
                  <Link
                    className={clsx(
                      classes.textDecorationNone,
                      common_classes.removeOnSmallScreen,
                    )}
                    to="/login"
                  >
                    <CustomButton
                      variant="outlined"
                      size="large"
                      secondaryButtonStyle
                      customButtonStyle
                    >
                      {t('pageWrapper.navbar.login')}
                    </CustomButton>
                  </Link>
                  <Link
                    className={clsx(
                      classes.textDecorationNone,
                      common_classes.removeOnSmallScreen,
                    )}
                    to="/signup"
                  >
                    <CustomButton
                      variant="contained"
                      size="large"
                      primaryButtonStyle
                      customButtonStyle
                      className={common_classes.marginLeft1em}
                    >
                      {t('pageWrapper.navbar.signup')}
                    </CustomButton>
                  </Link>

                  <MenuRoundedIcon
                    className={common_classes.addOnSmallScreen}
                    aria-label={t('pageWrapper.navbar.menu')}
                    aria-controls="menu"
                    aria-haspopup="true"
                    onClick={e => handleSetState(handleProfileMenuOpen(e))}
                  />
                  <Menu
                    className={common_classes.addOnSmallScreen}
                    disableScrollLock={true}
                    id="menu"
                    anchorEl={anchor_el}
                    anchorOrigin={{
                      vertical: 'top',
                      horizontal: 'right',
                    }}
                    keepMounted
                    transformOrigin={{
                      vertical: 'top',
                      horizontal: 'right',
                    }}
                    open={profileMenuOpen}
                    onClose={e => handleSetState(handleProfileMenuClose(e))}
                  >
                    <MenuItem>
                      <Link className={classes.textDecorationNone} to="/login">
                        <Typography
                          variant="subtitle2"
                          color="textPrimary"
                          component="span"
                        >
                          {t('pageWrapper.navbar.login')}
                        </Typography>
                      </Link>
                    </MenuItem>
                    <MenuItem>
                      <Link className={classes.textDecorationNone} to="/signup">
                        <Typography
                          variant="subtitle2"
                          color="textPrimary"
                          component="span"
                        >
                          {t('pageWrapper.navbar.signup')}
                        </Typography>
                      </Link>
                    </MenuItem>
                  </Menu>
                </>
              ) : (
                <>
                  <Link
                    className={clsx(
                      classes.textDecorationNone,
                      common_classes.marginRight1em,
                      common_classes.removeOnSmallScreen,
                    )}
                    to="/projects/create"
                  >
                    <CustomButton
                      variant="contained"
                      primaryButtonStyle
                      customButtonStyle
                      size="small"
                    >
                      {t('pageWrapper.navbar.createProject')}
                    </CustomButton>
                  </Link>
                  <IconButton
                    className={clsx(
                      classes.toggleSearchFormStyle,
                      classes.addOn894,
                    )}
                    id="toggle-search"
                    aria-label="toggle search form"
                    onClick={() =>
                      handleSetState(handleToggleSearchForm(state))
                    }
                  >
                    <SearchIcon />
                  </IconButton>
                  <NotificationButton
                    className={clsx(
                      common_classes.marginRight1em,
                      common_classes.removeOnSmallScreen,
                    )}
                  />
                  <Avatar
                    className={clsx(
                      classes.avatarStyle,
                      common_classes.removeOnSmallScreen,
                    )}
                    aria-label={`${props.auth.username}' Avatar`}
                    aria-controls="profile_menu"
                    aria-haspopup="true"
                    onClick={e => handleSetState(handleProfileMenuOpen(e))}
                    src={props.auth.avatar}
                    alt={props.auth.username}
                  />
                  <Menu
                    className={classes.profileMenuStyle}
                    disableScrollLock={true}
                    id="profile_menu"
                    anchorEl={anchor_el}
                    anchorOrigin={{
                      vertical: 'top',
                      horizontal: 'right',
                    }}
                    keepMounted
                    transformOrigin={{
                      vertical: 'top',
                      horizontal: 'right',
                    }}
                    open={profileMenuOpen}
                    onClose={e => handleSetState(handleProfileMenuClose(e))}
                  >
                    <MenuItem>
                    <Tooltip title={props.auth.username} placement="top">
                      <Typography
                        variant="subtitle2"
                        color="textPrimary"
                        component="span"
                        className={classes.profileStyle}
                      >
                        {props.auth.username }
                      </Typography>
                      </Tooltip>
                    </MenuItem>
                    <MenuItem>
                      <a className={classes.textDecorationNone} href="/profile">
                        <Typography
                          variant="subtitle2"
                          color="textPrimary"
                          component="span"
                        >
                          {t('pageWrapper.navbar.profile')}
                        </Typography>
                      </a>
                    </MenuItem>
                    <MenuItem className={common_classes.addOnSmallScreen}>
                      <Link
                        className={classes.textDecorationNone}
                        to="/projects/create"
                      >
                        <Typography
                          variant="subtitle2"
                          color="textPrimary"
                          component="span"
                        >
                          {t('pageWrapper.navbar.createProject')}
                        </Typography>
                      </Link>
                    </MenuItem>
                    <MenuItem>
                      <Link
                        className={classes.textDecorationNone}
                        to={`/creators/${props.auth.username}/projects`}
                      >
                        <Typography
                          variant="subtitle2"
                          color="textPrimary"
                          component="span"
                        >
                          {t('pageWrapper.navbar.projects')}
                        </Typography>
                      </Link>
                    </MenuItem>
                    <MenuItem>
                      <Link
                        className={classes.textDecorationNone}
                        to={`/creators/${props.auth.username}/followers`}
                      >
                        <Typography
                          variant="subtitle2"
                          color="textPrimary"
                          component="span"
                        >
                          {t('pageWrapper.navbar.followers')}
                        </Typography>
                      </Link>
                    </MenuItem>
                    <MenuItem>
                      <Link
                        className={classes.textDecorationNone}
                        to={`/creators/${props.auth.username}/following`}
                      >
                        <Typography
                          variant="subtitle2"
                          color="textPrimary"
                          component="span"
                        >
                          {t('pageWrapper.navbar.following')}
                        </Typography>
                      </Link>
                    </MenuItem>
                    <MenuItem>
                      <Link
                        className={classes.textDecorationNone}
                        to="/projects/saved"
                      >
                        <Typography
                          variant="subtitle2"
                          color="textPrimary"
                          component="span"
                        >
                          {t('pageWrapper.navbar.savedProjects')}
                        </Typography>
                      </Link>
                    </MenuItem>
                    <MenuItem className={classes.logOutStyle}>
                      <Typography
                        className={common_classes.colorRed}
                        variant="subtitle2"
                        component="span"
                        onClick={e => logout(e, props)}
                      >
                        {t('pageWrapper.navbar.logout')}
                      </Typography>
                    </MenuItem>
                  </Menu>
                </>
              )}
            </div>
          </Toolbar>
          {open_search_form ? (
            <ClickAwayListener
              onClickAway={e => handleSetState(closeSearchFormOrIgnore(e))}
            >
              <form
                action="/search"
                className={clsx(classes.smallSearchFormStyle, classes.addOn894)}
                role="search"
                ref={formRef}
              >
                <FormControl variant="outlined" style={{ minWidth: 'unset' }}>
                  <InputSelect
                    searchType={searchType}
                    onSearchTypeChange={setSearchType}
                    name="type"
                  >
                    <MenuItem value={SearchType.PROJECTS}>Projects</MenuItem>
                    <MenuItem value={SearchType.CREATORS}>Creators</MenuItem>
                    <MenuItem value={SearchType.TAGS}>Tags</MenuItem>
                  </InputSelect>
                </FormControl>
                <FormControl
                  variant="outlined"
                  style={{ flex: '1 1 auto', maxWidth: '350px' }}
                >
                  <InputLabel
                    htmlFor="q"
                    className={classes.searchFormLabelStyle}
                  >
                    {t('pageWrapper.inputs.search.label')}
                  </InputLabel>
                  <Autocomplete
                    options={options}
                    defaultValue={
                      props.location.search &&
                      getQueryParams(window.location.href).get('q')
                    }
                    renderOption={(option, { inputValue }) => (
                      <Option
                        option={option}
                        inputValue={inputValue}
                        onOptionClick={onSearchOptionClick}
                      />
                    )}
                    onChange={onSearchOptionClick}
                  >
                    {params => (
                      <TextField
                        name="q"
                        id="q"
                        type="search"
                        variant="outlined"
                        {...params}
                        InputProps={{
                          ...params.InputProps,
                          className: clsx(
                            classes.smallSearchFormInputStyle,
                            'search-form-input',
                          ),
                          endAdornment: (
                            <InputAdornment position="end">
                              <IconButton
                                type="submit"
                                className={classes.searchFormSubmitStyle}
                                aria-label={t(
                                  'pageWrapper.inputs.search.label',
                                )}
                              >
                                <SearchIcon />
                              </IconButton>
                            </InputAdornment>
                          ),
                          pattern: '(.|s)*S(.|s)*',
                        }}
                        placeholder={`${t(
                          'pageWrapper.inputs.search.label',
                        )}...`}
                        onChange={e => setQuery(e.target.value)}
                      />
                    )}
                  </Autocomplete>
                </FormControl>
              </form>
            </ClickAwayListener>
          ) : null}
        </Container>
      </AppBar>
      <Toolbar ref={backToTopEl} />

      {loading ? <LoadingPage /> : props.children}

      <footer className={clsx('footer-distributed', classes.footerStyle)}>
        <Box>
          <a href="https://unstructured.studio">
            <img
              src={
                zubhub?.footer_logo_url
                  ? zubhub.footer_logo_url
                  : unstructuredLogo
              }
              className={classes.footerLogoStyle}
              alt="unstructured-studio-logo"
            />
          </a>
          <div>
            <Box
              className={clsx(
                classes.languageSelectBoxStyle,
                common_classes.displayInlineFlex,
                common_classes.alignCenter,
                common_classes.addOnSmallScreen,
              )}
            >
              <TranslateIcon />
              <Select
                className={classes.languageSelectStyle}
                value=""
                onChange={e => handleChangeLanguage({ e, props })}
              >
                {Object.keys(languageMap).map((ln, index) => (
                  <MenuItem key={index} value={ln}>
                    {languageMap[ln]}
                  </MenuItem>
                ))}
              </Select>
            </Box>
            <Box
              className={clsx(
                classes.languageSelectBoxStyle,
                common_classes.displayInlineFlex,
                common_classes.alignCenter,
                common_classes.removeOnSmallScreen,
              )}
            >
              <TranslateIcon />
              <Select
                className={classes.languageSelectStyle}
                value={props.i18n.language}
                onChange={e => handleChangeLanguage({ e, props })}
              >
                {Object.keys(languageMap).map((ln, index) => (
                  <MenuItem key={index} value={ln}>
                    {languageMap[ln]}
                  </MenuItem>
                ))}
              </Select>
            </Box>
          </div>
        </Box>

        <section className={classes.footerSectionStyle}>
          <Box className={classes.footerBoxStyle}>
            <Typography
              variant="subtitle2"
              color="textPrimary"
              className={classes.footerTitleStyle}
            >
              {t('pageWrapper.footer.privacy')}
            </Typography>

            <Link
              to={`/privacy_policy`}
              className={common_classes.textDecorationNone}
            >
              <Typography
                variant="subtitle2"
                color="textPrimary"
                className={classes.footerLinkStyle}
              >
                {t('pageWrapper.footer.guidelines')}
              </Typography>
            </Link>

            <Link
              to={`/terms_of_use`}
              className={common_classes.textDecorationNone}
            >
              <Typography
                variant="subtitle2"
                color="textPrimary"
                className={classes.footerLinkStyle}
              >
                {t('pageWrapper.footer.termsOfUse')}
              </Typography>
            </Link>
          </Box>

          <Box className={classes.footerBoxStyle}>
            <Typography
              variant="subtitle2"
              color="textPrimary"
              className={classes.footerTitleStyle}
            >
              {t('pageWrapper.footer.about')}
            </Typography>

            <Link to="/about" className={common_classes.textDecorationNone}>
              <Typography
                variant="subtitle2"
                color="textPrimary"
                className={classes.footerLinkStyle}
              >
                {t('pageWrapper.footer.zubhub')}
              </Typography>
            </Link>
          </Box>

          <Box className={classes.footerBoxStyle}>
            <Typography
              variant="subtitle2"
              color="textPrimary"
              className={classes.footerTitleStyle}
            >
              {t('pageWrapper.footer.help')}
            </Typography>

            <a
              target="__blank"
              rel="noreferrer"
              href={
                hero.tinkering_resource_url
                  ? hero.tinkering_resource_url
                  : 'https://kriti.unstructured.studio/'
              }
              className={common_classes.textDecorationNone}
            >
              <Typography
                variant="subtitle2"
                color="textPrimary"
                className={classes.footerLinkStyle}
              >
                {t('pageWrapper.footer.resources')}
              </Typography>
            </a>

            <Link
              to={`/faqs`}
              className={clsx(
                common_classes.textDecorationNone,
                common_classes.displayNone,
              )}
            >
              <Typography
                variant="subtitle2"
                color="textPrimary"
                className={classes.footerLinkStyle}
              >
                {t('pageWrapper.footer.faqs')}
              </Typography>
            </Link>

            <a
              href="mailto:[email protected]"
              className={common_classes.textDecorationNone}
            >
              <Typography
                variant="subtitle2"
                color="textPrimary"
                className={classes.footerLinkStyle}
              >
                {t('pageWrapper.footer.contactUs')}
              </Typography>
            </a>
          </Box>
        </section>

        <Zoom in={useScrollTrigger}>
          <div
            onClick={e => handleScrollTopClick(e, backToTopEl)}
            role="presentation"
            className={classes.scrollTopButtonStyle}
          >
            <Fab color="secondary" size="small" aria-label="scroll back to top">
              <KeyboardArrowUpIcon />
            </Fab>
          </div>
        </Zoom>
      </footer>
    </>
  );
}
Example #13
Source File: AddEditCollege.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditCollege = props => {
  const history = useHistory();
  const classes = useStyles();

  const [formState, setFormState] = useState({
    backDrop: false,
    isValid: false,
    values: {},
    adminValues: {},
    touched: {},
    errors: {},
    states: [],
    isSuccess: false,
    dynamicBar: [{ index: Math.random() }],
    dynamicBarError: [],
    isEditCollege: props["editCollege"] ? props["editCollege"] : false,
    dataForEdit: props["dataForEdit"] ? props["dataForEdit"] : {},
    counter: 0,
    isStateClearFilter: false,
    showing: false,
    dataToShowForMultiSelect: [],
    addresses: genericConstants.COLLEGE_ADDRESSES,
    isCollegeAdmin:
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
        ? true
        : false
  });
  const { className, ...rest } = props;
  const [user, setUser] = useState([]);
  const [states, setStates] = useState(
    props.stateOption ? props.stateOption : []
  );
  const [zones, setZones] = useState(props.zoneOption ? props.zoneOption : []);
  const [rpcs, setRpcs] = useState(props.rpcOption ? props.rpcOption : []);
  const [districts, setDistricts] = useState(
    props.districtOption ? props.districtOption : []
  );
  const [streamsData, setStreamsData] = useState([]);
  const [streamsDataBackup, setStreamsDataBackup] = useState([]);
  const [isGetAdminData, setIsGetAdminData] = useState(false);
  const [tpoData, setTpoData] = useState([]);
  const [principalData, setPrincipalData] = useState([]);
  const [validateAddress, setValidateAddress] = useState([]);
  const inputLabel = React.useRef(null);
  const [collegeInfo, setCollegeInfo] = useState({
    college:
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
        ? auth.getUserInfo().studentInfo &&
          auth.getUserInfo().studentInfo.organization
          ? auth.getUserInfo().studentInfo.organization
          : {}
        : {},
    state:
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
        ? auth.getUserInfo().state
        : {},
    rpc:
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
        ? auth.getUserInfo().rpc
        : {},
    zone:
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
        ? auth.getUserInfo().zone
        : {}
  });

  React.useEffect(() => {
    if (
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.MEDHAADMIN
    ) {
      setFormState(formState => ({
        ...formState,
        showing: true
      }));
    } else if (
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
    ) {
      setFormState(formState => ({
        ...formState,
        showing: false
      }));
    }
  }, []);

  /** Part for editing college */
  if (formState.isEditCollege && !formState.counter) {
    formState.backDrop = true;
    if (props["dataForEdit"]) {
      if (props["dataForEdit"]["name"]) {
        formState.values[collegeName] = props["dataForEdit"]["name"];
      }
      if (props["dataForEdit"]["college_code"]) {
        formState.values[collegeCode] = props["dataForEdit"]["college_code"];
      }
      if (props["dataForEdit"]["contact"]) {
        formState.addresses =
          props["dataForEdit"]["contact"]["addresses"].length > 0
            ? props["dataForEdit"]["contact"]["addresses"]
            : genericConstants.COLLEGE_ADDRESSES;
      }
      if (props["dataForEdit"]["contact"]) {
        formState.values[contactNumber] =
          props["dataForEdit"]["contact"]["phone"];
      }
      if (props["dataForEdit"]["contact"]) {
        formState.values[collegeEmail] =
          props["dataForEdit"]["contact"]["email"];
      }
      // if (
      //   props["dataForEdit"]["contact"] &&
      //   props["dataForEdit"]["contact"]["state"]
      // ) {
      //   formState.values["state"] = props["dataForEdit"]["contact"]["state"];
      // }
      // if (
      //   props["dataForEdit"]["contact"] &&
      //   props["dataForEdit"]["contact"]["district"]
      // ) {
      //   formState.values[district] =
      //     props["dataForEdit"]["contact"]["district"]["id"];
      // }
      if (props["dataForEdit"]["blocked"]) {
        formState.values[block] = props["dataForEdit"]["blocked"];
      }
      if (props["dataForEdit"]["zone"]) {
        formState.values["zone"] = props["dataForEdit"]["zone"]["id"];
      }
      if (props["dataForEdit"]["rpc"]) {
        formState.values["rpc"] = props["dataForEdit"]["rpc"]["id"];
      }
      if (
        props["dataForEdit"]["principal"] &&
        props["dataForEdit"]["principal"]["contact"] &&
        props["dataForEdit"]["principal"]["contact"]["user"]
      ) {
        formState.values[principal] =
          props["dataForEdit"]["principal"]["contact"]["user"];
        formState.adminValues[principal] =
          props["dataForEdit"]["principal"]["contact"]["individual"];
      }
      if (
        props["dataForEdit"]["stream_strength"] &&
        props["dataForEdit"]["stream_strength"].length
      ) {
        let dynamicBar = [];
        for (let i in props["dataForEdit"]["stream_strength"]) {
          let tempDynamicBarrValue = {};
          tempDynamicBarrValue["index"] = Math.random();
          tempDynamicBarrValue[streams] =
            props["dataForEdit"]["stream_strength"][i]["stream"]["id"];
          tempDynamicBarrValue[firstYearStrength] = props["dataForEdit"][
            "stream_strength"
          ][i]["first_year_strength"].toString();
          tempDynamicBarrValue[secondYearStrength] = props["dataForEdit"][
            "stream_strength"
          ][i]["second_year_strength"].toString();
          tempDynamicBarrValue[thirdYearStrength] = props["dataForEdit"][
            "stream_strength"
          ][i]["third_year_strength"].toString();
          dynamicBar.push(tempDynamicBarrValue);
        }
        formState.dynamicBar = dynamicBar;
      }
      formState.backDrop = false;

      formState.counter += 1;
    }
  }

  /** Here we initialize our data and bring users, states and streams*/
  useEffect(() => {
    formState.backDrop = true;
    let paramsForPageSize = {
      name_contains: "Uttar Pradesh"
    };

    serviceProviders
      .serviceProviderForGetRequest(STATES_URL, paramsForPageSize)
      .then(res => {
        formState.states = res.data.result;
        setStates(res.data.result);
      })
      .catch(error => {
        console.log("error", error);
      });

    // let params = {
    //   pageSize: -1,
    //   "state.name": "Uttar Pradesh"
    // };
    // serviceProviders
    //   .serviceProviderForGetRequest(DISTRICTS_URL, params)
    //   .then(res => {
    //     setDistricts(res.data.result);
    //   })
    //   .catch(error => {
    //     console.log("error", error);
    //   });
    serviceProviders
      .serviceProviderForGetRequest(STREAMS_URL, {
        pageSize: -1
      })
      .then(res => {
        setStreamsDataBackup(res.data.result);
      })
      .catch(error => {
        console.log("error", error);
      });
    serviceProviders
      .serviceProviderForGetRequest(STREAMS_URL, {
        pageSize: -1
      })
      .then(res => {
        let dataForEditing = res.data.result;
        if (formState.isEditCollege) {
          let tempStreamData = dataForEditing;
          let streamStrengthArray = props["dataForEdit"]["stream_strength"];
          for (let i in streamStrengthArray) {
            let id = streamStrengthArray[i]["stream"]["id"];
            for (let j in tempStreamData) {
              if (tempStreamData[j]["id"] === id) tempStreamData.splice(j, 1);
            }
          }
          setStreamsData(tempStreamData);
        } else {
          setStreamsData(dataForEditing);
        }
      })
      .catch(error => {
        console.log("error", error);
      });
    formState.backDrop = false;
  }, []);

  /** Gets data for Principals and tpos */
  useEffect(() => {
    fetchCollegeAdminData();
    return () => {};
  }, []);

  async function fetchCollegeAdminData() {
    if (auth.getUserInfo().role.name === roleConstants.MEDHAADMIN) {
      if (formState.isEditCollege) {
        let user_url =
          COLLEGES_URL +
          "/" +
          formState.dataForEdit["id"] +
          "/" +
          strapiConstants.STRAPI_ADMIN;
        serviceProviders
          .serviceProviderForGetRequest(user_url)
          .then(res => {
            setUser(res.data.result);
            prePopulateDataForTpo(res.data.result);
          })
          .catch(error => {
            console.log("error", error);
          });
      } else {
        setUser([]);
      }
    } else if (auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN) {
      const studentId =
        auth.getUserInfo() !== null &&
        auth.getUserInfo().studentInfo &&
        auth.getUserInfo().studentInfo.organization &&
        auth.getUserInfo().studentInfo.organization.id
          ? auth.getUserInfo().studentInfo.organization.id
          : null;
      let user_url =
        COLLEGES_URL + "/" + studentId + "/" + strapiConstants.STRAPI_ADMIN;
      serviceProviders
        .serviceProviderForGetRequest(user_url)
        .then(res => {
          setUser(res.data.result);
          prePopulateDataForTpo(res.data.result);
        })
        .catch(error => {
          console.log("error", error);
        });
    }
  }

  const prePopulateDataForTpo = tpoData => {
    if (formState.isEditCollege) {
      if (
        props["dataForEdit"]["tpos"] &&
        props["dataForEdit"]["tpos"].length !== 0
      ) {
        let array = [];
        tpoData.map(tpo => {
          for (let i in props["dataForEdit"]["tpos"]) {
            if (
              props["dataForEdit"]["tpos"][i]["contact"]["individual"] ===
              tpo["id"]
            ) {
              array.push(tpo);
            }
          }
        });
        setFormState(formState => ({
          ...formState,
          dataToShowForMultiSelect: array
        }));
        let finalData = [];
        for (let i in props["dataForEdit"]["tpos"]) {
          finalData.push(
            props["dataForEdit"]["tpos"][i]["contact"]["individual"]
          );
        }
        let finalDataId = [];
        for (let i in props["dataForEdit"]["tpos"]) {
          finalDataId.push(props["dataForEdit"]["tpos"][i]["id"]);
        }
        formState.values[tpos] = finalDataId;
        formState.adminValues[tpos] = finalData;
      }
    }
  };

  /** This gets data into zones, rpcs and districts when we change the state */
  useEffect(() => {
    if (formState.addresses[0][state]) {
      fetchZoneRpcDistrictData();
    }
    return () => {};
  }, [formState.addresses[0][state]]);

  /** Common function to get zones, rpcs, districts after changing state */
  async function fetchZoneRpcDistrictData() {
    let zones_url =
      STATES_URL +
      "/" +
      formState.addresses[0][state] +
      "/" +
      strapiConstants.STRAPI_ZONES;

    await serviceProviders
      .serviceProviderForGetRequest(zones_url)
      .then(res => {
        setZones(res.data.result);
      })
      .catch(error => {
        console.log("error", error);
      });

    let rpcs_url =
      STATES_URL +
      "/" +
      formState.addresses[0][state] +
      "/" +
      strapiConstants.STRAPI_RPCS;

    await serviceProviders
      .serviceProviderForGetRequest(rpcs_url)
      .then(res => {
        if (Array.isArray(res.data)) {
          setRpcs(res.data[0].result);
        } else {
          setRpcs(res.data.result);
        }
      })
      .catch(error => {
        console.log("error", error);
      });
    let params = {
      pageSize: -1,
      "state.name": "Uttar Pradesh"
    };
    serviceProviders
      .serviceProviderForGetRequest(DISTRICTS_URL, params)
      .then(res => {
        setDistricts(res.data.result);
      })
      .catch(error => {
        console.log("error", error);
      });
    // let params = {
    //   pageSize: -1,
    //   "state.id": formState.values[state]
    // };

    // if (formState.values[state] !== undefined) {
    //   await serviceProviders
    //     .serviceProviderForGetRequest(DISTRICTS_URL, params)
    //     .then(res => {
    //       setDistricts(res.data.result);
    //     })
    //     .catch(error => {
    //       console.log("error", error);
    //     });
    // }
  }

  /** This gets Principal Email and contact number*/
  useEffect(() => {
    if (formState.adminValues[principal]) {
      getPrincipalName(formState.adminValues[principal]);
    } else {
      setIsGetAdminData(false);
      setPrincipalData([]);
    }
    return () => {};
  }, [formState.adminValues[principal]]);

  const getPrincipalName = ID => {
    let principalURL;
    principalURL =
      strapiConstants.STRAPI_DB_URL +
      strapiConstants.STRAPI_VIEW_USERS +
      "/" +
      ID;
    serviceProviders
      .serviceProviderForGetRequest(principalURL)
      .then(res => {
        setIsGetAdminData(true);
        setPrincipalData(res.data.result);
      })
      .catch(error => {
        setIsGetAdminData(false);
        console.log("error", error, error.response);
      });
  };

  /** This gets TPOs Email and contact number */
  useEffect(() => {
    if (formState.adminValues[tpos]) {
      setTpoData([]);
      getTpoName(formState.adminValues[tpos]);
    } else {
      setIsGetAdminData(false);
      setTpoData([]);
    }
    return () => {};
  }, [formState.adminValues[tpos]]);

  const getTpoName = ID => {
    let tpoURL = [];
    for (let i = 0; i < ID.length; i++) {
      tpoURL[i] =
        strapiConstants.STRAPI_DB_URL +
        strapiConstants.STRAPI_VIEW_USERS +
        "/" +
        ID[i];
    }
    serviceProviders
      .serviceProviderForAllGetRequest(tpoURL)
      .then(res => {
        let tpoarray = [];
        for (let j = 0; j < res.length; j++) {
          tpoarray.push(res[j].data.result);
        }
        setTpoData(tpoarray);
      })
      .catch(error => {
        setIsGetAdminData(false);
        console.log("error", error);
      });
  };

  /** Handle change for text fields */
  const handleChange = e => {
    e.persist();
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [e.target.name]:
          e.target.type === "checkbox" ? e.target.checked : e.target.value
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      }
    }));
    if (formState.errors.hasOwnProperty(e.target.name)) {
      delete formState.errors[e.target.name];
    }
  };

  /** Handle change for autocomplete fields */
  const handleChangeAutoComplete = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (eventName === tpos) {
      formState.dataToShowForMultiSelect = value;
    }
    if (get(CollegeFormSchema[eventName], "type") === "multi-select") {
      let finalValues = [];
      let finalIds = [];
      for (let i in value) {
        finalValues.push(value[i]["contact"]["user"]["id"]);
        finalIds.push(value[i]["id"]);
      }
      value = {
        id: finalValues,
        tpoId: finalIds
      };
    }
    if (value !== null) {
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          [eventName]: value.id
        },
        touched: {
          ...formState.touched,
          [eventName]: true
        },
        isStateClearFilter: false
      }));
      if (eventName === tpos) {
        setFormState(formState => ({
          ...formState,
          values: {
            ...formState.values,
            [eventName]: value.id
          },
          adminValues: {
            ...formState.adminValues,
            [eventName]: value.tpoId
          },
          touched: {
            ...formState.touched,
            [eventName]: true
          },
          isStateClearFilter: false
        }));
      }
      if (eventName === principal) {
        setFormState(formState => ({
          ...formState,
          values: {
            ...formState.values,
            [eventName]: value.contact.user.id
          },
          adminValues: {
            ...formState.adminValues,
            [eventName]: value.id
          },
          touched: {
            ...formState.touched,
            [eventName]: true
          },
          isStateClearFilter: false
        }));
      }
      if (eventName === state) {
        fetchZoneRpcDistrictData();
      }
      /** This is used to remove any existing errors if present in auto complete */
      if (formState.errors.hasOwnProperty(eventName)) {
        delete formState.errors[eventName];
      }
    } else {
      let setStateFilterValue = false;
      /** If we click cross for state the zone and rpc should clear off! */
      if (eventName === state) {
        /** 
        This flag is used to determine that state is cleared which clears 
        off zone and rpc by setting their value to null 
        */
        setStateFilterValue = true;
        /** 
        When state is cleared then clear rpc and zone 
        */
        setRpcs([]);
        setZones([]);
        setDistricts([]);
        delete formState.values[zone];
        delete formState.values[rpc];
        delete formState.values[district];
      }
      setFormState(formState => ({
        ...formState,
        isStateClearFilter: setStateFilterValue
      }));
      /** This is used to remove clear out data form auto complete when we click cross icon of auto complete */
      delete formState.values[eventName];
      delete formState.adminValues[eventName];
    }
  };

  /** Dynamic bar */
  const addNewRow = e => {
    e.persist();
    setFormState(formState => ({
      ...formState,
      dynamicBar: [...formState.dynamicBar, { index: Math.random() }]
    }));
  };
  const clickOnDelete = (record, index) => {
    setFormState(formState => ({
      ...formState,
      dynamicBar: formState.dynamicBar.filter(r => r !== record)
    }));
    if (record[streams]) {
      let streamsTempArray = [];
      streamsTempArray = streamsData;
      streamsDataBackup.map(streams => {
        if (record["streams"] === streams["id"]) {
          streamsTempArray.push(streams);
        }
      });
      setStreamsData(streamsTempArray);
    }
  };

  /** Handling multi select values for dynamic bar */
  const handleChangeForDynamicGrid = (
    eventName,
    event,
    selectedValueForAutoComplete,
    dynamicGridValue,
    isAutoComplete,
    isTextBox
  ) => {
    event.persist();
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (isAutoComplete) {
      if (selectedValueForAutoComplete !== null) {
        setFormState(formState => ({
          ...formState,
          dynamicBar: formState.dynamicBar.map(r => {
            if (r["index"] === dynamicGridValue["index"]) {
              let streamsTempArray = [];
              streamsData.map(streams => {
                if (streams["id"] !== selectedValueForAutoComplete["id"]) {
                  streamsTempArray.push(streams);
                }
              });
              setStreamsData(streamsTempArray);
              r[eventName] = selectedValueForAutoComplete["id"];
              return r;
            } else {
              return r;
            }
          })
        }));
      } else {
        /** This is used to remove clear out data form auto complete when we click cross icon of auto complete */
        setFormState(formState => ({
          ...formState,
          dynamicBar: formState.dynamicBar.map(r => {
            if (r["index"] === dynamicGridValue["index"]) {
              let streamsTempArray = [];
              streamsTempArray = streamsData;
              streamsDataBackup.map(streams => {
                if (r[eventName] === streams["id"]) {
                  streamsTempArray.push(streams);
                }
              });
              setStreamsData(streamsTempArray);
              delete r[eventName];
              return r;
            } else {
              return r;
            }
          })
        }));
      }
    }
    if (isTextBox) {
      if (
        event.target.value === "" ||
        regexForPercentage.test(event.target.value)
      ) {
        setFormState(formState => ({
          ...formState,
          dynamicBar: formState.dynamicBar.map(r => {
            if (r["index"] === dynamicGridValue["index"]) {
              r[eventName] = event.target.value;
              if (r[eventName] === "") {
                delete r[eventName];
              }
              return r;
            } else {
              return r;
            }
          })
        }));
      }
    }
    /** Clear errors if any */
    formState.dynamicBarError.map(errorValues => {
      if (errorValues["index"] === dynamicGridValue["index"]) {
        delete errorValues[eventName];
      }
    });
  };

  /** Validate DynamicGrid */
  const validateDynamicGridValues = () => {
    let validationCounter = 0;
    /** Empty the error array of dynamic bar */
    formState.dynamicBarError = [];
    formState.dynamicBar.map(value => {
      let valueToPutInDynmicBarError = {};
      valueToPutInDynmicBarError["index"] = value["index"];
      /** Validate dyanmic bar */
      if (
        value.hasOwnProperty(streams) &&
        (!value.hasOwnProperty(firstYearStrength) ||
          !value.hasOwnProperty(secondYearStrength) ||
          !value.hasOwnProperty(thirdYearStrength))
      ) {
        if (!value.hasOwnProperty(firstYearStrength))
          valueToPutInDynmicBarError[firstYearStrength] = "Required";

        if (!value.hasOwnProperty(secondYearStrength))
          valueToPutInDynmicBarError[secondYearStrength] = "Required";

        if (!value.hasOwnProperty(thirdYearStrength))
          valueToPutInDynmicBarError[thirdYearStrength] = "Required";

        validationCounter += 1;
      } else if (
        value.hasOwnProperty(firstYearStrength) &&
        value.hasOwnProperty(secondYearStrength) &&
        value.hasOwnProperty(thirdYearStrength) &&
        !value.hasOwnProperty(streams)
      ) {
        valueToPutInDynmicBarError[streams] =
          "Stream is required as Strength is present";
        validationCounter += 1;
      }
      formState.dynamicBarError.push(valueToPutInDynmicBarError);
    });
    if (validationCounter > 0) {
      return false;
    } else {
      return true;
    }
  };

  const handleSubmit = event => {
    const isValidAddress = validateAddresses();
    /** Validate DynamicGrid */
    let isDynamicBarValid;
    isDynamicBarValid = validateDynamicGridValues();
    /** Validate rest other valuesv */
    let isValid = false;
    let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
      formState.values,
      CollegeFormSchema
    );
    if (checkAllFieldsValid) {
      /** Evaluated only if all keys are valid inside formstate */
      formState.errors = formUtilities.setErrors(
        formState.values,
        CollegeFormSchema
      );
      if (formUtilities.checkEmpty(formState.errors)) {
        isValid = true;
      }
    } else {
      /** This is used to find out which all required fields are not filled */
      formState.values = formUtilities.getListOfKeysNotPresent(
        formState.values,
        CollegeFormSchema
      );
      formState.errors = formUtilities.setErrors(
        formState.values,
        CollegeFormSchema
      );
    }
    /** Check if both form and dynamicBar id valid */
    if (isValid && isDynamicBarValid && isValidAddress) {
      postCollegeData();
      /** Set state to reload form */
      setFormState(formState => ({
        ...formState,
        isValid: true
      }));
    } else {
      setFormState(formState => ({
        ...formState,
        isValid: false
      }));
    }
    event.preventDefault();
  };

  const hasError = field => (formState.errors[field] ? true : false);

  const checkErrorInDynamicBar = (field, currentDynamicBarValue) => {
    let errorData = { error: false, value: "" };
    if (formState.dynamicBarError.length) {
      formState.dynamicBarError.map(barErrorValue => {
        if (barErrorValue["index"] === currentDynamicBarValue["index"]) {
          if (barErrorValue.hasOwnProperty(field)) {
            errorData.error = true;
            errorData.value = barErrorValue[field];
          }
        }
      });
    }
    return errorData;
  };

  const getDynamicBarData = () => {
    let streamStrengthArrayValues = [];
    formState.dynamicBar.map(field => {
      let streamStrengthValue = {};
      if (
        field.hasOwnProperty(streams) &&
        field.hasOwnProperty(firstYearStrength)
      ) {
        streamStrengthValue["stream"] = field[streams];
        streamStrengthValue["first_year_strength"] = parseInt(
          field[firstYearStrength]
        );
        streamStrengthValue["second_year_strength"] = parseInt(
          field[secondYearStrength]
        );
        streamStrengthValue["third_year_strength"] = parseInt(
          field[thirdYearStrength]
        );
        streamStrengthArrayValues.push(streamStrengthValue);
      }
    });
    return streamStrengthArrayValues;
  };

  const postCollegeData = async () => {
    let streamStrengthArray = [];
    const adressess = formState.addresses;
    streamStrengthArray = getDynamicBarData();
    let postData = databaseUtilities.addCollege(
      formState.values[collegeName],
      formState.values[collegeCode],
      adressess,
      formState.values[contactNumber],
      formState.values[collegeEmail].toLowerCase(),
      formState.values[block] ? formState.values[block] : false,
      formState.values[principal] ? formState.values[principal] : null,
      formState.values[state] ? formState.values[state] : null,
      formState.values[rpc] ? formState.values[rpc] : null,
      formState.values[zone] ? formState.values[zone] : null,
      formState.values[district] ? formState.values[district] : null,
      streamStrengthArray,
      formState.values[tpos] ? formState.values[tpos] : []
    );
    formState.backDrop = true;
    if (formState.isEditCollege) {
      let EDIT_COLLEGE_URL =
        strapiConstants.STRAPI_DB_URL + strapiConstants.STRAPI_CONTACT_URL;
      let EDIT_URL = strapiConstants.STRAPI_EDIT_COLLEGE;
      serviceProviders
        .serviceProviderForPutRequest(
          EDIT_COLLEGE_URL,
          formState.dataForEdit.contact["id"],
          postData,
          EDIT_URL
        )
        .then(res => {
          if (auth.getUserInfo().role.name === roleConstants.MEDHAADMIN) {
            history.push({
              pathname: routeConstants.MANAGE_COLLEGE,
              fromeditCollege: true,
              isDataEdited: true,
              editedCollegeData: res.data,
              editResponseMessage: "",
              editedData: {}
            });
          } else if (
            auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
          ) {
            commonUtilities.updateUser();
            history.push({
              pathname: routeConstants.VIEW_COLLEGE,
              fromeditCollege: true,
              isDataEdited: true,
              editedCollegeData: res.data,
              editResponseMessage: "",
              editedData: {}
            });
          }
          formState.backDrop = false;
        })
        .catch(error => {
          console.log(error.response);
          let errorMessage;

          if (
            error.response !== undefined &&
            error.response.status !== undefined &&
            error.response.status === 400
          ) {
            if (error.response.data["message"]) {
              errorMessage = error.response.data["message"];
            }
          }
          history.push({
            pathname: routeConstants.MANAGE_COLLEGE,
            fromeditCollege: true,
            isDataEdited: false,
            editResponseMessage: errorMessage ? errorMessage : "",
            editedData: {}
          });
          formState.backDrop = false;
        });
    } else {
      serviceProviders
        .serviceProviderForPostRequest(ADD_COLLEGES_URL, postData)
        .then(res => {
          history.push({
            pathname: routeConstants.MANAGE_COLLEGE,
            fromAddCollege: true,
            isDataAdded: true,
            addedCollegeData: res.data,
            addResponseMessage: "",
            addedData: {}
          });
          formState.backDrop = false;
        })
        .catch(error => {
          console.log("errorCollege", error, error.response);
          let errorMessage;

          if (
            error.response !== undefined &&
            error.response.status !== undefined &&
            error.response.status === 400
          ) {
            if (error.response.data["message"]) {
              errorMessage = error.response.data["message"];
            }
          }
          history.push({
            pathname: routeConstants.MANAGE_COLLEGE,
            fromAddCollege: true,
            isDataAdded: false,
            addResponseMessage: errorMessage ? errorMessage : "",
            addedData: {}
          });
          formState.backDrop = false;
        });
    }
  };

  const handleStateAndDistrictChange = (type, value, idx) => {
    formState.addresses[idx][type] = value && value.id;
    if (type == "state" && formState.isCollegeAdmin) {
      formState.addresses[idx]["district"] = null;
    }

    if (type == "state" && !formState.isCollegeAdmin) {
      if (props.isCollegeAdmin) {
        formState.addresses[idx]["district"] = null;
      } else {
        formState.addresses[idx]["district"] = null;

        setRpcs([]);
        setZones([]);
        setDistricts([]);
        delete formState.values[zone];
        delete formState.values[rpc];
      }
    }
    validateAddresses();
    setFormState(formState => ({
      ...formState
    }));
  };

  const handleAddressChange = (idx, e, type) => {
    e.persist();

    const addresses = formState.addresses.map((addr, index) => {
      if (index == idx) {
        return { ...addr, [type]: e.target.value };
      } else {
        return addr;
      }
    });
    validateAddresses();
    setFormState(formState => ({
      ...formState,
      addresses
    }));
  };

  const validateAddresses = () => {
    const addresses = formState.addresses;
    let errors = [];
    let isError = false;
    addresses.forEach(addr => {
      let errorObject = {};
      if (!(addr.address_line_1 && addr.address_line_1.length > 0)) {
        isError = true;
        errorObject["address_line_1"] = {
          error: true,
          message: "Address is required"
        };
      } else {
        errorObject["address_line_1"] = {
          error: false,
          message: null
        };
      }

      if (!addr.state) {
        isError = true;
        errorObject["state"] = {
          error: true,
          message: "State is required"
        };
      } else {
        errorObject["state"] = {
          error: false,
          message: null
        };
      }

      if (!addr.district) {
        isError = true;
        errorObject["district"] = {
          error: true,
          message: "District is required"
        };
      } else {
        errorObject["district"] = {
          error: false,
          message: null
        };
      }

      if (!addr.city) {
        isError = true;
        errorObject["city"] = {
          error: true,
          message: "City is required"
        };
      } else {
        errorObject["city"] = {
          error: false,
          message: null
        };
      }

      if (!addr.pincode) {
        isError = true;
        errorObject["pincode"] = {
          error: true,
          message: "Pincode is required"
        };
      } else {
        errorObject["pincode"] = {
          error: false,
          message: null
        };
      }

      errors.push(errorObject);
    });

    setValidateAddress(errors);
    return !isError;
  };

  const clickedCancelButton = () => {
    if (auth.getUserInfo().role.name === roleConstants.MEDHAADMIN) {
      history.push({
        pathname: routeConstants.MANAGE_COLLEGE
      });
    } else if (auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN) {
      history.push({
        pathname: routeConstants.VIEW_COLLEGE
      });
    }
  };
  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        <Typography variant="h4" gutterBottom>
          {formState.isEditCollege
            ? genericConstants.EDIT_COLLEGE_TEXT
            : genericConstants.ADD_COLLEGE_TEXT}
        </Typography>
      </Grid>
      <Grid spacing={3}>
        <Card>
          {/* <form id="form" autoComplete="off" noValidate onSubmit={handleSubmit}> */}
          <CardContent>
            <Grid item xs={12} md={6} xl={3}>
              <Grid container spacing={3} className={classes.formgrid}>
                <Grid item md={6} xs={12}>
                  <TextField
                    fullWidth
                    // helperText="Please specify the college name"
                    id={get(CollegeFormSchema[collegeName], "id")}
                    label={get(CollegeFormSchema[collegeName], "label")}
                    name={collegeName}
                    onChange={handleChange}
                    placeholder={get(
                      CollegeFormSchema[collegeName],
                      "placeholder"
                    )}
                    required
                    type={get(CollegeFormSchema[collegeName], "type")}
                    value={formState.values[collegeName] || ""}
                    error={hasError(collegeName)}
                    helperText={
                      hasError(collegeName)
                        ? formState.errors[collegeName].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    variant="outlined"
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <TextField
                    fullWidth
                    id={get(CollegeFormSchema[collegeCode], "id")}
                    label={get(CollegeFormSchema[collegeCode], "label")}
                    name={collegeCode}
                    onChange={handleChange}
                    placeholder={get(
                      CollegeFormSchema[collegeCode],
                      "placeholder"
                    )}
                    required
                    value={formState.values[collegeCode] || ""}
                    error={hasError(collegeCode)}
                    helperText={
                      hasError(collegeCode)
                        ? formState.errors[collegeCode].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    variant="outlined"
                  />
                </Grid>
              </Grid>
              <Grid container spacing={3} className={classes.MarginBottom}>
                {/* <Grid item md={12} xs={12}>
                  <TextField
                    fullWidth
                    id={get(CollegeFormSchema[address], "id")}
                    label={get(CollegeFormSchema[address], "label")}
                    name={address}
                    onChange={handleChange}
                    required
                    placeholder={get(CollegeFormSchema[address], "placeholder")}
                    value={formState.values[address] || ""}
                    error={hasError(address)}
                    helperText={
                      hasError(address)
                        ? formState.errors[address].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    variant="outlined"
                  />
                </Grid> */}
                {formState.addresses.map((addr, idx) => {
                  return (
                    <Grid item md={12} xs={12}>
                      <Grid item md={12} xs={12} className={classes.streamcard}>
                        <Card className={classes.streamoffer}>
                          <InputLabel
                            htmlFor="outlined-address-card"
                            fullwidth={true.toString()}
                          >
                            {addr.address_type == "Temporary"
                              ? "Local Address"
                              : "Address"}
                          </InputLabel>
                          <Grid
                            container
                            spacing={3}
                            className={classes.MarginBottom}
                          >
                            <Grid
                              item
                              md={12}
                              xs={12}
                              style={{ marginTop: "8px" }}
                            >
                              <TextField
                                id="address"
                                label="Address Line "
                                name="address"
                                value={
                                  formState.addresses[idx].address_line_1 || ""
                                }
                                variant="outlined"
                                required
                                fullWidth
                                onChange={event =>
                                  handleAddressChange(
                                    idx,
                                    event,
                                    "address_line_1"
                                  )
                                }
                                error={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["address_line_1"][
                                      "error"
                                    ]) ||
                                  false
                                }
                                helperText={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["address_line_1"][
                                      "message"
                                    ]) ||
                                  null
                                }
                              />
                            </Grid>
                          </Grid>
                          <Grid
                            container
                            spacing={3}
                            className={classes.MarginBottom}
                          >
                            <Grid item md={6} xs={12}>
                              <Autocomplete
                                id="state"
                                className={classes.root}
                                options={states}
                                getOptionLabel={option => option.name}
                                onChange={(event, value) => {
                                  handleStateAndDistrictChange(
                                    "state",
                                    value,
                                    idx
                                  );
                                }}
                                value={
                                  states[
                                    states.findIndex(function (item, i) {
                                      return (
                                        item.id ===
                                        formState.addresses[idx].state
                                      );
                                    })
                                  ] || null
                                }
                                renderInput={params => (
                                  <TextField
                                    {...params}
                                    label="State"
                                    variant="outlined"
                                    name="tester"
                                    error={
                                      (validateAddress[idx] &&
                                        validateAddress[idx]["state"][
                                          "error"
                                        ]) ||
                                      false
                                    }
                                    helperText={
                                      (validateAddress[idx] &&
                                        validateAddress[idx]["state"][
                                          "message"
                                        ]) ||
                                      null
                                    }
                                  />
                                )}
                              />
                            </Grid>
                            <Grid item md={6} xs={12}>
                              <FormControl
                                variant="outlined"
                                fullWidth
                                className={classes.formControl}
                              >
                                <InputLabel
                                  ref={inputLabel}
                                  id="districts-label"
                                >
                                  {/* Districts */}
                                </InputLabel>

                                <Autocomplete
                                  id={get(CollegeFormSchema[district], "id")}
                                  options={districts}
                                  getOptionLabel={option => option.name}
                                  onChange={(event, value) => {
                                    handleStateAndDistrictChange(
                                      "district",
                                      value,
                                      idx
                                    );
                                  }}
                                  name={district}
                                  /** This is used to set the default value to the auto complete */
                                  value={
                                    formState.isStateClearFilter
                                      ? null
                                      : districts[
                                          districts.findIndex(function (
                                            item,
                                            i
                                          ) {
                                            return (
                                              item.id ===
                                              formState.addresses[idx].district
                                            );
                                          })
                                        ] ||
                                        null /** Please give a default " " blank value */
                                  }
                                  renderInput={params => (
                                    <TextField
                                      {...params}
                                      error={
                                        (validateAddress[idx] &&
                                          validateAddress[idx]["district"][
                                            "error"
                                          ]) ||
                                        false
                                      }
                                      helperText={
                                        (validateAddress[idx] &&
                                          validateAddress[idx]["district"][
                                            "message"
                                          ]) ||
                                        null
                                      }
                                      placeholder={get(
                                        CollegeFormSchema[district],
                                        "placeholder"
                                      )}
                                      value={option => option.id}
                                      name={district}
                                      key={option => option.id}
                                      label={get(
                                        CollegeFormSchema[district],
                                        "label"
                                      )}
                                      variant="outlined"
                                    />
                                  )}
                                />
                              </FormControl>
                            </Grid>
                            <Grid item md={6} xs={12}>
                              <TextField
                                id="city"
                                label="City"
                                name="city"
                                value={formState.addresses[idx].city || ""}
                                variant="outlined"
                                required
                                fullWidth
                                onChange={event =>
                                  handleAddressChange(idx, event, "city")
                                }
                                error={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["city"]["error"]) ||
                                  false
                                }
                                helperText={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["city"]["message"]) ||
                                  null
                                }
                              />
                            </Grid>
                            <Grid item md={6} xs={12}>
                              <TextField
                                id="pincode"
                                label="Pincode"
                                name="pincode"
                                value={formState.addresses[idx].pincode || ""}
                                variant="outlined"
                                required
                                fullWidth
                                onChange={event =>
                                  handleAddressChange(idx, event, "pincode")
                                }
                                error={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["pincode"]["error"]) ||
                                  false
                                }
                                helperText={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["pincode"][
                                      "message"
                                    ]) ||
                                  null
                                }
                              />
                            </Grid>

                            <Grid item md={6} xs={12}>
                              {formState.isCollegeAdmin ? (
                                <ReadOnlyTextField
                                  id="ZoneName"
                                  label={get(CollegeFormSchema[zone], "label")}
                                  defaultValue={collegeInfo.zone.name}
                                />
                              ) : (
                                <FormControl
                                  variant="outlined"
                                  fullWidth
                                  className={classes.formControl}
                                >
                                  <InputLabel ref={inputLabel} id="zone-label">
                                    {/* Zone */}
                                  </InputLabel>

                                  <Autocomplete
                                    id={get(CollegeFormSchema[zone], "id")}
                                    options={
                                      zones ? zones : <CircularProgress />
                                    }
                                    getOptionLabel={option => option.name}
                                    onChange={(event, value) => {
                                      handleChangeAutoComplete(
                                        zone,
                                        event,
                                        value
                                      );
                                    }}
                                    /** This is used to set the default value to the auto complete */
                                    value={
                                      formState.isStateClearFilter
                                        ? null
                                        : zones[
                                            zones.findIndex(function (item, i) {
                                              return (
                                                item.id ===
                                                formState.values[zone]
                                              );
                                            })
                                          ] ||
                                          null /** Please give a default " " blank value */
                                    }
                                    name={zone}
                                    renderInput={params => (
                                      <TextField
                                        {...params}
                                        required
                                        error={hasError(zone)}
                                        helperText={
                                          hasError(zone)
                                            ? formState.errors[zone].map(
                                                error => {
                                                  return error + " ";
                                                }
                                              )
                                            : null
                                        }
                                        placeholder={get(
                                          CollegeFormSchema[zone],
                                          "placeholder"
                                        )}
                                        value={option => option.id}
                                        name={rpc}
                                        key={option => option.id}
                                        label={get(
                                          CollegeFormSchema[zone],
                                          "label"
                                        )}
                                        variant="outlined"
                                      />
                                    )}
                                  />
                                </FormControl>
                              )}
                            </Grid>
                            <Grid item md={6} xs={12}>
                              {formState.isCollegeAdmin ? (
                                <ReadOnlyTextField
                                  id={get(CollegeFormSchema[rpcs], "id")}
                                  label={get(CollegeFormSchema[rpc], "label")}
                                  defaultValue={collegeInfo.rpc.name}
                                />
                              ) : (
                                <FormControl
                                  variant="outlined"
                                  fullWidth
                                  className={classes.formControl}
                                >
                                  <InputLabel ref={inputLabel} id="rpcs-label">
                                    {/* RPCs */}
                                  </InputLabel>

                                  <Autocomplete
                                    id={get(CollegeFormSchema[rpc], "id")}
                                    options={rpcs}
                                    getOptionLabel={option => option.name}
                                    onChange={(event, value) => {
                                      handleChangeAutoComplete(
                                        rpc,
                                        event,
                                        value
                                      );
                                    }}
                                    name={rpc}
                                    /** This is used to set the default value to the auto complete */
                                    value={
                                      formState.isStateClearFilter
                                        ? null
                                        : rpcs[
                                            rpcs.findIndex(function (item, i) {
                                              return (
                                                item.id ===
                                                formState.values[rpc]
                                              );
                                            })
                                          ] ||
                                          null /** Please give a default " " blank value */
                                    }
                                    renderInput={params => (
                                      <TextField
                                        {...params}
                                        required
                                        error={hasError(rpc)}
                                        helperText={
                                          hasError(rpc)
                                            ? formState.errors[rpc].map(
                                                error => {
                                                  return error + " ";
                                                }
                                              )
                                            : null
                                        }
                                        placeholder={get(
                                          CollegeFormSchema[rpc],
                                          "placeholder"
                                        )}
                                        value={option => option.id}
                                        name={rpc}
                                        key={option => option.id}
                                        label={get(
                                          CollegeFormSchema[rpc],
                                          "label"
                                        )}
                                        variant="outlined"
                                      />
                                    )}
                                  />
                                </FormControl>
                              )}
                            </Grid>
                          </Grid>
                        </Card>
                      </Grid>
                    </Grid>
                  );
                })}
              </Grid>
            </Grid>
            <Divider className={classes.divider} />
            <Grid item xs={12} md={6} xl={3}>
              <Grid container spacing={3} className={classes.formgrid}>
                <Grid item md={12} xs={12}>
                  <TextField
                    fullWidth
                    label={get(CollegeFormSchema[collegeEmail], "label")}
                    id={get(CollegeFormSchema[collegeEmail], "id")}
                    name={collegeEmail}
                    onChange={handleChange}
                    placeholder={get(
                      CollegeFormSchema[collegeEmail],
                      "placeholder"
                    )}
                    required
                    value={formState.values[collegeEmail] || ""}
                    error={hasError(collegeEmail)}
                    helperText={
                      hasError(collegeEmail)
                        ? formState.errors[collegeEmail].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    variant="outlined"
                  />
                </Grid>
              </Grid>
            </Grid>
            <Grid item xs={12} md={6} xl={3}>
              <Grid container spacing={3} className={classes.formgrid}>
                <Grid item md={6} xs={12}>
                  <TextField
                    id="contact_number"
                    fullWidth
                    label={get(CollegeFormSchema[contactNumber], "label")}
                    name={contactNumber}
                    onChange={handleChange}
                    required
                    placeholder={get(
                      CollegeFormSchema[contactNumber],
                      "placeholder"
                    )}
                    value={formState.values[contactNumber] || ""}
                    error={hasError(contactNumber)}
                    helperText={
                      hasError(contactNumber)
                        ? formState.errors[contactNumber].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    variant="outlined"
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <div
                    style={{ display: formState.showing ? "block" : "none" }}
                  >
                    <FormGroup row>
                      <FormControlLabel
                        control={
                          <Switch
                            name={block}
                            checked={formState.values[block] || false}
                            onChange={handleChange}
                            value={formState.values[block] || false}
                            error={hasError(block).toString()}
                            helpertext={
                              hasError(block)
                                ? formState.errors[block].map(error => {
                                    return error + " ";
                                  })
                                : null
                            }
                          />
                        }
                        label={
                          formState.values[block] === true ? "Unblock" : "Block"
                        }
                      />
                    </FormGroup>
                  </div>
                </Grid>
              </Grid>
              {((auth.getUserInfo() !== null &&
                auth.getUserInfo().role !== null &&
                auth.getUserInfo().role.name === roleConstants.MEDHAADMIN) ||
                (auth.getUserInfo() !== null &&
                  auth.getUserInfo().role !== null &&
                  auth.getUserInfo().role.name ===
                    roleConstants.COLLEGEADMIN)) &&
              formState.isEditCollege ? (
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12}>
                    <Autocomplete
                      id={get(CollegeFormSchema[tpos], "id")}
                      multiple
                      options={user}
                      getOptionLabel={option => option.contact.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete(tpos, event, value);
                      }}
                      name={tpos}
                      filterSelectedOptions
                      value={formState.dataToShowForMultiSelect || null}
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError(tpos)}
                          helperText={
                            hasError(tpos)
                              ? formState.errors[tpos].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                          placeholder={get(
                            CollegeFormSchema[tpos],
                            "placeholder"
                          )}
                          label={get(CollegeFormSchema[tpos], "label")}
                          variant="outlined"
                        />
                      )}
                    />
                    {/* </FormControl> */}
                  </Grid>
                </Grid>
              ) : null}
            </Grid>
            {tpoData ? (
              <Grid item xs={12} md={6} xl={3}>
                {tpoData.map(tpo => (
                  <Grid container spacing={3} className={classes.MarginBottom}>
                    <Grid item md={6} xs={12}>
                      <ReadOnlyTextField
                        id="TPO Email"
                        label={"Tpo Email"}
                        defaultValue={tpo.contact.email}
                      />
                    </Grid>
                    <Grid item md={6} xs={12}>
                      <ReadOnlyTextField
                        id="TPO Contact Number"
                        label={"TPO Contact Number"}
                        defaultValue={tpo.contact.phone}
                      />
                    </Grid>
                  </Grid>
                ))}
              </Grid>
            ) : null}
            {((auth.getUserInfo() !== null &&
              auth.getUserInfo().role !== null &&
              auth.getUserInfo().role.name === roleConstants.MEDHAADMIN) ||
              (auth.getUserInfo() !== null &&
                auth.getUserInfo().role !== null &&
                auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN)) &&
            formState.isEditCollege ? (
              <Grid item xs={12} md={6} xl={3}>
                <Grid container className={classes.formgrid}>
                  <Grid item md={12} xs={12}>
                    <Autocomplete
                      id={get(CollegeFormSchema[principal], "id")}
                      options={user}
                      getOptionLabel={option => option.contact.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete(principal, event, value);
                      }}
                      /** This is used to set the default value to the auto complete */
                      value={
                        user[
                          user.findIndex(function (item, i) {
                            return (
                              item.contact.user.id ===
                              formState.values[principal]
                            );
                          })
                        ] || null /** Please give a default " " blank value */
                      }
                      name={principal}
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError(principal)}
                          helperText={
                            hasError(principal)
                              ? formState.errors[principal].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                          placeholder={get(
                            CollegeFormSchema[principal],
                            "placeholder"
                          )}
                          value={option => option.id}
                          name={principal}
                          key={option => option.id}
                          label={get(CollegeFormSchema[principal], "label")}
                          variant="outlined"
                        />
                      )}
                    />
                    {/* </FormControl> */}
                  </Grid>
                </Grid>
              </Grid>
            ) : null}
            {principalData && isGetAdminData ? (
              <Grid item xs={12} md={6} xl={3}>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={6} xs={12}>
                    <ReadOnlyTextField
                      id="Principal Email"
                      label={"Principal Email"}
                      defaultValue={
                        principalData.contact
                          ? principalData.contact.email
                            ? principalData.contact.email
                            : ""
                          : ""
                      }
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <ReadOnlyTextField
                      id="Principal Contact Number"
                      label={"Principal Contact Number"}
                      defaultValue={
                        principalData.contact
                          ? principalData.contact.phone
                            ? principalData.contact.phone
                            : ""
                          : ""
                      }
                    />
                  </Grid>
                </Grid>
              </Grid>
            ) : null}

            <Divider className={classes.divider} />
            <Grid item xs={12} md={10} xl={8}>
              <Grid container spacing={1} className={classes.formgrid}>
                <Grid item md={12} xs={12} className={classes.streamcard}>
                  <Card className={classes.streamoffer}>
                    <InputLabel
                      htmlFor="outlined-stream-card"
                      fullwidth={true.toString()}
                    >
                      {genericConstants.STREAMS_OFFERED_TEXT}
                    </InputLabel>

                    {formState.dynamicBar.map((val, idx) => {
                      let streamId = `stream-${idx}`,
                        firstYearStrengthId = `first-year-strength-${idx}`,
                        secondYearStrengthId = `second-year-strength-${idx}`,
                        thirdYearStrengthId = `third-year-strength-${idx}`;
                      return (
                        <Card
                          id="outlined-stream-card"
                          fullwidth={true.toString()}
                          className={classes.streamcardcontent}
                          key={idx}
                        >
                          <CardContent>
                            <Grid container spacing={1}>
                              <Grid item xs={12} md={3}>
                                <FormControl
                                  variant="outlined"
                                  fullWidth
                                  className={classes.formControl}
                                >
                                  <InputLabel
                                    ref={inputLabel}
                                    id="demo-simple-select-outlined-label"
                                  >
                                    {/* Streams */}
                                  </InputLabel>
                                  <Autocomplete
                                    id={streamId}
                                    options={streamsData}
                                    getOptionLabel={option => option.name}
                                    onChange={(event, value) => {
                                      handleChangeForDynamicGrid(
                                        streams,
                                        event,
                                        value,
                                        val,
                                        true,
                                        false
                                      );
                                    }}
                                    data-id={idx}
                                    name={streamId}
                                    value={
                                      streamsDataBackup[
                                        streamsDataBackup.findIndex(function (
                                          item,
                                          i
                                        ) {
                                          return (
                                            item.id ===
                                            formState.dynamicBar[idx][streams]
                                          );
                                        })
                                      ] || null
                                    }
                                    renderInput={params => (
                                      <TextField
                                        {...params}
                                        value={option => option.id}
                                        name={streamId}
                                        error={
                                          checkErrorInDynamicBar(streams, val)[
                                            "error"
                                          ]
                                        }
                                        helperText={
                                          checkErrorInDynamicBar(streams, val)[
                                            "error"
                                          ]
                                            ? checkErrorInDynamicBar(
                                                streams,
                                                val
                                              )["value"]
                                            : null
                                        }
                                        placeholder={get(
                                          CollegeFormSchema[streams],
                                          "placeholder"
                                        )}
                                        key={option => option.id}
                                        label={get(
                                          CollegeFormSchema[streams],
                                          "label"
                                        )}
                                        variant="outlined"
                                      />
                                    )}
                                  />
                                </FormControl>
                              </Grid>
                              {/** Need to map streams with strength */}
                              <Grid item xs>
                                <TextField
                                  label="1st Year Strength"
                                  name={firstYearStrengthId}
                                  variant="outlined"
                                  fullWidth
                                  data-id={idx}
                                  id={firstYearStrengthId}
                                  value={
                                    formState.dynamicBar[idx][
                                      firstYearStrength
                                    ] || ""
                                  }
                                  error={
                                    checkErrorInDynamicBar(
                                      firstYearStrength,
                                      val
                                    )["error"]
                                  }
                                  helperText={
                                    checkErrorInDynamicBar(
                                      firstYearStrength,
                                      val
                                    )["error"]
                                      ? checkErrorInDynamicBar(
                                          firstYearStrength,
                                          val
                                        )["value"]
                                      : null
                                  }
                                  placeholder={get(
                                    CollegeFormSchema[firstYearStrength],
                                    "placeholder"
                                  )}
                                  onChange={event => {
                                    handleChangeForDynamicGrid(
                                      firstYearStrength,
                                      event,
                                      null,
                                      val,
                                      false,
                                      true
                                    );
                                  }}
                                />
                              </Grid>
                              <Grid item xs>
                                <TextField
                                  label="2nd Year Strength"
                                  name={secondYearStrengthId}
                                  variant="outlined"
                                  fullWidth
                                  data-id={idx}
                                  id={secondYearStrengthId}
                                  value={
                                    formState.dynamicBar[idx][
                                      secondYearStrength
                                    ] || ""
                                  }
                                  error={
                                    checkErrorInDynamicBar(
                                      secondYearStrength,
                                      val
                                    )["error"]
                                  }
                                  helperText={
                                    checkErrorInDynamicBar(
                                      secondYearStrength,
                                      val
                                    )["error"]
                                      ? checkErrorInDynamicBar(
                                          secondYearStrength,
                                          val
                                        )["value"]
                                      : null
                                  }
                                  placeholder={get(
                                    CollegeFormSchema[secondYearStrength],
                                    "placeholder"
                                  )}
                                  onChange={event => {
                                    handleChangeForDynamicGrid(
                                      secondYearStrength,
                                      event,
                                      null,
                                      val,
                                      false,
                                      true
                                    );
                                  }}
                                />
                              </Grid>
                              <Grid item xs>
                                <TextField
                                  label="3rd Year Strength"
                                  name={thirdYearStrengthId}
                                  variant="outlined"
                                  fullWidth
                                  data-id={idx}
                                  id={thirdYearStrengthId}
                                  value={
                                    formState.dynamicBar[idx][
                                      thirdYearStrength
                                    ] || ""
                                  }
                                  error={
                                    checkErrorInDynamicBar(
                                      thirdYearStrength,
                                      val
                                    )["error"]
                                  }
                                  helperText={
                                    checkErrorInDynamicBar(
                                      thirdYearStrength,
                                      val
                                    )["error"]
                                      ? checkErrorInDynamicBar(
                                          thirdYearStrength,
                                          val
                                        )["value"]
                                      : null
                                  }
                                  placeholder={get(
                                    CollegeFormSchema[thirdYearStrength],
                                    "placeholder"
                                  )}
                                  onChange={event => {
                                    handleChangeForDynamicGrid(
                                      thirdYearStrength,
                                      event,
                                      null,
                                      val,
                                      false,
                                      true
                                    );
                                  }}
                                />
                              </Grid>
                              <Grid item xs={1}>
                                {idx > 0 ? (
                                  <DeleteForeverOutlinedIcon
                                    onClick={e => clickOnDelete(val, idx)}
                                    style={{ color: "red", fontSize: "24px" }}
                                  />
                                ) : (
                                  ""
                                )}
                              </Grid>
                            </Grid>
                          </CardContent>
                        </Card>
                      );
                    })}
                    <div className={classes.btnspaceadd}>
                      <Grid item xs={12} md={3} lg={2} xl={2}>
                        <YellowButton
                          disabled={streamsData.length ? false : true}
                          color="primary"
                          variant="contained"
                          className={classes.add_more_btn}
                          onClick={addNewRow}
                        >
                          {genericConstants.ADD_MORE_TEXT}
                        </YellowButton>
                      </Grid>
                    </div>
                  </Card>
                </Grid>
              </Grid>
            </Grid>
          </CardContent>
          <Grid item xs={12} className={classes.CardActionGrid}>
            <CardActions className={classes.btnspace}>
              <Grid item xs={12}>
                <Grid item xs={12} md={6} xl={3}>
                  <Grid container spacing={3}>
                    <Grid item md={2} xs={12}>
                      <YellowButton
                        id="submit"
                        type="submit"
                        color="primary"
                        variant="contained"
                        onClick={handleSubmit}
                        className={classes.submitbtn}
                      >
                        {genericConstants.SAVE_BUTTON_TEXT}
                      </YellowButton>
                    </Grid>
                    <Grid item md={2} xs={12}>
                      <GrayButton
                        color="primary"
                        variant="contained"
                        onClick={clickedCancelButton}
                        className={classes.resetbtn}
                      >
                        {genericConstants.CANCEL_BUTTON_TEXT}
                      </GrayButton>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
            </CardActions>
          </Grid>
          {/* </form> */}
        </Card>
      </Grid>
      <Backdrop className={classes.backDrop} open={formState.backDrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </Grid>
  );
}
Example #14
Source File: AddEditEducation.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditEducation = props => {
  const history = useHistory();
  const classes = useStyles();
  const studentInfo =
    auth.getUserInfo() !== null &&
    auth.getUserInfo().role.name === roleConstants.STUDENT
      ? auth.getUserInfo().studentInfo.contact.id
      : auth.getStudentIdFromCollegeAdmin();

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

  const EDUCATION_URL =
    strapiConstants.STRAPI_DB_URL + strapiConstants.STRAPI_EDUCATIONS;

  const [isSuccess, setIsSuccess] = useState(false);
  const [isFailed, setIsFailed] = useState(false);
  const [formState, setFormState] = useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    flag: 0,
    hideYear: false,
    isSuccess: false,
    isEditEducation: props["editEducation"] ? props["editEducation"] : false,
    dataForEdit: props["dataForEdit"] ? props["dataForEdit"] : {},
    counter: 0,
    otherId: 0
  });

  const [boards, setBoards] = useState([]);
  const [academicYears, setAcademicYears] = useState([]);

  useEffect(() => {
    fetchDropdowns(strapiConstants.STRAPI_BOARDS, setBoards);
    fetchDropdowns(strapiConstants.STRAPI_ACADEMIC_YEARS, setAcademicYears);
  }, []);

  useEffect(() => {
    const marksObtained = parseInt(formState.values["marksObtained"]);
    const totalMarks = parseInt(formState.values["totalMarks"]);
    if (marksObtained > 0 && marksObtained <= totalMarks && totalMarks > 0) {
      const marks = (marksObtained / totalMarks) * 100;
      delete formState.errors[percentage];
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          percentage: marks.toFixed(2)
        },
        errors: {
          ...formState.errors
        }
      }));
    }

    let updateState = false,
      errorMessage = null;
    if (marksObtained && totalMarks && marksObtained > totalMarks) {
      updateState = true;
      errorMessage = ["Marks Obtained should be less than total Marks"];
    }

    if (marksObtained <= 0) {
      updateState = true;
      errorMessage = ["Marks should be greater than 0"];
    }

    if (totalMarks <= 0) {
      updateState = true;
      errorMessage = ["Total Marks should be greater than 0"];
    }

    if (updateState) {
      formState.errors[percentage] = errorMessage;
      delete formState.values[percentage];
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values
        },
        errors: {
          ...formState.errors
        }
      }));
    }
  }, [formState.values["marksObtained"], formState.values["totalMarks"]]);

  useEffect(() => {
    const pursuing = formState.values["pursuing"];
    if (pursuing) {
      delete formState.values["marksObtained"];
      delete formState.values["totalMarks"];
      delete formState.values["percentage"];
      delete formState.values["board"];

      const currentAcademicYear = getCurrentAcademicYear();
      const undergraduate = genericConstants.QUALIFICATION_LIST.find(
        q => q.id == "undergraduate"
      );

      if (currentAcademicYear) {
        formState.values[yearOfPassing] = currentAcademicYear.id;
      }

      if (undergraduate) {
        formState.values[qualification] = undergraduate.id;
      }

      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values
        }
      }));
    }
  }, [formState.values[pursuing]]);

  useEffect(() => {
    if (!formState.values["otherQualification"]) {
      delete formState.values["otherQualification"];
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values
        }
      }));
    }
  }, [formState.values["otherQualification"]]);

  useEffect(() => {
    if (
      formState.values[qualification] == "secondary" ||
      formState.values[qualification] == "senior_secondary" ||
      formState.values[qualification] === "graduation" ||
      formState.values[qualification] === "postgraduate" ||
      formState.values[qualification] === "diploma" ||
      formState.values[qualification] === "iti" ||
      formState.values[qualification] === "other"
    ) {
      delete formState.errors[educationYear];
      delete formState.values[educationYear];
      setFormState(formState => ({
        ...formState,
        errors: {
          ...formState.errors
        }
      }));
    }

    if (
      formState.values[qualification] == "undergraduate" ||
      formState.values[qualification] == "postgraduate"
    ) {
      delete formState.errors[board];
      delete formState.values[board];
      setFormState(formState => ({
        ...formState,
        errors: {
          ...formState.errors
        }
      }));
    }

    if (formState.values[qualification] === "other") {
      delete formState.errors[educationYear];
      delete formState.values[educationYear];
      setFormState(formState => ({
        ...formState,
        errors: {
          ...formState.errors
        }
      }));
    }
  }, [formState.values[qualification]]);

  const fetchDropdowns = (link, setList) => {
    const url =
      strapiConstants.STRAPI_DB_URL +
      link +
      "?pageSize=-1&_sort=start_date:asc";
    axios
      .get(url)
      .then(({ data }) => {
        if (link === "boards") {
          const id = data.result
            .map(board => {
              if (board.name === "Other") return board.id;
            })
            .filter(c => c);

          setFormState(formState => ({
            ...formState,
            otherId: id[0]
          }));
        }
        const list = data.result;
        setList(list);
      })
      .catch(error => {
        console.log(error);
      });
  };

  /** Part for editing Education */
  if (formState.isEditEducation && !formState.counter) {
    setLoaderStatus(true);
    if (props["dataForEdit"]) {
      if (props["dataForEdit"]["year_of_passing"]) {
        formState.values[yearOfPassing] =
          props["dataForEdit"]["year_of_passing"]["id"];
      }
      if (props["dataForEdit"]["education_year"]) {
        formState.values[educationYear] =
          props["dataForEdit"]["education_year"];
      }
      if (props["dataForEdit"]["percentage"]) {
        formState.values[percentage] = props["dataForEdit"]["percentage"];
      }
      if (props["dataForEdit"]["qualification"]) {
        formState.values[qualification] = props["dataForEdit"]["qualification"];
        if (
          formState.values[qualification] === "secondary" ||
          formState.values[qualification] === "senior_secondary"
        ) {
          EducationSchema.qualification.required = false;
          EducationSchema.qualification.validations = {};
          setFormState(formState => ({
            ...formState,
            hideYear: true
          }));
        }
      }
      if (props["dataForEdit"]["other_qualification"]) {
        formState.values["otherQualification"] =
          props["dataForEdit"]["other_qualification"];
      }
      if (props["dataForEdit"]["institute"]) {
        formState.values[institute] = props["dataForEdit"]["institute"];
      }
      if (props["dataForEdit"]["pursuing"]) {
        formState.values[pursuing] = props["dataForEdit"]["pursuing"];
      }

      if (props["dataForEdit"]["board"]) {
        formState.values[board] = props["dataForEdit"]["board"]["id"];
      }
      if (props["dataForEdit"]["other_board"]) {
        formState.values["otherboard"] = props["dataForEdit"]["other_board"];
      }

      if (props["dataForEdit"]["marks_obtained"]) {
        formState.values[marksObtained] =
          props["dataForEdit"]["marks_obtained"];
      }
      if (props["dataForEdit"]["total_marks"]) {
        formState.values[totalMarks] = props["dataForEdit"]["total_marks"];
      }

      formState.counter += 1;
    }
    setLoaderStatus(false);
  }

  /** This handle change is used to handle changes to text field */
  const handleChange = event => {
    /** TO SET VALUES IN FORMSTATE */
    event.persist();
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [event.target.name]:
          event.target.type === "checkbox"
            ? event.target.checked
            : event.target.value
      },
      touched: {
        ...formState.touched,
        [event.target.name]: true
      }
    }));

    /** This is used to remove any existing errors if present in text field */
    if (formState.errors.hasOwnProperty(event.target.name)) {
      delete formState.errors[event.target.name];
    }

    if (event.target.name == "pursuing") {
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values
        },
        errors: {}
      }));
    }
  };

  /** This checks if the corresponding field has errors */
  const hasError = field => (formState.errors[field] ? true : false);

  /** Handle submit handles the submit and performs all the validations */
  const handleSubmit = event => {
    setLoaderStatus(true);
    const schema = getSchema();

    let isValid = false;
    // /** Checkif all fields are present in the submitted form */
    let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
      formState.values,
      schema
    );
    if (checkAllFieldsValid) {
      /** Evaluated only if all keys are valid inside formstate */
      formState.errors = formUtilities.setErrors(formState.values, schema);
      /** Checks if the form is empty */
      if (formUtilities.checkEmpty(formState.errors)) {
        isValid = true;
      }
    } else {
      /** This is used to find out which all required fields are not filled */
      formState.values = formUtilities.getListOfKeysNotPresent(
        formState.values,
        schema
      );
      /** This sets errors by comparing it with the json schema provided */
      formState.errors = formUtilities.setErrors(formState.values, schema);
    }

    if (isValid) {
      /** CALL POST FUNCTION */
      postEducationData();
    } else {
      setFormState(formState => ({
        ...formState,
        isValid: false
      }));
    }
    setLoaderStatus(false);
    event.preventDefault();
  };

  const getSchema = () => {
    let defaultSchema = Object.assign({}, EducationSchema);
    const isPursuing = formState.values[pursuing];
    const isQualificationReq = formState.values[qualification];

    const isOtherSelected = formState.values[qualification];
    if (isOtherSelected == "other") {
      defaultSchema["otherQualification"] = {
        label: "Other qualification",
        id: "otherQualification",
        autoComplete: "otherQualification",
        required: true,
        placeholder: "Other qualification",
        autoFocus: true,
        type: "number",
        validations: {
          required: {
            value: "true",
            message: "Other qualification is required"
          }
        }
      };
      defaultSchema[educationYear] = {
        ...defaultSchema[educationYear],
        required: false
      };
    }

    if (formState.values[board] === formState.otherId) {
      defaultSchema["otherboard"] = {
        label: "Other Board",
        id: "otherboard",
        autoComplete: "otherboard",
        required: true,
        placeholder: "Other board",
        autoFocus: true,
        type: "text",
        validations: {
          required: {
            value: "true",
            message: "Other board is required"
          }
        }
      };
    }

    if (
      isQualificationReq == "secondary" ||
      isQualificationReq == "senior_secondary" ||
      isQualificationReq === "graduation" ||
      isQualificationReq === "postgraduate" ||
      isQualificationReq === "diploma" ||
      isQualificationReq === "iti" ||
      isQualificationReq === "other"
    ) {
      defaultSchema[educationYear] = {
        ...defaultSchema[educationYear],
        required: false
      };
    }

    if (
      isQualificationReq == "undergraduate" ||
      isQualificationReq == "graduation" ||
      isQualificationReq === "diploma" ||
      isQualificationReq === "iti" ||
      isQualificationReq == "postgraduate"
    ) {
      defaultSchema[board] = {
        ...defaultSchema[board],
        required: false
      };
    }

    if (isPursuing) {
      defaultSchema[percentage] = {
        ...defaultSchema[percentage],
        required: false
      };
      defaultSchema[marksObtained] = {
        ...defaultSchema[marksObtained],
        required: false
      };
      defaultSchema[totalMarks] = {
        ...defaultSchema[totalMarks],
        required: false
      };
      defaultSchema[board] = {
        ...defaultSchema[board],
        required: false
      };
    }

    return defaultSchema;
  };

  const postEducationData = async () => {
    // const id = studentInfo ? studentInfo.id : null;

    let postData = databaseUtilities.addEducation(
      formState.values[yearOfPassing],
      formState.values[educationYear],
      formState.values[percentage],
      formState.values[qualification],
      formState.values[institute],
      formState.values[pursuing],
      formState.values[board],
      formState.values["otherQualification"],
      formState.values[marksObtained],
      formState.values[totalMarks],
      formState.values["otherboard"]
    );
    // Adding student id to post data
    postData.contact = studentInfo;
    if (formState.isEditEducation) {
      serviceProviders
        .serviceProviderForPutRequest(
          EDUCATION_URL,
          formState.dataForEdit["id"],
          postData
        )
        .then(res => {
          if (formState.flag === 1) {
            history.push({
              pathname: routeConstants.VIEW_DOCUMENTS
            });
            setLoaderStatus(false);
          } else {
            history.push({
              pathname: routeConstants.VIEW_EDUCATION,
              fromEditEducation: true,
              isDataEdited: true,
              editResponseMessage: "",
              editedData: {}
            });
          }
          setLoaderStatus(false);
        })
        .catch(error => {
          console.log(error);
          history.push({
            pathname: routeConstants.VIEW_EDUCATION,
            fromEditEducation: true,
            isDataEdited: false,
            editResponseMessage: "",
            editedData: {},
            error: error.response.data ? error.response.data.message : ""
          });
          setLoaderStatus(false);
        });
    } else {
      serviceProviders
        .serviceProviderForPostRequest(EDUCATION_URL, postData)
        .then(res => {
          setIsSuccess(true);
          if (formState.flag === 1) {
            history.push({
              pathname: routeConstants.VIEW_DOCUMENTS
            });
            setLoaderStatus(false);
          } else {
            history.push({
              pathname: routeConstants.VIEW_EDUCATION,
              fromAddEducation: true,
              isDataAdded: true,
              addResponseMessage: "",
              addedData: {}
            });
          }
          setLoaderStatus(false);
        })
        .catch(error => {
          history.push({
            pathname: routeConstants.VIEW_EDUCATION,
            fromAddEducation: true,
            isDataAdded: false,
            addResponseMessage: "",
            addedData: {},
            error: error.response.data ? error.response.data.message : ""
          });
          setLoaderStatus(false);
        });
    }
  };

  const handleChangeAutoComplete = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (eventName === qualification && value) {
      if (
        value.id === "secondary" ||
        value.id === "senior_secondary" ||
        value.id === "graduation" ||
        value.id === "postgraduate" ||
        value.id === "diploma" ||
        value.id === "iti" ||
        value.id === "other"
      ) {
        EducationSchema.qualification.required = false;
        EducationSchema.qualification.validations = {};
        setFormState(formState => ({
          ...formState,
          hideYear: true
        }));
      } else {
        setFormState(formState => ({
          ...formState,
          hideYear: false
        }));
      }
      if (value.id == "undergraduate") {
        EducationSchema.qualification.required = true;
        EducationSchema.qualification.validations = {
          required: {
            value: "true",
            message: "Education year is required"
          }
        };
      }
    } else {
      EducationSchema.qualification.required = true;
      EducationSchema.qualification.validations = {
        required: {
          value: "true",
          message: "Qualification is required"
        }
      };
      // setFormState(formState => ({
      //   ...formState,
      //   hideYear: false
      // }));
    }
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [eventName]: value ? value.id : ""
      },
      touched: {
        ...formState.touched,
        [eventName]: true
      }
    }));
    if (formState.errors.hasOwnProperty(eventName)) {
      delete formState.errors[eventName];
    }
  };

  const saveAndNext = event => {
    event.preventDefault();
    formState["flag"] = 1;
    handleSubmit(event);
  };

  const getCurrentAcademicYear = () => {
    return academicYears.find(ay => {
      const { start_date, end_date } = ay;

      const start = moment(start_date);
      const end = moment(end_date);
      const current = moment();

      if (moment(current).isBetween(start, end)) {
        return ay;
      }
    });
  };

  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        {isSuccess ? (
          <Alert severity="success">
            {genericConstants.ALERT_SUCCESS_BUTTON_MESSAGE}
          </Alert>
        ) : null}
        {isFailed ? (
          <Alert severity="error">
            {genericConstants.ALERT_ERROR_BUTTON_MESSAGE}
          </Alert>
        ) : null}
      </Grid>
      <Grid spacing={3} className={classes.formgrid}>
        <Card className={classes.root} variant="outlined">
          <form autoComplete="off" noValidate>
            <CardContent>
              <Grid item xs={8}>
                <Grid container className={classes.formgridInputFile}>
                  <Grid item xs={12} md={6} xl={3}>
                    <Grid container spacing={3}>
                      <Grid item md={12} xs={12}>
                        <FormGroup row>
                          <FormControlLabel
                            control={
                              <Switch
                                name={pursuing}
                                checked={formState.values[pursuing] || false}
                                onChange={handleChange}
                                value={formState.values[pursuing] || false}
                              />
                            }
                            label={
                              formState.values[pursuing] === true
                                ? "Pursuing"
                                : "Passed"
                            }
                          />
                        </FormGroup>
                      </Grid>
                    </Grid>

                    <Grid container spacing={3}>
                      <Grid item md={12} xs={12}>
                        <Autocomplete
                          id="year-of-passing"
                          // className={claselementrootses.}
                          options={academicYears}
                          getOptionLabel={option => option.name}
                          disabled={!!formState.values[pursuing]}
                          onChange={(event, value) => {
                            handleChangeAutoComplete(
                              yearOfPassing,
                              event,
                              value
                            );
                          }}
                          value={
                            academicYears[
                              academicYears.findIndex(function (item) {
                                return (
                                  item.id === formState.values[yearOfPassing]
                                );
                              })
                            ] || null
                          }
                          renderInput={params => (
                            <TextField
                              {...params}
                              error={hasError(yearOfPassing)}
                              label={
                                formState.values["pursuing"]
                                  ? "Current Year"
                                  : "Year of passing"
                              }
                              variant="outlined"
                              name="tester"
                              helperText={
                                hasError(yearOfPassing)
                                  ? formState.errors[yearOfPassing].map(
                                      error => {
                                        return error + " ";
                                      }
                                    )
                                  : null
                              }
                            />
                          )}
                        />
                      </Grid>
                    </Grid>

                    <Grid container spacing={3}>
                      <Grid item md={12} xs={12}>
                        <Autocomplete
                          // className={classes.elementroot}
                          id="qualification-list"
                          options={genericConstants.QUALIFICATION_LIST}
                          getOptionLabel={option => option.name}
                          onChange={(event, value) => {
                            handleChangeAutoComplete(
                              qualification,
                              event,
                              value
                            );
                          }}
                          value={
                            genericConstants.QUALIFICATION_LIST[
                              genericConstants.QUALIFICATION_LIST.findIndex(
                                function (item) {
                                  return (
                                    item.id === formState.values[qualification]
                                  );
                                }
                              )
                            ] || null
                          }
                          renderInput={params => (
                            <TextField
                              {...params}
                              error={hasError(qualification)}
                              label="Qualification"
                              variant="outlined"
                              name="tester"
                              helperText={
                                hasError(qualification)
                                  ? formState.errors[qualification].map(
                                      error => {
                                        return error + " ";
                                      }
                                    )
                                  : null
                              }
                            />
                          )}
                        />
                      </Grid>
                    </Grid>
                    {formState.values[qualification] == "other" ? (
                      <Grid container spacing={3}>
                        <Grid item md={12} xs={12}>
                          <TextField
                            fullWidth
                            id="otherQualification"
                            label="Other Qualification"
                            margin="normal"
                            name="otherQualification"
                            onChange={handleChange}
                            type="text"
                            value={formState.values["otherQualification"] || ""}
                            error={hasError("otherQualification")}
                            helperText={
                              hasError("otherQualification")
                                ? formState.errors["otherQualification"].map(
                                    error => {
                                      return error + " ";
                                    }
                                  )
                                : null
                            }
                            variant="outlined"
                            // className={classes.elementroot}
                          />
                        </Grid>
                      </Grid>
                    ) : null}
                    {!formState.hideYear ? (
                      <Grid container spacing={3}>
                        <Grid item md={12} xs={12}>
                          <Autocomplete
                            id="education-list"
                            // className={classes.elementroot}
                            options={genericConstants.EDUCATIONS}
                            getOptionLabel={option => option.value}
                            onChange={(event, value) => {
                              handleChangeAutoComplete(
                                educationYear,
                                event,
                                value
                              );
                            }}
                            value={
                              genericConstants.EDUCATIONS[
                                genericConstants.EDUCATIONS.findIndex(function (
                                  item
                                ) {
                                  return (
                                    item.id === formState.values[educationYear]
                                  );
                                })
                              ] || null
                            }
                            renderInput={params => (
                              <TextField
                                {...params}
                                error={hasError(educationYear)}
                                label="Education Year"
                                // required={
                                //   !(
                                //     formState.values[qualification] ==
                                //       "secondary" ||
                                //     formState.values[qualification] ==
                                //       "senior_secondary"
                                //   )
                                // }
                                variant="outlined"
                                name="tester"
                                helperText={
                                  hasError(educationYear)
                                    ? formState.errors[educationYear].map(
                                        error => {
                                          return error + " ";
                                        }
                                      )
                                    : null
                                }
                              />
                            )}
                          />
                        </Grid>
                      </Grid>
                    ) : null}
                    <Grid container spacing={3}>
                      <Grid item md={12} xs={12}>
                        <Autocomplete
                          // className={classes.elementroot}
                          id="board-list"
                          options={boards}
                          getOptionLabel={option => option.name}
                          onChange={(event, value) => {
                            handleChangeAutoComplete(board, event, value);
                          }}
                          value={
                            boards[
                              boards.findIndex(function (item) {
                                return item.id === formState.values[board];
                              })
                            ] || null
                          }
                          renderInput={params => (
                            <TextField
                              {...params}
                              error={hasError(board)}
                              label="Board"
                              variant="outlined"
                              name="tester"
                              helperText={
                                hasError(board)
                                  ? formState.errors[board].map(error => {
                                      return error + " ";
                                    })
                                  : null
                              }
                            />
                          )}
                        />
                      </Grid>
                    </Grid>
                    {formState.values[board] == formState.otherId ? (
                      <Grid container spacing={3}>
                        <Grid item md={12} xs={12}>
                          <TextField
                            fullWidth
                            id="otherboard"
                            label="Other board"
                            margin="normal"
                            name="otherboard"
                            onChange={handleChange}
                            type="text"
                            value={formState.values["otherboard"] || ""}
                            error={hasError("otherboard")}
                            helperText={
                              hasError("otherboard")
                                ? formState.errors["otherboard"].map(error => {
                                    return error + " ";
                                  })
                                : null
                            }
                            variant="outlined"
                            // className={classes.elementroot}
                          />
                        </Grid>
                      </Grid>
                    ) : null}
                    <Grid container spacing={3}>
                      <Grid item md={6} xs={12}>
                        <TextField
                          fullWidth
                          id={get(EducationSchema[marksObtained], "id")}
                          label={get(EducationSchema[marksObtained], "label")}
                          name={marksObtained}
                          onChange={handleChange}
                          type={get(EducationSchema[marksObtained], "type")}
                          value={formState.values[marksObtained] || ""}
                          error={hasError(marksObtained)}
                          helperText={
                            hasError(marksObtained)
                              ? formState.errors[marksObtained].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                          variant="outlined"
                          disabled={!!formState.values[pursuing]}
                        />
                      </Grid>
                      <Grid item md={6} xs={12}>
                        <TextField
                          fullWidth
                          id={get(EducationSchema[totalMarks], "id")}
                          label={get(EducationSchema[totalMarks], "label")}
                          name={totalMarks}
                          onChange={handleChange}
                          type={get(EducationSchema[totalMarks], "type")}
                          value={formState.values[totalMarks] || ""}
                          error={hasError(totalMarks)}
                          helperText={
                            hasError(totalMarks)
                              ? formState.errors[totalMarks].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                          variant="outlined"
                          disabled={!!formState.values[pursuing]}
                        />
                      </Grid>
                    </Grid>
                    <Grid container spacing={3}>
                      <Grid item md={12} xs={12}>
                        <TextField
                          fullWidth
                          id={get(EducationSchema[percentage], "id")}
                          label={get(EducationSchema[percentage], "label")}
                          name={percentage}
                          onChange={handleChange}
                          type={get(EducationSchema[percentage], "type")}
                          value={formState.values[percentage] || ""}
                          error={hasError(percentage)}
                          helperText={
                            hasError(percentage)
                              ? formState.errors[percentage].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                          variant="outlined"
                          disabled
                        />
                      </Grid>
                    </Grid>
                    <Grid container spacing={3}>
                      <Grid item md={12} xs={12}>
                        <TextField
                          fullWidth
                          id={institute}
                          label="Institute"
                          name={institute}
                          onChange={handleChange}
                          type="text"
                          value={formState.values[institute] || ""}
                          error={hasError(institute)}
                          helperText={
                            hasError(institute)
                              ? formState.errors[institute].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                          variant="outlined"
                          // className={classes.elementroot}
                        />
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
            </CardContent>
            <Grid item xs={12} className={classes.CardActionGrid}>
              <CardActions className={classes.btnspace}>
                <Grid item xs={12}>
                  <Grid item xs={12} md={6} xl={3}>
                    <Grid container spacing={3}>
                      <Grid item md={2} xs={12}>
                        <YellowButton
                          type="submit"
                          color="primary"
                          variant="contained"
                          style={{ marginRight: "18px" }}
                          onClick={handleSubmit}
                        >
                          {genericConstants.SAVE_BUTTON_TEXT}
                        </YellowButton>
                      </Grid>
                      <Grid item md={3} xs={12}>
                        <YellowButton
                          color="primary"
                          type="submit"
                          mfullWidth
                          variant="contained"
                          style={{ marginRight: "18px" }}
                          onClick={saveAndNext}
                        >
                          <span>
                            {genericConstants.SAVE_AND_NEXT_BUTTON_TEXT}
                          </span>
                        </YellowButton>
                      </Grid>
                      <Grid item md={2} xs={12}>
                        <GrayButton
                          type="submit"
                          color="primary"
                          variant="contained"
                          to={routeConstants.VIEW_EDUCATION}
                        >
                          {genericConstants.CANCEL_BUTTON_TEXT}
                        </GrayButton>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </CardActions>
            </Grid>
          </form>
        </Card>
      </Grid>
    </Grid>
  );
}
Example #15
Source File: AddEditUser.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditUser = props => {
  /** Initializing all the hooks */
  const classes = useStyles();
  const history = useHistory();
  const [formState, setFormState] = useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    isSuccess: false,
    isZoneBlocked: props.isZoneBlocked === "false" ? false : true,
    isRPCBlocked: props.isRPCBlocked === "false" ? false : true,
    isCollegeBlocked: props.isCollegeBlocked === "false" ? false : true,
    showPassword: props.showPassword ? props.showPassword : false,
    isEditUser: props["editUser"] ? props["editUser"] : false,
    dataForEdit: props["dataForEdit"] ? props["dataForEdit"] : {},
    counter: props.counter ? props.counter : 0,
    isCollegeAdmin:
      auth.getUserInfo() !== undefined &&
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name !== undefined &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
        ? true
        : false
  });
  const [states, setStates] = useState(
    props.stateOption ? props.stateOption : []
  );
  const [backdrop, setBackDrop] = useState(false);
  const [zones, setZones] = useState(props.zoneOption ? props.zoneOption : []);
  const [rpcs, setRpcs] = useState(props.rpcOption ? props.rpcOption : []);
  const [colleges, setColleges] = useState(
    props.collegeOption ? props.collegeOption : []
  );
  const [roles, setRoles] = useState(props.option ? props.option : []);
  const [isDisable, setIsDisable] = useState(false);

  /** Part for editing user */
  if (formState.isEditUser && !formState.counter) {
    if (props["dataForEdit"]) {
      formState.values[password] = undefined;
      if (props["dataForEdit"]["first_name"]) {
        formState.values[firstname] = props["dataForEdit"]["first_name"];
      }
      if (props["dataForEdit"]["last_name"]) {
        formState.values[lastname] = props["dataForEdit"]["last_name"];
      }
      if (
        props["dataForEdit"]["contact"] &&
        props["dataForEdit"]["contact"]["email"]
      ) {
        formState.values[email] = props["dataForEdit"]["contact"]["email"];
      }
      if (
        props["dataForEdit"]["contact"] &&
        props["dataForEdit"]["contact"]["phone"]
      ) {
        formState.values[contact] = props["dataForEdit"]["contact"]["phone"];
      }
      if (
        props["dataForEdit"]["contact"] &&
        props["dataForEdit"]["contact"]["user"] &&
        props["dataForEdit"]["contact"]["user"]["blocked"]
      ) {
        formState.values[blocked] =
          props["dataForEdit"]["contact"]["user"]["blocked"];
      }
      if (
        props["dataForEdit"]["contact"] &&
        props["dataForEdit"]["contact"]["user"] &&
        props["dataForEdit"]["contact"]["user"]["role"] &&
        props["dataForEdit"]["contact"]["user"]["role"]["id"]
      ) {
        formState.values[role] =
          props["dataForEdit"]["contact"]["user"]["role"]["id"];
      }
      if (
        props["dataForEdit"]["contact"]["user"]["role"]["name"] ===
          roleConstants.STUDENT ||
        props["dataForEdit"]["contact"]["user"]["role"]["name"] ===
          roleConstants.MEDHAADMIN ||
        props["dataForEdit"]["contact"]["user"]["role"]["name"] ===
          roleConstants.DEPARTMENTADMIN
      ) {
        setFormState(formState => ({
          ...formState,
          isCollegeBlocked: true,
          isRPCBlocked: true,
          isZoneBlocked: true
        }));
      } else if (
        props["dataForEdit"]["contact"]["user"]["role"]["name"] ===
        roleConstants.RPCADMIN
      ) {
        setFormState(formState => ({
          ...formState,
          isCollegeBlocked: true,
          isRPCBlocked: false,
          isZoneBlocked: true
        }));
      } else if (
        props["dataForEdit"]["contact"]["user"]["role"]["name"] ===
        roleConstants.ZONALADMIN
      ) {
        setFormState(formState => ({
          ...formState,
          isCollegeBlocked: true,
          isRPCBlocked: true,
          isZoneBlocked: false
        }));
      } else if (
        props["dataForEdit"]["contact"]["user"]["role"]["name"] ===
        roleConstants.COLLEGEADMIN
      ) {
        setFormState(formState => ({
          ...formState,
          isCollegeBlocked: false,
          isRPCBlocked: true,
          isZoneBlocked: true
        }));
      }
      if (
        props["dataForEdit"]["contact"] &&
        props["dataForEdit"]["contact"]["user"] &&
        props["dataForEdit"]["contact"]["user"]["role"] &&
        props["dataForEdit"]["contact"]["user"]["role"]["name"] ===
          roleConstants.STUDENT
      ) {
        /** For populating state */
        if (
          props["dataForEdit"] &&
          props["dataForEdit"]["contact"] &&
          props["dataForEdit"]["contact"]["state"]
        ) {
          formState.values[state] =
            props["dataForEdit"]["contact"]["state"]["id"];
        } else {
          formState.values[state] = "";
        }

        /** For populating zone */
        if (
          props["dataForEdit"]["organization"] &&
          props["dataForEdit"]["organization"]["zone"]
        ) {
          formState.values[zone] =
            props["dataForEdit"]["organization"]["zone"]["id"];
        } else {
          formState.values[zone] = "";
        }

        /** For populating rpc */
        if (
          props["dataForEdit"]["organization"] &&
          props["dataForEdit"]["organization"]["rpc"]
        ) {
          formState.values[rpc] = props["dataForEdit"]["organization"]["rpc"];
        } else {
          formState.values[rpc] = "";
        }

        /** For populating ipc */
        if (props["dataForEdit"]["organization"]) {
          formState.values[college] =
            props["dataForEdit"]["organization"]["id"];
        } else {
          formState.values[college] = "";
        }
      } else {
        /** For populating state */
        if (
          props["dataForEdit"] &&
          props["dataForEdit"]["contact"] &&
          props["dataForEdit"]["contact"]["user"] &&
          props["dataForEdit"]["contact"]["user"]["state"]
        ) {
          formState.values[state] =
            props["dataForEdit"]["contact"]["user"]["state"]["id"];
        } else {
          formState.values[state] = "";
        }

        /** For populating zone */
        if (
          props["dataForEdit"] &&
          props["dataForEdit"]["contact"] &&
          props["dataForEdit"]["contact"]["user"] &&
          props["dataForEdit"]["contact"]["user"]["zone"]
        ) {
          formState.values[zone] =
            props["dataForEdit"]["contact"]["user"]["zone"]["id"];
        } else {
          formState.values[zone] = "";
        }

        /** For populating rpc */
        if (
          props["dataForEdit"] &&
          props["dataForEdit"]["contact"] &&
          props["dataForEdit"]["contact"]["user"] &&
          props["dataForEdit"]["contact"]["user"]["rpc"]
        ) {
          formState.values[rpc] =
            props["dataForEdit"]["contact"]["user"]["rpc"]["id"];
        } else {
          formState.values[rpc] = "";
        }

        /** For populating ipc */
        if (props["dataForEdit"]["organization"]) {
          formState.values[college] =
            props["dataForEdit"]["organization"]["id"];
        } else {
          formState.values[college] = "";
        }
      }
    }
    formState.counter += 1;
  }

  /** Use Effect function to set roles */
  useEffect(() => {
    /** Initially clear all the vlidations */
    clearValidations();

    let paramsForPageSize = {
      pageSize: -1
    };

    serviceProvider
      .serviceProviderForGetRequest(COLLEGE_URL, paramsForPageSize)
      .then(res => {
        setColleges(res.data.result);
      })
      .catch(error => {
        console.log(error);
      });

    serviceProvider
      .serviceProviderForGetRequest(STATES_URL, paramsForPageSize)
      .then(res => {
        res.data.result.map(s => {
          if (s.name === "Uttar Pradesh") {
            stateId = s.id;
            let zones_url =
              STATES_URL +
              "/" +
              stateId +
              "/" +
              strapiApiConstants.STRAPI_ZONES;

            serviceProvider
              .serviceProviderForGetRequest(zones_url)
              .then(res => {
                setZones(res.data.result);
              })
              .catch(error => {
                console.log("error", error);
              });
          }
        });
        setStates(res.data.result);
      })
      .catch(error => {
        console.log(error);
      });

    serviceProvider
      .serviceProviderForGetRequest(ROLES_URL, paramsForPageSize)
      .then(res => {
        let roles = [];
        let studentRole = null;
        for (let i in res.data.roles) {
          if (
            res.data.roles[i]["name"] !== "Admin" &&
            res.data.roles[i]["name"] !== "Authenticated" &&
            res.data.roles[i]["name"] !== "Public" &&
            res.data.roles[i]["name"] !== roleConstants.STUDENT &&
            res.data.roles[i]["name"] !== roleConstants.RPCADMIN
          ) {
            roles.push(res.data.roles[i]);
          }
          if (
            formState.isEditUser &&
            res.data.roles[i]["name"] === roleConstants.STUDENT
          ) {
            studentRole = res.data.roles[i];
          }
          if (
            formState.dataForEdit["contact"] &&
            formState.dataForEdit["contact"]["user"] &&
            formState.dataForEdit["contact"]["user"]["role"] &&
            formState.dataForEdit["contact"]["user"]["role"]["name"] ===
              roleConstants.STUDENT
          ) {
            setIsDisable(true);
          } else {
            setIsDisable(false);
          }
        }
        if (
          formState.isEditUser &&
          formState.dataForEdit["contact"]["user"]["role"]["name"] ===
            roleConstants.STUDENT
        ) {
          setRoles([studentRole]);
        } else {
          setRoles(roles);
        }
      })
      .catch(error => {
        console.log(error);
      });
  }, []);

  const handleChange = e => {
    /** TO SET VALUES IN FORMSTATE */
    e.persist();
    setFormState(formState => ({
      ...formState,

      values: {
        ...formState.values,
        [e.target.name]:
          e.target.type === "checkbox" ? e.target.checked : e.target.value
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      }
    }));
    if (formState.errors.hasOwnProperty(e.target.name)) {
      delete formState.errors[e.target.name];
    }
  };

  /** Handle change for autocomplete fields */
  const handleChangeAutoComplete = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (value !== null) {
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          [eventName]: value.id
        },
        touched: {
          ...formState.touched,
          [eventName]: true
        },
        isStateClearFilter: false
      }));
      if (eventName === college) {
        setFormState(formState => ({
          ...formState,
          values: {
            ...formState.values,
            [zone]: value.zone.id,
            [rpc]: value.rpc.id
          }
        }));
      }
      /** Get dependent roles */
      if (eventName === role) {
        let roleName = value.id;
        clearValidations();
        setValidationsForDifferentRoles(roleName);
      }
      /** This is used to remove any existing errors if present in auto complete */
      if (formState.errors.hasOwnProperty(eventName)) {
        delete formState.errors[eventName];
      }
    } else {
      let setStateFilterValue = false;
      /** If we click cross for state the zone and rpc should clear off! */
      if (eventName === state) {
        /** 
        This flag is used to determine that state is cleared which clears 
        off zone and rpc by setting their value to null 
        */
        setStateFilterValue = true;
        clearZoneRpcCollege();
        /** 
        When state is cleared then clear rpc and zone 
        */
      }
      if (eventName === zone || eventName === rpc) {
        setFormState(formState => ({
          ...formState,
          isCollegeBlocked: true
        }));
        delete formState.values[college];
      }
      /** Clear dependent roles */
      if (eventName === role) {
        clearZoneRpcCollege();
        clearValidations();
      }
      setFormState(formState => ({
        ...formState,
        isStateClearFilter: setStateFilterValue
      }));
      /** This is used to remove clear out data form auto complete when we click cross icon of auto complete */
      delete formState.values[eventName];
    }
  };

  const clearZoneRpcCollege = () => {
    setFormState(formState => ({
      ...formState,
      isCollegeBlocked: true,
      isRPCBlocked: true,
      isZoneBlocked: true
    }));
    delete formState.values[zone];
    delete formState.values[rpc];
    delete formState.values[college];
  };

  const clearValidations = () => {
    delete formState.errors[rpc];
    delete formState.errors[state];
    delete formState.errors[zone];
    delete formState.errors[college];
    UserSchema[rpc]["required"] = false;
    UserSchema[state]["required"] = false;
    UserSchema[zone]["required"] = false;
    UserSchema[college]["required"] = false;
    UserSchema[rpc]["validations"] = {};
    UserSchema[state]["validations"] = {};
    UserSchema[zone]["validations"] = {};
    UserSchema[college]["validations"] = {};
  };

  const setValidationsForDifferentRoles = (roleId, forSubmit = false) => {
    let roleName = "";
    for (let i in roles) {
      if (roles[i]["id"] === roleId) {
        roleName = roles[i]["name"];
        break;
      }
    }
    if (roleName === roleConstants.COLLEGEADMIN) {
      delete formState.errors[rpc];
      delete formState.errors[zone];
      UserSchema[state]["required"] = true;
      UserSchema[college]["required"] = true;
      UserSchema[state]["validations"] = VALIDATIONFORSTATE;
      UserSchema[college]["validations"] = VALIDATIONFORCOLLEGE;

      setFormState(formState => ({
        ...formState,
        isCollegeBlocked: false,
        isRPCBlocked: true,
        isZoneBlocked: true
      }));
    } else if (roleName === roleConstants.RPCADMIN) {
      delete formState.errors[zone];
      delete formState.errors[college];
      UserSchema[rpc]["required"] = true;
      UserSchema[state]["required"] = true;
      UserSchema[rpc]["validations"] = VALIDATIONFORRPC;
      UserSchema[state]["validations"] = VALIDATIONFORSTATE;
      setFormState(formState => ({
        ...formState,
        isCollegeBlocked: true,
        isRPCBlocked: false,
        isZoneBlocked: true
      }));
    } else if (roleName === roleConstants.ZONALADMIN) {
      delete formState.errors[state];
      delete formState.errors[zone];
      UserSchema[state]["required"] = true;
      UserSchema[zone]["required"] = true;
      UserSchema[state]["validations"] = VALIDATIONFORSTATE;
      UserSchema[zone]["validations"] = VALIDATIONFORZONE;
      setFormState(formState => ({
        ...formState,
        isCollegeBlocked: true,
        isRPCBlocked: true,
        isZoneBlocked: false
      }));
    } else if (
      roleName === roleConstants.MEDHAADMIN ||
      roleName === roleConstants.DEPARTMENTADMIN
    ) {
      clearValidations();
      setFormState(formState => ({
        ...formState,
        isCollegeBlocked: true,
        isRPCBlocked: true,
        isZoneBlocked: true
      }));
    } else if (roleName === roleConstants.STUDENT) {
      clearValidations();
      setFormState(formState => ({
        ...formState,
        isCollegeBlocked: true,
        isRPCBlocked: true,
        isZoneBlocked: true
      }));
    }
  };
  const handleSubmit = event => {
    event.preventDefault();
    setBackDrop(true);
    formState.values[state] = stateId;
    if (formState.isEditUser) {
      UserSchema[password]["required"] = false;
      UserSchema[password]["validations"] = {
        validatePasswordMinLength: {
          value: "true",
          message: "Password is too short"
        }
      };
      if (formState.values[role]) {
        setValidationsForDifferentRoles(formState.values[role], true);
      }
    } else {
      UserSchema[password]["required"] = true;
      UserSchema[password]["validations"] = {
        required: {
          value: "true",
          message: "password is required"
        },
        validatePasswordMinLength: {
          value: "true",
          message: "Password is too short"
        }
      };
    }
    let isValid = false;
    let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
      formState.values,
      UserSchema
    );
    if (checkAllFieldsValid) {
      /** Evaluated only if all keys are valid inside formstate */
      formState.errors = formUtilities.setErrors(formState.values, UserSchema);
      if (formUtilities.checkEmpty(formState.errors)) {
        isValid = true;
      }
    } else {
      /** This is used to find out which all required fields are not filled */
      formState.values = formUtilities.getListOfKeysNotPresent(
        formState.values,
        UserSchema
      );
      formState.errors = formUtilities.setErrors(formState.values, UserSchema);
    }
    if (isValid) {
      /** CALL POST FUNCTION */
      postUserData();

      /** Call axios from here */
      setFormState(formState => ({
        ...formState,
        isValid: true
      }));
    } else {
      setBackDrop(false);
      setFormState(formState => ({
        ...formState,
        isValid: false
      }));
    }
  };

  const postUserData = async () => {
    setBackDrop(true);
    let postData = databaseUtilities.addUser(
      formState.values[contact],
      formState.values[email],
      formState.values[firstname],
      formState.values[lastname],
      formState.values[password] ? formState.values[password] : undefined,
      formState.values[contact],
      formState.values[blocked] ? formState.values[blocked] : false,
      formState.values[state] ? formState.values[state] : null,
      formState.values[zone] ? formState.values[zone] : null,
      formState.values[rpc] ? formState.values[rpc] : null,
      formState.values[college] ? formState.values[college] : null,
      formState.values[role] ? formState.values[role] : null
    );
    if (formState.isEditUser) {
      let EDIT_USER_URL =
        strapiApiConstants.STRAPI_DB_URL +
        strapiApiConstants.STRAPI_CONTACT_URL;
      let EDIT_URL = strapiApiConstants.STRAPI_EDIT_STUDENT + "?fromuser=true";
      serviceProvider
        .serviceProviderForPutRequest(
          EDIT_USER_URL,
          formState.dataForEdit.contact["id"],
          postData,
          EDIT_URL
        )
        .then(res => {
          history.push({
            pathname: routeConstants.MANAGE_USER,
            fromeditUser: true,
            isDataEdited: true,
            editedUserName: res.data.result,
            editResponseMessage: "",
            editedData: {}
          });
          setBackDrop(false);
        })
        .catch(error => {
          let errorMessage;

          if (
            error.response !== undefined &&
            error.response.status !== undefined &&
            error.response.status === 400
          ) {
            if (error.response.data["message"]) {
              errorMessage = error.response.data["message"];
            }
          }
          history.push({
            pathname: routeConstants.MANAGE_USER,
            fromeditUser: true,
            isDataEdited: false,
            editResponseMessage: errorMessage ? errorMessage : "",
            editedData: {}
          });
          setBackDrop(false);
        });
    } else {
      serviceProvider
        .serviceProviderForPostRequest(USERS_URL, postData)
        .then(res => {
          history.push({
            pathname: routeConstants.MANAGE_USER,
            fromAddUser: true,
            isDataAdded: true,
            addedUserName: res.data.user,
            addResponseMessage: "",
            addedData: {}
          });
          setBackDrop(false);
        })
        .catch(error => {
          let errorMessage;

          if (
            error.response !== undefined &&
            error.response.status !== undefined &&
            error.response.status === 400
          ) {
            if (error.response.data["message"]) {
              errorMessage = error.response.data["message"];
            }
          }
          history.push({
            pathname: routeConstants.MANAGE_USER,
            fromAddUser: true,
            isDataAdded: false,
            addResponseMessage: errorMessage ? errorMessage : "",
            addedData: {}
          });
        });
      setBackDrop(false);
    }
  };

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

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

  const hasError = field => (formState.errors[field] ? true : false);
  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        <Typography variant="h4" gutterBottom>
          {formState.isEditUser
            ? genericConstants.EDIT_USER_TITLE
            : genericConstants.ADD_USER_TITLE}
        </Typography>
      </Grid>
      <Grid spacing={3}>
        <Card>
          <form
            id="userForm"
            autoComplete="off"
            noValidate
            onSubmit={handleSubmit}
          >
            <CardContent>
              <Grid item xs={12} md={6} xl={3}>
                <Grid container spacing={3} className={classes.formgrid}>
                  <Grid item md={6} xs={12}>
                    <TextField
                      id={get(UserSchema[firstname], "id")}
                      label={get(UserSchema[firstname], "label")}
                      placeholder={get(UserSchema[firstname], "placeholder")}
                      name={firstname}
                      value={formState.values[firstname] || ""}
                      error={hasError(firstname)}
                      variant="outlined"
                      required
                      fullWidth
                      onChange={handleChange}
                      helperText={
                        hasError(firstname)
                          ? formState.errors[firstname].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <TextField
                      id={get(UserSchema[lastname], "id")}
                      label={get(UserSchema[lastname], "label")}
                      placeholder={get(UserSchema[lastname], "placeholder")}
                      name={lastname}
                      value={formState.values[lastname] || ""}
                      error={hasError(lastname)}
                      variant="outlined"
                      required
                      fullWidth
                      onChange={handleChange}
                      helperText={
                        hasError(lastname)
                          ? formState.errors[lastname].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12}>
                    <TextField
                      id={get(UserSchema[email], "id")}
                      label={get(UserSchema[email], "label")}
                      placeholder={get(UserSchema[email], "placeholder")}
                      name={email}
                      value={formState.values[email] || ""}
                      error={hasError(email)}
                      variant="outlined"
                      required
                      fullWidth
                      onChange={handleChange}
                      helperText={
                        hasError(email)
                          ? formState.errors[email].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={6} xs={12}>
                    <TextField
                      id={get(UserSchema[contact], "id")}
                      label={get(UserSchema[contact], "label")}
                      placeholder={get(UserSchema[contact], "placeholder")}
                      name={contact}
                      value={formState.values[contact] || ""}
                      error={hasError(contact)}
                      variant="outlined"
                      required
                      fullWidth
                      onChange={handleChange}
                      helperText={
                        hasError(contact)
                          ? formState.errors[contact].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id={get(UserSchema[role], "id")}
                      className={classes.root}
                      options={roles}
                      disabled={isDisable}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete(role, event, value);
                      }}
                      value={
                        roles[
                          roles.findIndex(function (item, i) {
                            return item.id === formState.values[role];
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError(role)}
                          label={get(UserSchema[role], "label")}
                          placeholder={get(UserSchema[role], "placeholder")}
                          variant="outlined"
                          name="tester"
                          helperText={
                            hasError(role)
                              ? formState.errors[role].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
              </Grid>
              <Divider className={classes.divider} />
              <Grid item xs={12} md={6} xl={3}>
                <Grid container spacing={3} className={classes.formgrid}>
                  <Grid item md={6} xs={12}>
                    <FormControl variant="outlined" fullWidth>
                      <InputLabel
                        htmlFor="outlined-adornment-password"
                        fullWidth
                        error={hasError(password)}
                      >
                        {get(UserSchema[password], "label")}
                      </InputLabel>
                      <OutlinedInput
                        id={get(UserSchema[password], "id")}
                        placeholder={get(UserSchema[password], "placeholder")}
                        name={password}
                        required
                        fullWidth
                        error={hasError(password)}
                        type={formState.showPassword ? "text" : "password"}
                        value={formState.values[password] || ""}
                        onChange={handleChange}
                        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}
                      />
                      <FormHelperText error={hasError(password)}>
                        {hasError(password)
                          ? formState.errors[password].map(error => {
                              return error + " ";
                            })
                          : null}
                      </FormHelperText>
                    </FormControl>
                  </Grid>
                  <Grid item md={4} xs={12}>
                    <FormGroup row>
                      <FormControlLabel
                        id="blocked"
                        control={
                          <Switch
                            id="blocked"
                            name={blocked}
                            checked={formState.values[blocked] || false}
                            onChange={handleChange}
                            value={formState.values[blocked] || false}
                            error={hasError(blocked)}
                            helperText={
                              hasError(blocked)
                                ? formState.errors[blocked].map(error => {
                                    return error + " ";
                                  })
                                : null
                            }
                          />
                        }
                        label={formState.values[blocked] ? "Unblock" : "Block"}
                      />
                    </FormGroup>
                  </Grid>
                </Grid>
              </Grid>

              <Grid item xs={12} md={6} xl={3}>
                <Grid container spacing={3} className={classes.formgrid}>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id={get(UserSchema[zone], "id")}
                      className={classes.root}
                      disabled={isDisable || formState.isZoneBlocked}
                      options={zones}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete(zone, event, value);
                      }}
                      value={
                        isDisable || formState.isZoneBlocked
                          ? null
                          : zones[
                              zones.findIndex(function (item, i) {
                                return item.id === formState.values[zone];
                              })
                            ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          label={get(UserSchema[zone], "label")}
                          placeholder={get(UserSchema[zone], "placeholder")}
                          variant="outlined"
                          error={hasError(zone)}
                          helperText={
                            hasError(zone)
                              ? formState.errors[zone].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id={get(UserSchema[college], "id")}
                      className={classes.root}
                      disabled={isDisable || formState.isCollegeBlocked}
                      options={colleges}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete(college, event, value);
                      }}
                      value={
                        isDisable || formState.isCollegeBlocked
                          ? null
                          : colleges[
                              colleges.findIndex(function (item, i) {
                                return item.id === formState.values[college];
                              })
                            ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          label={get(UserSchema[college], "label")}
                          placeholder={get(UserSchema[college], "placeholder")}
                          variant="outlined"
                          error={hasError(college)}
                          helperText={
                            hasError(college)
                              ? formState.errors[college].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
              </Grid>
            </CardContent>
            <Grid item xs={12} className={classes.CardActionGrid}>
              <CardActions className={classes.btnspace}>
                <Grid item xs={12}>
                  <Grid item xs={12} md={6} xl={3}>
                    <Grid container spacing={3}>
                      <Grid item md={2} xs={12}>
                        <YellowButton
                          type="submit"
                          color="primary"
                          variant="contained"
                        >
                          {genericConstants.SAVE_BUTTON_TEXT}
                        </YellowButton>
                      </Grid>
                      <Grid item md={2} xs={12}>
                        <GrayButton
                          type="submit"
                          color="primary"
                          variant="contained"
                          to={routeConstants.MANAGE_USER}
                        >
                          {genericConstants.CANCEL_BUTTON_TEXT}
                        </GrayButton>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </CardActions>
            </Grid>
          </form>
        </Card>
      </Grid>
      <Backdrop className={classes.backDrop} open={backdrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </Grid>
  );
}
Example #16
Source File: ViewUser.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
ViewUser = props => {
  const classes = useStyles();
  const history = useHistory();
  const { loaderStatus, setLoaderStatus } = useContext(LoaderContext);
  const [isDisable, setIsDisable] = useState(false);

  const [formState, setFormState] = useState({
    userDetails: []
  });
  useEffect(() => {
    getUserData();
  }, []);

  const getUserData = async () => {
    setLoaderStatus(true);
    let paramsForUser;

    if (auth.getUserInfo().role.name === roleConstants.MEDHAADMIN) {
      paramsForUser = props["location"]["dataForEdit"];
    }
    let VIEW_USER_URL = USER_URL + "/" + paramsForUser;
    if (paramsForUser !== undefined) {
      await serviceProviders
        .serviceProviderForGetRequest(VIEW_USER_URL)
        .then(res => {
          if (
            res.data.result.contact.user.role.name === roleConstants.STUDENT
          ) {
            setIsDisable(true);
          } else {
            setIsDisable(false);
          }
          setFormState(formState => ({
            ...formState,
            userDetails: res.data.result
          }));
        })
        .catch(error => {
          console.log("error", error);
        });
    } else {
      history.push({
        pathname: routeConstants.MANAGE_USER
      });
    }
    setLoaderStatus(false);
  };

  const editData = () => {
    getDataForEdit(props["location"]["dataForEdit"]);
  };

  const getDataForEdit = async id => {
    setLoaderStatus(true);
    let EDIT_USER_URL = USER_URL + "/" + id;
    await serviceProviders
      .serviceProviderForGetRequest(EDIT_USER_URL)
      .then(res => {
        let editData = res.data.result;
        /** move to edit page */
        history.push({
          pathname: routeConstants.EDIT_USER,
          editUser: true,
          dataForEdit: editData
        });
      })
      .catch(error => {
        console.log("error");
      });
    setLoaderStatus(false);
  };
  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        <Typography variant="h4" gutterBottom>
          {genericConstants.VIEW_USER_TITLE}
        </Typography>
      </Grid>
      <Grid spacing={3}>
        <Card>
          <CardContent>
            <Grid item xs={12} md={6} xl={3}>
              <Grid container spacing={3} className={classes.formgrid}>
                <Grid item md={6} xs={12}>
                  <ReadOnlyTextField
                    id="firstname"
                    label="First Name"
                    defaultValue={formState.userDetails.first_name}
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <ReadOnlyTextField
                    id="lastname"
                    label="Last Name"
                    defaultValue={formState.userDetails.last_name}
                  />
                </Grid>
              </Grid>
              <Grid container spacing={3} className={classes.MarginBottom}>
                <Grid item md={12} xs={12}>
                  <ReadOnlyTextField
                    id="email"
                    label="Email"
                    defaultValue={
                      formState.userDetails.contact
                        ? formState.userDetails.contact.user
                          ? formState.userDetails.contact.user.email
                            ? formState.userDetails.contact.user.email
                            : ""
                          : ""
                        : ""
                    }
                  />
                </Grid>
              </Grid>
              <Grid container spacing={3} className={classes.MarginBottom}>
                <Grid item md={6} xs={12}>
                  <ReadOnlyTextField
                    id="contact"
                    label="Contact"
                    defaultValue={
                      formState.userDetails.contact
                        ? formState.userDetails.contact.phone
                          ? formState.userDetails.contact.phone
                          : ""
                        : ""
                    }
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <ReadOnlyTextField
                    id="role"
                    label="Role"
                    defaultValue={
                      formState.userDetails.contact
                        ? formState.userDetails.contact.user
                          ? formState.userDetails.contact.user.role
                            ? formState.userDetails.contact.user.role.name
                            : ""
                          : ""
                        : ""
                    }
                  />
                </Grid>
              </Grid>
            </Grid>
            <Divider className={classes.divider} />
            <Grid item md={4} xs={12}>
              <FormGroup row>
                <FormControlLabel
                  control={
                    <Switch
                      checked={
                        formState.userDetails.contact
                          ? formState.userDetails.contact.user
                            ? formState.userDetails.contact.user.blocked ||
                              false
                            : ""
                          : ""
                      }
                      value={
                        formState.userDetails.contact
                          ? formState.userDetails.contact.user
                            ? formState.userDetails.contact.user.blocked
                            : ""
                          : ""
                      }
                      disabled={true}
                    />
                  }
                  label={
                    formState.userDetails.contact
                      ? formState.userDetails.contact.user
                        ? formState.userDetails.contact.user.blocked
                          ? "Blocked"
                          : "Unblocked"
                        : ""
                      : ""
                  }
                />
              </FormGroup>
            </Grid>
            <Divider className={classes.divider} />
            <Grid item xs={12} md={6} xl={3}>
              <Grid container spacing={3} className={classes.formgrid}>
                {/* <Grid item md={6} xs={12}>
                  <ReadOnlyTextField
                    id="state"
                    label="State"
                    disabled={isDisable}
                    defaultValue={
                      isDisable
                        ? null
                        : formState.userDetails.contact
                        ? formState.userDetails.contact.user
                          ? formState.userDetails.contact.user.state
                            ? formState.userDetails.contact.user.state.name
                            : ""
                          : ""
                        : ""
                    }
                  />
                </Grid> */}
                <Grid item md={6} xs={12}>
                  <ReadOnlyTextField
                    id="zone"
                    label="Zone"
                    disabled={isDisable}
                    defaultValue={
                      isDisable
                        ? null
                        : formState.userDetails.contact
                        ? formState.userDetails.contact.user
                          ? formState.userDetails.contact.user.zone
                            ? formState.userDetails.contact.user.zone.name
                            : ""
                          : ""
                        : ""
                    }
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <ReadOnlyTextField
                    id="rpc"
                    label="RPC"
                    disabled={isDisable}
                    defaultValue={
                      isDisable
                        ? null
                        : formState.userDetails.contact
                        ? formState.userDetails.contact.user
                          ? formState.userDetails.contact.user.rpc
                            ? formState.userDetails.contact.user.rpc.name
                            : ""
                          : ""
                        : ""
                    }
                  />
                </Grid>
              </Grid>
              <Grid container spacing={3} className={classes.MarginBottom}>
                <Grid item md={6} xs={12}>
                  <ReadOnlyTextField
                    id="college"
                    label="College"
                    disabled={isDisable}
                    defaultValue={
                      isDisable
                        ? null
                        : formState.userDetails.organization
                        ? formState.userDetails.organization.name
                          ? formState.userDetails.organization.name
                          : ""
                        : ""
                    }
                  />
                </Grid>
              </Grid>
            </Grid>
          </CardContent>
          <Grid item xs={12} className={classes.CardActionGrid}>
            <CardActions className={classes.btnspace}>
              <Grid item xs={12}>
                <Grid item xs={12} md={6} xl={3}>
                  <Grid container spacing={3}>
                    <Grid item md={2} xs={12}>
                      <YellowButton
                        type="submit"
                        color="primary"
                        variant="contained"
                        onClick={editData}
                        className={classes.submitbtn}
                      >
                        Edit
                      </YellowButton>
                    </Grid>

                    <Grid item md={2} xs={12}>
                      <GrayButton
                        color="primary"
                        variant="contained"
                        to={routeConstants.MANAGE_USER}
                        className={classes.resetbtn}
                      >
                        Cancel
                      </GrayButton>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
            </CardActions>
          </Grid>
        </Card>
      </Grid>
    </Grid>
  );
}
Example #17
Source File: user-details.js    From js-miniapp with MIT License 4 votes vote down vote up
function UserDetails(props: UserDetailsProps) {
  const [state, dispatch] = useReducer(dataFetchReducer, initialState);
  const classes = useStyles();

  const buttonClassname = clsx({
    [classes.buttonFailure]: state.isError,
    [classes.buttonSuccess]: !state.isError,
  });

  function requestUserDetails() {
    const permissionsList = [
      {
        name: CustomPermissionName.USER_NAME,
        description:
          'We would like to display your Username on your profile page.',
      },
      {
        name: CustomPermissionName.PROFILE_PHOTO,
        description:
          'We would like to display your Profile Photo on your profile page.',
      },
      {
        name: CustomPermissionName.CONTACT_LIST,
        description: 'We would like to send messages to your contacts.',
      },
    ];

    props
      .requestPermissions(permissionsList)
      .then((permissions) => filterAllowedPermissions(permissions))
      .then((permissions) =>
        Promise.all([
          hasPermission(CustomPermissionName.USER_NAME, permissions)
            ? props.getUserName()
            : null,
          hasPermission(CustomPermissionName.PROFILE_PHOTO, permissions)
            ? props.getProfilePhoto()
            : null,
          hasPermission(CustomPermissionName.CONTACT_LIST, permissions)
            ? props.getContacts()
            : null,
        ])
      )
      .then(() => dispatch({ type: 'FETCH_SUCCESS' }))
      .catch((e) => {
        console.error(e);
        dispatch({ type: 'FETCH_FAILURE' });
      });
  }

  function requestPoints() {
    const permissionsList = [
      {
        name: CustomPermissionName.POINTS,
        description:
          'We would like to display your Points on your profile page.',
      },
    ];

    props
      .requestPermissions(permissionsList)
      .then((permissions) => filterAllowedPermissions(permissions))
      .then((permissions) =>
        Promise.all([
          hasPermission(CustomPermissionName.POINTS, permissions)
            ? props.getPoints()
            : null,
        ])
      )
      .then(() => dispatch({ type: 'POINTS_FETCH_SUCCESS' }))
      .catch((e) => {
        console.error(e);
        dispatch({ type: 'POINTS_FETCH_FAILURE' });
      });
  }

  function filterAllowedPermissions(permissions) {
    return permissions
      .filter(
        (permission) => permission.status === CustomPermissionStatus.ALLOWED
      )
      .map((permission) => permission.name);
  }

  function handleClick(e) {
    if (!state.isLoading) {
      e.preventDefault();
      dispatch({ type: 'FETCH_INIT' });
      requestUserDetails();
    }
  }

  function handlePointsClick(e) {
    if (!state.isLoading) {
      e.preventDefault();
      dispatch({ type: 'POINTS_FETCH_INIT' });
      requestPoints();
    }
  }

  function ProfilePhoto() {
    const hasDeniedPermission =
      state.hasRequestedPermissions &&
      !hasPermission(CustomPermissionName.PROFILE_PHOTO);

    return [
      hasDeniedPermission ? (
        <ListItemText
          primary='"Profile Photo" permission not granted.'
          className={classes.red}
          key="avatar-error"
        />
      ) : null,
      <Avatar
        src={props.profilePhoto}
        className={classes.profilePhoto}
        key="avatar"
      />,
    ];
  }

  function UserDetails() {
    const hasDeniedPermission =
      state.hasRequestedPermissions &&
      !hasPermission(CustomPermissionName.USER_NAME);

    return (
      <Paper className={classes.paper}>
        <CardHeader subheader="User Details" />
        <TextField
          variant="outlined"
          disabled={true}
          className={classes.formInput}
          id="input-name"
          error={state.isError || hasDeniedPermission}
          label={'Name'}
          value={
            hasDeniedPermission
              ? '"User Name" permission not granted.'
              : props.userName || ' '
          }
        />
      </Paper>
    );
  }

  function ContactList() {
    const hasDeniedPermision =
      state.hasRequestedPermissions &&
      !hasPermission(CustomPermissionName.CONTACT_LIST);

    return (
      <Paper className={classes.paper}>
        <CardHeader subheader="Contact List" />
        <List className={classes.contactsList}>
          {hasDeniedPermision && (
            <ListItem>
              <ListItemText
                primary='"Contacts" permission not granted.'
                className={classes.red}
              />
            </ListItem>
          )}
          {!hasDeniedPermision &&
            props.contactList &&
            props.contactList.map((contact) => (
              <ListItem divider>
                <ListItemAvatar>
                  <Avatar className={classes.contactIcon} />
                </ListItemAvatar>
                <ListItemText
                  primary={contact.id}
                  secondary={
                    <React.Fragment>
                      <Typography>
                        {contact.name && contact.name !== '' && (
                          <span>{'Name: ' + contact.name}</span>
                        )}
                      </Typography>
                      <Typography>
                        {contact.email && contact.email !== '' && (
                          <span>{'Email: ' + contact.email}</span>
                        )}
                      </Typography>
                    </React.Fragment>
                  }
                />
              </ListItem>
            ))}
        </List>
      </Paper>
    );
  }

  function PointBalance() {
    const hasDeniedPermission =
      state.hasRequestedPointPermissions &&
      !hasPermission(CustomPermissionName.POINTS);

    return (
      <Paper className={classes.paper}>
        <CardHeader subheader="Points" />
        <TextField
          variant="outlined"
          disabled={true}
          className={classes.formInput}
          id="input-points-standard"
          error={state.isPointsError || hasDeniedPermission}
          label={'Points (Standard)'}
          value={
            hasDeniedPermission
              ? '"Points" permission not granted.'
              : props.points !== undefined &&
                props.points.standard !== undefined
              ? props.points.standard.toString()
              : '-'
          }
        />
        <TextField
          variant="outlined"
          disabled={true}
          className={classes.formInput}
          id="input-points-term"
          error={state.isPointsError || hasDeniedPermission}
          label={'Points (Time-Limited)'}
          value={
            hasDeniedPermission
              ? '"Points" permission not granted.'
              : props.points !== undefined && props.points.term !== undefined
              ? props.points.term.toString()
              : '-'
          }
        />
        <TextField
          variant="outlined"
          disabled={true}
          className={classes.formInput}
          id="input-points-cash"
          error={state.isPointsError || hasDeniedPermission}
          label={'Points (Rakuten Cash)'}
          value={
            hasDeniedPermission
              ? '"Points" permission not granted.'
              : props.points !== undefined && props.points.cash !== undefined
              ? props.points.cash.toString()
              : '-'
          }
        />
      </Paper>
    );
  }

  function CardActionsForm() {
    return (
      <FormGroup column="true" className={classes.rootUserGroup}>
        <div className={classes.wrapper}>
          <Button
            onClick={handleClick}
            variant="contained"
            color="primary"
            classes={{ root: classes.button }}
            className={buttonClassname}
            disabled={state.isLoading}
            data-testid="fetchUserButton"
          >
            Fetch User Details
          </Button>
          {state.isLoading && (
            <CircularProgress size={20} className={classes.buttonProgress} />
          )}
        </div>
        {state.isError && (
          <Typography variant="body1" className={classes.error}>
            Error fetching the User Details
          </Typography>
        )}
      </FormGroup>
    );
  }

  function CardPointActionsForm() {
    return (
      <FormGroup column="true" className={classes.rootUserGroup}>
        <div className={classes.wrapper}>
          <Button
            onClick={handlePointsClick}
            variant="contained"
            color="primary"
            classes={{ root: classes.button }}
            className={buttonClassname}
            disabled={state.isPointsLoading}
            data-testid="fetchPointsButton"
          >
            Fetch Points
          </Button>
          {state.isPointsLoading && (
            <CircularProgress size={20} className={classes.buttonProgress} />
          )}
        </div>
        {state.isPointsError && (
          <Typography variant="body1" className={classes.error}>
            Error fetching the points
          </Typography>
        )}
      </FormGroup>
    );
  }

  function hasPermission(permission, permissionList: ?(string[])) {
    permissionList = permissionList || props.permissions || [];
    return permissionList.indexOf(permission) > -1;
  }

  return (
    <div className={classes.scrollable}>
      <GreyCard className={classes.card}>
        <CardContent>
          <div
            className={classes.dataFormsWrapper}
            data-testid="dataFormsWrapper"
          >
            {ProfilePhoto()}
            {UserDetails()}
            {ContactList()}
          </div>
        </CardContent>
        <CardActions classes={{ root: classes.rootCardActions }}>
          {CardActionsForm()}
        </CardActions>

        <CardContent>
          <div
            className={classes.dataFormsWrapper}
            data-testid="pointDataFormsWrapper"
          >
            {PointBalance()}
          </div>
        </CardContent>
        <CardActions classes={{ root: classes.rootCardActions }}>
          {CardPointActionsForm()}
        </CardActions>
      </GreyCard>
    </div>
  );
}
Example #18
Source File: secure-storage.js    From js-miniapp with MIT License 4 votes vote down vote up
function SecureStorageComponent(props: SecureStorageProps) {
  const [state, dispatch] = useReducer(dataFetchReducer, initialState);
  const classes = useStyles();
  const [storeKey, setStoreKey] = useState('');
  const [storeKeyValue, setStoreKeyValue] = useState('');
  const [storeKey1, setStoreKey1] = useState('');
  const [storeKeyValue1, setStoreKeyValue1] = useState('');
  const [getItemUsingKey, setGetItemUsingKey] = useState('');
  const [removeItemUsingKey, setRemoveItemUsingKey] = useState('');
  const [removeItemUsingKey1, setRemoveItemUsingKey1] = useState('');

  const buttonClassname = clsx({
    [classes.buttonFailure]: state.isError,
    [classes.buttonSuccess]: !state.isError,
  });

  function isEmpty(str) {
    return !str || str.trim().length === 0;
  }

  function setSecureStorageButtonClick(e) {
    if (
      isKeyAndValueEmpty(storeKey, storeKeyValue) &&
      isKeyAndValueEmpty(storeKey1, storeKeyValue1)
    ) {
      dispatch({
        type: 'INPUT_FAILURE',
        miniAppError: null,
        inputError: 'Please enter Key and Value',
      });
      return;
    }

    if (
      isValidKeyValue(storeKey, storeKeyValue) &&
      isValidKeyValue(storeKey1, storeKeyValue1)
    ) {
      dispatch({ type: 'RESET', miniAppError: null, inputError: null });
      saveItems();
    } else {
      console.log('ERROR');
      dispatch({
        type: 'INPUT_FAILURE',
        miniAppError: null,
        inputError: 'Please enter both Key and Value',
      });
    }
  }

  function saveItems() {
    if (!state.isLoading) {
      dispatch({ type: 'FETCH_INIT', miniAppError: null, inputError: null });
      const keyValuePair = {};
      keyValuePair[storeKey] = storeKeyValue;
      keyValuePair[storeKey1] = storeKeyValue1;
      Object.keys(keyValuePair).forEach((key) => {
        if (!keyValuePair[key]) delete keyValuePair[key];
      });
      requestSetItems(keyValuePair);
    }
  }

  function requestSetItems(keyValuePair) {
    props
      .requestSetItems(JSON.stringify(keyValuePair))
      .then((response) => {
        console.log('Page - SetItems - Success', response);
        dispatch({
          type: 'FETCH_SUCCESS',
          miniAppError: null,
          inputError: null,
        });
      })
      .catch((miniAppError) => {
        console.log('Page - SetItems - Error: ', miniAppError);
        dispatch({ type: 'FETCH_FAILURE', miniAppError, inputError: null });
      });
  }

  function getSecureStorageButtonClick(e) {
    if (!isEmpty(getItemUsingKey)) {
      if (!state.isLoading) {
        dispatch({ type: 'FETCH_INIT', miniAppError: null, inputError: null });
        props
          .requestGetItem(getItemUsingKey)
          .then((response) => {
            console.log('Page - GetItems - Success', response);
            dispatch({
              type: 'FETCH_SUCCESS',
              miniAppError: null,
              inputError: null,
            });
          })
          .catch((miniAppError) => {
            console.log('Page - GetItems - Error: ', miniAppError);
            dispatch({ type: 'FETCH_FAILURE', miniAppError, inputError: null });
          });
      }
    } else {
      dispatch({
        type: 'INPUT_FAILURE',
        miniAppError: null,
        inputError: 'Key cannot be empty',
      });
    }
  }

  function removeItemsFromSecureStorageButtonClick(e) {
    const keys = [removeItemUsingKey, removeItemUsingKey1];
    const filteredKeys = keys.filter(function (str) {
      return isEmpty(str) === false;
    });
    if (!state.isLoading) {
      dispatch({ type: 'FETCH_INIT', miniAppError: null, inputError: null });
      props
        .requestRemoveItems(filteredKeys)
        .then((response) => {
          console.log('Page - RemoveItems - Success', response);
          dispatch({
            type: 'FETCH_SUCCESS',
            miniAppError: null,
            inputError: null,
          });
        })
        .catch((miniAppError) => {
          console.log('Page - RemoveItems - Error: ', miniAppError);
          dispatch({ type: 'FETCH_FAILURE', miniAppError, inputError: null });
        });
    }
  }

  function getSizeButtonClick(e) {
    if (!state.isLoading) {
      dispatch({ type: 'FETCH_INIT', miniAppError: null, inputError: null });
      props
        .requestSize()
        .then((response) => {
          console.log('Page - Size - Success', response);
          dispatch({
            type: 'FETCH_SUCCESS',
            miniAppError: null,
            inputError: null,
          });
        })
        .catch((miniAppError) => {
          console.log('Page - Size - Error: ', miniAppError);
          dispatch({ type: 'FETCH_FAILURE', miniAppError, inputError: null });
        });
    }
  }

  function clearSecureStorageSizeButtonClick(e) {
    if (!state.isLoading) {
      dispatch({ type: 'FETCH_INIT', miniAppError: null, inputError: null });
      props
        .requestClear()
        .then((response) => {
          console.log('Page - clearStorageItems - Success', response);
          dispatch({
            type: 'STORAGE_CLEAR_SUCCESS',
            miniAppError: null,
            inputError: null,
          });
        })
        .catch((miniAppError) => {
          console.log('Page - clearSecureStorageItems - Error: ', miniAppError);
          dispatch({ type: 'FETCH_FAILURE', miniAppError, inputError: null });
        });
    }
  }

  function isKeyAndValueEmpty(key, val) {
    return isEmpty(key) && isEmpty(val);
  }

  function isValidKeyValue(key, val) {
    if (isEmpty(key) && !isEmpty(val)) {
      return false;
    } else if (!isEmpty(key) && isEmpty(val)) {
      return false;
    }
    return true;
  }

  function SetSecureStorageCardActionsForm() {
    return (
      <FormGroup column="true" className={classes.rootUserGroup}>
        <Fragment>
          <TextField
            variant="outlined"
            className={classes.formInput}
            id="input-name"
            label={'Key'}
            value={storeKey}
            onChange={(e) => setStoreKey(e.target.value)}
          />
          <TextField
            variant="outlined"
            className={classes.formInput}
            id="input-name"
            label={'Value'}
            value={storeKeyValue}
            onChange={(e) => setStoreKeyValue(e.target.value)}
          />
        </Fragment>
        <br />
        <Fragment>
          <TextField
            variant="outlined"
            className={classes.formInput}
            id="input-name"
            label={'Key'}
            value={storeKey1}
            onChange={(e) => setStoreKey1(e.target.value)}
          />
          <TextField
            variant="outlined"
            className={classes.formInput}
            id="input-name"
            label={'Value'}
            value={storeKeyValue1}
            onChange={(e) => setStoreKeyValue1(e.target.value)}
          />
        </Fragment>
        <br />
        <br />
        <Button
          onClick={setSecureStorageButtonClick}
          variant="contained"
          color="primary"
          classes={{ root: classes.button }}
          className={buttonClassname}
          disabled={state.isLoading}
          data-testid="setSecureStorage"
        >
          Set Secure Storage
        </Button>
        {state.isLoading && (
          <CircularProgress size={20} className={classes.buttonProgress} />
        )}
        {!state.isLoading && state.isError && (
          <Typography variant="body1" className={classes.red}>
            {state.inputError}
          </Typography>
        )}
        {!state.isLoading && state.isError && (
          <Typography variant="body1" className={classes.red}>
            {state.error}
          </Typography>
        )}
        {!state.isLoading && state.isSuccess && (
          <Typography variant="body1" className={classes.red}>
            Items stored Successfully
          </Typography>
        )}
      </FormGroup>
    );
  }

  function GetSecureStorageCardActionsForm() {
    return (
      <FormGroup column="true" className={classes.rootUserGroup}>
        <TextField
          variant="outlined"
          className={classes.formInput}
          id="input-name"
          label={'Key'}
          value={getItemUsingKey}
          onChange={(e) => setGetItemUsingKey(e.target.value)}
        />
        <br />
        <Button
          onClick={getSecureStorageButtonClick}
          variant="contained"
          color="primary"
          classes={{ root: classes.button }}
          className={buttonClassname}
          disabled={state.isLoading}
          data-testid="getSecureStorage"
        >
          Get Secure Storage
        </Button>
        {state.isLoading && (
          <CircularProgress size={20} className={classes.buttonProgress} />
        )}
        {!state.isLoading && state.isError && (
          <Typography variant="body1" className={classes.red}>
            {state.inputError}
          </Typography>
        )}
        {!state.isLoading && state.isError && (
          <Typography variant="body1" className={classes.red}>
            {state.error}
          </Typography>
        )}
        {!state.isLoading && !state.isError && (
          <Typography variant="body1" className={classes.red}>
            {props.getItems}
          </Typography>
        )}
      </FormGroup>
    );
  }

  function RemoveSecureStorageCardActionsForm() {
    return (
      <FormGroup column="true" className={classes.rootUserGroup}>
        <TextField
          variant="outlined"
          className={classes.formInput}
          id="input-name"
          label={'Key'}
          value={removeItemUsingKey}
          onChange={(e) => setRemoveItemUsingKey(e.target.value)}
        />
        <br />
        <TextField
          variant="outlined"
          className={classes.formInput}
          id="input-name"
          label={'Key'}
          value={removeItemUsingKey1}
          onChange={(e) => setRemoveItemUsingKey1(e.target.value)}
        />
        <br />
        <br />
        <Button
          onClick={removeItemsFromSecureStorageButtonClick}
          variant="contained"
          color="primary"
          classes={{ root: classes.button }}
          className={buttonClassname}
          disabled={state.isLoading}
          data-testid="removeSecureStorage"
        >
          Remove Items
        </Button>
        {state.isLoading && (
          <CircularProgress size={20} className={classes.buttonProgress} />
        )}
        {!state.isLoading && state.isError && (
          <Typography variant="body1" className={classes.red}>
            {state.inputError}
          </Typography>
        )}
        {!state.isLoading && state.isError && (
          <Typography variant="body1" className={classes.red}>
            {state.error}
          </Typography>
        )}
        {!state.isLoading && state.isSuccess && (
          <Typography variant="body1" className={classes.red}>
            Items removed Successfully
          </Typography>
        )}
      </FormGroup>
    );
  }

  function OtherFunctionalitiesCardActionsForm() {
    return (
      <FormGroup column="true" className={classes.rootUserGroup}>
        <Button
          onClick={getSizeButtonClick}
          variant="contained"
          color="primary"
          classes={{ root: classes.button }}
          className={buttonClassname}
          disabled={state.isLoading}
          data-testid="getSizeSecureStorage"
        >
          Get Size
        </Button>
        <br />
        <Button
          onClick={clearSecureStorageSizeButtonClick}
          variant="contained"
          color="primary"
          classes={{ root: classes.button }}
          className={buttonClassname}
          disabled={state.isLoading}
          data-testid="clearSecureStorage"
        >
          Clear Storage
        </Button>

        {state.isLoading && (
          <CircularProgress size={20} className={classes.buttonProgress} />
        )}
        {!state.isLoading && state.isError && (
          <Typography variant="body1" className={classes.red}>
            {state.inputError}
          </Typography>
        )}
        {!state.isLoading && state.isError && (
          <Typography variant="body1" className={classes.red}>
            {state.error}
          </Typography>
        )}
        {!state.isLoading && !state.isError && state.isSuccess && props.size && (
          <Typography variant="body1" className={classes.red}>
            <div>Maximum Size: {props.size.max}</div>
            <div>Used Space: {props.size.used}</div>
            <div>Available: {props.size.max - props.size.used}</div>
          </Typography>
        )}
        {!state.isLoading && !state.isError && state.isStorageCleaned && (
          <Typography variant="body1" className={classes.red}>
            Storage Cleared Successfully
          </Typography>
        )}
      </FormGroup>
    );
  }

  function QA() {
    return (
      <FormGroup column="true" className={classes.rootUserGroup}>
        <Button
          onClick={pushRandom5kRecords}
          variant="contained"
          color="primary"
          classes={{ root: classes.button }}
          className={buttonClassname}
          disabled={state.isLoading}
        >
          Push 5k Records
        </Button>
        <br />
        <Button
          onClick={pushRandom10kRecords}
          variant="contained"
          color="primary"
          classes={{ root: classes.button }}
          className={buttonClassname}
          disabled={state.isLoading}
        >
          Push 10k Records
        </Button>

        <br />
        <Button
          onClick={pushRandom100kRecords}
          variant="contained"
          color="primary"
          classes={{ root: classes.button }}
          className={buttonClassname}
          disabled={state.isLoading}
        >
          Push 100k Records
        </Button>

        {state.isLoading && (
          <CircularProgress size={20} className={classes.buttonProgress} />
        )}
        {!state.isLoading && state.isError && (
          <Typography variant="body1" className={classes.red}>
            {state.inputError}
          </Typography>
        )}
        {!state.isLoading && state.isError && (
          <Typography variant="body1" className={classes.red}>
            {state.error}
          </Typography>
        )}
      </FormGroup>
    );
  }

  function pushRandom5kRecords() {
    if (!state.isLoading) {
      pushRandomRecords('', 5000);
    }
  }

  function pushRandom10kRecords() {
    if (!state.isLoading) {
      pushRandomRecords('JS Sample - ', 10000);
    }
  }

  function pushRandom100kRecords() {
    if (!state.isLoading) {
      pushRandomRecords('JS - ', 100000);
    }
  }

  function pushRandomRecords(prefix, maxCount) {
    if (!state.isLoading) {
      dispatch({ type: 'FETCH_INIT', miniAppError: null, inputError: null });
      const keyValuePair = {};
      for (let i = 0; i < maxCount; i++) {
        keyValuePair[prefix + i] = JSON.stringify(i);
      }
      requestSetItems(keyValuePair);
    }
  }
  const [value, setValue] = React.useState('1');

  const handleChange = (event: Event, newValue: string) => {
    dispatch({ type: 'RESET', miniAppError: null, inputError: null });
    setValue(newValue);
  };

  return (
    <Container className={classes.wrapperContainer}>
      <TabContext value={value}>
        <TabList
          variant="scrollable"
          onChange={handleChange}
          aria-label="simple tabs example"
        >
          <Tab label="Set" value="1" />
          <Tab label="Get" value="2" />
          <Tab label="Remove" value="3" />
          <Tab label="Others" value="4" />
          <Tab label="QA" value="5" />
        </TabList>
        <TabPanel value="1">{SetSecureStorageCardActionsForm()}</TabPanel>
        <TabPanel value="2">{GetSecureStorageCardActionsForm()}</TabPanel>
        <TabPanel value="3">{RemoveSecureStorageCardActionsForm()}</TabPanel>
        <TabPanel value="4">{OtherFunctionalitiesCardActionsForm()}</TabPanel>
        <TabPanel value="5">{QA()}</TabPanel>
      </TabContext>
    </Container>
  );
}
Example #19
Source File: Settings.js    From akashlytics-deploy with GNU General Public License v3.0 4 votes vote down vote up
export function Settings(props) {
  const [isEditing, setIsEditing] = useState(false);
  const [isNodesOpen, setIsNodesOpen] = useState(false);
  const classes = useStyles();
  const { settings, setSettings, refreshNodeStatuses, isRefreshingNodeStatus } = useSettings();
  const {
    handleSubmit,
    control,
    reset,
    formState: { errors }
  } = useForm();
  const formRef = useRef();
  const { selectedNode, nodes } = settings;

  const onIsCustomNodeChange = (event) => {
    const isChecked = event.target.checked;
    const apiEndpoint = isChecked ? settings.apiEndpoint : selectedNode.api;
    const rpcEndpoint = isChecked ? settings.rpcEndpoint : selectedNode.rpc;

    reset();

    setSettings({ ...settings, isCustomNode: isChecked, apiEndpoint, rpcEndpoint }, (newSettings) => {
      refreshNodeStatuses(newSettings);
    });
  };

  const onNodeChange = (event, newNodeId) => {
    const newNode = nodes.find((n) => n.id === newNodeId);
    const apiEndpoint = newNode.api;
    const rpcEndpoint = newNode.rpc;

    setSettings({ ...settings, apiEndpoint, rpcEndpoint, selectedNode: newNode });
  };

  const onRefreshNodeStatus = async () => {
    await refreshNodeStatuses();
  };

  /**
   *  Update the custom settings
   * @param {Object} data {apiEndpoint: string, rpcEndpoint: string}
   */
  const onSubmit = (data) => {
    const customNodeUrl = new URL(data.apiEndpoint);
    setIsEditing(false);
    setSettings({ ...settings, ...data, customNode: { ...settings.customNode, id: customNodeUrl.hostname } }, (newSettings) => {
      refreshNodeStatuses(newSettings);
    });
  };

  return (
    <Box className={classes.root}>
      <Helmet title="Settings" />

      <Box className={classes.titleContainer}>
        <Typography variant="h3" className={classes.title}>
          Settings
        </Typography>
      </Box>

      <Box marginTop="1rem">
        <FormGroup>
          {!settings.isCustomNode && (
            <Box display="flex" alignItems="center">
              <FormControl>
                <Autocomplete
                  disableClearable
                  open={isNodesOpen}
                  options={nodes.map((n) => n.id)}
                  style={{ width: 300 }}
                  value={settings.selectedNode.id}
                  defaultValue={settings.selectedNode.id}
                  getOptionSelected={(option, value) => option === value}
                  onChange={onNodeChange}
                  renderInput={(params) => (
                    <ClickAwayListener onClickAway={() => setIsNodesOpen(false)}>
                      <TextField
                        {...params}
                        label="Node"
                        variant="outlined"
                        onClick={() => setIsNodesOpen((prev) => !prev)}
                        InputProps={{
                          ...params.InputProps,
                          classes: { root: clsx(classes.nodeInput, classes.inputClickable), input: classes.inputClickable },
                          endAdornment: (
                            <InputAdornment position="end">
                              <Box marginRight=".5rem" display="inline-flex">
                                <KeyboardArrowDownIcon fontSize="small" />
                              </Box>
                              <NodeStatus latency={Math.floor(selectedNode.latency)} status={selectedNode.status} />
                            </InputAdornment>
                          )
                        }}
                      />
                    </ClickAwayListener>
                  )}
                  renderOption={(option) => {
                    const node = nodes.find((n) => n.id === option);
                    return (
                      <Box display="flex" alignItems="center" justifyContent="space-between" width="100%">
                        <div>{option}</div>
                        <NodeStatus latency={Math.floor(node.latency)} status={node.status} />
                      </Box>
                    );
                  }}
                  disabled={settings.isCustomNode}
                />
              </FormControl>

              <Box marginLeft="1rem">
                <IconButton onClick={() => onRefreshNodeStatus()} aria-label="refresh" disabled={isRefreshingNodeStatus}>
                  {isRefreshingNodeStatus ? <CircularProgress size="1.5rem" /> : <RefreshIcon />}
                </IconButton>
              </Box>
            </Box>
          )}

          <FormControlLabel
            className={classes.switch}
            control={<Switch checked={!!settings.isCustomNode} onChange={onIsCustomNodeChange} color="primary" />}
            label="Custom node"
          />
        </FormGroup>
      </Box>

      {settings.isCustomNode && (
        <form className={classes.form} onSubmit={handleSubmit(onSubmit)} ref={formRef}>
          <div className={classes.fieldRow}>
            <FormLabel className={classes.formLabel}>Api Endpoint:</FormLabel>

            {isEditing ? (
              <FormControl error={!errors.apiEndpoint} className={classes.formControl}>
                <Controller
                  control={control}
                  name="apiEndpoint"
                  rules={{
                    required: true,
                    validate: (v) => isUrl(v)
                  }}
                  defaultValue={settings.apiEndpoint}
                  render={({ fieldState, field }) => {
                    const helperText = fieldState.error?.type === "validate" ? "Url is invalid." : "Api endpoint is required.";

                    return (
                      <TextField
                        {...field}
                        type="text"
                        variant="outlined"
                        error={!!fieldState.invalid}
                        helperText={fieldState.invalid && helperText}
                        className={classes.formValue}
                      />
                    );
                  }}
                />
              </FormControl>
            ) : (
              <Typography variant="body1" className={classes.formValue}>
                {settings.apiEndpoint}
              </Typography>
            )}
          </div>

          <div className={classes.fieldRow}>
            <FormLabel className={classes.formLabel}>Rpc Endpoint:</FormLabel>

            {isEditing ? (
              <FormControl error={!errors.apiEndpoint} className={classes.formControl}>
                <Controller
                  control={control}
                  name="rpcEndpoint"
                  rules={{
                    required: true,
                    validate: (v) => isUrl(v)
                  }}
                  defaultValue={settings.rpcEndpoint}
                  render={({ fieldState, field }) => {
                    const helperText = fieldState.error?.type === "validate" ? "Url is invalid." : "Rpc endpoint is required.";

                    return (
                      <TextField
                        {...field}
                        type="text"
                        variant="outlined"
                        error={!!fieldState.invalid}
                        helperText={fieldState.invalid && helperText}
                        className={classes.formValue}
                      />
                    );
                  }}
                />
              </FormControl>
            ) : (
              <Typography variant="body1" className={classes.formValue}>
                {settings.rpcEndpoint}
              </Typography>
            )}
          </div>

          <Box paddingTop="1rem">
            {!isEditing && (
              <Button variant="contained" color="primary" onClick={() => setIsEditing(!isEditing)}>
                Edit
              </Button>
            )}

            {isEditing && (
              <>
                <Button
                  variant="contained"
                  onClick={() => {
                    reset(null, { keepDefaultValues: true });
                    setIsEditing(false);
                  }}
                >
                  Cancel
                </Button>
                <Button
                  variant="contained"
                  color="primary"
                  type="submit"
                  className={classes.submitButton}
                  onClick={() => formRef.current.dispatchEvent(new Event("submit"))}
                >
                  Submit
                </Button>
              </>
            )}
          </Box>
        </form>
      )}
    </Box>
  );
}
Example #20
Source File: auth-token.js    From js-miniapp with MIT License 4 votes vote down vote up
function AuthToken(props: AuthTokenProps) {
  const [state, dispatch] = useReducer(dataFetchReducer, initialState);
  const classes = useStyles();
  const [scope, setScope] = useState({
    audience: 'rae',
    scopes: ['idinfo_read_openid', 'memberinfo_read_point'],
  });
  const buttonClassname = clsx({
    [classes.buttonFailure]: state.isError,
    [classes.buttonSuccess]: !state.isError,
  });
  const onAudienceChange = (event) => {
    setScope({ ...scope, audience: event.target.value });
  };
  const onScopesChange = (event) => {
    setScope({ ...scope, scopes: event.target.value.split(', ') });
  };

  function requestAccessTokenPermission() {
    const permissionsList = [
      {
        name: CustomPermissionName.ACCESS_TOKEN,
        description:
          'We would like to get the Access token details to share with this Mini app',
      },
    ];

    props
      .requestPermissions(permissionsList)
      .then((permissions) =>
        permissions
          .filter(
            (permission) => permission.status === CustomPermissionStatus.ALLOWED
          )
          .map((permission) => permission.name)
      )
      .then((permissions) =>
        Promise.all([
          hasPermission(CustomPermissionName.ACCESS_TOKEN, permissions)
            ? props.getAccessToken(scope.audience, scope.scopes)
            : null,
        ])
      )
      .then(() => dispatch({ type: 'FETCH_SUCCESS' }))
      .catch((miniAppError) => {
        console.error(miniAppError);
        dispatch({ type: 'FETCH_FAILURE', miniAppError });
      });
  }

  function hasPermission(permission, permissionList: ?(string[])) {
    permissionList = permissionList || props.permissions || [];
    return permissionList.indexOf(permission) > -1;
  }

  function handleClick(e) {
    if (!state.isLoading) {
      e.preventDefault();
      dispatch({ type: 'FETCH_INIT' });
      requestAccessTokenPermission();
    }
  }

  function ButtonWrapper() {
    return (
      <div className={classes.wrapper}>
        <Button
          onClick={handleClick}
          variant="contained"
          color="primary"
          className={buttonClassname}
          disabled={state.isLoading}
          data-testid="authButton"
        >
          Authentication
        </Button>
        {state.isLoading && (
          <CircularProgress size={20} className={classes.buttonProgress} />
        )}
      </div>
    );
  }

  function AccessToken() {
    const hasDeniedPermission =
      state.hasRequestedPermissions &&
      !hasPermission(CustomPermissionName.ACCESS_TOKEN);

    return hasDeniedPermission ? (
      <ListItemText
        primary="Access Token permission is denied by the user."
        className={classes.red}
      />
    ) : null;
  }

  return (
    <GreyCard height="auto">
      <CardContent>
        <FormGroup column="true" classes={{ root: classes.rootFormGroup }}>
          <Fragment>
            <FormControl className={classes.formControl}>
              <TextField
                id="audience"
                label="Audience"
                className={classes.fields}
                onChange={onAudienceChange}
                value={scope.audience}
              />
            </FormControl>
            <FormControl className={classes.formControl}>
              <TextField
                id="scopes"
                label="Scopes"
                className={classes.fields}
                onChange={onScopesChange}
                value={scope.scopes.join(', ')}
              />
            </FormControl>
          </Fragment>
          {ButtonWrapper()}
          {!state.isLoading && !state.isError && props.accessToken && (
            <Typography variant="body1" className={classes.success}>
              Token: {props.accessToken.token}
            </Typography>
          )}
          {!state.isLoading && !state.isError && props.accessToken && (
            <Typography variant="body1" className={classes.success}>
              Valid until: {displayDate(props.accessToken.validUntil)}
            </Typography>
          )}
          {!state.isLoading && state.isError && (
            <Typography variant="body1" className={classes.red}>
              {state.error}
            </Typography>
          )}
          <div>{AccessToken()}</div>
        </FormGroup>
      </CardContent>
    </GreyCard>
  );
}
Example #21
Source File: promo-code-form.js    From horondi_admin with MIT License 4 votes vote down vote up
function PromoCodeForm({
  pathToPromoCodesPage,
  promoValidationSchema,
  addPromoCodeHandler,
  goToPromoPage,
  initialState = {
    code: '',
    dateTo: '',
    dateFrom: '',
    discount: '',
    categories: []
  }
}) {
  const styles = useStyles();
  const commonStyles = useCommonStyles();

  const { promoCodesConsts } = orders;
  let { checkboxes } = promoCodesConsts.categories;

  const {
    data: categoriesList,
    loading,
    error
  } = useQuery(getCategoriesList, {
    fetchPolicy: 'no-cache'
  });

  if (categoriesList) {
    checkboxes = [
      ...checkboxes,
      ...categoriesList.getAllCategories.items.map((item) => ({
        label: item.name[0].value,
        value: item.code
      }))
    ];
  }

  const {
    values,
    handleSubmit,
    handleChange,
    handleBlur,
    touched,
    errors,
    setFieldValue
  } = useFormik({
    validationSchema: promoValidationSchema,
    initialValues: initialState,
    onSubmit: () =>
      addPromoCodeHandler({
        variables: {
          id: _id,
          promoCode: {
            code,
            dateTo,
            dateFrom,
            discount,
            categories
          }
        }
      }).then(goToPromoPage)
  });

  const unblock = useUnsavedChangesHandler(values);

  const { code, dateTo, dateFrom, discount, categories, _id } = values;

  const handlerDateHandler = (value, string) => setFieldValue(string, value);

  const { SAVE } = productsTranslations;

  const allCategoriesHandler = () => {
    categories.length === checkboxes.length
      ? setFieldValue('categories', [])
      : setFieldValue('categories', [...checkboxes.map(({ value }) => value)]);
  };

  const allCategoriesCheckbox = (
    <FormControlLabel
      className={styles.checkboxes}
      label='Всі товари'
      control={
        <Checkbox
          color='primary'
          name='categories'
          checked={categories.length === checkboxes.length}
          indeterminate={
            categories.length < checkboxes.length && categories.length > 0
          }
          onChange={allCategoriesHandler}
        />
      }
    />
  );

  const checkoxGroup = checkboxes.map((item) => (
    <FormControlLabel
      key={item.label}
      control={
        <Checkbox
          onChange={handleChange}
          checked={categories.includes(item.value)}
          name='categories'
          color='primary'
          value={item.value}
        />
      }
      label={item.label}
    />
  ));

  if (loading || error) {
    return <LoadingBar />;
  }

  return (
    <div className={commonStyles.container}>
      <div className={styles.fixedButtons}>
        <Grid item>
          <BackButton pathBack={pathToPromoCodesPage} />
        </Grid>
        <Grid>
          <SaveButton
            type={productFormValues.submit}
            title={SAVE}
            onClickHandler={handleSubmit}
            values={values}
            errors={errors}
            unblockFunction={unblock}
          />
        </Grid>
      </div>

      <span className={styles.title}>{promoCodesConsts.createPromo}</span>
      <form>
        <div>
          <span
            className={styles.subTitle}
          >{`${promoCodesConsts.namePromo}:`}</span>
          <div className={styles.promoNameContainer}>
            <TextField
              id='code'
              label={promoCodesConsts.namePromo}
              variant='outlined'
              value={code}
              className={styles.textField}
              error={!!(touched.code ? errors.code : null)}
              helperText={touched.code ? errors.code : ''}
              onBlur={handleBlur}
              onChange={handleChange}
            />
          </div>
        </div>
        <div>
          <span className={styles.subTitle}>
            {promoCodesConsts.date.validityPeriod}
          </span>
          <div className={styles.dataContainer}>
            <div className={styles.dataPickerContainer}>
              <DatePicker
                placeholder={promoCodesConsts.date.validFrom}
                oneTap
                style={{ width: 200 }}
                value={dateFrom}
                onChange={(value) => handlerDateHandler(value, 'dateFrom')}
              />
              {touched.dateFrom && errors.dateFrom && (
                <div className={styles.errorDate}>{errors.dateFrom}</div>
              )}
            </div>

            <div className={styles.dataPickerContainer}>
              <DatePicker
                placeholder={promoCodesConsts.date.validTo}
                oneTap
                style={{ width: 200 }}
                id='dateTo'
                value={dateTo}
                onChange={(value) => handlerDateHandler(value, 'dateTo')}
              />
              {touched.dateTo && errors.dateTo && (
                <div className={styles.errorDate}>{errors.dateTo}</div>
              )}
            </div>
          </div>
        </div>

        <div>
          <span className={styles.subTitle}>
            {promoCodesConsts.discount.title}
          </span>
          <TextField
            id='discount'
            label={promoCodesConsts.discount.label}
            variant='outlined'
            type='number'
            className={styles.textField}
            value={discount}
            error={!!(touched.discount ? errors?.discount : null)}
            helperText={touched.discount ? errors?.discount : null}
            onBlur={handleBlur}
            onChange={handleChange}
            InputProps={{ inputProps: { min: 0, max: 90 } }}
          />
          <div>
            <span className={styles.subTitle}>
              {promoCodesConsts.categories.title}
            </span>
            <FormControl>
              <FormGroup>
                {allCategoriesCheckbox}
                {checkoxGroup}
              </FormGroup>
              {touched.categories && errors.categories && (
                <div className={styles.errorCategory}>{errors.categories}</div>
              )}
            </FormControl>
          </div>
        </div>
      </form>
    </div>
  );
}
Example #22
Source File: CreateGameDialog.js    From dipact with GNU General Public License v3.0 4 votes vote down vote up
render() {
		return (
			<React.Fragment>
				<Dialog
					onEntered={helpers.genOnback(this.close)}
					open={this.state.open}
					disableBackdropClick={false}
					onClose={this.close}
					fullScreen
				>
					<AppBar>
						<Toolbar>
							<IconButton
								edge="start"
								color="inherit"
								onClick={this.close}
								aria-label="close"
							>
								<CloseIcon />
							</IconButton>
							<Typography variant="h6" style={{ paddingLeft: "16px" }}>
								Create new game
							</Typography>
						</Toolbar>
					</AppBar>

					<div
						style={{
							maxWidth: "920px",
							marginTop: "72px",
							marginLeft: "auto",
							marginRight: "auto",
						}}
					>
						<div
							style={{
								margin: "auto",
								width: "calc(100% - 32px)",
							}}
						>
							<div
								id="step1"
								style={{
									display: "flex",
									flexDirection: "column",
								}}
							>
								<div style={{ display: "flex" }}>
									<TextField
										key="Desc"
										label="Name"
										margin="dense"
										value={this.state.newGameProperties["Desc"]}
										onChange={this.newGamePropertyUpdater("Desc")}
										style={{
											marginBottom: "8px",
											flexGrow: "1",
										}}
									/>
									<IconButton
										onClick={(_) => {
											this.setState((state, props) => {
												state = Object.assign({}, state);
												state.newGameProperties.Desc = helpers.randomGameName();
												return state;
											});
										}}
									>
										<RandomGameNameIcon />
									</IconButton>
								</div>

								<FormControlLabel
									control={
										<Checkbox
											checked={this.state.newGameProperties["Private"]}
											onChange={this.newGamePropertyUpdater("Private")}
										/>
									}
									label="Private game"
									style={{ marginBottom: "8px" }}
								/>

								<React.Fragment>
									<FormControlLabel
										control={
											<Checkbox
												disabled={!this.state.newGameProperties.Private}
												checked={
													this.state.newGameProperties["GameMasterEnabled"]
												}
												onChange={this.newGamePropertyUpdater(
													"GameMasterEnabled"
												)}
											/>
										}
										label="Manage as Game Master"
										style={{ marginBottom: "8px" }}
									/>

									{this.state.newGameProperties.Private ? (
										<FormHelperText>
											As game master, you can pause/resume games and control who
											joins (and as what nation). To play yourself, you need to
											join as a player after creating your game.
										</FormHelperText>
									) : (
										<FormHelperText>
											Game master only allowed in private games (risk of abuse)
										</FormHelperText>
									)}

									{this.state.newGameProperties.Private &&
									this.state.newGameProperties.GameMasterEnabled ? (
										<React.Fragment>
											<FormControlLabel
												control={
													<Checkbox
														checked={
															this.state.newGameProperties[
																"RequireGameMasterInvitation"
															]
														}
														onChange={this.newGamePropertyUpdater(
															"RequireGameMasterInvitation"
														)}
													/>
												}
												label="Require assignment to join"
												style={{ marginBottom: "8px" }}
											/>
											<FormHelperText>
												Only players assigned (a nation) by you can join
												(whitelist).
											</FormHelperText>
										</React.Fragment>
									) : (
										""
									)}
								</React.Fragment>

								<InputLabel
									shrink
									id="variantlabel"
									style={{
										marginTop: "16px",
									}}
								>
									Variant
								</InputLabel>
								<Select
									key="Variant"
									labelId="variantlabel"
									value={this.state.newGameProperties["Variant"]}
									onChange={this.newGamePropertyUpdater("Variant")}
									style={{ marginBottom: "16px" }}
								>
									{Globals.variants.map((variant) => {
										return (
											<MenuItem
												key={variant.Properties.Name}
												value={variant.Properties.Name}
											>
												{variant.Properties.Name} {" ("}
												{variant.Properties.Nations.length} players)
											</MenuItem>
										);
									})}
								</Select>

								<Typography
									style={{ paddingBottom: "4px" }}
									variant="body2"
									fontStyle="italic"
								>
									<i>{this.state.variant.Properties.Description}</i>
								</Typography>
								<img
									src={this.state.variant.Links[3].URL}
									alt="Variant"
									style={{
										paddingBottom: "4px",
										maxHeight: "300px",
									}}
								/>
								<Typography variant="body2" style={{ paddingBottom: "4px" }}>
									Start year: {this.state.variant.Properties.Start.Year}
								</Typography>
								<Typography variant="body2" style={{ paddingBottom: "16px" }}>
									Original author: {this.state.variant.Properties.CreatedBy}
								</Typography>

								<Typography
									variant="caption"
									style={{ color: "rgba(0,0,0,0.57)" }}
								>
									Variant Rules
								</Typography>
								<Typography
									style={{
										paddingBottom: "16px",
										overflowWrap: "break-word",
									}}
									variant="body1"
								>
									{this.state.variant.Properties.Rules}
								</Typography>

								<Typography
									variant="caption"
									style={{ color: "rgba(0,0,0,0.57)" }}
								>
									Nation selection
								</Typography>

								<RadioGroup
									key="NationAllocation"
									value={parseInt(
										this.state.newGameProperties["NationAllocation"]
									)}
									onChange={this.newGamePropertyUpdater("NationAllocation", {
										int: true,
									})}
									style={{
										flexDirection: "row",
										flexWrap: "wrap",
										width: "calc(100% - 32px)",
									}}
								>
									<FormControlLabel
										value={0}
										key={0}
										control={<Radio />}
										label="Random"
									/>
									<FormControlLabel
										value={1}
										key={1}
										control={<Radio />}
										label="Preference based"
									/>
								</RadioGroup>
							</div>
							<div>
								<Typography
									variant="subtitle2"
									style={{
										marginTop: "16px",
										marginBottom: "16px",
									}}
								>
									Game length
								</Typography>
							</div>

							<div
								id="step2"
								style={{
									display: "flex",
									flexDirection: "column",
								}}
							>
								<Box display="flex" key="PhaseLengthMinutes">
									<TextField
										name="phase-length-multiplier"
										label="Phase length"
										type="number"
										inputProps={{ min: 1 }}
										value={this.state.phaseLengthMultiplier}
										onChange={this.setPhaseLength}
										style={{ minWidth: "170px" }}
									/>
									<Select
										name="phase-length-unit"
										value={this.state.phaseLengthUnit}
										onChange={this.setPhaseLength}
									>
										<MenuItem key={1} value={1}>
											{this.state.phaseLengthMultiplier === 1
												? "Minute"
												: "Minutes"}
										</MenuItem>
										<MenuItem key={60} value={60}>
											{this.state.phaseLengthMultiplier === 1
												? "Hour"
												: "Hours"}
										</MenuItem>
										<MenuItem key={60 * 24} value={60 * 24}>
											{this.state.phaseLengthMultiplier === 1 ? "Day" : "Days"}
										</MenuItem>
									</Select>
								</Box>

								<FormControlLabel
									key="samePhaseLength"
									control={
										<Checkbox
											name="same-phase-length"
											checked={!this.state.samePhaseLength}
											onChange={this.setNonMovementPhaseLength}
										/>
									}
									label="Shorter adjustment phases"
								/>
								{this.state.samePhaseLength ? (
									""
								) : (
									<Box
										display="flex"
										key="nonmovementPhaseLengthMinutes"
										style={{ paddingLeft: "32px" }}
									>
										<TextField
											name="non-movement-phase-length-multiplier"
											label="Adjustment phase length"
											type="number"
											inputProps={{ min: 1 }}
											value={this.state.nonMovementPhaseLengthMultiplier}
											onChange={this.setNonMovementPhaseLength}
											style={{ minWidth: "170px" }}
										/>
										<Select
											name="non-movement-phase-length-unit"
											value={this.state.nonMovementPhaseLengthUnit}
											onChange={this.setNonMovementPhaseLength}
										>
											<MenuItem key={1} value={1}>
												{this.state.nonMovementPhaseLengthMultiplier === 1
													? "Minute"
													: "Minutes"}
											</MenuItem>
											<MenuItem key={60} value={60}>
												{this.state.nonMovementPhaseLengthMultiplier === 1
													? "Hour"
													: "Hours"}
											</MenuItem>
											<MenuItem key={60 * 24} value={60 * 24}>
												{this.state.nonMovementPhaseLengthMultiplier === 1
													? "Day"
													: "Days"}
											</MenuItem>
										</Select>
									</Box>
								)}

								<FormControlLabel
									control={
										<Checkbox
											checked={this.state.newGameProperties["SkipMuster"]}
											onChange={this.newGamePropertyUpdater("SkipMuster")}
										/>
									}
									label="Skip Get Ready phase"
									style={{ marginBottom: "8px" }}
								/>
								<FormHelperText>
									The Get Ready phase asks players to confirm they're ready. If
									players don't respond, they are removed and the game goes back
									to try to find replacements before the game can start. This
									prevents absent people ruining a game.
								</FormHelperText>

								<FormControlLabel
									key="endEarly"
									control={
										<Checkbox
											name="end-game-early"
											onChange={(ev) => {
												ev.persist();
												this.setState((state, props) => {
													state = Object.assign({}, state);
													state.endEarly = ev.target.checked;
													state.newGameProperties.LastYear = ev.target.checked
														? this.state.variant.Properties.Start.Year + 7
														: 0;
													return state;
												});
											}}
											checked={this.state.endEarly}
										/>
									}
									label="End in draw after number of years"
								/>
								{this.state.endEarly ? (
									<Box
										display="flex"
										key="last-year"
										style={{ paddingLeft: "32px" }}
									>
										<TextField
											type="number"
											style={{ minWidth: "240px" }}
											error={
												this.state.newGameProperties.LastYear <
												this.state.variant.Properties.Start.Year + 1
													? true
													: false
											}
											helperText={
												this.state.newGameProperties.LastYear <
												this.state.variant.Properties.Start.Year + 1
													? "Must be after the start year"
													: ""
											}
											label={
												"End after year (game starts " +
												this.state.variant.Properties.Start.Year +
												")"
											}
											value={this.state.newGameProperties.LastYear}
											onChange={this.newGamePropertyUpdater("LastYear", {
												int: true,
											})}
										/>
									</Box>
								) : (
									""
								)}
							</div>
							<div>
								<Typography
									variant="subtitle2"
									style={{
										marginTop: "16px",
										marginBottom: "16px",
									}}
								>
									Chat
								</Typography>
							</div>
							<div id="part3">
								<Typography
									variant="caption"
									style={{ color: "rgba(0,0,0,0.57)" }}
								>
									Allow chats:
								</Typography>
								<FormGroup>
									{this.checkboxField("DisableConferenceChat", {
										invert: true,
										label: "Conference (all players)",
									})}
									{this.checkboxField("DisableGroupChat", {
										invert: true,
										label: "Group",
									})}
									{this.checkboxField("DisablePrivateChat", {
										invert: true,
										label: "Individual",
									})}
									<FormControlLabel
										control={
											<Checkbox
												disabled={!this.state.newGameProperties["Private"]}
												checked={
													this.state.newGameProperties["Private"]
														? this.state.newGameProperties["Anonymous"]
														: this.state.newGameProperties[
																"DisableConferenceChat"
														  ] &&
														  this.state.newGameProperties[
																"DisableGroupChat"
														  ] &&
														  this.state.newGameProperties["DisablePrivateChat"]
												}
												onChange={this.newGamePropertyUpdater("Anonymous")}
											/>
										}
										label="Anonymous"
									/>
								</FormGroup>
								{this.state.newGameProperties["Private"] ? (
									""
								) : (
									<FormHelperText style={{ marginBottom: "12px" }}>
										Anonymous only allowed in private games (risk of abuse)
									</FormHelperText>
								)}
							</div>
							<div>
								<InputLabel shrink id="chatLanguageLabel">
									Chat language
								</InputLabel>

								<Select
									key="ChatLanguageISO639_1"
									labelId="chatLanguageLabel"
									disabled={
										this.state.newGameProperties["DisableConferenceChat"] &&
										this.state.newGameProperties["DisableGroupChat"] &&
										this.state.newGameProperties["DisablePrivateChat"]
									}
									value={
										this.state.newGameProperties["ChatLanguageISO639_1"]
											? this.state.newGameProperties["ChatLanguageISO639_1"]
											: "players_choice"
									}
									onChange={this.newGamePropertyUpdater("ChatLanguageISO639_1")}
									style={{
										marginBottom: "16px",
										minWidth: "220px",
									}}
								>
									<MenuItem key="players_choice" value="players_choice">
										Players choice
									</MenuItem>
									{helpers.iso639_1Codes.map((lang) => {
										return (
											<MenuItem key={lang.name} value={lang.code}>
												{lang.name}
											</MenuItem>
										);
									})}
								</Select>
								<Typography
									variant="subtitle2"
									style={{
										marginTop: "16px",
										marginBottom: "16px",
									}}
								>
									Player requirements
								</Typography>
							</div>
							<div id="part4">
								{this.state.newGameProperties["Private"] ? (
									<Typography
										variant="body1"
										style={{
											marginTop: "4px",
											marginBottom: "8px",
											color: "#f44336",
										}}
									>
										For private games we advise you to not add requirements, so
										your friends can all join your game.
									</Typography>
								) : (
									""
								)}
								{this.limitedCheckboxedFloatField("MinReliability", {
									defaultValue: Math.min(
										10,
										Math.floor(Globals.userStats.Properties.Reliability)
									),
									checkbox: {
										label: "Reliability (important)",
										caption: "Find players that keep playing",
									},
									textfield: {
										label: "Minimum reliability score",
									},
									max: {
										value: this.state.userStats.Properties.Reliability,
										helperText:
											"Can't be higher than your own reliability (" +
											helpers.twoDecimals(
												this.state.userStats.Properties.Reliability
											) +
											")",
									},
									min: null,
								})}
								{this.limitedCheckboxedFloatField("MinQuickness", {
									defaultValue: Math.min(
										10,
										Math.floor(Globals.userStats.Properties.Quickness)
									),
									checkbox: {
										label: "Quickness",
										caption:
											"Find players that confirm their orders before deadline",
									},
									textfield: {
										label: "Minimum quickness score",
									},
									max: {
										value: this.state.userStats.Properties.Quickness,
										helperText:
											"Can't be higher than your own quickness (" +
											helpers.twoDecimals(
												this.state.userStats.Properties.Quickness
											) +
											")",
									},
									min: null,
								})}

								{this.limitedCheckboxedFloatField("MinRating", {
									defaultValue: 0,
									checkbox: {
										label: "Minimum rating",
										caption: "Find players that are challenging",
									},
									textfield: {
										label: "Minimum rating",
									},
									helperText:
										"Removes the least challenging " +
										(100 -
											helpers.ratingPercentile(
												this.state.newGameProperties.MinRating
											)) +
										"% of active players",
									max: {
										value: this.state.userStats.Properties.TrueSkill.Rating,
										helperText:
											"Can't be higher than your own rating (" +
											helpers.twoDecimals(
												this.state.userStats.Properties.TrueSkill.Rating
											) +
											")",
									},
									min: null,
								})}

								{this.limitedCheckboxedFloatField("MaxRating", {
									defaultValue: helpers.twoDecimals(
										this.state.userStats.Properties.TrueSkill.Rating,
										true
									),
									checkbox: {
										label: "Maximum rating",
										caption: "Find players that aren't too challenging",
									},
									helperText:
										"Removes the most challenging " +
										helpers.ratingPercentile(
											this.state.newGameProperties.MaxRating
										) +
										"% of active players",
									textfield: {
										label: "Maximum rating",
									},
									min: {
										value: this.state.userStats.Properties.TrueSkill.Rating,
										helperText:
											"Can't be lower than your own rating (" +
											helpers.twoDecimals(
												this.state.userStats.Properties.TrueSkill.Rating,
												true
											) +
											")",
									},
									max: null,
								})}
							</div>
						</div>
						<div style={{ padding: "16px", textAlign: "center" }}>
							<Button
								variant="contained"
								onClick={this.createGame}
								color="primary"
							>
								Create
							</Button>
						</div>
					</div>
				</Dialog>
				<NationPreferencesDialog
					parentCB={(c) => {
						this.nationPreferencesDialog = c;
					}}
					onSelected={null}
				/>
			</React.Fragment>
		);
	}
Example #23
Source File: DfuView.js    From Nemesis with GNU General Public License v3.0 4 votes vote down vote up
render() {
    return (
      <Paper className="dfu-view-root">
        <div style={{ display: "flex" }}>
          <Typography paragraph variant="h6">
            {this.state.dfu && <FormattedMessage id="dfu.flash.title" />}
            {this.state.imuf && <FormattedMessage id="imuf.title" />}
          </Typography>
          <div style={{ flexGrow: 1 }} />
          {this.props.goBack && (
            <Button color="primary" onClick={this.props.goBack}>
              <FormattedMessage id="common.go-back" />
            </Button>
          )}
        </div>
        <div style={{ display: "flex" }}>
          <HelperSelect
            style={{ flex: 1 }}
            label="dfu.release.title"
            value={this.state.currentRelease}
            disabled={this.state.isFlashing}
            onChange={event => {
              this.setState({ currentRelease: event.target.value });

              if (this.state.imuf) {
                this.setState({
                  selectedUrl: event.target.value.assets[0].browser_download_url
                });
              } else {
                console.log("dfu");
                this.setState({ selectedUrl: null });
                this.setState({ selectedFile: null });
              }
              this.clearLocalFile();
            }}
            items={
              this.state.releaseList &&
              this.state.releaseList.map(release => {
                return {
                  value: release,
                  label: release.name || "Choose One..."
                };
              })
            }
          />
        </div>
        <div style={{ display: "flex" }}>
          {this.state.current !== "IMU-F" && (
            <HelperSelect
              style={{ flex: 1 }}
              label="dfu.target.title"
              value={this.state.currentTarget}
              disabled={this.state.isFlashing}
              onChange={event => {
                this.setState({ currentTarget: event.target.value });
                this.setState({
                  selectedUrl: event.target.value.browser_download_url
                });
                this.setState({ selectedFile: null });
              }}
              items={
                this.state.currentRelease &&
                this.state.currentRelease.assets.map(target => {
                  return {
                    value: target,
                    label: target.label || "Choose One..."
                  };
                })
              }
            />
          )}
          {this.state.allowUpload && (
            <div
              style={{
                display: "flex",
                alignItems: "center",
                padding: "0 8px 0 0"
              }}
            >
              <Typography>
                <FormattedMessage id="common.or" />
              </Typography>
            </div>
          )}
          {this.state.allowUpload && (
            <Input
              id="file_input"
              style={{ flex: 1, marginBottom: 8 }}
              type="file"
              name="fileUpload"
              inputProps={{
                accept: "bin"
              }}
              onChange={event => {
                this.loadLocalFile(event);
                this.setState({ currentRelease: null });
              }}
            />
          )}
        </div>
        <div className="flex-center">
          {this.state.dfu && (
            <FormGroup component="fieldset" style={{ paddingLeft: 10 }}>
              <FormControlLabel
                control={
                  <Switch
                    checked={this.state.chipErase}
                    onChange={(event, chipErase) =>
                      this.setState({ chipErase })
                    }
                  />
                }
                label={<FormattedMessage id="dfu.full-erase" />}
              />
            </FormGroup>
          )}
          <Button
            style={{ margin: "20px", flex: 1 }}
            color="primary"
            variant="contained"
            onClick={() => this.handleFlash()}
            disabled={
              this.state.isFlashing ||
              (!this.state.selectedFile && !this.state.selectedUrl)
            }
          >
            <FormattedMessage id="common.flash" />
          </Button>
        </div>
        <Paper>
          {!this.state.selectedFile && (
            <Typography style={{ "max-height": "60vh", overflow: "auto" }}>
              <ReactMarkdown
                renderers={{
                  link: props => (
                    <a href={props.href} target="_blank">
                      {props.children}
                    </a>
                  )
                }}
                source={this.state.currentRelease.body}
                classNames={this.state.theme}
              />
            </Typography>
          )}
        </Paper>
        <CliView disabled={true} startText={this.cliNotice} ref="cliView" />
      </Paper>
    );
  }
Example #24
Source File: Filter.jsx    From Turnip-Calculator with MIT License 4 votes vote down vote up
Filter = ({ filters, onChange, openShareDialog }) => {
  const [clearDataDialogOpen, setClearDataDialogOpen] = useState(false);
  const { t } = useTranslation();
  const TextFieldClasses = useTextFieldStyles();
  const [currentPriceIndex, setCurrentPriceIndex] = useState(
    calculateCurrentPriceIndex
  );

  useInterval(() => {
    // It will not re-render the component if didn't change.
    const newPriceIndex = calculateCurrentPriceIndex();
    setCurrentPriceIndex(newPriceIndex);
  }, 1000);

  const handleChange = useCallback(
    (index) => ({
      target: {
        value,
        validity: { valid },
      },
    }) => {
      if (!valid) return;
      const newFilters = Array.from({ length: 13 }, (v, i) =>
        index === i ? value : filters[i]
      );
      onChange(newFilters);
    },
    [filters, onChange]
  );

  const names = [
    t("Buy Price"),
    ...t("Mon Tue Wed Thu Fri Sat")
      .split(" ")
      .reduce(
        (curr, day) => [...curr, ...[`${day} ${t("AM")}`, `${day} ${t("PM")}`]],
        []
      ),
  ];

  const fields = Array.from({ length: 13 }, (v, i) => i).map((index) => (
    <TextField
      key={`value-${index}`}
      type="tel"
      variant="standard"
      color="secondary"
      label={names[index]}
      fullWidth
      inputProps={{ pattern: "[0-9]*", tabIndex: 0 }}
      InputLabelProps={{
        shrink: true,
        classes: { root: TextFieldClasses.InputLabel },
      }}
      InputProps={{
        startAdornment: (
          <InputAdornment position="start">
            <img src={bells} alt="Bag of bells" />
          </InputAdornment>
        ),
        classes: {
          root: TextFieldClasses.Input,
        },
      }}
      value={filters[index] || ""}
      placeholder={currentPriceIndex === index ? t("Now") : ""}
      onChange={handleChange(index)}
    />
  ));

  return (
    <>
      <ClearDataDialog
        open={clearDataDialogOpen}
        dismiss={() => setClearDataDialogOpen(false)}
        confirm={() => {
          setClearDataDialogOpen(false);
          onChange([]);
        }}
      />
      <Box
        borderRadius={16}
        bgcolor="primary.light"
        display="flex"
        flexDirection="column"
      >
        <FormGroup>
          <Box
            m={2}
            p={2}
            mb={-1}
            borderRadius={16}
            bgcolor="bkgs.mainAlt"
            display="flex"
          >
            {fields[0]}
          </Box>
          <Box
            m={2}
            ml={1}
            mr={1}
            display="flex"
            flexWrap="wrap"
            alignItems="stretch"
          >
            {fields.slice(1).reduce(
              (prev, curr, index) =>
                index % 2
                  ? [
                      ...prev.slice(0, -1),
                      <Box
                        display="flex"
                        key={index}
                        p={1}
                        width={{ xs: 0.5, sm: 1 / 3, md: 1 / 6 }}
                      >
                        <Box
                          p={2}
                          bgcolor="bkgs.mainAlt"
                          borderRadius={16}
                          display="flex"
                          flexDirection="column"
                          justifyContent="space-between"
                        >
                          <Box m={1}>{prev.slice(-1)}</Box>
                          <Box m={1}>{curr}</Box>
                        </Box>
                      </Box>,
                    ]
                  : [...prev, curr],
              []
            )}
          </Box>
        </FormGroup>
        <Box alignSelf="flex-end" mt={-2} display="flex">
          <Box mx={1}>
            <Button onClick={openShareDialog}>{t("shareButton")}</Button>
          </Box>
          <ClearButton onClick={() => setClearDataDialogOpen(true)} />
        </Box>
      </Box>
    </>
  );
}
Example #25
Source File: MentorFilter.js    From mentors-website with MIT License 4 votes vote down vote up
MentorFilter = (props) => {
  const classes = useStyles();

  const {
    mentors,
    name,
    skill,
    country,
    searchByMentorName,
    choseSkill,
    choseCountry,
    choseFavMentors,
    isFavMentors,
  } = props;

  const handleSkillSelection = (e) => {
    choseSkill(e.target.value);
  };
  const handleCountrySelection = (e) => {
    choseCountry(e.target.value);
  };
  const handleFavMentorsChange = () => {
    choseFavMentors(!isFavMentors);
  };

  //creating a unique skills array.
  const skills = [...new Set(mentors.map((mentor) => mentor.skills).flat())];
  //creating a unique countries array.
  const filteredCountries = [
    ...new Set(mentors.map((mentor) => mentor.countryAlpha2Code)),
  ];
  const countries = filteredCountries.map((country) => {
    return {
      value: country,
      label: arabCountries[country],
    };
  });

  const handleNameSearch = (e) => {
    searchByMentorName(e.target.value);
  }

  const handleSkillClear = () => {
    choseSkill("");
  };
  const handleNameClear = () => {
    searchByMentorName("");
  };
  const handleCountryClear = () => {
    choseCountry("");
  };
  return (
    <form className={classes.root} noValidate autoComplete="off">
      <Grid container spacing={2}>
        <Grid item xs={12}>
          <Typography variant="h6" color="primary">
            Filter
          </Typography>
        </Grid>
        <Grid item xs={12}>
            <TextField
              value={name}
              variant="outlined"
              label="Name"
              select
              helperText="Filter mentors by name"
              onChange={handleNameSearch}
              fullWidth
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">
                    {name && (
                      <IconButton
                        aria-label="clear filter"
                        className={classes.clearBtn}
                        onClick={handleNameClear}
                        edge="end"
                      >
                        <ClearIcon />
                      </IconButton>
                    )}
                  </InputAdornment>
                ),
              }}
              
            >
              {mentors.map((mentor) => (
              <MenuItem key={mentor.id} value={mentor.name}>
                {mentor.name}
              </MenuItem>
            ))}
            </TextField>
        </Grid>
        <Grid item xs={12}>
          {/*FILTER BY SKILLS */}
          <TextField
            variant="outlined"
            id="standard-select-currency"
            select
            label="Skill"
            value={skill}
            onChange={handleSkillSelection}
            helperText="filter mentors by skills"
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  {skill && (
                    <IconButton
                      aria-label="clear filter"
                      className={classes.clearBtn}
                      onClick={handleSkillClear}
                      edge="end"
                    >
                      <ClearIcon />
                    </IconButton>
                  )}
                </InputAdornment>
              ),
            }}
            fullWidth
          >
            {skills.map((skill) => (
              <MenuItem key={skill} value={skill}>
                {skill}
              </MenuItem>
            ))}
          </TextField>
        </Grid>
        <Grid item xs={12}>
          <TextField
            variant="outlined"
            id="standard-select-currency"
            select
            label="country"
            value={country}
            onChange={handleCountrySelection}
            helperText="filter mentors by country"
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  {country && (
                    <IconButton
                      aria-label="clear filter"
                      className={classes.clearBtn}
                      onClick={handleCountryClear}
                      edge="end"
                    >
                      <ClearIcon />
                    </IconButton>
                  )}
                </InputAdornment>
              ),
            }}
            fullWidth
          >
            {countries.map((country) => (
              <MenuItem key={country.value} value={country.value}>
                {country.label}
              </MenuItem>
            ))}
          </TextField>
        </Grid>
        <Grid item xs={12}>
          <FormGroup>
            <FormControlLabel
              control={
                <Switch
                  color="secondary"
                  checked={isFavMentors}
                  onChange={handleFavMentorsChange}
                  aria-label={
                    isFavMentors ? "Favourite Mentors" : "All Mentors"
                  }
                />
              }
              label={
                <Typography color={isFavMentors ? "secondary" : "initial"}>
                  Favorite Mentors
                </Typography>
              }
            />
          </FormGroup>
        </Grid>
      </Grid>
    </form>
  );
}
Example #26
Source File: Filter.js    From to-view-list with MIT License 4 votes vote down vote up
Filter = () => {
  const [, dispatch] = useEntryContext();
  const [filter, setFilter] = useState({
    videos: false,
    articles: false,
    others: false,
    viewed: false,
    starred: false,
  });
  const classes = useFilterStyles();
  const { videos, articles, others, viewed, starred } = filter;

  const handleCheckboxChange = (event) => {
    setFilter({ ...filter, [event.target.name]: event.target.checked });
  };

  const handleApplyFilter = (e) => {
    e.preventDefault();
    if (Object.values(filter).every((v) => v === false)) {
      return dispatch(resetFilter());
    }

    dispatch(setFilterValues(filter));
  };

  const handleUncheck = () => {
    setFilter({
      videos: false,
      articles: false,
      others: false,
      viewed: false,
      starred: false,
    });
    dispatch(resetFilter());
  };

  return (
    <form className={classes.root} onSubmit={handleApplyFilter}>
      <FormGroup row className={classes.checkboxGroup}>
        <FormControlLabel
          control={
            <Checkbox
              checked={videos}
              onChange={handleCheckboxChange}
              name="videos"
            />
          }
          label="Videos"
        />
        <FormControlLabel
          control={
            <Checkbox
              checked={articles}
              onChange={handleCheckboxChange}
              name="articles"
            />
          }
          label="Articles"
        />
        <FormControlLabel
          control={
            <Checkbox
              checked={others}
              onChange={handleCheckboxChange}
              name="others"
            />
          }
          label="Others"
        />
        <FormControlLabel
          control={
            <Checkbox
              checked={viewed}
              onChange={handleCheckboxChange}
              name="viewed"
            />
          }
          label="Viewed"
        />
        <FormControlLabel
          control={
            <Checkbox
              checked={starred}
              onChange={handleCheckboxChange}
              name="starred"
            />
          }
          label="Starred"
        />
        <Button
          onClick={handleUncheck}
          startIcon={<RotateLeftIcon />}
          variant="outlined"
          size="small"
          className={classes.resetBtn}
        >
          Reset
        </Button>
      </FormGroup>
      <Button
        type="submit"
        variant="contained"
        color="primary"
        startIcon={<FilterListIcon />}
        className={classes.filterButton}
      >
        Apply Filter
      </Button>
    </form>
  );
}
Example #27
Source File: ChronicSick.js    From web with GNU General Public License v3.0 4 votes vote down vote up
ChronicSick = ({ handelGoToNextStep }) => {
  const { handleChange, setFieldValue, values } = useFormikContext();

  const handleSelectChronicSick = () => {
    setFieldValue(FIELD_IS_CHRONIC_SICK, VALUE_IS_CHRONIC_SICK_YES);
  };

  const handleSelectNoChronicSick = () => {
    setFieldValue(FIELD_IS_CHRONIC_SICK, VALUE_IS_CHRONIC_SICK_NO);
    chronicSickValues.map(field => field.field).forEach(item => setFieldValue(item, false));
  };

  const handleSetFieldValue = (field, value) => {
    setFieldValue(field, value);
  };

  const isAnyFieldSelected = () =>
    values[FIELD_IS_CHRONIC_SICK] === VALUE_IS_CHRONIC_SICK_NO || chronicSickValues.find(_obj => values[_obj.field]);

  const goToNextStep = () => {
    if (isAnyFieldSelected()) {
      handelGoToNextStep();
    }
  };

  const renderCheckboxes = chronicSickValues.map(({ field, description, placeholder }) => (
    <Fragment key={field}>
      <Checkbox
        checked={values[field]}
        label={
          <Label>
            <T i18nKey={field} />
          </Label>
        }
        name={field}
        onChange={() => handleSetFieldValue(field, !values[field])}
        size="big"
        value={values[field] || ''}
      />
      {values[field] && placeholder && (
        <InputWrapper>
          <TextField
            label={<T i18nKey={placeholder} />}
            name={description}
            onChange={handleChange}
            value={values[description] || ''}
          />
        </InputWrapper>
      )}
    </Fragment>
  ));

  const disabled = !isAnyFieldSelected();

  const isChronicSick = values[FIELD_IS_CHRONIC_SICK] === VALUE_IS_CHRONIC_SICK_YES;

  return (
    <>
      <Title>
        <T i18nKey="chronic_sick_text1" />
      </Title>
      <Wrapper>
        <FormGroup>
          <Radio
            checked={values[FIELD_IS_CHRONIC_SICK] === VALUE_IS_CHRONIC_SICK_NO}
            label={
              <Label>
                <T i18nKey="chronic_sick_text2" />
              </Label>
            }
            onChange={handleSelectNoChronicSick}
            name={FIELD_IS_CHRONIC_SICK}
          />
          <Radio
            checked={values[FIELD_IS_CHRONIC_SICK] === VALUE_IS_CHRONIC_SICK_YES}
            label={
              <Label>
                <T i18nKey="chronic_sick_text3" />
              </Label>
            }
            onChange={handleSelectChronicSick}
            name={FIELD_IS_CHRONIC_SICK}
          />
        </FormGroup>
      </Wrapper>

      {isChronicSick && (
        <SubContainer>
          <Description>
            <T i18nKey="chronic_sick_text4" />
          </Description>
          {renderCheckboxes}
        </SubContainer>
      )}
      <Actions>
        <Button disabled={disabled} onClick={goToNextStep} label={<T i18nKey="button_next" />} />
      </Actions>
    </>
  );
}
Example #28
Source File: Create.js    From course-manager with MIT License 4 votes vote down vote up
// ----------------------------------------------------------------------

export default function Create() {
  const navigate = useNavigate();
  const [isAdmin, setIsAdmin] = useState(false);
  const [isMod, setIsMod] = useState(false);
  const [isSupporter, setIsSupporter] = useState(false);

  const UserSchema = Yup.object().shape({
    fullName: Yup.string().required('Full name is required'),
    username: Yup.string().required('Username is required'),
    email: Yup.string().email('Email must be a valid email address').required('Email is required')
  });

  const formik = useFormik({
    initialValues: {
      fullName: '',
      username: '',
      email: ''
    },
    validationSchema: UserSchema,
    onSubmit: async (values) => {
      const roles = [];
      if (isAdmin) roles.push('ADMIN');
      if (isSupporter) roles.push('SUPPORTER');
      if (isMod) roles.push('MOD');

      const newUser = await apis.user.create({
        ...values,
        roles
      });
      console.log(`New user ${newUser.username}`);
      navigate('/dashboard/user', { replace: true });
    }
  });

  const handleChange = (event) => {
    switch (event.target.name) {
      case 'isAdmin':
        setIsAdmin(event.target.checked);
        if (event.target.checked) {
          setIsMod(false);
          setIsSupporter(false);
        }
        break;
      case 'isMod':
        setIsMod(event.target.checked);
        break;
      case 'isSupporter':
        setIsSupporter(event.target.checked);
        break;
      default:
        break;
    }
  };

  const { errors, touched, isSubmitting, handleSubmit, getFieldProps } = formik;

  return (
    <Page title="List | Minimal-UI">
      <Container>
        <Stack direction="row" alignItems="center" justifyContent="space-between" mb={5}>
          <Typography variant="h4" gutterBottom>
            Edit User
          </Typography>
          <Button
            variant="contained"
            component={RouterLink}
            to="#"
            startIcon={<Icon icon={plusFill} />}
          >
            New List
          </Button>
        </Stack>
        <FormikProvider value={formik}>
          <Form autoComplete="off" noValidate onSubmit={handleSubmit}>
            <Stack spacing={3}>
              <TextField
                fullWidth
                autoComplete="username"
                type="text"
                label="Username"
                {...getFieldProps('username')}
                error={Boolean(touched.username && errors.username)}
                helperText={touched.username && errors.username}
              />
              <TextField
                fullWidth
                autoComplete="fullName"
                type="text"
                label="Full name"
                {...getFieldProps('fullName')}
                error={Boolean(touched.fullName && errors.fullName)}
                helperText={touched.fullName && errors.fullName}
              />
              <TextField
                fullWidth
                autoComplete="email"
                type="email"
                label="Email"
                {...getFieldProps('email')}
                error={Boolean(touched.email && errors.email)}
                helperText={touched.email && errors.email}
              />
              <FormControlLabel
                control={<ODCheckbox checked={isAdmin} onChange={handleChange} name="isAdmin" />}
                label="Is Admin"
              />
              <FormGroup row>
                <FormControlLabel
                  disabled={isAdmin}
                  control={<ODCheckbox checked={isMod} onChange={handleChange} name="isMod" />}
                  label="Is Mod"
                />
                <FormControlLabel
                  disabled={isAdmin}
                  control={
                    <ODCheckbox checked={isSupporter} onChange={handleChange} name="isSupporter" />
                  }
                  label="Is Supporter"
                />
              </FormGroup>
              <LoadingButton
                fullWidth
                size="large"
                type="submit"
                variant="contained"
                loading={isSubmitting}
              >
                Submit
              </LoadingButton>
            </Stack>
          </Form>
        </FormikProvider>
        <Card />
      </Container>
    </Page>
  );
}
Example #29
Source File: CourseFilterSidebar.js    From course-manager with MIT License 4 votes vote down vote up
export default function ShopFilterSidebar({
  isOpenFilter,
  onResetFilter,
  onOpenFilter,
  onCloseFilter,
  formik
}) {
  const { values, getFieldProps, handleChange } = formik;

  return (
    <>
      <Button
        disableRipple
        color="inherit"
        endIcon={<Icon icon={roundFilterList} />}
        onClick={onOpenFilter}
      >
        Filters&nbsp;
      </Button>

      <FormikProvider value={formik}>
        <Form autoComplete="off" noValidate>
          <Drawer
            anchor="right"
            open={isOpenFilter}
            onClose={onCloseFilter}
            PaperProps={{
              sx: { width: 280, border: 'none', overflow: 'hidden' }
            }}
          >
            <Stack
              direction="row"
              alignItems="center"
              justifyContent="space-between"
              sx={{ px: 1, py: 2 }}
            >
              <Typography variant="subtitle1" sx={{ ml: 1 }}>
                Filters
              </Typography>
              <IconButton onClick={onCloseFilter}>
                <Icon icon={closeFill} width={20} height={20} />
              </IconButton>
            </Stack>

            <Divider />

            <Scrollbar>
              <Stack spacing={3} sx={{ p: 3 }}>
                <div>
                  <Typography variant="subtitle1" gutterBottom>
                    Gender
                  </Typography>
                  <FormGroup>
                    {FILTER_GENDER_OPTIONS.map((item) => (
                      <FormControlLabel
                        key={item}
                        control={
                          <Checkbox
                            {...getFieldProps('gender')}
                            value={item}
                            checked={values.gender.includes(item)}
                          />
                        }
                        label={item}
                      />
                    ))}
                  </FormGroup>
                </div>

                <div>
                  <Typography variant="subtitle1" gutterBottom>
                    Category
                  </Typography>
                  <RadioGroup {...getFieldProps('category')}>
                    {FILTER_CATEGORY_OPTIONS.map((item) => (
                      <FormControlLabel key={item} value={item} control={<Radio />} label={item} />
                    ))}
                  </RadioGroup>
                </div>

                <div>
                  <Typography variant="subtitle1" gutterBottom>
                    Colour
                  </Typography>
                  <ColorManyPicker
                    name="colors"
                    colors={FILTER_COLOR_OPTIONS}
                    onChange={handleChange}
                    onChecked={(color) => values.colors.includes(color)}
                    sx={{ maxWidth: 36 * 4 }}
                  />
                </div>

                <div>
                  <Typography variant="subtitle1" gutterBottom>
                    Price
                  </Typography>
                  <RadioGroup {...getFieldProps('priceRange')}>
                    {FILTER_PRICE_OPTIONS.map((item) => (
                      <FormControlLabel
                        key={item.value}
                        value={item.value}
                        control={<Radio />}
                        label={item.label}
                      />
                    ))}
                  </RadioGroup>
                </div>

                <div>
                  <Typography variant="subtitle1" gutterBottom>
                    Rating
                  </Typography>
                  <RadioGroup {...getFieldProps('rating')}>
                    {FILTER_RATING_OPTIONS.map((item, index) => (
                      <FormControlLabel
                        key={item}
                        value={item}
                        control={
                          <Radio
                            disableRipple
                            color="default"
                            icon={<Rating readOnly value={4 - index} />}
                            checkedIcon={<Rating readOnly value={4 - index} />}
                          />
                        }
                        label="& Up"
                        sx={{
                          my: 0.5,
                          borderRadius: 1,
                          '& > :first-of-type': { py: 0.5 },
                          '&:hover': {
                            opacity: 0.48,
                            '& > *': { bgcolor: 'transparent' }
                          },
                          ...(values.rating.includes(item) && {
                            bgcolor: 'background.neutral'
                          })
                        }}
                      />
                    ))}
                  </RadioGroup>
                </div>
              </Stack>
            </Scrollbar>

            <Box sx={{ p: 3 }}>
              <Button
                fullWidth
                size="large"
                type="submit"
                color="inherit"
                variant="outlined"
                onClick={onResetFilter}
                startIcon={<Icon icon={roundClearAll} />}
              >
                Clear All
              </Button>
            </Box>
          </Drawer>
        </Form>
      </FormikProvider>
    </>
  );
}