@material-ui/core#FormHelperText JavaScript Examples

The following examples show how to use @material-ui/core#FormHelperText. 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: AddGraph.js    From Interceptor with MIT License 6 votes vote down vote up
render() {
    //console.log("Rendering AddGraph");
    return (
      <Dialog
        open={this.props.show}
        aria-labelledby="form-dialog-title"
      >
        <DialogTitle id="form-dialog-title">Add Graph</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} direction="column" alignItems="center">
            <Grid item>
              <FormControl>
                <InputLabel htmlFor="plotname">Plot Name</InputLabel>
                <Input
                  id="plotname"
                  onChange={event => this.plotname = event.target.value}
                  aria-describedby="plotname-helper-text"
                  inputProps={{
                    'aria-label': 'Plot Name',
                  }}
                />
                <FormHelperText id="plotname-helper-text">Can be left empty</FormHelperText>
              </FormControl>
            </Grid>
            <Grid item>
            <ToggleButtonGroup orientation="vertical" value={this.lines} onChange={(event, lines) => {this.lines = lines; this.setState({render_revision: this.state.render_revision + 1}); } } aria-label="lines available">
              {this.renderButtons()}
            </ToggleButtonGroup>
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => this.props.addplot(this.plotname, this.lines)} color="default">
            Save
        </Button>
        </DialogActions>
      </Dialog>
    );
  }
Example #2
Source File: OperationForm.js    From Designer-Client with GNU General Public License v3.0 5 votes vote down vote up
export default function OperationForm(props) {
  const classes = useStyles();
  const operation = props.operation;

  return (
    <div className={classes.formContainer}>
      <div className={classes.formGroup}>
        <FormControl fullWidth={true}>
          <InputLabel htmlFor="operation-title">ģ˜¤ķ¼ė ˆģ“ģ…˜ ėŖ…ģ¹­</InputLabel>
          <Input id="operation-title" value={operation.title}></Input>
        </FormControl>
      </div>

      <div className={classes.formGroup}>
        <FormControl fullWidth={true}>
          <TextField
            id="operation-description"
            label="ģ˜¤ķ¼ė ˆģ“ģ…˜ ģ„¤ėŖ…"
            multiline
            rows={5}
            value={operation.desc}
            aria-describedby="description-helper-text"
            name="description"
            placeholder="API ģ“ģš©ģžģ—ź²Œ ģ•ˆė‚“ė˜ėŠ” ģ„¤ėŖ…źø€ ģž…ė‹ˆė‹¤. ė°ģ“ķ„°ģ˜ ģ“ķ•“ė„¼ ģœ„ķ•œ ģ„¤ėŖ…ģ„ ģ¹œģ ˆķžˆ ģž‘ģ„±ķ•“ ģ£¼ģ„øģš”."
          />
        </FormControl>
      </div>

      <div className={classes.formGroup}>
        <Grid container spacing={2}>
          <Grid item xs={12} sm={3}>
            <FormControl fullWidth={true}>
              <InputLabel width="100%" htmlFor="operation-method">
                ķ˜øģ¶œ ė°©ģ‹
              </InputLabel>
              <Select
                labelId="operation-method"
                id="namespace-input"
                name="method"
                value={operation.method || 'GET'}
              >
                <MenuItem value={"GET"}>GET</MenuItem>
              </Select>
              <FormHelperText id="operation-method-text">Http metodė„¼ ģ„ ķƒķ•“ģ£¼ģ„øģš”. ķ˜„ģž¬ GET źø°ėŠ„ė§Œ ģ§€ģ›ķ•©ė‹ˆė‹¤.</FormHelperText>
            </FormControl>
          </Grid>

          <Grid item xs={12} sm={9}>
            <FormControl fullWidth={true}>
              <InputLabel width="100%" htmlFor="operation-end-point">ķ˜øģ¶œ ģ£¼ģ†Œ</InputLabel>
              <Input id="operation-end-point" value={operation.endPoint || ''} aria-describedby="entityName-helper-text" name="entityName" />
              <FormHelperText id="operation-end-point-text">{`https://OOOOOO.go.kr/api/APINAME/v1/TEST`}</FormHelperText>
            </FormControl>  
          </Grid>
        </Grid>
      </div>
    </div>
  )
}
Example #3
Source File: New.js    From Designer-Client with GNU General Public License v3.0 5 votes vote down vote up
export function OperationNew(props) {
  const apis = useSelector(state => state.apis.items);
  let meta = props.location.state ? props.location.state.meta : null;
  const api = apis.find(el => el.id == meta.apiId);
  const loading = useSelector(state => state.operations.loading);
  const dispatch = useDispatch();

  const initialForm = {
    api: api,
    metaId: meta.id,
    title: "",
    description: "",
    method: "get",
    entityName: ""
  }

  const [form, setForm] = useState(initialForm);

  const handleChange = (e) => {
    setForm({
      ...form,
      [e.target.name]: e.target.value
    })
  }

  const onSaveButtonClick = (e) => {
    dispatch(operationActions.postOperation(form));
  }

  return (
    <Container>
      <PageTitle text="ģ˜¤ķ¼ė ˆģ“ģ…˜ ģ •ģ˜"/>
      <Box mt={2}>
        <FormControl fullWidth={true}>
          <InputLabel width="100%" htmlFor="title-input">ģ œėŖ©</InputLabel>
          <Input id="title-input" aria-describedby="title-helper-text" name="title" value={form.title} onChange={handleChange}/>
        </FormControl>
      </Box>
      <Box mt={2}>
        <FormControl fullWidth={true}>
          <TextField
            id="description-input"
            label="Description"
            multiline
            rows={5}
            variant="filled"
            aria-describedby="description-helper-text"
            name="description" value={form.description} onChange={handleChange}
          />
        </FormControl>
      </Box>
      <Box mt={2}>
        <FormControl fullWidth={true}>
          <InputLabel width="100%" htmlFor="namespace-input">Method</InputLabel>
          <Select
            labelId="demo-simple-select-label"
            id="namespace-input"
            name="method"
            value={form.method}
            onChange={handleChange}
          >
            <MenuItem value={"get"}>GET</MenuItem>
          </Select>
          <FormHelperText id="namespace-helper-text">Http metodė„¼ ģ„ ķƒķ•“ģ£¼ģ„øģš”. ķ˜„ģž¬ GET źø°ėŠ„ė§Œ ģ§€ģ›ķ•©ė‹ˆė‹¤.</FormHelperText>
        </FormControl>
      </Box>
      <Box mt={2}>
        <FormControl fullWidth={true}>
          <InputLabel width="100%" htmlFor="entityName-input">ķ˜øģ¶œ ģ£¼ģ†Œ</InputLabel>
          <Input id="entityName-input" aria-describedby="entityName-helper-text" name="entityName" value={form.entityName} onChange={handleChange}/>
          <FormHelperText id="namespace-helper-text">{`https://OOOOOO.go.kr/api/APINAME/v1/${form.entityName}`}</FormHelperText>
        </FormControl>  
      </Box>
      <Box mt={2} textAlign="right">
        <Button disabled={loading} variant="contained" color="primary" onClick={onSaveButtonClick}>ģ €ģž„</Button>
      </Box>
    </Container>
  )
}
Example #4
Source File: FeaturedPost.js    From alexa-community-jaipur with MIT License 5 votes vote down vote up
export default function FeaturedPost(props) {
  const classes = useStyles();
  const { post } = props;

  return (
    <Grid item xs={12} md={6}>
      <Card className={classes.card}>
        <div className={classes.cardDetails}>
          <CardContent>
            <Typography component="h2" variant="h5">
              {post.title}
            </Typography>
            <Typography variant="subtitle1" color="textSecondary">
              {post.date}
            </Typography>
            <Typography variant="subtitle1" paragraph>
              {post.description}
            </Typography>
            {post.suggestionPlaceholder ? (
              <Grid container direction="row">
                <FormControl>
                  <Grid item>
                    <InputLabel htmlFor="suggestions">
                      {post.suggestionPlaceholder}
                    </InputLabel>
                    <Input
                      id="suggestions"
                      aria-describedby="my-helper-suggestions"
                    />
                    <Button type="submit">Submit</Button>
                  </Grid>
                  <FormHelperText id="my-helper-suggestions">
                    We will try to cover the most asked topics.
                  </FormHelperText>
                </FormControl>
              </Grid>
            ) : null}
            {post.feedback ? (
              <Grid container direction="row">
                <FormControl>
                  <Grid item>
                    <InputLabel htmlFor="feedback">{post.feedback}</InputLabel>
                    <Input id="feedback" aria-describedby="my-helper-text" />
                    <Button type="submit">Submit</Button>
                  </Grid>
                  <FormHelperText id="my-helper-text">
                    Your feedback helps us improve.
                  </FormHelperText>
                </FormControl>
              </Grid>
            ) : null}
            <Typography variant="subtitle1" color="primary">
              <Button href="#" disabled={post.buttonDisable}>
                {post.buttonText}
              </Button>
            </Typography>
          </CardContent>
        </div>
        <Hidden xsDown>
          <CardMedia
            className={classes.cardMedia}
            image={post.image}
            title={post.imageTitle}
          />
        </Hidden>
      </Card>
    </Grid>
  );
}
Example #5
Source File: GraphSettings.js    From Interceptor with MIT License 5 votes vote down vote up
render() {
    //console.log("Rendering GraphSettings");
    return (
      <Dialog
        open={this.props.show}
        aria-labelledby="form-dialog-title"
      >
        <DialogTitle id="form-dialog-title">Graphs settings</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} direction="column" alignItems="flex-start">
            <Grid item>
              <FormControl>
                <InputLabel htmlFor="cols">Graph columns</InputLabel>
                <Input
                  id="cols"
                  value={this.state.cols}
                  onChange={event => this.setState({ cols: Math.min(Math.max(parseInt(event.target.value), 1), 12) })}
                  aria-describedby="cols-helper-text"
                  inputProps={{
                    'aria-label': 'Graph columns',
                  }}
                />
                <FormHelperText id="cols-helper-text">Max: 12</FormHelperText>
              </FormControl>
            </Grid>
            <Grid item>
              <FormControl>
                <InputLabel htmlFor="rateHz">Render rate</InputLabel>
                <Input
                  id="rateHz"
                  value={this.state.rateHz}
                  onChange={event => this.setState({ rateHz: Math.min(Math.max(parseInt(event.target.value), 0.5), 20) })}
                  endAdornment={<InputAdornment position="end">Hz</InputAdornment>}
                  aria-describedby="rateHz-helper-text"
                  inputProps={{
                    'aria-label': 'Render rate',
                  }}
                />
                <FormHelperText id="rateHz-helper-text">Min: 0.5, Max: 20</FormHelperText>
              </FormControl>
            </Grid>
            <Grid item>
              <FormControl>
                <InputLabel htmlFor="max_datapoints">Max data points</InputLabel>
                <Input
                  id="max_datapoints"
                  value={this.state.max_datapoints}
                  onChange={event => this.setState({ max_datapoints: Math.min(Math.max(parseInt(event.target.value), 20), 10000) })}
                  aria-describedby="max_datapoints-helper-text"
                  inputProps={{
                    'aria-label': 'Max data points',
                  }}
                />
                <FormHelperText id="max_datapoints-helper-text">Max: 10000</FormHelperText>
              </FormControl>
            </Grid>
            <Grid item>
              <FormControlLabel
                control={<Switch checked={this.state.webgl} onChange={() => this.setState({ webgl: !this.state.webgl })} name="webGL" />}
                label="WebGL support"
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => this.props.setSettings(this.state.cols, this.state.rateHz, this.state.max_datapoints, this.state.webgl)} color="default">
            Save
        </Button>
        </DialogActions>
      </Dialog>
    );
  }
Example #6
Source File: MainSettings.js    From Interceptor with MIT License 5 votes vote down vote up
render() {
    //console.log("Rendering MainSettings");
    return (
      <Dialog
        open={this.props.show}
        aria-labelledby="form-dialog-title"
      >
        <DialogTitle id="form-dialog-title">Main settings</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} direction="column" alignItems="flex-start">
            <Grid item>
              <FormControl>
                <InputLabel htmlFor="ws_url">WebSocket URL</InputLabel>
                <Input
                  id="ws_url"
                  value={this.state.ws_url}
                  onChange={event => this.setState({ ws_url: event.target.value })}
                  aria-describedby="ws_url-helper-text"
                  inputProps={{
                    'aria-label': 'WebSocket URL',
                  }}
                />
                <FormHelperText id="ws_url-helper-text">Tethered WiFi ws://192.168.43.1:8989</FormHelperText>
              </FormControl>
            </Grid>
            <Grid item>
              <FormControl>
                <InputLabel htmlFor="rateHz">Render rate</InputLabel>
                <Input
                  id="rateHz"
                  value={this.state.rateHz}
                  onChange={event => this.setState({ rateHz: Math.min(Math.max(parseInt(event.target.value), 0.5), 20) })}
                  endAdornment={<InputAdornment position="end">Hz</InputAdornment>}
                  aria-describedby="rateHz-helper-text"
                  inputProps={{
                    'aria-label': 'Render rate',
                  }}
                />
                <FormHelperText id="rateHz-helper-text">Min: 0.5, Max: 20</FormHelperText>
              </FormControl>
            </Grid>
            <Grid item>
              <FormControlLabel
                control={<Switch checked={this.state.dark_theme} onChange={() => this.setState({ dark_theme: !this.state.dark_theme })} name="dark_theme" />}
                label="Dark theme"
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => this.props.setSettings(this.state.ws_url, this.state.rateHz, this.state.dark_theme)} color="default">
            Save
        </Button>
        </DialogActions>
      </Dialog>
    );
  }
Example #7
Source File: index.jsx    From redive_linebot with MIT License 5 votes vote down vote up
EditForm = ({ onCancel, onSubmit }) => {
  const classes = useStyles();
  const [{ data: bossData = [], loading }] = useAxios("/api/Admin/WorldBoss");
  const bossEl = useRef(null);
  const announceEl = useRef(null);
  const startTimeEl = useRef(null);
  const endTimeEl = useRef(null);

  const handleSubmit = () => {
    const [startAt, endAt] = [startTimeEl.current.value, endTimeEl.current.value];

    if (startAt >= endAt) {
      alert("č«‹ē¢ŗčŖę“»å‹•ę™‚é–“");
      return;
    }

    onSubmit({
      world_boss_id: parseInt(bossEl.current.value),
      announcement: announceEl.current.value,
      start_time: startAt,
      end_time: endAt,
    });
  };

  return (
    <Grid container spacing={1} component={Paper} className={classes.form}>
      {loading && <HeartbeatLoading />}
      <Grid item xs={12}>
        <Typography variant="h5">äø–ē•ŒēŽ‹ę“»å‹•ē®”ē†</Typography>
      </Grid>
      <Grid item xs={12}>
        <FormControl fullWidth>
          <NativeSelect fullWidth inputRef={bossEl}>
            {bossData.map(boss => (
              <option key={boss.id} value={boss.id}>
                {boss.name}
              </option>
            ))}
          </NativeSelect>
          <FormHelperText>č«‹éø꓇äø–ē•ŒēŽ‹ä¾†ē¶å®šę“»å‹•ļ¼Œč‹„ē„”äø–ē•ŒēŽ‹ļ¼Œč«‹å…ˆåŽ»ę–°å¢žäø–ē•ŒēŽ‹</FormHelperText>
        </FormControl>
      </Grid>
      <Grid item xs={12}>
        <TextField label="ę“»å‹•å…¬å‘Š" multiline fullWidth margin="normal" inputRef={announceEl} />
      </Grid>
      <Grid item xs={6}>
        <FormControl fullWidth required margin="normal">
          <FormLabel>é–‹å§‹ę™‚é–“</FormLabel>
          <Input inputProps={{ type: "datetime-local" }} inputRef={startTimeEl} />
        </FormControl>
      </Grid>
      <Grid item xs={6}>
        <FormControl fullWidth required margin="normal">
          <FormLabel>ēµęŸę™‚é–“</FormLabel>
          <Input inputProps={{ type: "datetime-local" }} inputRef={endTimeEl} />
        </FormControl>
      </Grid>
      <Grid item xs={6}>
        <Button variant="contained" color="secondary" fullWidth onClick={onCancel}>
          å–ę¶ˆ
        </Button>
      </Grid>
      <Grid item xs={6}>
        <Button variant="contained" color="primary" fullWidth onClick={handleSubmit}>
          ę–°å¢ž
        </Button>
      </Grid>
    </Grid>
  );
}
Example #8
Source File: CreateProject.jsx    From zubhub with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @function CreateProject View
 * @author Raymond Ndibe <[email protected]>
 *
 * @todo - describe function's signature
 */
function CreateProject(props) {
  const [category, setCategory] = React.useState([]);

  const classes = useStyles();
  const common_classes = useCommonStyles();

  const refs = {
    title_el: React.useRef(null),
    desc_el: React.useRef(null),
    image_el: React.useRef(null),
    image_upload_button_el: React.useRef(null),
    video_upload_button_el: React.useRef(null),
    image_count_el: React.useRef(null),
    video_el: React.useRef(null),
    video_file_el: React.useRef(null),
    video_selection_feedback_el: React.useRef(null),
    add_materials_used_el: React.useRef(null),
    add_tags_el: React.useRef(null),
    publish_type_el: React.useRef(null),
    publish_visible_to_el: React.useRef(null),
  };

  const [state, setState] = React.useState({
    ...JSON.parse(JSON.stringify(vars.default_state)),
  });

  React.useEffect(() => {
    if (props.match.params.id) {
      Promise.all([getProject(refs, props, state), getCategories(props)]).then(
        result => handleSetState({ ...result[0], ...result[1] }),
      );
    } else {
      handleSetState(getCategories(props));
    }
    handleSetState(buildPublishTypes(props));
  }, []);

  React.useEffect(() => {
    checkMediaFilesErrorState(refs, props);
  }, [
    props.errors['project_images'],
    props.touched['project_images'],
    props.errors['video'],
    props.touched['video'],
  ]);

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

  const {
    desc_input_is_focused,
    video_upload_dialog_open,
    media_upload,
    categories,
    tag_suggestion,
    tag_suggestion_open,
    select_video_file,
    publish_types,
    publish_visible_to_suggestion_open,
    publish_visible_to_suggestion,
  } = state;
  const { t } = props;
  const id = props.match.params.id;
  if (!props.auth.token) {
    return <ErrorPage error={t('createProject.errors.notLoggedIn')} />;
  } else {
    return (
      <Box className={classes.root}>
        <Container className={classes.containerStyle}>
          <Card className={classes.cardStyle}>
            <CardActionArea>
              <CardContent>
                <form
                  className="project-create-form"
                  name="create_project"
                  noValidate="noValidate"
                  onSubmit={e =>
                    !vars.upload_in_progress
                      ? initUpload(e, state, props, handleSetState)
                      : e.preventDefault()
                  }
                >
                  <Typography
                    className={classes.titleStyle}
                    gutterBottom
                    variant="h5"
                    component="h2"
                    color="textPrimary"
                  >
                    {!id
                      ? t('createProject.welcomeMsg.primary')
                      : t('createProject.inputs.edit')}
                  </Typography>
                  <Typography
                    variant="body2"
                    color="textSecondary"
                    component="p"
                    className={classes.descStyle}
                  >
                    {t('createProject.welcomeMsg.secondary')}
                  </Typography>

                  <Grid container spacing={3}>
                    <Grid item xs={12}>
                      <Box
                        component="p"
                        className={
                          props.status &&
                          props.status['non_field_errors'] &&
                          classes.errorBox
                        }
                      >
                        {props.status && props.status['non_field_errors'] && (
                          <Box component="span" className={classes.error}>
                            {props.status['non_field_errors']}
                          </Box>
                        )}
                      </Box>
                    </Grid>

                    <Grid item xs={12} className={common_classes.marginTop1em}>
                      <FormControl
                        className={clsx(classes.margin, classes.textField)}
                        variant="outlined"
                        size="small"
                        fullWidth
                        margin="small"
                        error={
                          (props.status && props.status['title']) ||
                          (props.touched['title'] && props.errors['title'])
                        }
                      >
                        <label htmlFor="title">
                          <Typography
                            color="textSecondary"
                            className={clsx(
                              classes.customLabelStyle,
                              common_classes.marginBottom1em,
                            )}
                          >
                            <Box className={classes.fieldNumberStyle}>1</Box>
                            {t('createProject.inputs.title.label')}
                          </Typography>
                        </label>
                        <OutlinedInput
                          ref={refs.title_el}
                          className={classes.customInputStyle}
                          id="title"
                          name="title"
                          type="text"
                          onChange={e => handleTextFieldChange(e, props)}
                          onBlur={e => handleTextFieldBlur(e, props)}
                        />
                        <FormHelperText
                          error
                          className={classes.fieldHelperTextStyle}
                        >
                          {(props.status && props.status['title']) ||
                            (props.touched['title'] &&
                              props.errors['title'] &&
                              t(
                                `createProject.inputs.title.errors.${props.errors['title']}`,
                              ))}
                        </FormHelperText>
                      </FormControl>
                    </Grid>

                    <Grid item xs={12} className={common_classes.marginTop1em}>
                      <FormControl
                        className={clsx(classes.margin, classes.textField)}
                        variant="outlined"
                        size="small"
                        fullWidth
                        margin="small"
                      >
                        <label htmlFor="description">
                          <Typography
                            color="textSecondary"
                            className={clsx(
                              classes.customLabelStyle,
                              common_classes.marginBottom1em,
                            )}
                          >
                            <Box className={classes.fieldNumberStyle}>2</Box>
                            {t('createProject.inputs.description.label')}
                          </Typography>
                        </label>
                        <Typography
                          color="textSecondary"
                          variant="caption"
                          component="span"
                          className={clsx(
                            classes.fieldHelperTextStyle,
                            common_classes.marginBottom1em,
                          )}
                        >
                          {t('createProject.inputs.description.helperText')}
                        </Typography>
                        <ClickAwayListener
                          onClickAway={() =>
                            handleSetState({ desc_input_is_focused: false })
                          }
                        >
                          <ReactQuill
                            ref={refs.desc_el}
                            className={clsx(
                              classes.descInputStyle,
                              {
                                [classes.descInputFocusStyle]:
                                  desc_input_is_focused,
                              },
                              {
                                [classes.descInputErrorStyle]:
                                  (props.status &&
                                    props.status['description']) ||
                                  (props.touched['description'] &&
                                    props.errors['description']),
                              },
                            )}
                            modules={vars.quill.modules}
                            formats={vars.quill.formats}
                            defaultValue={''}
                            placeholder={t(
                              'createProject.inputs.description.placeholder',
                            )}
                            onChange={value =>
                              handleDescFieldChange(
                                value,
                                props,
                                handleSetState,
                              )
                            }
                            onFocus={() =>
                              handleDescFieldFocusChange(
                                null,
                                props,
                                handleSetState,
                              )
                            }
                          />
                        </ClickAwayListener>
                        <FormHelperText
                          error
                          className={classes.fieldHelperTextStyle}
                        >
                          {(props.status && props.status['description']) ||
                            (props.touched['description'] &&
                              props.errors['description'] &&
                              t(
                                `createProject.inputs.description.errors.${props.errors['description']}`,
                              ))}
                        </FormHelperText>
                      </FormControl>
                    </Grid>

                    <Grid item xs={12} className={common_classes.marginTop1em}>
                      <FormControl
                        fullWidth
                        error={
                          (props.status && props.status['project_images']) ||
                          (props.touched['project_images'] &&
                            props.errors['project_images'])
                        }
                      >
                        <label htmlFor="project_images">
                          <Typography
                            color="textSecondary"
                            className={classes.customLabelStyle}
                          >
                            <Box className={classes.fieldNumberStyle}>3</Box>
                            {t('createProject.inputs.projectImages.label')}
                          </Typography>
                        </label>

                        <Typography
                          color="textSecondary"
                          variant="caption"
                          component="span"
                          className={clsx(
                            classes.fieldHelperTextStyle,
                            common_classes.marginBottom1em,
                          )}
                        >
                          {t(
                            'createProject.inputs.projectImages.topHelperText',
                          )}
                        </Typography>
                        <Grid container spacing={1}>
                          <Grid item xs={12} sm={6} md={6}>
                            <CustomButton
                              ref={refs.image_upload_button_el}
                              variant="outlined"
                              size="large"
                              margin="normal"
                              id="image_upload_button"
                              startIcon={<ImageIcon />}
                              onClick={e =>
                                handleImageButtonClick(e, props, refs)
                              }
                              secondaryButtonStyle
                              mediaUploadButtonStyle
                              customButtonStyle
                              fullWidth
                            >
                              {t('createProject.inputs.projectImages.label2')}
                            </CustomButton>
                            <Typography
                              color="textSecondary"
                              variant="caption"
                              component="span"
                              ref={refs.image_count_el}
                            ></Typography>
                          </Grid>
                        </Grid>
                        <input
                          ref={refs.image_el}
                          className={classes.displayNone}
                          aria-hidden="true"
                          type="file"
                          accept="image/*"
                          id="project_images"
                          name="project_images"
                          multiple
                          onChange={_ =>
                            handleImageFieldChange(
                              refs,
                              props,
                              state,
                              handleSetState,
                            )
                          }
                          onBlur={props.handleBlur}
                        />
                        <FormHelperText
                          error
                          className={classes.fieldHelperTextStyle}
                        >
                          {(props.status && props.status['images']) ||
                            (props.errors['project_images'] &&
                              t(
                                `createProject.inputs.projectImages.errors.${props.errors['project_images']}`,
                              ))}
                        </FormHelperText>
                      </FormControl>
                    </Grid>

                    <Grid item xs={12} className={common_classes.marginTop1em}>
                      <FormControl
                        fullWidth
                        error={
                          (props.status && props.status['video']) ||
                          (props.touched['video'] && props.errors['video'])
                        }
                      >
                        <label htmlFor="video">
                          <Typography
                            color="textSecondary"
                            className={classes.customLabelStyle}
                          >
                            <Box className={classes.fieldNumberStyle}>4</Box>
                            {t('createProject.inputs.video.label')}
                          </Typography>
                        </label>

                        <Typography
                          color="textSecondary"
                          variant="caption"
                          component="span"
                          className={clsx(
                            classes.fieldHelperTextStyle,
                            common_classes.marginBottom1em,
                          )}
                        >
                          {t('createProject.inputs.video.topHelperText')}
                        </Typography>
                        <Grid container spacing={1}>
                          <Grid item xs={12} sm={6} md={6}>
                            <CustomButton
                              ref={refs.video_upload_button_el}
                              variant="outlined"
                              size="large"
                              margin="normal"
                              id="video_upload_button"
                              startIcon={<VideoIcon />}
                              onClick={e =>
                                handleSetState(
                                  handleVideoButtonClick(
                                    e,
                                    props,
                                    video_upload_dialog_open,
                                  ),
                                )
                              }
                              secondaryButtonStyle
                              mediaUploadButtonStyle
                              customButtonStyle
                              fullWidth
                            >
                              {t('createProject.inputs.video.label2')}
                            </CustomButton>
                            <Typography
                              color="textSecondary"
                              variant="caption"
                              component="span"
                              ref={refs.video_selection_feedback_el}
                            ></Typography>
                          </Grid>
                        </Grid>
                        <FormHelperText
                          error
                          className={classes.fieldHelperTextStyle}
                        >
                          {(props.status && props.status['video']) ||
                            (props.errors['video'] &&
                              t(
                                `createProject.inputs.video.errors.${props.errors['video']}`,
                              ))}
                        </FormHelperText>
                        <Typography
                          color="textSecondary"
                          variant="caption"
                          component="span"
                          className={classes.fieldHelperTextStyle}
                        >
                          {t('createProject.inputs.video.bottomHelperText')}
                        </Typography>
                      </FormControl>
                    </Grid>

                    <Grid item xs={12} className={common_classes.marginTop1em}>
                      <FormControl
                        className={clsx(classes.margin, classes.textField)}
                        variant="outlined"
                        size="small"
                        fullWidth
                        margin="small"
                        error={
                          (props.status && props.status['materials_used']) ||
                          (props.touched['materials_used'] &&
                            props.errors['materials_used'])
                        }
                      >
                        <label htmlFor="add_materials_used">
                          <Typography
                            color="textSecondary"
                            className={clsx(
                              classes.customLabelStyle,
                              common_classes.marginBottom1em,
                            )}
                          >
                            <Box className={classes.fieldNumberStyle}>5</Box>
                            {t('createProject.inputs.materialsUsed.label')}
                          </Typography>
                        </label>

                        <Grid container spacing={1} alignItems="flex-end">
                          <Grid item xs={12} sm={8}>
                            <Box ref={refs.add_materials_used_el}>
                              {buildMaterialUsedNodes({
                                props,
                                refs,
                                classes,
                                common_classes,
                              })}
                            </Box>
                          </Grid>
                          <Grid item xs={12} sm={4} md={4}>
                            <CustomButton
                              variant="outlined"
                              size="large"
                              onClick={e => addMaterialsUsedNode(e, props)}
                              secondaryButtonStyle
                              customButtonStyle
                              fullWidth
                            >
                              <AddIcon />{' '}
                              {t('createProject.inputs.materialsUsed.addMore')}
                            </CustomButton>
                          </Grid>
                          <FormHelperText
                            error
                            className={classes.fieldHelperTextStyle}
                          >
                            {(props.status && props.status['materials_used']) ||
                              (props.touched['materials_used'] &&
                                props.errors['materials_used'] &&
                                t(
                                  `createProject.inputs.materialsUsed.errors.${props.errors['materials_used']}`,
                                ))}
                          </FormHelperText>
                        </Grid>
                      </FormControl>
                    </Grid>

                    <Grid item xs={12} className={common_classes.marginTop1em}>
                      <FormControl
                        className={clsx(classes.margin, classes.textField)}
                        variant="outlined"
                        size="small"
                        fullWidth
                        margin="small"
                        error={
                          (props.status && props.status['category']) ||
                          (props.touched['category'] &&
                            props.errors['category'])
                        }
                      >
                        <label htmlFor="category">
                          <Typography
                            color="textSecondary"
                            className={classes.customLabelStyle}
                          >
                            <Box className={classes.fieldNumberStyle}>6</Box>
                            {t('createProject.inputs.category.label')}
                          </Typography>
                        </label>
                        <Typography
                          color="textSecondary"
                          variant="caption"
                          component="span"
                          className={clsx(
                            classes.fieldHelperTextStyle,
                            common_classes.marginBottom1em,
                          )}
                        >
                          {t('createProject.inputs.category.topHelperText')}
                        </Typography>
                        <Select
                          labelId="category"
                          id="category"
                          name="category"
                          className={classes.customInputStyle}
                          value={
                            props.values.category ? props.values.category : ''
                          }
                          onChange={props.handleChange}
                          onBlur={props.handleBlur}
                        >
                          <MenuItem value="">
                            <em>None</em>
                          </MenuItem>
                          {Array.isArray(categories) &&
                            categories.map(category => (
                              <MenuItem key={category.id} value={category.name}>
                                {category.name}
                              </MenuItem>
                            ))}
                        </Select>
                        <FormHelperText
                          error
                          className={classes.fieldHelperTextStyle}
                        >
                          {(props.status && props.status['category']) ||
                            (props.touched['category'] &&
                              props.errors['category'] &&
                              t(
                                `createProject.inputs.category.errors.${props.errors['category']}`,
                              ))}
                        </FormHelperText>
                      </FormControl>
                    </Grid>

                    <Grid item xs={12} className={common_classes.marginTop1em}>
                      <FormControl
                        className={clsx(classes.margin, classes.textField)}
                        variant="outlined"
                        size="small"
                        fullWidth
                        margin="small"
                        error={
                          (props.status && props.status['tags']) ||
                          (props.touched['tags'] && props.errors['tags'])
                        }
                      >
                        <label htmlFor="add_tags">
                          <Typography
                            color="textSecondary"
                            className={classes.customLabelStyle}
                          >
                            <Box className={classes.fieldNumberStyle}>7</Box>
                            {t('createProject.inputs.tags.label')}
                          </Typography>
                        </label>

                        <Typography
                          color="textSecondary"
                          variant="caption"
                          component="span"
                          className={clsx(
                            classes.fieldHelperTextStyle,
                            common_classes.marginBottom1em,
                          )}
                        >
                          {t('createProject.inputs.tags.topHelperText')}
                        </Typography>
                        <Box className={classes.tagsViewStyle}>
                          {props.values['tags'] &&
                            JSON.parse(props.values['tags']).map((tag, num) =>
                              tag && tag.name ? (
                                <Chip
                                  className={classes.customChipStyle}
                                  key={num}
                                  label={tag.name}
                                  onDelete={e => removeTag(e, props, tag.name)}
                                  color="secondary"
                                  variant="outlined"
                                />
                              ) : null,
                            )}
                          <input
                            ref={refs.add_tags_el}
                            className={classes.tagsInputStyle}
                            name="tags"
                            type="text"
                            autocomplete="off"
                            placeholder={
                              props.values['tags'] &&
                              JSON.parse(props.values['tags']).length >= 5
                                ? t(
                                    'createProject.inputs.tags.errors.limitReached',
                                  )
                                : `${t('createProject.inputs.tags.addTag')}...`
                            }
                            onChange={e => {
                              handleSuggestTags(
                                e,
                                props,
                                state,
                                handleSetState,
                              );
                              handleSetState(handleAddTags(e, props));
                            }}
                            onBlur={e => {
                              handleAddTags(e, props);
                            }}
                          />
                          <ClickAwayListener
                            onClickAway={() =>
                              handleSetState({
                                tag_suggestion_open: false,
                                tag_suggestion: [],
                              })
                            }
                          >
                            <Box
                              className={clsx(
                                classes.tagSuggestionStyle,
                                !tag_suggestion_open
                                  ? common_classes.displayNone
                                  : null,
                              )}
                            >
                              {tag_suggestion && tag_suggestion.length > 0 ? (
                                tag_suggestion.map((tag, index) => (
                                  <Typography
                                    key={index}
                                    color="textPrimary"
                                    className={classes.tagSuggestionTextStyle}
                                    onClick={() => {
                                      clearTimeout(vars.timer.id);
                                      handleSetState(
                                        handleAddTags(
                                          {
                                            currentTarget: {
                                              value: `${tag.name},`,
                                            },
                                          },
                                          props,
                                          refs.add_tags_el,
                                        ),
                                      );
                                    }}
                                  >
                                    {tag.name}
                                  </Typography>
                                ))
                              ) : (
                                <CircularProgress size={30} thickness={3} />
                              )}
                            </Box>
                          </ClickAwayListener>
                        </Box>
                        <FormHelperText
                          error
                          className={classes.fieldHelperTextStyle}
                        >
                          {(props.status && props.status['tags']) ||
                            (props.touched['tags'] &&
                              props.errors['tags'] &&
                              t(
                                `createProject.inputs.tags.errors.${props.errors['tags']}`,
                              ))}
                        </FormHelperText>
                      </FormControl>
                    </Grid>

                    <Grid item xs={12} className={common_classes.marginTop1em}>
                      <FormControl
                        className={clsx(classes.margin, classes.textField)}
                        variant="outlined"
                        size="small"
                        fullWidth
                        margin="small"
                        error={
                          (props.status && props.status['publish']) ||
                          (props.touched['publish'] && props.errors['publish'])
                        }
                      >
                        <label htmlFor="publish">
                          <Typography
                            color="textSecondary"
                            className={classes.customLabelStyle}
                          >
                            <Box className={classes.fieldNumberStyle}>8</Box>
                            {t('createProject.inputs.publish.label')}
                          </Typography>
                        </label>

                        <Typography
                          color="textSecondary"
                          variant="caption"
                          component="span"
                          className={clsx(
                            classes.fieldHelperTextStyle,
                            common_classes.marginBottom1em,
                          )}
                        >
                          {t('createProject.inputs.publish.topHelperText')}
                        </Typography>

                        <Select
                          ref={refs.publish_type_el}
                          labelId="publish"
                          id="publish"
                          name="publish"
                          className={classes.customInputStyle}
                          value={
                            props.values.publish
                              ? props.values.publish.type
                              : publish_types[0]
                              ? publish_types[0].value
                              : ''
                          }
                          onChange={e => handlePublishFieldChange(e, props)}
                          onBlur={e => handlePublishFieldBlur(e, props)}
                        >
                          {publish_types.map(type => (
                            <MenuItem key={type.name} value={type.value}>
                              {t(`createProject.inputs.publish.publishTypes.${type.name}`)}
                            </MenuItem>
                          ))}
                        </Select>

                        <Box
                          className={clsx(
                            classes.tagsViewStyle,
                            common_classes.marginTop1em,
                            {
                              [common_classes.displayNone]:
                                props.values.publish?.type !==
                                publish_type['Preview'],
                            },
                          )}
                        >
                          {props.values.publish?.visible_to &&
                            props.values['publish']['visible_to'].map(
                              (username, num) =>
                                username ? (
                                  <Chip
                                    className={classes.customChipStyle}
                                    key={num}
                                    label={username}
                                    onDelete={e =>
                                      handleRemovePublishVisibleTo(
                                        e,
                                        props,
                                        username,
                                      )
                                    }
                                    color="secondary"
                                    variant="outlined"
                                  />
                                ) : null,
                            )}
                          <input
                            ref={refs.publish_visible_to_el}
                            className={classes.tagsInputStyle}
                            name="publish_visible_to"
                            type="text"
                            autocomplete="off"
                            placeholder={`${t(
                              'createProject.inputs.publish.addUsernames',
                            )}...`}
                            onChange={e => {
                              handleSuggestPublishVisibleTo(
                                e,
                                props,
                                state,
                                handleSetState,
                              );
                              handleSetState(
                                handleAddPublishVisibleTo(e, props),
                              );
                            }}
                            onBlur={e => {
                              handleAddPublishVisibleTo(e, props);
                            }}
                          />
                          <ClickAwayListener
                            onClickAway={() =>
                              handleSetState({
                                publish_visible_to_suggestion_open: false,
                                publish_visible_to_suggestion: [],
                              })
                            }
                          >
                            <Box
                              className={clsx(
                                classes.tagSuggestionStyle,
                                !publish_visible_to_suggestion_open
                                  ? common_classes.displayNone
                                  : null,
                              )}
                            >
                              {publish_visible_to_suggestion &&
                              publish_visible_to_suggestion.length > 0 ? (
                                publish_visible_to_suggestion.map(
                                  (username, index) => (
                                    <Typography
                                      key={index}
                                      color="textPrimary"
                                      className={classes.tagSuggestionTextStyle}
                                      onClick={() => {
                                        clearTimeout(vars.timer.id);
                                        handleSetState(
                                          handleAddPublishVisibleTo(
                                            {
                                              currentTarget: {
                                                value: `${username},`,
                                              },
                                            },
                                            props,
                                            refs.publish_visible_to_el,
                                          ),
                                        );
                                      }}
                                    >
                                      {username}
                                    </Typography>
                                  ),
                                )
                              ) : (
                                <CircularProgress size={30} thickness={3} />
                              )}
                            </Box>
                          </ClickAwayListener>
                        </Box>
                        <FormHelperText
                          error
                          className={classes.fieldHelperTextStyle}
                        >
                          {(props.status && props.status['publish']) ||
                            (props.touched['publish'] &&
                              props.errors['publish'] &&
                              t(
                                `createProject.inputs.publish.errors.${props.errors['publish']}`,
                              ))}
                        </FormHelperText>
                      </FormControl>
                    </Grid>

                    <Grid item xs={12}>
                      <CustomButton
                        variant="contained"
                        size="large"
                        type="submit"
                        primaryButtonStyle
                        customButtonStyle
                        fullWidth
                      >
                        {!id
                          ? t('createProject.inputs.submit')
                          : t('createProject.inputs.edit')}
                      </CustomButton>
                    </Grid>
                  </Grid>

                  <Dialog
                    PaperProps={{
                      style: {
                        backgroundColor: 'transparent',
                        boxShadow: 'none',
                      },
                    }}
                    open={video_upload_dialog_open}
                    onClose={async () =>
                      handleSetState({
                        ...(await handleVideoFieldCancel(refs, props, state)),
                        video_upload_dialog_open: false,
                      })
                    }
                    aria-labelledby="video upload dialog"
                  >
                    <Container
                      className={clsx(
                        classes.containerStyle,
                        classes.videoInputDialogContainerStyle,
                      )}
                    >
                      <Card
                        className={clsx(
                          classes.cardStyle,
                          classes.videoInputDialogCardStyle,
                        )}
                      >
                        <CardActionArea>
                          <CardContent>
                            <div
                              className={
                                classes.videoInputDialogControlSectionStyle
                              }
                            >
                              <CustomButton
                                className={
                                  classes.videoInputDialogControlButtonStyle
                                }
                                primaryButtonStyle={!select_video_file}
                                secondaryButtonStyle={select_video_file}
                                size="medium"
                                onClick={_ =>
                                  handleSetState({ select_video_file: false })
                                }
                              >
                                <div
                                  className={
                                    classes.videoInputDialogControlButtonUseTextDescStyle
                                  }
                                >
                                  {t(
                                    'createProject.inputs.video.dialogURLToggle',
                                  )}
                                </div>
                                <InsertLinkIcon
                                  className={
                                    classes.videoInputDialogControlButtonUseIconDescStyle
                                  }
                                />
                              </CustomButton>
                              <CustomButton
                                className={
                                  classes.videoInputDialogControlButtonStyle
                                }
                                primaryButtonStyle={select_video_file}
                                secondaryButtonStyle={!select_video_file}
                                size="medium"
                                onClick={_ =>
                                  handleSetState(
                                    handleSelectVideoFileChecked(
                                      refs.video_file_el.current,
                                    ),
                                  )
                                }
                              >
                                <div
                                  className={
                                    classes.videoInputDialogControlButtonUseTextDescStyle
                                  }
                                >
                                  {t(
                                    'createProject.inputs.video.dialogFileToggle',
                                  )}
                                </div>
                                <MovieIcon
                                  className={
                                    classes.videoInputDialogControlButtonUseIconDescStyle
                                  }
                                />
                              </CustomButton>
                            </div>
                            <Grid container spacing={1} alignItems="flex-end">
                              <Grid
                                item
                                xs={12}
                                sm={12}
                                className={clsx(
                                  common_classes.marginTop1em,
                                  classes.videoInputDialogBodyGridStyle,
                                )}
                              >
                                {!select_video_file ? (
                                  <FormControl
                                    className={clsx(
                                      classes.margin,
                                      classes.textField,
                                      classes.videoInputDialogURLFormControlStyle,
                                    )}
                                    variant="outlined"
                                    size="small"
                                  >
                                    <InputLabel
                                      className={classes.customLabelStyle}
                                      htmlFor="url-input"
                                    >
                                      {t(
                                        'createProject.inputs.video.dialogURLFieldLabel',
                                      )}
                                    </InputLabel>
                                    <OutlinedInput
                                      ref={refs.video_el}
                                      className={classes.customInputStyle}
                                      type="text"
                                      name="url-input"
                                      labelWidth={calculateLabelWidth(
                                        t(
                                          'createProject.inputs.video.dialogURLFieldLabel',
                                        ),
                                        document,
                                      )}
                                      placeholder="https://youtube.com/..."
                                      onChange={async e =>
                                        handleSetState(
                                          await handleVideoFieldChange(
                                            e,
                                            refs,
                                            props,
                                            state,
                                            handleSetState,
                                          ),
                                        )
                                      }
                                    />
                                  </FormControl>
                                ) : null}
                                {select_video_file ? (
                                  <p className={classes.videoFileName}>
                                    {refs.video_file_el.current?.files?.[0]
                                      ? refs.video_file_el.current?.files?.[0]
                                          ?.name
                                      : t(
                                          'createProject.inputs.video.dialogFileToggle',
                                        )}
                                  </p>
                                ) : null}
                                <CustomButton
                                  className={
                                    classes.videoInputDialogActionButtonStyle
                                  }
                                  secondaryButtonStyle
                                  variant="outlined"
                                  size="medium"
                                  onClick={async () =>
                                    handleSetState({
                                      ...(await handleVideoFieldCancel(
                                        refs,
                                        props,
                                        state,
                                      )),
                                      video_upload_dialog_open: false,
                                    })
                                  }
                                >
                                  <CloseIcon />
                                </CustomButton>

                                <CustomButton
                                  className={
                                    classes.videoInputDialogActionButtonStyle
                                  }
                                  primaryButtonStyle
                                  size="medium"
                                  onClick={async () =>
                                    handleSetState({
                                      ...(await handleVideoSelectDone(
                                        refs,
                                        props,
                                        state,
                                      )),
                                      video_upload_dialog_open: false,
                                    })
                                  }
                                >
                                  <CheckIcon />
                                </CustomButton>

                                <input
                                  className={common_classes.displayNone}
                                  ref={refs.video_file_el}
                                  type="file"
                                  accept="video/*"
                                  id="video"
                                  name="video"
                                  onChange={async e => {
                                    handleSetState(
                                      await handleVideoFieldChange(
                                        e,
                                        refs,
                                        props,
                                        state,
                                        handleSetState,
                                      ),
                                    );
                                  }}
                                  onBlur={props.handleBlur}
                                />
                              </Grid>
                            </Grid>
                          </CardContent>
                        </CardActionArea>
                      </Card>
                    </Container>
                  </Dialog>
                </form>
                <Dialog
                  PaperProps={{
                    style: {
                      backgroundColor: 'transparent',
                      boxShadow: 'none',
                    },
                  }}
                  className={classes.uploadProgressDialogStyle}
                  open={media_upload.upload_dialog}
                  aria-labelledby="upload progress dialog"
                >
                  <Box
                    className={classes.uploadProgressIndicatorContainerStyle}
                  >
                    <CircularProgress
                      className={classes.uploadProgressStyle}
                      variant="determinate"
                      size={70}
                      thickness={6}
                      value={media_upload.upload_percent}
                    />
                    <Box
                      top={0}
                      left={0}
                      bottom={0}
                      right={0}
                      position="absolute"
                      display="flex"
                      alignItems="center"
                      justifyContent="center"
                    >
                      <Typography
                        className={classes.uploadProgressLabelStyle}
                        variant="caption"
                        component="div"
                      >{`${Math.round(
                        media_upload.upload_percent,
                      )}%`}</Typography>
                    </Box>
                  </Box>
                </Dialog>
              </CardContent>
            </CardActionArea>
          </Card>
        </Container>
      </Box>
    );
  }
}
Example #9
Source File: avatar.js    From horondi_client_fe with MIT License 4 votes vote down vote up
Avatar = ({ setUserImageUrl, userImageUrl, setUpload, setDeleteAvatar, t }) => {
  const classes = useStyles();
  const [errorMessage, setErrorMessage] = useState('');

  const checkFileSize = (file) => {
    if (file.size < 5120000) {
      errorMessage && setErrorMessage();
      return true;
    }

    setErrorMessage(t('error.profile.size'));
    return false;
  };

  const checkExtension = (file) => {
    const availableExtensions = ['jpeg', 'jpg', 'png'];
    const fileExtension = file.name.split('.').pop().toLowerCase();

    if (availableExtensions.includes(fileExtension)) {
      errorMessage && setErrorMessage();
      return true;
    }

    setErrorMessage(t('error.profile.extension'));
    return false;
  };

  const checkDimension = async (result) => {
    const image = new Image();

    const promiseImg = new Promise((resolve, reject) => {
      image.onload = () => {
        if (image.height <= 100 && image.width <= 100) {
          resolve(true);
        } else {
          resolve(false);
        }
      };

      image.onerror = (error) => reject(error);
    });

    image.src = result;

    return promiseImg;
  };

  const handleImageLoad = async ({ target }) => {
    const image = target.files[0];

    if (image && checkExtension(image) && checkFileSize(image)) {
      const reader = new FileReader();

      reader.onload = async ({ target: { result } }) => {
        if (await checkDimension(result)) {
          setUserImageUrl(result);
          setUpload(image);
        } else {
          setErrorMessage(t('error.profile.dimension'));
        }
      };

      reader.readAsDataURL(image);
    }
  };

  const handleLableClass = () => (userImageUrl ? classes.updateLabel : classes.uploadLabel);

  const deleteAvatar = () => {
    setUserImageUrl(null);
    setUpload(null);
    setDeleteAvatar(true);
  };

  return (
    <div className={classes.imageContainer}>
      {userImageUrl && (
        <>
          <DeleteIcon className={classes.deleteIcon} onClick={deleteAvatar} />
          <img
            src={userImageUrl}
            alt='profile-logo'
            className={classes.userImage}
            data-testid='renderedimage'
          />
        </>
      )}
      <input
        type='file'
        className={classes.photoUpload}
        id='photoUpload'
        onChange={handleImageLoad}
        accept='image/jpg, image/jpeg, image/png'
        data-testid='imageInput'
      />
      <label
        htmlFor='photoUpload'
        className={`${classes.imageContainerLabel} ${handleLableClass()}`}
      >
        <Button component='span' className={classes.uploadBtn}>
          <CameraIcon className={classes.cameraIcon} />
          <FormHelperText
            data-testid='errorText'
            error={Boolean(errorMessage)}
            className={classes.formHelper}
          >
            {errorMessage}
          </FormHelperText>
        </Button>
      </label>
    </div>
  );
}
Example #10
Source File: EditProfile.jsx    From zubhub with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @function EditProfile View
 * @author Raymond Ndibe <[email protected]>
 *
 * @todo - describe function's signature
 */
function EditProfile(props) {
  const refs = {
    username_el: React.useRef(null),
    location_el: React.useRef(null),
    email_el: React.useRef(null),
    phone_el: React.useRef(null),
    bio_el: React.useRef(null),
  };

  const [state, setState] = React.useState({
    locations: [],
    tool_tip_open: false,
  });

  React.useEffect(() => {
    getProfile(refs, props);
    handleSetState(getLocations(props));
  }, []);

  const classes = useStyles();

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

  const { locations, tool_tip_open } = state;
  const { t } = props;

  return (
    <Box className={classes.root}>
      <Container className={classes.containerStyle}>
        <Card className={classes.cardStyle}>
          <CardActionArea>
            <CardContent>
              <form
                className="auth-form"
                name="signup"
                noValidate="noValidate"
                onSubmit={e => editProfile(e, props, toast)}
              >
                <Typography
                  gutterBottom
                  variant="h5"
                  component="h2"
                  color="textPrimary"
                  className={classes.titleStyle}
                >
                  {t('editProfile.welcomeMsg.primary')}
                </Typography>
                <Typography
                  className={classes.descStyle}
                  variant="body2"
                  color="textSecondary"
                  component="p"
                >
                  {t('editProfile.welcomeMsg.secondary')}
                </Typography>
                <Grid container spacing={3}>
                  <Grid item xs={12}>
                    <Box
                      component="p"
                      className={
                        props.status &&
                        props.status['non_field_errors'] &&
                        classes.errorBox
                      }
                    >
                      {props.status && props.status['non_field_errors'] && (
                        <Box component="span" className={classes.error}>
                          {props.status['non_field_errors']}
                        </Box>
                      )}
                    </Box>
                  </Grid>
                  <Grid item xs={12} sm={6} md={6}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['username']) ||
                        (props.touched['username'] && props.errors['username'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        htmlFor="username"
                      >
                        {t('editProfile.inputs.username.label')}
                      </InputLabel>
                      <ClickAwayListener
                        onClickAway={() => handleSetState(handleTooltipClose())}
                      >
                        <Tooltip
                          title={t('editProfile.tooltips.noRealName')}
                          placement="top-start"
                          arrow
                          onClose={() => handleSetState(handleTooltipClose())}
                          PopperProps={{
                            disablePortal: true,
                          }}
                          open={tool_tip_open}
                          disableFocusListener
                          disableHoverListener
                          disableTouchListener
                        >
                          <OutlinedInput
                            ref={refs.username_el}
                            className={clsx(classes.customInputStyle)}
                            id="username"
                            name="username"
                            type="text"
                            value={
                              props.values.username ? props.values.username : ''
                            }
                            onClick={() => handleSetState(handleTooltipOpen())}
                            onChange={props.handleChange}
                            onBlur={props.handleBlur}
                            labelWidth={calculateLabelWidth(
                              t('editProfile.inputs.username.label'),
                              document,
                            )}
                          />
                        </Tooltip>
                      </ClickAwayListener>
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {(props.status && props.status['username']) ||
                          (props.touched['username'] &&
                            props.errors['username'] &&
                            t(
                              `editProfile.inputs.username.errors.${props.errors['username']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>

                  <Grid item xs={12} sm={6} md={6}>
                    <FormControl
                      ref={refs.location_el}
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['user_location']) ||
                        (props.touched['user_location'] &&
                          props.errors['user_location'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        id="user_location"
                      >
                        {t('editProfile.inputs.location.label')}
                      </InputLabel>
                      <Select
                        labelId="user_location"
                        id="user_location"
                        name="user_location"
                        className={clsx(classes.customInputStyle)}
                        value={
                          props.values.user_location
                            ? props.values.user_location
                            : ''
                        }
                        onChange={props.handleChange}
                        onBlur={props.handleBlur}
                        label="Location"
                      >
                        <MenuItem value="">
                          <em>None</em>
                        </MenuItem>
                        {Array.isArray(locations) &&
                          locations.map(location => (
                            <MenuItem key={location.name} value={location.name}>
                              {location.name}
                            </MenuItem>
                          ))}
                      </Select>
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {(props.status && props.status['user_location']) ||
                          (props.touched['user_location'] &&
                            props.errors['user_location'] &&
                            t(
                              `editProfile.inputs.location.errors.${props.errors['user_location']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>

                  <Grid item xs={12} sm={6} md={6}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['email']) ||
                        (props.touched['email'] && props.errors['email'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        htmlFor="email"
                      >
                        {t('editProfile.inputs.email.label')}
                      </InputLabel>
                      <OutlinedInput
                        ref={refs.email_el}
                        disabled={
                          props.status && props.status['init_email']
                            ? true
                            : false
                        }
                        className={clsx(classes.customInputStyle)}
                        id="email"
                        name="email"
                        type="text"
                        value={props.values.email ? props.values.email : ''}
                        onChange={props.handleChange}
                        onBlur={props.handleBlur}
                        labelWidth={calculateLabelWidth(
                          t('editProfile.inputs.email.label'),
                          document,
                        )}
                      />
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {props.status && props.status['init_email'] && (
                          <Typography
                            color="textSecondary"
                            variant="caption"
                            component="span"
                            className={classes.fieldHelperTextStyle}
                          >
                            {t('editProfile.inputs.email.disabledHelperText')}
                          </Typography>
                        )}
                        <br />
                        {(props.status && props.status['email']) ||
                          (props.touched['email'] &&
                            props.errors['email'] &&
                            t(
                              `editProfile.inputs.email.errors.${props.errors['email']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>

                  <Grid item xs={12} sm={6} md={6}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['phone']) ||
                        (props.touched['phone'] && props.errors['phone'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        htmlFor="phone"
                      >
                        {t('editProfile.inputs.phone.label')}
                      </InputLabel>
                      <OutlinedInput
                        ref={refs.phone_el}
                        disabled={
                          props.status && props.status['init_phone']
                            ? true
                            : false
                        }
                        className={clsx(classes.customInputStyle)}
                        id="phone"
                        name="phone"
                        type="phone"
                        value={props.values.phone ? props.values.phone : ''}
                        onChange={props.handleChange}
                        onBlur={props.handleBlur}
                        labelWidth={calculateLabelWidth(
                          t('editProfile.inputs.phone.label'),
                          document,
                        )}
                      />
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {props.status && props.status['init_phone'] && (
                          <Typography
                            color="textSecondary"
                            variant="caption"
                            component="span"
                            className={classes.fieldHelperTextStyle}
                          >
                            {t('editProfile.inputs.phone.disabledHelperText')}
                          </Typography>
                        )}
                        <br />
                        {(props.status && props.status['phone']) ||
                          (props.touched['phone'] &&
                            props.errors['phone'] &&
                            t(
                              `editProfile.inputs.phone.errors.${props.errors['phone']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>

                  <Grid item xs={12}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="small"
                      error={
                        (props.status && props.status['bio']) ||
                        (props.touched['bio'] && props.errors['bio'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        htmlFor="bio"
                      >
                        {t('editProfile.inputs.bio.label')}
                      </InputLabel>
                      <OutlinedInput
                        ref={refs.bio_el}
                        className={clsx(classes.customInputStyle)}
                        id="bio"
                        name="bio"
                        type="text"
                        multiline
                        rows={6}
                        rowsMax={6}
                        value={props.values.bio ? props.values.bio : ''}
                        onChange={props.handleChange}
                        onBlur={props.handleBlur}
                        labelWidth={calculateLabelWidth(
                          t('editProfile.inputs.bio.label'),
                          document,
                        )}
                      />
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        <Typography
                          color="textSecondary"
                          variant="caption"
                          component="span"
                          className={classes.fieldHelperTextStyle}
                        >
                          {t('editProfile.inputs.bio.helpText')}
                        </Typography>
                        <br />
                        {(props.status && props.status['bio']) ||
                          (props.touched['bio'] &&
                            props.errors['bio'] &&
                            t(
                              `editProfile.inputs.bio.errors.${props.errors['bio']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>

                  <Grid item xs={12}>
                    <CustomButton
                      variant="contained"
                      size="large"
                      primaryButtonStyle
                      type="submit"
                      fullWidth
                      customButtonStyle
                    >
                      {t('editProfile.inputs.submit')}
                    </CustomButton>
                  </Grid>
                </Grid>
              </form>
              <Grid container spacing={3}>
                <Grid item xs={12}>
                  <Box className={classes.center}>
                    <Divider className={classes.divider} />
                    <Typography
                      variant="body2"
                      color="textSecondary"
                      component="p"
                    >
                      {t('editProfile.or')}
                    </Typography>
                    <Divider className={classes.divider} />
                  </Box>
                </Grid>
                <Grid item xs={12}>
                  <Link to="/profile" className={classes.textDecorationNone}>
                    <CustomButton
                      variant="outlined"
                      size="large"
                      secondaryButtonStyle
                      customButtonStyle
                      fullWidth
                    >
                      {t('editProfile.backToProfile')}
                    </CustomButton>
                  </Link>
                </Grid>
              </Grid>
            </CardContent>
          </CardActionArea>
        </Card>
      </Container>
    </Box>
  );
}
Example #11
Source File: Login.jsx    From zubhub with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @function Login View
 * @author Raymond Ndibe <[email protected]>
 *
 * @todo - describe function's signature
 */
function Login(props) {
  const classes = useStyles();

  const [state, setState] = React.useState({
    show_password: false,
  });

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

  const { show_password } = state;
  const { t } = props;

  return (
    <Box className={classes.root}>
      <Container className={classes.containerStyle}>
        <Card className={classes.cardStyle}>
          <CardActionArea>
            <CardContent>
              <form
                className="auth-form"
                name="login"
                noValidate="noValidate"
                onSubmit={e => handleSetState(login(e, props))}
              >
                <Typography
                  gutterBottom
                  variant="h5"
                  component="h2"
                  color="textPrimary"
                  className={classes.titleStyle}
                >
                  {t('login.welcomeMsg.primary')}
                </Typography>
                <Typography
                  className={classes.descStyle}
                  variant="body2"
                  color="textSecondary"
                  component="p"
                >
                  {t('login.welcomeMsg.secondary')}
                </Typography>
                <Grid container spacing={3}>
                  <Grid item xs={12}>
                    <Box
                      component="p"
                      className={
                        props.status &&
                        props.status['non_field_errors'] &&
                        classes.errorBox
                      }
                    >
                      {props.status && props.status['non_field_errors'] && (
                        <Box component="span" className={classes.error}>
                          {props.status['non_field_errors']}
                        </Box>
                      )}
                    </Box>
                  </Grid>
                  <Grid item xs={12} sm={6} md={6}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['username']) ||
                        (props.touched['username'] && props.errors['username'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        htmlFor="username"
                      >
                        {t('login.inputs.username.label')}
                      </InputLabel>
                      <OutlinedInput
                        className={classes.customInputStyle}
                        id="username"
                        name="username"
                        type="text"
                        onChange={props.handleChange}
                        onBlur={props.handleBlur}
                        labelWidth={calculateLabelWidth(
                          t('login.inputs.username.label'),
                          document,
                        )}
                      />
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {(props.status && props.status['username']) ||
                          (props.touched['username'] &&
                            props.errors['username'] &&
                            t(
                              `login.inputs.username.errors.${props.errors['username']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>

                  <Grid item xs={12} sm={6} md={6}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['password']) ||
                        (props.touched['password'] && props.errors['password'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        htmlFor="password"
                      >
                        {t('login.inputs.password.label')}
                      </InputLabel>
                      <OutlinedInput
                        className={classes.customInputStyle}
                        id="password"
                        name="password"
                        type={show_password ? 'text' : 'password'}
                        onChange={props.handleChange}
                        onBlur={props.handleBlur}
                        endAdornment={
                          <InputAdornment position="end">
                            <IconButton
                              aria-label="toggle password visibility"
                              onClick={() =>
                                handleSetState(handleClickShowPassword(state))
                              }
                              onMouseDown={handleMouseDownPassword}
                              edge="end"
                            >
                              {show_password ? (
                                <Visibility />
                              ) : (
                                <VisibilityOff />
                              )}
                            </IconButton>
                          </InputAdornment>
                        }
                        labelWidth={calculateLabelWidth(
                          t('login.inputs.password.label'),
                          document,
                        )}
                      />
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {(props.status && props.status['password']) ||
                          (props.touched['password'] &&
                            props.errors['password'] &&
                            t(
                              `login.inputs.password.errors.${props.errors['password']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>
                  <Grid item xs={12}>
                    <CustomButton
                      variant="contained"
                      size="large"
                      type="submit"
                      primaryButtonStyle
                      customButtonStyle
                      fullWidth
                    >
                      {t('login.inputs.submit')}
                    </CustomButton>
                  </Grid>
                </Grid>
              </form>
              <Grid container spacing={3}>
                <Grid item xs={12}>
                  <Box className={classes.center}>
                    <Divider className={classes.divider} />
                    <Typography
                      className={classes.dividerText}
                      variant="body2"
                      color="textSecondary"
                      component="p"
                    >
                      {t('login.notAMember')}
                    </Typography>
                    <Divider className={classes.divider} />
                  </Box>
                </Grid>
                <Grid item xs={12}>
                  <Link to="/signup" className={classes.textDecorationNone}>
                    <CustomButton
                      variant="outlined"
                      size="large"
                      secondaryButtonStyle
                      customButtonStyle
                      fullWidth
                    >
                      {t('login.signup')}
                    </CustomButton>
                  </Link>
                </Grid>
                <Grid item xs={12}>
                  <Box className={classes.center}>
                    <Link
                      to="/password-reset"
                      className={classes.secondaryLink}
                    >
                      {t('login.forgotPassword')}
                    </Link>
                  </Box>
                </Grid>
              </Grid>
            </CardContent>
          </CardActionArea>
        </Card>
      </Container>
    </Box>
  );
}
Example #12
Source File: PasswordReset.jsx    From zubhub with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @function PasswordReset View
 * @author Raymond Ndibe <[email protected]>
 *
 * @todo - describe function's signature
 */
function PasswordReset(props) {
  const classes = useStyles();
  const { t } = props;

  return (
    <Box className={classes.root}>
      <Container className={classes.containerStyle}>
        <Card className={classes.cardStyle}>
          <CardActionArea>
            <CardContent>
              <form
                className="auth-form"
                name="password_reset"
                noValidate="noValidate"
                onSubmit={e => sendPasswordResetLink(e, props)}
              >
                <Typography
                  gutterBottom
                  variant="h5"
                  component="h2"
                  color="textPrimary"
                  className={classes.titleStyle}
                >
                  {t('passwordReset.welcomeMsg.primary')}
                </Typography>
                <Typography
                  className={classes.descStyle}
                  variant="body2"
                  color="textSecondary"
                  component="p"
                >
                  {t('passwordReset.welcomeMsg.secondary')}
                </Typography>
                <Grid container spacing={3}>
                  <Grid item xs={12}>
                    <Box
                      component="p"
                      className={
                        props.status &&
                        props.status['non_field_errors'] &&
                        classes.errorBox
                      }
                    >
                      {props.status && props.status['non_field_errors'] && (
                        <Box component="span" className={classes.error}>
                          {props.status['non_field_errors']}
                        </Box>
                      )}
                    </Box>
                  </Grid>
                  <Grid item xs={12}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['email']) ||
                        (props.touched['email'] && props.errors['email'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        htmlFor="email"
                      >
                        {t('passwordReset.inputs.email.label')}
                      </InputLabel>
                      <OutlinedInput
                        className={classes.customInputStyle}
                        id="email"
                        name="email"
                        type="text"
                        onChange={props.handleChange}
                        onBlur={props.handleBlur}
                        labelWidth={calculateLabelWidth(
                          t('passwordReset.inputs.email.label'),
                          document,
                        )}
                      />
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {(props.status && props.status['email']) ||
                          (props.touched['email'] &&
                            props.errors['email'] &&
                            t(
                              `passwordReset.inputs.email.errors.${props.errors['email']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>
                  <Grid item xs={12}>
                    <CustomButton
                      variant="contained"
                      size="large"
                      primaryButtonStyle
                      customButtonStyle
                      type="submit"
                      fullWidth
                    >
                      {t('passwordReset.inputs.submit')}
                    </CustomButton>
                  </Grid>
                </Grid>
              </form>
            </CardContent>
          </CardActionArea>
        </Card>
      </Container>
    </Box>
  );
}
Example #13
Source File: PasswordResetConfirm.jsx    From zubhub with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @function PasswordResetConfirm View
 * @author Raymond Ndibe <[email protected]>
 *
 * @todo - describe function's signature
 */
function PasswordResetConfirm(props) {
  const classes = useStyles();

  const [state, setState] = React.useState({
    show_password1: false,
    show_password2: false,
  });

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

  const { show_password1, show_password2 } = state;
  const { t } = props;

  return (
    <Box className={classes.root}>
      <Container className={classes.containerStyle}>
        <Card className={classes.cardStyle}>
          <CardActionArea>
            <CardContent>
              <form
                className="auth-form"
                name="password_reset_confirm"
                noValidate="noValidate"
                onSubmit={e => resetPassword(e, props)}
              >
                <Typography
                  gutterBottom
                  variant="h5"
                  component="h2"
                  color="textPrimary"
                  className={classes.titleStyle}
                >
                  {t('passwordResetConfirm.welcomeMsg.primary')}
                </Typography>
                <Grid container spacing={3}>
                  <Grid item xs={12}>
                    <Box
                      component="p"
                      className={
                        props.status &&
                        props.status['non_field_errors'] &&
                        classes.errorBox
                      }
                    >
                      {props.status && props.status['non_field_errors'] && (
                        <Box component="span" className={classes.error}>
                          {props.status['non_field_errors']}
                        </Box>
                      )}
                    </Box>
                  </Grid>

                  <Grid item xs={12} sm={6} md={6}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['new_password1']) ||
                        (props.touched['new_password1'] &&
                          props.errors['new_password1'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        htmlFor="new_password1"
                      >
                        {t('passwordResetConfirm.inputs.newPassword1.label')}
                      </InputLabel>
                      <OutlinedInput
                        className={classes.customInputStyle}
                        id="new_password1"
                        name="new_password1"
                        type={show_password1 ? 'text' : 'password'}
                        onChange={props.handleChange}
                        onBlur={props.handleBlur}
                        endAdornment={
                          <InputAdornment position="end">
                            <IconButton
                              aria-label="toggle password visibility"
                              onClick={(_, field = 1) =>
                                handleSetState(
                                  handleClickShowPassword(field, state),
                                )
                              }
                              onMouseDown={handleMouseDownPassword}
                              edge="end"
                            >
                              {show_password1 ? (
                                <Visibility />
                              ) : (
                                <VisibilityOff />
                              )}
                            </IconButton>
                          </InputAdornment>
                        }
                        labelWidth={calculateLabelWidth(
                          t('passwordResetConfirm.inputs.newPassword1.label'),
                          document,
                        )}
                      />
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {(props.status && props.status['new_password1']) ||
                          (props.touched['new_password1'] &&
                            props.errors['new_password1'] &&
                            t(
                              `passwordResetConfirm.inputs.newPassword1.errors.${props.errors['new_password1']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>

                  <Grid item xs={12} sm={6} md={6}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['new_password2']) ||
                        (props.touched['new_password2'] &&
                          props.errors['new_password2'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        htmlFor="new_password2"
                      >
                        {t('passwordResetConfirm.inputs.newPassword2.label')}
                      </InputLabel>
                      <OutlinedInput
                        className={classes.customInputStyle}
                        id="new_password2"
                        name="new_password2"
                        type={show_password2 ? 'text' : 'password'}
                        onChange={props.handleChange}
                        onBlur={props.handleBlur}
                        endAdornment={
                          <InputAdornment position="end">
                            <IconButton
                              aria-label="toggle password visibility"
                              onClick={(_, field = 2) =>
                                handleSetState(
                                  handleClickShowPassword(field, state),
                                )
                              }
                              onMouseDown={handleMouseDownPassword}
                              edge="end"
                            >
                              {show_password2 ? (
                                <Visibility />
                              ) : (
                                <VisibilityOff />
                              )}
                            </IconButton>
                          </InputAdornment>
                        }
                        labelWidth={calculateLabelWidth(
                          t('passwordResetConfirm.inputs.newPassword2.label'),
                          document,
                        )}
                      />
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {(props.status && props.status['new_password2']) ||
                          (props.touched['new_password2'] &&
                            props.errors['new_password2'] &&
                            t(
                              `passwordResetConfirm.inputs.newPassword2.errors.${props.errors['new_password2']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>
                  <Grid item xs={12}>
                    <CustomButton
                      variant="contained"
                      size="large"
                      type="submit"
                      primaryButtonStyle
                      customButtonStyle
                      fullWidth
                    >
                      {t('passwordResetConfirm.inputs.submit')}
                    </CustomButton>
                  </Grid>
                </Grid>
              </form>
            </CardContent>
          </CardActionArea>
        </Card>
      </Container>
    </Box>
  );
}
Example #14
Source File: Signup.jsx    From zubhub with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @function Signup View
 * @author Raymond Ndibe <[email protected]>
 *
 * @todo - describe function's signature
 */
function Signup(props) {
  const classes = useStyles();

  const refs = {
    phone_el: React.useRef(null),
    location_el: React.useRef(null),
    date_of_birth_el: React.useRef(null),
  };

  const [state, setState] = React.useState({
    locations: [],
    show_password1: false,
    show_password2: false,
    tool_tip_open: false,
    subscribe_box_checked: false,
  });

  React.useEffect(() => {
    handleSetState(getLocations(props));
  }, []);

  React.useEffect(() => {
    initIntlTelInput(props, refs);
  }, [refs.phone_el]);

  React.useEffect(() => {
    setLabelWidthOfStaticFields(refs, document, props);
  }, [props.i18n.language]);

  React.useEffect(() => {
    if (props.touched['email']) {
      vars.email_field_touched = true;
    } else {
      vars.email_field_touched = false;
    }

    if (props.touched['phone']) {
      vars.phone_field_touched = true;
    } else {
      vars.phone_field_touched = false;
    }
  }, [props.touched['email'], props.touched['phone']]);

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

  const {
    locations,
    tool_tip_open,
    show_password1,
    show_password2,
    subscribe_box_checked,
  } = state;
  const { t } = props;

  return (
    <Box className={classes.root}>
      <Container className={classes.containerStyle}>
        <Card className={classes.cardStyle}>
          <CardActionArea>
            <CardContent>
              <form
                className="auth-form"
                name="signup"
                noValidate="noValidate"
                onSubmit={e => signup(e, props)}
              >
                <Typography
                  gutterBottom
                  variant="h5"
                  component="h2"
                  color="textPrimary"
                  className={classes.titleStyle}
                >
                  {t('signup.welcomeMsg.primary')}
                </Typography>
                <Typography
                  className={classes.descStyle}
                  variant="body2"
                  color="textSecondary"
                  component="p"
                >
                  {t('signup.welcomeMsg.secondary')}
                </Typography>
                <Grid container spacing={3}>
                  <Grid item xs={12}>
                    <Box
                      component="p"
                      className={
                        props.status &&
                        props.status['non_field_errors'] &&
                        classes.errorBox
                      }
                    >
                      {props.status && props.status['non_field_errors'] && (
                        <Box component="span" className={classes.error}>
                          {props.status['non_field_errors']}
                        </Box>
                      )}
                    </Box>
                  </Grid>
                  <Grid item xs={12}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['username']) ||
                        (props.touched['username'] && props.errors['username'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        htmlFor="username"
                      >
                        {t('signup.inputs.username.label')}
                      </InputLabel>
                      <ClickAwayListener
                        onClickAway={() => handleSetState(handleTooltipClose())}
                      >
                        <Tooltip
                          title={t('signup.tooltips.noRealName')}
                          placement="top-start"
                          arrow
                          onClose={() => handleSetState(handleTooltipClose())}
                          PopperProps={{
                            disablePortal: true,
                          }}
                          open={tool_tip_open}
                          disableFocusListener
                          disableHoverListener
                          disableTouchListener
                        >
                          <OutlinedInput
                            className={classes.customInputStyle}
                            id="username"
                            name="username"
                            type="text"
                            onClick={() => handleSetState(handleTooltipOpen())}
                            onChange={props.handleChange}
                            onBlur={props.handleBlur}
                            labelWidth={calculateLabelWidth(
                              t('signup.inputs.username.label'),
                              document,
                            )}
                          />
                        </Tooltip>
                      </ClickAwayListener>
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {(props.status && props.status['username']) ||
                          (props.touched['username'] &&
                            props.errors['username'] &&
                            t(
                              `signup.inputs.username.errors.${props.errors['username']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>

                  <Grid item xs={12} sm={6} md={6}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['user_location']) ||
                        (props.touched['user_location'] &&
                          props.errors['user_location'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        id="user_location"
                      >
                        {t('signup.inputs.location.label')}
                      </InputLabel>
                      <Select
                        ref={refs.location_el}
                        labelId="user_location"
                        id="user_location"
                        name="user_location"
                        className={classes.customInputStyle}
                        value={
                          props.values.user_location
                            ? props.values.user_location
                            : ''
                        }
                        onChange={e => handleLocationChange(e, props)}
                        onBlur={props.handleBlur}
                        // label="Location"
                        labelWidth={calculateLabelWidth(
                          t('signup.inputs.location.label'),
                          document,
                        )}
                      >
                        <MenuItem value="">
                          <em>None</em>
                        </MenuItem>
                        {Array.isArray(locations) &&
                          locations.map(location => (
                            <MenuItem key={location.name} value={location.name}>
                              {location.name}
                            </MenuItem>
                          ))}
                      </Select>
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {(props.status && props.status['user_location']) ||
                          (props.touched['user_location'] &&
                            props.errors['user_location'] &&
                            t(
                              `signup.inputs.location.errors.${props.errors['user_location']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>

                  <Grid item xs={12} sm={6} md={6}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['dateOfBirth']) ||
                        (props.touched['dateOfBirth'] &&
                          props.errors['dateOfBirth'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        htmlFor="dateOfBirth"
                        shrink
                      >
                        {t('signup.inputs.dateOfBirth.label')}
                      </InputLabel>
                      <OutlinedInput
                        ref={refs.date_of_birth_el}
                        className={clsx(classes.customInputStyle)}
                        id="dateOfBirth"
                        name="dateOfBirth"
                        type="date"
                        onChange={props.handleChange}
                        onBlur={props.handleBlur}
                      />
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {(props.status && props.status['dateOfBirth']) ||
                          (props.touched['dateOfBirth'] &&
                            props.errors['dateOfBirth'] &&
                            t(
                              `signup.inputs.dateOfBirth.errors.${props.errors['dateOfBirth']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>

                  <Grid item xs={12} sm={6} md={6}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['phone']) ||
                        (props.touched['phone'] && props.errors['phone'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        shrink
                        htmlFor="phone"
                      >
                        {t('signup.inputs.phone.label')}
                      </InputLabel>
                      <OutlinedInput
                        ref={refs.phone_el}
                        className={clsx(
                          classes.customInputStyle,
                          classes.locationInputStyle,
                        )}
                        id="phone"
                        name="phone"
                        type="phone"
                        onChange={props.handleChange}
                        onBlur={props.handleBlur}
                      />
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {(props.status && props.status['phone']) ||
                          (props.touched['phone'] &&
                            props.errors['phone'] &&
                            t(
                              `signup.inputs.phone.errors.${props.errors['phone']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>

                  <Grid item xs={12} sm={6} md={6}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['email']) ||
                        (props.touched['email'] && props.errors['email'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        htmlFor="email"
                      >
                        {t('signup.inputs.email.label')}
                      </InputLabel>
                      <OutlinedInput
                        className={classes.customInputStyle}
                        id="email"
                        name="email"
                        type="text"
                        onChange={props.handleChange}
                        onBlur={props.handleBlur}
                        labelWidth={calculateLabelWidth(
                          t('signup.inputs.email.label'),
                          document,
                        )}
                      />
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {(props.status && props.status['email']) ||
                          (props.touched['email'] &&
                            props.errors['email'] &&
                            t(
                              `signup.inputs.email.errors.${props.errors['email']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>

                  <Grid item xs={12} sm={6} md={6}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['password1']) ||
                        (props.touched['password1'] &&
                          props.errors['password1'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        htmlFor="password1"
                      >
                        {t('signup.inputs.password1.label')}
                      </InputLabel>
                      <OutlinedInput
                        className={classes.customInputStyle}
                        id="password1"
                        name="password1"
                        type={show_password1 ? 'text' : 'password'}
                        onChange={props.handleChange}
                        onBlur={props.handleBlur}
                        endAdornment={
                          <InputAdornment position="end">
                            <IconButton
                              aria-label={t(
                                'signup.ariaLabel.togglePasswordVisibility',
                              )}
                              onClick={() =>
                                setState({
                                  ...state,
                                  show_password1: !show_password1,
                                })
                              }
                              onMouseDown={handleMouseDownPassword}
                              edge="end"
                            >
                              {show_password1 ? (
                                <Visibility />
                              ) : (
                                <VisibilityOff />
                              )}
                            </IconButton>
                          </InputAdornment>
                        }
                        labelWidth={calculateLabelWidth(
                          t('signup.inputs.password1.label'),
                          document,
                        )}
                      />
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {(props.status && props.status['password1']) ||
                          (props.touched['password1'] &&
                            props.errors['password1'] &&
                            t(
                              `signup.inputs.password1.errors.${props.errors['password1']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>

                  <Grid item xs={12} sm={6} md={6}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="normal"
                      error={
                        (props.status && props.status['password2']) ||
                        (props.touched['password2'] &&
                          props.errors['password2'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        htmlFor="password2"
                      >
                        {t('signup.inputs.password2.label')}
                      </InputLabel>
                      <OutlinedInput
                        className={classes.customInputStyle}
                        id="password2"
                        name="password2"
                        type={show_password2 ? 'text' : 'password'}
                        onChange={props.handleChange}
                        onBlur={props.handleBlur}
                        endAdornment={
                          <InputAdornment position="end">
                            <IconButton
                              aria-label={t(
                                'signup.ariaLabel.togglePasswordVisibility',
                              )}
                              onClick={() =>
                                setState({
                                  ...state,
                                  show_password2: !show_password2,
                                })
                              }
                              onMouseDown={handleMouseDownPassword}
                              edge="end"
                            >
                              {show_password2 ? (
                                <Visibility />
                              ) : (
                                <VisibilityOff />
                              )}
                            </IconButton>
                          </InputAdornment>
                        }
                        labelWidth={calculateLabelWidth(
                          t('signup.inputs.password2.label'),
                          document,
                        )}
                      />
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        {(props.status && props.status['password2']) ||
                          (props.touched['password2'] &&
                            props.errors['password2'] &&
                            t(
                              `signup.inputs.password2.errors.${props.errors['password2']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>

                  <Grid item xs={12}>
                    <FormControl
                      className={clsx(classes.margin, classes.textField)}
                      variant="outlined"
                      size="small"
                      fullWidth
                      margin="small"
                      error={
                        (props.status && props.status['bio']) ||
                        (props.touched['bio'] && props.errors['bio'])
                      }
                    >
                      <InputLabel
                        className={classes.customLabelStyle}
                        htmlFor="bio"
                      >
                        {t('signup.inputs.bio.label')}
                      </InputLabel>
                      <OutlinedInput
                        className={classes.customInputStyle}
                        id="bio"
                        name="bio"
                        type="text"
                        multiline
                        rows={6}
                        rowsMax={6}
                        onChange={props.handleChange}
                        onBlur={props.handleBlur}
                        labelWidth={calculateLabelWidth(
                          t('signup.inputs.bio.label'),
                          document,
                        )}
                      />
                      <FormHelperText
                        className={classes.fieldHelperTextStyle}
                        error
                      >
                        <Typography
                          color="textSecondary"
                          variant="caption"
                          component="span"
                          className={classes.fieldHelperTextStyle}
                        >
                          {t('signup.inputs.bio.helpText')}
                        </Typography>
                        <br />
                        {(props.status && props.status['bio']) ||
                          (props.touched['bio'] &&
                            props.errors['bio'] &&
                            t(
                              `signup.inputs.bio.errors.${props.errors['bio']}`,
                            ))}
                      </FormHelperText>
                    </FormControl>
                  </Grid>
                  <Grid item xs={12}>
                    <FormControlLabel
                      value={subscribe_box_checked}
                      onChange={e =>
                        handleSetState(
                          handleToggleSubscribeBox(e, props, state),
                        )
                      }
                      control={
                        <Checkbox
                          name="subscribe"
                          id="subscribe"
                          color="primary"
                        />
                      }
                      label={
                        <Typography
                          color="textSecondary"
                          variant="caption"
                          component="span"
                          className={classes.fieldHelperTextStyle}
                        >
                          {t('signup.unsubscribe')}
                        </Typography>
                      }
                      labelPlacement="end"
                    />
                  </Grid>

                  <Grid item xs={12}>
                    <CustomButton
                      variant="contained"
                      size="large"
                      primaryButtonStyle
                      type="submit"
                      fullWidth
                      customButtonStyle
                    >
                      {t('signup.inputs.submit')}
                    </CustomButton>
                  </Grid>
                </Grid>
              </form>
              <Grid container spacing={3}>
                <Grid item xs={12}>
                  <Box className={classes.center}>
                    <Divider className={classes.divider} />
                    <Typography
                      variant="body2"
                      color="textSecondary"
                      component="p"
                    >
                      {t('signup.alreadyAMember')}
                    </Typography>
                    <Divider className={classes.divider} />
                  </Box>
                </Grid>
                <Grid item xs={12}>
                  <Link to="/login" className={classes.textDecorationNone}>
                    <CustomButton
                      variant="outlined"
                      size="large"
                      secondaryButtonStyle
                      customButtonStyle
                      fullWidth
                    >
                      {t('signup.login')}
                    </CustomButton>
                  </Link>
                </Grid>
              </Grid>
            </CardContent>
          </CardActionArea>
        </Card>
      </Container>
    </Box>
  );
}
Example #15
Source File: AddEditActivity.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditActivity = props => {
  let history = useHistory();
  const dateFrom = "dateFrom";
  const dateTo = "dateTo";

  const [editorState, setEditorState] = useState(EditorState.createEmpty());
  const [backDrop, setBackDrop] = useState(false);

  const [formState, setFormState] = useState({
    isValid: false,
    values: {
      dateFrom: moment(),
      dateTo: moment()
    },
    touched: {},
    errors: {},
    isSuccess: false,
    showPassword: false,
    editActivity: props.location.editActivity
      ? props.location.editActivity
      : false,
    dataForEdit: props.location.dataForEdit
      ? props.location.dataForEdit
      : false,
    counter: 0,
    testCounter: 0,
    stream: [],
    files: null,
    descriptionError: false,
    discriptionMinLengthError: false,
    previewFile: {},
    showPreview: false,
    showEditPreview: props.location.editActivity
      ? props.location.dataForEdit.upload_logo
        ? true
        : false
      : false,
    showNoImage: props.location.editActivity
      ? false
      : props.location.editActivity
  });

  if (formState.dataForEdit && !formState.counter) {
    if (props.location["dataForEdit"]) {
      if (props.location["dataForEdit"]["title"]) {
        formState.values["activityname"] =
          props.location["dataForEdit"]["title"];
      }
      if (props.location["dataForEdit"]["activitytype"]) {
        formState.values["activitytype"] =
          props.location["dataForEdit"]["activitytype"]["id"];
      }
      if (
        props.location["dataForEdit"]["academic_year"] &&
        props.location["dataForEdit"]["academic_year"]["id"]
      ) {
        formState.values["academicyear"] =
          props.location["dataForEdit"]["academic_year"]["id"];
      }
      if (props.location["dataForEdit"]["streams"]) {
        formState.values["stream"] = props.location["dataForEdit"]["streams"];
      }
      if (props.location["dataForEdit"]["address"]) {
        formState.values["address"] = props.location["dataForEdit"]["address"];
      }
      if (props.location["dataForEdit"]["education_year"]) {
        formState.values["educationyear"] =
          props.location["dataForEdit"]["education_year"];
      }
      if (props.location["dataForEdit"]["activity_status"]) {
        formState.values["activitystatus"] =
          props.location["dataForEdit"]["activity_status"];
      }
      if (
        props.location["dataForEdit"]["question_set"] &&
        props.location["dataForEdit"]["question_set"]
      ) {
        formState.values["questionSet"] =
          props.location["dataForEdit"]["question_set"]["id"];
      }
      if (props.location["dataForEdit"]["description"]) {
        // formState.values["description"] = props["dataForEdit"]["description"];
        const blocksFromHtml = htmlToDraft(
          props.location["dataForEdit"]["description"]
        );
        const { contentBlocks, entityMap } = blocksFromHtml;
        const contentState = ContentState.createFromBlockArray(
          contentBlocks,
          entityMap
        );
        const editorState = EditorState.createWithContent(contentState);
        setEditorState(editorState);
      }
      if (props.location["dataForEdit"]["trainer_name"]) {
        formState.values["trainer"] =
          props.location["dataForEdit"]["trainer_name"];
      }

      if (
        props.location["dataForEdit"]["contact"] &&
        props.location["dataForEdit"]["contact"]["id"]
      ) {
        formState.values["college"] =
          props.location["dataForEdit"]["contact"]["id"];
      }
      if (props.location["dataForEdit"]["start_date_time"]) {
        formState.values[dateFrom] = moment(
          props.location["dataForEdit"]["start_date_time"]
        );
      }
      if (props.location["dataForEdit"]["end_date_time"]) {
        formState.values[dateTo] = moment(
          props.location["dataForEdit"]["end_date_time"]
        );
      }
      if (
        props.location["dataForEdit"]["upload_logo"] &&
        props.location["dataForEdit"]["upload_logo"]["id"]
      ) {
        formState.files = props.location["dataForEdit"]["upload_logo"];
        //      formState.values["files"] =
        //        props.location["dataForEdit"]["upload_logo"]["name"];
      }
    }
    formState.counter += 1;
  }

  if (props.location.state && !formState.counter) {
    if (props.location.state.contactNumber && props.location.state.otp) {
      formState.values["contact"] = props.location.state.contactNumber;
      formState.values["otp"] = props.location.state.otp;
    }
    formState.counter += 1;
  }

  // const [selectedDateFrom, setSelectedDateFrom] = React.useState(new Date());
  // const [selectedDateTo, setSelectedDateTo] = React.useState(new Date());
  const { setLoaderStatus } = useContext(LoaderContext);

  const educationyearlist = [
    { name: "First", id: "First" },
    { name: "Second", id: "Second" },
    { name: "Third", id: "Third" }
  ];

  const activityNameList = [
    { name: "Soft Skills 1", id: "Soft Skills 1" },
    { name: "Soft Skills 2", id: "Soft Skills 2" },
    { name: "Career Awareness 1", id: "Career Awareness 1" },
    { name: "Career Awareness 2", id: "Career Awareness 2" },
    { name: "Job Preparation 1", id: "Job Preparation 1" },
    { name: "Job Preparation 2", id: "Job Preparation 2" },
    { name: "Job Preparation 3", id: "Job Preparation 3" },
    { name: "Industrial Visit", id: "Industrial Visit" },
    { name: "Industry Talk", id: "Industry Talk" }
  ];

  const activityStatus = [
    { name: "Scheduled", id: "scheduled" },
    { name: "Completed", id: "completed" },
    { name: "Cancelled", id: "cancelled" }
  ];

  const [stream, setStream] = useState([]);
  const [isFailed, setIsFailed] = useState(false);

  const classes = useStyles();

  const [collegelist, setcollegelist] = useState(
    props.collegeListForTest ? props.collegeListForTest : []
  );
  const [streamlist, setstreamlist] = useState(
    props.streamListForTest ? props.streamListForTest : []
  );
  const [collegeStreamList, setCollegeStreamList] = useState(
    props.collegeStreamListForTest ? props.collegeStreamListForTest : []
  );
  const [activityType, setActivityType] = useState(
    props.activityTypeListForTest ? props.activityTypeListForTest : []
  );
  const [questionSetData, setQuestionSetData] = useState(
    props.questionSetListForTest ? props.questionSetListForTest : []
  );

  if (
    !formState.dataForEdit &&
    props.isDataForTesting &&
    !formState.testCounter
  ) {
    const html = "<p>Test Data</p>";
    const contentBlock = htmlToDraft(html);
    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(
        contentBlock.contentBlocks
      );
      const editorState = EditorState.createWithContent(contentState);
      setEditorState(editorState);
      formState.testCounter += 1;
    }
  }

  useEffect(() => {
    serviceProvider
      .serviceProviderForGetRequest(QUESTION_SET)
      .then(res => {
        setQuestionSetData(res.data);
      })
      .catch(error => {});
    getColleges();
    getStreams();
    getActivityTypes();
  }, []);

  const getActivityTypes = async () => {
    const activityTypeUrl =
      strapiApiConstants.STRAPI_DB_URL +
      strapiApiConstants.STRAPI_ACTIVITY_TYPE;
    await serviceProvider
      .serviceProviderForGetRequest(activityTypeUrl)
      .then(res => {
        setActivityType(res.data);
      })
      .catch(error => {});
  };

  const getStreams = () => {
    axios
      .get(strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_STREAMS)
      .then(res => {
        const list = res.data.map(({ id, name }) => ({
          id,
          name
        }));
        setstreamlist(list);

        if (formState.dataForEdit) {
          const streamIds = props.location["dataForEdit"]["streams"].map(
            stream => stream.id
          );
          const selectedStream = list.filter(stream => {
            if (includes(streamIds, stream.id)) {
              return stream;
            }
          });

          setStream(selectedStream);
        }
      });
  };

  useEffect(() => {
    setLoaderStatus(true);
    if (
      formState.values.hasOwnProperty("college") &&
      formState.values["college"] &&
      collegelist.length > 0
    ) {
      const college = collegelist.find(
        college => college.contact.id == formState.values["college"]
      );

      const collegeStreamIds = college.stream_strength.map(s => s.stream.id);
      const list = streamlist.filter(stream => {
        if (includes(collegeStreamIds, stream.id)) {
          return stream;
        }
      });

      setCollegeStreamList(list);
    }

    setLoaderStatus(false);
  }, [formState.values["college"], collegelist, streamlist]);

  const handleSubmit = event => {
    event.preventDefault();
    setBackDrop(true);

    let isValid = false;
    let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
      formState.values,
      ActivityFormSchema
    );
    if (checkAllFieldsValid) {
      /** Evaluated only if all keys are valid inside formstate */
      formState.errors = formUtilities.setErrors(
        formState.values,
        ActivityFormSchema,
        true,
        dateFrom,
        dateTo
      );
      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,
        ActivityFormSchema
      );
      formState.errors = formUtilities.setErrors(
        formState.values,
        ActivityFormSchema,
        true,
        dateFrom,
        dateTo
      );
    }
    formState.descriptionError = false;

    if (
      convertToRaw(editorState.getCurrentContent()).blocks &&
      convertToRaw(editorState.getCurrentContent()).blocks.length
    ) {
      let arrayToCheckIn = convertToRaw(editorState.getCurrentContent()).blocks;
      let validationCounter = 0;
      let validationMinCounter = 0;
      for (let i in arrayToCheckIn) {
        if (
          arrayToCheckIn[i]["text"] &&
          arrayToCheckIn[i]["text"].trim().length !== 0
        ) {
          validationCounter += 1;
          break;
        }
      }
      if (validationCounter === 0) {
        formState.descriptionError = true;
      }
      for (let i in arrayToCheckIn) {
        if (
          arrayToCheckIn[i]["text"] &&
          arrayToCheckIn[i]["text"].trim().length > 320
        ) {
          validationMinCounter += 1;
          break;
        }
      }

      if (validationMinCounter !== 0) {
        formState.discriptionMinLengthError = true;
      }
    }
    if (
      isValid &&
      !formState.descriptionError &&
      !formState.discriptionMinLengthError
    ) {
      /** CALL POST FUNCTION */
      postActivityData();

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

  const postActivityData = () => {
    let postData;
    if (formState.editActivity) {
      postData = databaseUtilities.editActivity(
        formState.showPreview,
        formState.values["activityname"],
        formState.values["activitytype"],
        formState.values["college"],
        formState.values[dateFrom],
        formState.values[dateTo],
        formState.values["educationyear"],
        formState.values["address"],
        draftToHtml(convertToRaw(editorState.getCurrentContent())),
        formState.values["trainer"],
        stream.map(stream => stream.id),
        formState["dataForEdit"]["id"],
        formState.files,
        formState.values["questionSet"],
        formState.values["activitystatus"]
      );
      serviceProvider
        .serviceProviderForPutRequest(
          strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_ACTIVITY,
          formState.dataForEdit.id,
          postData
        )
        .then(response => {
          setFormState({ ...formState, isSuccess: true });
          history.push({
            pathname: routeConstants.MANAGE_ACTIVITY,
            isDataEdited: true,
            editedData: response.data,
            fromEditActivity: true
          });
          setBackDrop(false);
        })
        .catch(err => {
          setIsFailed(true);
          setBackDrop(false);
        });
    } else {
      postData = databaseUtilities.addActivity(
        formState.values["activityname"],
        formState.values["activitytype"],
        formState.values["college"],
        formState.values[dateFrom],
        formState.values[dateTo],
        formState.values["educationyear"],
        formState.values["address"],
        draftToHtml(convertToRaw(editorState.getCurrentContent())),
        formState.values["trainer"],
        stream.map(stream => stream.id),
        formState.files,
        formState.values["questionSet"]
      );
      serviceProvider
        .serviceProviderForPostRequest(
          strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_ACTIVITY,
          postData
        )
        .then(({ data }) => {
          history.push({
            pathname: routeConstants.MANAGE_ACTIVITY,
            isDataAdded: true,
            addedData: data,
            fromAddActivity: true
          });
          setBackDrop(false);
        })
        .catch(err => {
          setIsFailed(true);
          setBackDrop(false);
        });
    }
  };

  const getColleges = async () => {
    await serviceProvider
      .serviceProviderForGetRequest(
        strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_COLLEGES,
        { pageSize: -1 }
      )
      .then(res => {
        setcollegelist(
          res.data.result.map(({ id, name, contact, stream_strength }) => ({
            id,
            name,
            contact,
            stream_strength
          }))
        );
      });
  };

  const handleChangefile = e => {
    e.persist();
    setFormState(formState => ({
      ...formState,

      values: {
        ...formState.values,
        [e.target.name]: e.target.files[0].name
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      },
      files: e.target.files[0],
      previewFile: URL.createObjectURL(e.target.files[0]),
      showPreview: true,
      showEditPreview: false,
      showNoImage: false
    }));
    if (formState.errors.hasOwnProperty(e.target.name)) {
      delete formState.errors[e.target.name];
    }
  };
  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];
    }
  };

  const handleChangeAutoComplete = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (value !== null) {
      if (eventName === "college") {
        setFormState(formState => ({
          ...formState,
          values: {
            ...formState.values,
            [eventName]: value.contact.id
          },
          touched: {
            ...formState.touched,
            [eventName]: true
          }
        }));
      } else {
        setFormState(formState => ({
          ...formState,
          values: {
            ...formState.values,
            [eventName]: value.id
          },
          touched: {
            ...formState.touched,
            [eventName]: true
          }
        }));
      }
      if (formState.errors.hasOwnProperty(eventName)) {
        delete formState.errors[eventName];
      }
    } else {
      if (eventName === "college") {
        delete formState.values["stream"];
        formState.stream = [];
        setCollegeStreamList([]);
        setStream([]);
      }
      delete formState.values[eventName];
    }
  };

  const handleStreamChange = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (value !== null) {
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          [eventName]: value
        },
        touched: {
          ...formState.touched,
          [eventName]: true
        }
      }));
      if (formState.errors.hasOwnProperty(eventName)) {
        delete formState.errors[eventName];
      }
      setStream(value);
    }
  };

  const handleDateChange = (dateObject, event) => {
    if (formState.errors.hasOwnProperty(dateObject)) {
      delete formState.errors[dateObject];
    }
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [dateObject]: event
      },
      touched: {
        ...formState.touched,
        [dateObject]: true
      },
      isStateClearFilter: false
    }));
  };

  const hasError = field => (formState.errors[field] ? true : false);
  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        <Typography variant="h4" gutterBottom>
          {formState.editActivity
            ? genericConstants.EDIT_ACTIVITY_TEXT
            : genericConstants.ADD_ACTIVITY_TEXT}
        </Typography>
        {isFailed && formState.editActivity ? (
          <Collapse in={isFailed}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setIsFailed(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {genericConstants.ALERT_ERROR_DATA_EDITED_MESSAGE}
            </Alert>
          </Collapse>
        ) : null}
        {isFailed && !formState.editActivity ? (
          <Collapse in={isFailed}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setIsFailed(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {genericConstants.ALERT_ERROR_DATA_ADDED_MESSAGE}
            </Alert>
          </Collapse>
        ) : null}
      </Grid>
      <Grid spacing={3}>
        <Card>
          <form autoComplete="off" noValidate>
            <CardContent>
              <Grid item xs={12} md={6} xl={3}>
                <Grid container className={classes.formgridInputFile}>
                  <Grid item md={10} xs={12}>
                    <div className={classes.imageDiv}>
                      {formState.showPreview ? (
                        <Img
                          alt="abc"
                          loader={<Spinner />}
                          className={classes.UploadImage}
                          src={formState.previewFile}
                        />
                      ) : null}
                      {!formState.showPreview && !formState.showEditPreview ? (
                        <div className={classes.DefaultNoImage}></div>
                      ) : null}
                      {/* {formState.showEditPreview&&formState.dataForEdit.upload_logo===null? <div class={classes.DefaultNoImage}></div>:null} */}
                      {formState.showEditPreview &&
                      formState.dataForEdit["upload_logo"] !== null &&
                      formState.dataForEdit["upload_logo"] !== undefined &&
                      formState.dataForEdit["upload_logo"] !== {} ? (
                        <Img
                          src={
                            strapiApiConstants.STRAPI_DB_URL_WITHOUT_HASH +
                            formState.dataForEdit["upload_logo"]["url"]
                          }
                          loader={<Spinner />}
                          className={classes.UploadImage}
                        />
                      ) : null}
                      {formState.showNoImage ? (
                        <Img
                          src="/images/noImage.png"
                          loader={<Spinner />}
                          className={classes.UploadImage}
                        />
                      ) : null}
                    </div>
                  </Grid>
                </Grid>
                <Grid container className={classes.MarginBottom}>
                  <Grid item md={10} xs={12}>
                    <TextField
                      fullWidth
                      id="files"
                      margin="normal"
                      name="files"
                      placeholder="Upload Logo"
                      onChange={handleChangefile}
                      required
                      type="file"
                      inputProps={{ accept: "image/*" }}
                      //value={formState.values["files"] || ""}
                      error={hasError("files")}
                      helperText={
                        hasError("files")
                          ? formState.errors["files"].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                      variant="outlined"
                      className={classes.inputFile}
                    />
                    <label htmlFor={get(ActivityFormSchema["files"], "id")}>
                      <Button
                        variant="contained"
                        color="primary"
                        component="span"
                        fullWidth
                        className={classes.InputFileButton}
                        startIcon={<AddOutlinedIcon />}
                      >
                        ADD NEW FILE
                      </Button>
                    </label>
                  </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}>
                    <Autocomplete
                      id="activitytype"
                      className={classes.root}
                      options={activityType}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete("activitytype", event, value);
                      }}
                      value={
                        activityType[
                          activityType.findIndex(function (item, i) {
                            return item.id === formState.values.activitytype;
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError("activitytype")}
                          label="Activity Type"
                          variant="outlined"
                          name="tester"
                          helperText={
                            hasError("activitytype")
                              ? formState.errors["activitytype"].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.formgrid}>
                  <Grid item md={12} xs={12}>
                    <Autocomplete
                      id="activityname"
                      className={classes.root}
                      options={activityNameList}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete("activityname", event, value);
                      }}
                      value={
                        activityNameList[
                          activityNameList.findIndex(function (item, i) {
                            return item.id === formState.values["activityname"];
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError("activityname")}
                          label="Activity Name"
                          variant="outlined"
                          required
                          name="activityname"
                          helperText={
                            hasError("activityname")
                              ? formState.errors["activityname"].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12} className={"descriptionBox"}>
                    <Grid
                      className={
                        formState.descriptionError ||
                        formState.discriptionMinLengthError
                          ? classes.descriptionBoxError
                          : classes.descriptionBox
                      }
                    >
                      <Card className={classes.streamoffer}>
                        <InputLabel
                          htmlFor="outlined-stream-card"
                          fullwidth={true.toString()}
                          error={
                            formState.descriptionError ||
                            formState.discriptionMinLengthError
                          }
                        >
                          {genericConstants.DESCRIPTION}
                        </InputLabel>
                        <div className="rdw-root">
                          <Editor
                            id="description-editor"
                            editorState={editorState}
                            toolbarClassName="rdw-toolbar"
                            wrapperClassName="rdw-wrapper"
                            editorClassName="rdw-editor"
                            value={editorState}
                            onEditorStateChange={data => {
                              formState.descriptionError = false;
                              formState.discriptionMinLengthError = false;
                              setEditorState(data);
                            }}
                          />
                        </div>
                        {formState.descriptionError ? (
                          <FormHelperText error={true}>
                            Description is required
                          </FormHelperText>
                        ) : null}
                        {formState.discriptionMinLengthError ? (
                          <FormHelperText error={true}>
                            Description length should be less than 320
                            characters
                          </FormHelperText>
                        ) : null}
                      </Card>
                    </Grid>
                  </Grid>
                </Grid>

                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={6} xs={12}>
                    <CustomDateTimePicker
                      onChange={event => {
                        handleDateChange(dateFrom, event);
                      }}
                      value={formState.values[dateFrom] || null}
                      name={dateFrom}
                      label={get(ActivityFormSchema[dateFrom], "label")}
                      placeholder={get(
                        ActivityFormSchema[dateFrom],
                        "placeholder"
                      )}
                      fullWidth
                      error={hasError(dateFrom)}
                      helperText={
                        hasError(dateFrom)
                          ? formState.errors[dateFrom].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <CustomDateTimePicker
                      onChange={event => {
                        handleDateChange(dateTo, event);
                      }}
                      value={formState.values[dateTo] || null}
                      name={dateTo}
                      label={get(ActivityFormSchema[dateTo], "label")}
                      placeholder={get(
                        ActivityFormSchema[dateTo],
                        "placeholder"
                      )}
                      fullWidth
                      error={hasError(dateTo)}
                      helperText={
                        hasError(dateTo)
                          ? formState.errors[dateTo].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                </Grid>

                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12}>
                    <TextField
                      label="Address"
                      name="address"
                      value={formState.values["address"] || ""}
                      variant="outlined"
                      required
                      fullWidth
                      id="addressId"
                      onChange={handleChange}
                      error={hasError("address")}
                      helperText={
                        hasError("address")
                          ? formState.errors["address"].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                </Grid>

                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12}>
                    <Autocomplete
                      id="collegeId"
                      className={classes.root}
                      options={collegelist}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete("college", event, value);
                      }}
                      value={
                        collegelist[
                          collegelist.findIndex(function (item, i) {
                            return item.contact.id === formState.values.college;
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError("college")}
                          label="College"
                          variant="outlined"
                          required
                          name="tester"
                          helperText={
                            hasError("college")
                              ? formState.errors["college"].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12} className={classes.root}>
                    <Autocomplete
                      multiple={true}
                      id="collegeStreamID"
                      required
                      options={collegeStreamList}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleStreamChange("stream", event, value);
                      }}
                      value={stream}
                      filterSelectedOptions
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError("stream")}
                          label="Stream"
                          variant="outlined"
                          required
                          name="tester"
                          helperText={
                            hasError("stream")
                              ? formState.errors["stream"].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}>
                    <Autocomplete
                      id="educationYearId"
                      className={classes.root}
                      options={educationyearlist}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete("educationyear", event, value);
                      }}
                      value={
                        educationyearlist[
                          educationyearlist.findIndex(function (item, i) {
                            return item.id === formState.values.educationyear;
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError("educationyear")}
                          label="Education Year"
                          variant="outlined"
                          name="tester"
                          helperText={
                            hasError("educationyear")
                              ? formState.errors["educationyear"].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                  {formState.editActivity ? (
                    <Grid item md={6} xs={12}>
                      <Autocomplete
                        id="combo-box-demo"
                        className={classes.root}
                        options={activityStatus}
                        getOptionLabel={option => option.name}
                        onChange={(event, value) => {
                          handleChangeAutoComplete(
                            "activitystatus",
                            event,
                            value
                          );
                        }}
                        value={
                          activityStatus[
                            activityStatus.findIndex(function (item, i) {
                              return (
                                item.id === formState.values.activitystatus
                              );
                            })
                          ] || null
                        }
                        renderInput={params => (
                          <TextField
                            {...params}
                            error={hasError("activitystatus")}
                            label="Activity Status"
                            variant="outlined"
                            name="tester"
                            helperText={
                              hasError("activitystatus")
                                ? formState.errors["activitystatus"].map(
                                    error => {
                                      return error + " ";
                                    }
                                  )
                                : null
                            }
                          />
                        )}
                      />
                    </Grid>
                  ) : null}
                </Grid>
                <Grid container spacing={3} className={classes.formgrid}>
                  <Grid item md={6} xs={12}>
                    <TextField
                      label="Trainer Name"
                      name="trainer"
                      id="trainerId"
                      value={formState.values["trainer"] || ""}
                      variant="outlined"
                      required
                      fullWidth
                      onChange={handleChange}
                      error={hasError("trainer")}
                      helperText={
                        hasError("trainer")
                          ? formState.errors["trainer"].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id="question_set"
                      className={classes.root}
                      options={questionSetData}
                      placeholder={"Select Question Set"}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete("questionSet", event, value);
                      }}
                      required
                      value={
                        questionSetData[
                          questionSetData.findIndex(function (item, i) {
                            return item.id === formState.values["questionSet"];
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          label={"Question-Set"}
                          variant="outlined"
                          required
                          placeholder={"Select Question Set"}
                          error={hasError("questionSet")}
                          helperText={
                            hasError("questionSet")
                              ? formState.errors["questionSet"].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}>
                    {formState.editActivity ? (
                      <Grid container spacing={3}>
                        <Grid item md={2} xs={12}>
                          <YellowButton
                            color="primary"
                            type="submit"
                            mfullWidth
                            variant="contained"
                            style={{ marginRight: "18px" }}
                            onClick={handleSubmit}
                          >
                            <span>{genericConstants.SAVE_BUTTON_TEXT}</span>
                          </YellowButton>
                        </Grid>
                        <Grid item md={2} xs={12}>
                          <GrayButton
                            color="primary"
                            type="submit"
                            mfullWidth
                            variant="contained"
                            onClick={() => {
                              history.push(routeConstants.MANAGE_ACTIVITY);
                            }}
                          >
                            <span>{genericConstants.CANCEL_BUTTON_TEXT}</span>
                          </GrayButton>
                        </Grid>
                      </Grid>
                    ) : (
                      <Grid container spacing={3}>
                        <Grid item md={2} xs={12}>
                          <YellowButton
                            id="submitActivity"
                            color="primary"
                            type="submit"
                            mfullWidth
                            variant="contained"
                            style={{ marginRight: "18px" }}
                            onClick={handleSubmit}
                          >
                            <span>{genericConstants.SAVE_BUTTON_TEXT}</span>
                          </YellowButton>
                        </Grid>
                        <Grid item md={2} xs={12}>
                          <GrayButton
                            color="primary"
                            type="submit"
                            mfullWidth
                            variant="contained"
                            onClick={() => {
                              history.push(routeConstants.MANAGE_ACTIVITY);
                            }}
                          >
                            <span>{genericConstants.CANCEL_BUTTON_TEXT}</span>
                          </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: ChangePassword.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
ChangePassword = props => {
  const classes = useStyles();
  const [open, setOpen] = React.useState(true);
  const changePasswordClasses = ChangePasswordStyles();
  const { setLoaderStatus } = useContext(LoaderContext);
  const { setIndex } = useContext(SetIndexContext);
  setIndex(null);
  const [formState, setFormState] = useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    showNewPassword: false,
    showOldPassword: false,
    isSuccessChangingPassword: false,
    isErrorChangingPassword: false
  });

  const handleChange = e => {
    e.persist();
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [e.target.name]: e.target.value
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      }
    }));
    if (formState.errors.hasOwnProperty(e.target.name)) {
      delete formState.errors[e.target.name];
    }
  };

  const handleClickShowOldPassword = () => {
    setFormState({
      ...formState,
      showOldPassword: !formState.showOldPassword
    });
  };

  const handleClickShowNewPassword = () => {
    setFormState({
      ...formState,
      showNewPassword: !formState.showNewPassword
    });
  };
  const handleMouseDownPassword = event => {
    event.preventDefault();
  };

  const setLoader = () => {
    setLoaderStatus(true);
  };

  const handleSubmit = event => {
    event.preventDefault();
    setOpen(true);
    setLoader();
    let isValid = false;
    let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
      formState.values,
      ChangePasswordSchema
    );
    if (checkAllFieldsValid) {
      formState.errors = formUtilities.setErrors(
        formState.values,
        ChangePasswordSchema
      );
      if (formUtilities.checkEmpty(formState.errors)) {
        isValid = true;
      }
    } else {
      formState.values = formUtilities.getListOfKeysNotPresent(
        formState.values,
        ChangePasswordSchema
      );
      formState.errors = formUtilities.setErrors(
        formState.values,
        ChangePasswordSchema
      );
    }
    if (isValid) {
      postStateData();
      /** Call axios from here */
      setFormState(formState => ({
        ...formState,
        isValid: true,
        isErrorChangingPassword: false,
        isSuccessChangingPassword: false
      }));
    } else {
      setFormState(formState => ({
        ...formState,
        isValid: false,
        isErrorChangingPassword: false,
        isSuccessChangingPassword: false
      }));
      setLoaderStatus(false);
    }
  };
  const postStateData = () => {
    let postData = {
      username: auth.getUserInfo().username,
      oldPassword: formState.values[OLDPASSWORD],
      password: formState.values[NEWPASSWORD],
      passwordConfirmation: formState.values[NEWPASSWORD]
    };
    let headers = {
      "content-type": "application/json"
    };
    serviceProviders
      .serviceProviderForPostRequest(
        strapiApiConstants.STRAPI_DB_URL +
          strapiApiConstants.STRAPI_CHANGE_PASSWORD,
        postData,
        headers
      )
      .then(res => {
        setLoaderStatus(false);
        setFormState(formState => ({
          ...formState,
          isSuccessChangingPassword: true,
          isErrorChangingPassword: false,
          values: {}
        }));
      })
      .catch(error => {
        setLoaderStatus(false);
        setFormState(formState => ({
          ...formState,
          isSuccessChangingPassword: false,
          isErrorChangingPassword: true,
          values: {}
        }));
      });
    /** Set state to reload form */
    setFormState(formState => ({
      ...formState,
      isValid: true
    }));
  };

  const hasError = field => (formState.errors[field] ? true : false);
  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        <Typography variant="h4" gutterBottom>
          {genericConstants.CHANGE_PASSWORD}
        </Typography>
      </Grid>

      <Grid item xs={12} className={classes.formgrid}>
        {/** Error/Success messages to be shown for edit */}
        {formState.isSuccessChangingPassword &&
        !formState.isErrorChangingPassword ? (
          <Collapse in={open}>
            <Alert
              severity="success"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              Password Changed Successfully.
            </Alert>
          </Collapse>
        ) : null}
        {formState.isErrorChangingPassword &&
        !formState.isSuccessChangingPassword ? (
          <Collapse in={open}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              Error Changing Password.
            </Alert>
          </Collapse>
        ) : null}
      </Grid>

      <Grid item xs={12} className={classes.formgrid}>
        <Card className={classes.root} variant="outlined">
          <form autoComplete="off" noValidate onSubmit={handleSubmit}>
            <CardContent>
              <Grid container spacing={2}>
                <Grid item md={12} xs={12}>
                  <FormControl
                    fullWidth
                    className={clsx(
                      changePasswordClasses.margin,
                      classes.elementroot
                    )}
                    variant="outlined"
                  >
                    <InputLabel
                      htmlFor="outlined-adornment-password"
                      fullWidth
                      error={hasError(OLDPASSWORD)}
                    >
                      Old Password
                    </InputLabel>
                    <OutlinedInput
                      id={get(ChangePasswordSchema[OLDPASSWORD], "id")}
                      name={OLDPASSWORD}
                      type={formState.showOldPassword ? "text" : "password"}
                      value={formState.values[OLDPASSWORD] || ""}
                      onChange={handleChange}
                      fullWidth
                      error={hasError(OLDPASSWORD)}
                      endAdornment={
                        <InputAdornment
                          position="end"
                          error={hasError(OLDPASSWORD)}
                        >
                          <IconButton
                            aria-label="toggle password visibility"
                            onClick={handleClickShowOldPassword}
                            onMouseDown={handleMouseDownPassword}
                            edge="end"
                          >
                            {formState.showOldPassword ? (
                              <Visibility />
                            ) : (
                              <VisibilityOff />
                            )}
                          </IconButton>
                        </InputAdornment>
                      }
                      labelWidth={90}
                      InputLabelProps={{
                        classes: {
                          root: changePasswordClasses.cssLabel,
                          focused: changePasswordClasses.cssFocused
                        }
                      }}
                      InputProps={{
                        classes: {
                          root: changePasswordClasses.cssOutlinedInput,
                          focused: changePasswordClasses.cssFocused,
                          notchedOutline: changePasswordClasses.notchedOutline
                        }
                      }}
                    ></OutlinedInput>
                    <FormHelperText error={hasError(OLDPASSWORD)}>
                      {hasError(OLDPASSWORD)
                        ? formState.errors[OLDPASSWORD].map(error => {
                            return error + " ";
                          })
                        : null}
                    </FormHelperText>
                  </FormControl>
                </Grid>
                <Grid item md={12} xs={12}>
                  <FormControl
                    fullWidth
                    className={clsx(
                      changePasswordClasses.margin,
                      classes.elementroot
                    )}
                    variant="outlined"
                  >
                    <InputLabel
                      htmlFor="outlined-adornment-password"
                      fullWidth
                      error={hasError(NEWPASSWORD)}
                    >
                      New Password
                    </InputLabel>
                    <OutlinedInput
                      id={get(ChangePasswordSchema[NEWPASSWORD], "id")}
                      name={NEWPASSWORD}
                      type={formState.showNewPassword ? "text" : "password"}
                      value={formState.values[NEWPASSWORD] || ""}
                      onChange={handleChange}
                      fullWidth
                      error={hasError(NEWPASSWORD)}
                      endAdornment={
                        <InputAdornment
                          position="end"
                          error={hasError(NEWPASSWORD)}
                        >
                          <IconButton
                            aria-label="toggle password visibility"
                            onClick={handleClickShowNewPassword}
                            onMouseDown={handleMouseDownPassword}
                            edge="end"
                          >
                            {formState.showNewPassword ? (
                              <Visibility />
                            ) : (
                              <VisibilityOff />
                            )}
                          </IconButton>
                        </InputAdornment>
                      }
                      labelWidth={90}
                      InputLabelProps={{
                        classes: {
                          root: changePasswordClasses.cssLabel,
                          focused: changePasswordClasses.cssFocused
                        }
                      }}
                      InputProps={{
                        classes: {
                          root: changePasswordClasses.cssOutlinedInput,
                          focused: changePasswordClasses.cssFocused,
                          notchedOutline: changePasswordClasses.notchedOutline
                        }
                      }}
                    ></OutlinedInput>
                    <FormHelperText error={hasError(NEWPASSWORD)}>
                      {hasError(NEWPASSWORD)
                        ? formState.errors[NEWPASSWORD].map(error => {
                            return error + " ";
                          })
                        : null}
                    </FormHelperText>
                  </FormControl>
                </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={
                            auth.getUserInfo().role.name ===
                            roleConstants.STUDENT
                              ? routeConstants.VIEW_PROFILE
                              : routeConstants.DASHBOARD_URL
                          }
                        >
                          {genericConstants.CANCEL_BUTTON_TEXT}
                        </GrayButton>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </CardActions>
            </Grid>
          </form>
        </Card>
      </Grid>
    </Grid>
  );
}
Example #17
Source File: ForgotPassword.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
ForgotPassword = props => {
  const [openBackdrop, setOpenBackdrop] = React.useState(false);
  const [open, setOpen] = React.useState(true);
  const theme = useTheme();
  const history = useHistory();
  const classes = useStyles();
  const [isOtpVerificationFailed, setIsOtpVerificationFailed] = React.useState(
    false
  );

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

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

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

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

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

  function checkAllKeysPresent(obj) {
    let areFieldsValid = false;

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

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

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

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

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

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

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

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

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

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

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

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

            <Hidden mdDown>
              <CardMedia
                className={classes.cover}
                image={image}
                title="Live from space album cover"
              />
            </Hidden>
          </Paper>
        </div>
      </div>
    </div>
  );
}
Example #18
Source File: Login.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
LogIn = props => {
  const [openSpinner, setOpenSpinner] = React.useState(false);
  const [open, setOpen] = React.useState(true);
  const classes = useStyles();
  const theme = useTheme();
  const history = useHistory();
  const [ifSuccess, setIfSuccess] = React.useState(false);
  const [ifFailure, setIfFailure] = React.useState(false);
  const { index, setIndex } = useContext(SetIndexContext);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                  <FormControl
                    fullWidth
                    className={clsx(classes.margin, classes.textField)}
                    variant="outlined"
                  >
                    <InputLabel
                      htmlFor="outlined-adornment-password"
                      fullWidth
                      error={hasError(password)}
                    >
                      Password
                    </InputLabel>
                    <OutlinedInput
                      id={get(form[password], "id")}
                      name={password}
                      type={formState.showPassword ? "text" : "password"}
                      value={formState.values[password] || ""}
                      onChange={handleChange}
                      fullWidth
                      error={hasError(password)}
                      endAdornment={
                        <InputAdornment
                          position="end"
                          error={hasError(password)}
                        >
                          <IconButton
                            aria-label="toggle password visibility"
                            onClick={handleClickShowPassword}
                            onMouseDown={handleMouseDownPassword}
                            edge="end"
                          >
                            {formState.showPassword ? (
                              <Visibility />
                            ) : (
                              <VisibilityOff />
                            )}
                          </IconButton>
                        </InputAdornment>
                      }
                      labelWidth={70}
                      InputLabelProps={{
                        classes: {
                          root: classes.cssLabel,
                          focused: classes.cssFocused
                        }
                      }}
                      InputProps={{
                        classes: {
                          root: classes.cssOutlinedInput,
                          focused: classes.cssFocused,
                          notchedOutline: classes.notchedOutline
                        }
                      }}
                    ></OutlinedInput>
                    <FormHelperText error={hasError(password)}>
                      {hasError(password)
                        ? formState.errors[password].map(error => {
                            return error + " ";
                          })
                        : null}
                    </FormHelperText>
                    <Link
                      className={classes.forgotpass}
                      href={routeConstants.FORGOT_PASSWORD_URL}
                      variant="body2"
                      className={classes.linkColor}
                    >
                      {authPageConstants.FORGOT_PASSWORD_ROUTE_TEXT}
                    </Link>
                  </FormControl>
                  <Button
                    color="primary"
                    disabled={!formState.isValid}
                    type="submit"
                    fullWidth
                    variant="contained"
                    className={classes.submit}
                  >
                    {authPageConstants.SIGN_IN_BUTTON}
                  </Button>
                  <Grid container>
                    <Grid item xs={12} style={{ textAlign: "center" }}>
                      Don't have an account? |{" "}
                      <Link
                        href={routeConstants.REQUEST_OTP}
                        variant="body2"
                        className={classes.linkColor}
                      >
                        {authPageConstants.NEW_REG_ROUTE_TEXT}
                      </Link>
                    </Grid>
                  </Grid>
                </form>
              </div>
            </CardContent>
            <Hidden mdDown>
              <CardMedia
                className={classes.cover}
                image={image}
                title="Live from space album cover"
              />
            </Hidden>
            <Backdrop className={classes.backdrop} open={openSpinner}>
              <CircularProgress color="inherit" />
            </Backdrop>
          </Paper>
        </div>
      </div>
    </div>
  );
}
Example #19
Source File: AddEditEvent.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditEvent = props => {
  const [editorState, setEditorState] = React.useState(
    EditorState.createEmpty()
  );
  const { setLoaderStatus } = useContext(LoaderContext);
  const classes = useStyles();
  const history = useHistory();
  /** Initializiing form state value */
  const [formState, setFormState] = useState({
    isValid: false,
    values: {
      dateFrom: moment(),
      dateTo: moment()
    },
    touched: {},
    errors: {},
    stateId: null,
    setAllColleges: true,
    isSuccess: false,
    showPassword: false,
    isEditEvent: props["editEvent"] ? props["editEvent"] : false,
    dataForEdit: props["dataForEdit"] ? props["dataForEdit"] : {},
    counter: 0,
    files: {},
    filess: {},
    descriptionError: false,
    discriptionMinLengthError: false,
    dataToShowForCollegeMultiSelect: [],
    eventCollegeIds: [],
    dataToShowForStreamMultiSelect: [],
    eventStreamsIds: [],
    isCollegeAdminDoesNotHaveEditPreviliges: false,
    deleteImage: false,
    previewFile: {},
    showPreviewImage: false,
    showPreviewEditImage: false,
    showPreviewNoImage: false,
    showAddPreviewNoImage: true,
    dynamicBar: [{ index: Math.random() }],
    dynamicBarError: [],
    dynamicEducationBar: [{ index: Math.random() }],
    dynamicEducationBarError: [],
    isCollegeAdmin:
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
        ? true
        : false,
    isStateClearFilter: false,
    isContainDateValidation: true,
    isDateValidated: false
  });

  const [collegeInfo] = useState({
    college:
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
        ? 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
        : {}
  });
  const [backdrop, setBackDrop] = useState(false);
  const [states, setStates] = useState([]);
  const [zones, setZones] = useState([]);
  const [rpcs, setRpcs] = useState([]);
  const [colleges, setColleges] = useState([]);
  const [streams, setStreams] = useState(
    props.streamOption ? props.streamOption : []
  );
  const inputLabel = React.useRef(null);
  const [questionSetData, setQuestionSetData] = useState(
    props.questionOption ? props.questionOption : []
  );
  const [qualifications, setQualifications] = useState([
    { id: 1, value: "secondary", name: "Secondary" },
    { id: 2, value: "graduation", name: "Graduation" },
    { id: 3, value: "senior_secondary", name: "Senior Secondary" },
    { id: 4, name: "Diploma", value: "diploma" },
    { id: 5, name: "ITI", value: "iti" },
    // { id: 4, value: "undergraduate", name: "Undergraduate" },
    { id: 6, value: "postgraduate", name: "Postgraduate" },
    { id: 7, value: "other", name: "Other" }
  ]);
  const [qualificationsDataBackup] = useState([
    { id: 1, value: "secondary", name: "Secondary" },
    { id: 2, value: "graduation", name: "Graduation" },
    { id: 3, value: "senior_secondary", name: "Senior Secondary" },
    { id: 4, name: "Diploma", value: "diploma" },
    { id: 5, name: "ITI", value: "iti" },
    // { id: 4, value: "undergraduate", name: "Undergraduate" },
    { id: 6, value: "postgraduate", name: "Postgraduate" },
    { id: 7, value: "other", name: "Other" }
  ]);
  const [educations, setEducations] = useState([
    { id: 1, value: "First" },
    { id: 2, value: "Second" },
    { id: 3, value: "Third" }
  ]);
  const [educationsDataBackup] = useState([
    { id: 1, value: "First" },
    { id: 2, value: "Second" },
    { id: 3, value: "Third" }
  ]);
  if (formState.isEditEvent && !formState.counter) {
    setLoaderStatus(true);
    /** Part for editing state */
    if (props["dataForEdit"]) {
      if (props["dataForEdit"]["title"]) {
        formState.values[eventName] = props["dataForEdit"]["title"];
      }
      if (props["dataForEdit"]["description"]) {
        formState.values[description] = props["dataForEdit"]["description"];
        const blocksFromHtml = htmlToDraft(props["dataForEdit"]["description"]);
        const { contentBlocks, entityMap } = blocksFromHtml;
        const contentState = ContentState.createFromBlockArray(
          contentBlocks,
          entityMap
        );
        const editorState = EditorState.createWithContent(contentState);
        setEditorState(editorState);
      }
      if (props["dataForEdit"]["start_date_time"]) {
        formState.values[dateFrom] = props["dataForEdit"]["start_date_time"];
        //formState.defaultDate = date;
      }
      if (props["dataForEdit"]["end_date_time"]) {
        formState.values[dateTo] = props["dataForEdit"]["end_date_time"];
      }
      if (props["dataForEdit"]["address"]) {
        formState.values[address] = props["dataForEdit"]["address"];
      }

      if (props["dataForEdit"]["rpc"] && props["dataForEdit"]["rpc"]["id"]) {
        formState.values[rpc] = props["dataForEdit"]["rpc"]["id"];
      }
      if (props["dataForEdit"]["zone"] && props["dataForEdit"]["zone"]["id"]) {
        formState.values[zone] = props["dataForEdit"]["zone"]["id"];
      }
      if (
        props["dataForEdit"]["question_set"] &&
        props["dataForEdit"]["question_set"]["id"]
      ) {
        formState.values[questionSet] =
          props["dataForEdit"]["question_set"]["id"];
      }
      if (
        props["dataForEdit"]["state"] &&
        props["dataForEdit"]["state"]["id"]
      ) {
        formState.values[state] = props["dataForEdit"]["state"]["id"];
      }
      if (
        props["dataForEdit"] &&
        props["dataForEdit"]["educations"] &&
        props["dataForEdit"]["educations"].length
      ) {
        let dynamicEducationBar = [];
        for (let i in props["dataForEdit"]["educations"]) {
          let tempEducationDynamicBarValue = {};
          tempEducationDynamicBarValue["index"] = Math.random();
          tempEducationDynamicBarValue["id"] =
            props["dataForEdit"]["educations"][i]["id"];
          tempEducationDynamicBarValue[education] =
            props["dataForEdit"]["educations"][i]["education_year"];
          tempEducationDynamicBarValue[educationpercentage] =
            props["dataForEdit"]["educations"][i]["percentage"];
          dynamicEducationBar.push(tempEducationDynamicBarValue);
        }
        formState.dynamicEducationBar = dynamicEducationBar;
      }

      if (
        props["dataForEdit"] &&
        props["dataForEdit"]["qualifications"] &&
        props["dataForEdit"]["qualifications"].length
      ) {
        let dynamicBar = [];
        for (let i in props["dataForEdit"]["qualifications"]) {
          let tempDynamicBarValue = {};
          tempDynamicBarValue["index"] = Math.random();
          tempDynamicBarValue["id"] =
            props["dataForEdit"]["qualifications"][i]["id"];
          tempDynamicBarValue[qualification] =
            props["dataForEdit"]["qualifications"][i]["qualification"];
          tempDynamicBarValue[percentage] =
            props["dataForEdit"]["qualifications"][i]["percentage"];
          dynamicBar.push(tempDynamicBarValue);
        }
        formState.dynamicBar = dynamicBar;
      }
      if (props["dataForEdit"] && props["dataForEdit"]["upload_logo"]) {
        formState.showPreviewEditImage = true;
        formState.showAddPreviewNoImage = false;
      }
      if (
        props["dataForEdit"] &&
        props["dataForEdit"]["upload_logo"] === null
      ) {
        formState.showPreviewNoImage = true;
        formState.showAddPreviewNoImage = true;
      }
    }
    formState.counter += 1;
  }

  /** Use effect to populate Question Set */
  useEffect(() => {
    serviceProvider
      .serviceProviderForGetRequest(QUESTION_SET)
      .then(res => {
        setQuestionSetData(res.data);
      })
      .catch(error => {});
  }, []);

  /** Streams data for Prepopulating */
  const prePopulateStreamsData = streamsData => {
    if (props["editEvent"]) {
      if (
        props["dataForEdit"]["streams"] &&
        props["dataForEdit"]["streams"].length
      ) {
        let array = [];
        streamsData.map(stream => {
          for (let i in props["dataForEdit"]["streams"]) {
            if (props["dataForEdit"]["streams"][i]["id"] === stream["id"]) {
              array.push(stream);
            }
          }
        });
        setFormState(formState => ({
          ...formState,
          dataToShowForStreamMultiSelect: array
        }));
        let finalDataStream = [];
        for (let i in props["dataForEdit"]["streams"]) {
          finalDataStream.push(props["dataForEdit"]["streams"][i]["id"]);
        }
        formState.values[stream] = finalDataStream;
      }
    }
  };

  const prePopulateCollegeData = collegeData => {
    if (props["editEvent"]) {
      if (
        props["dataForEdit"]["contacts"] &&
        props["dataForEdit"]["contacts"].length
      ) {
        let array = [];
        collegeData.map(college => {
          for (let i in props["dataForEdit"]["contacts"]) {
            if (props["dataForEdit"]["contacts"][i]["id"] === college["id"]) {
              array.push(college);
            }
          }
        });
        let setAllColleges = false;
        if (collegeData.length === props["dataForEdit"]["contacts"].length) {
          setAllColleges = true;
        }
        setFormState(formState => ({
          ...formState,
          dataToShowForCollegeMultiSelect: array,
          setAllColleges: setAllColleges
        }));
        let finalData = [];
        for (let i in props["dataForEdit"]["contacts"]) {
          finalData.push(props["dataForEdit"]["contacts"][i]["contact"]["id"]);
        }
        formState.values[college] = finalData;
      }
    } else {
      let collegeArrayToSet = [];
      collegeData.map(c => {
        collegeArrayToSet.push(c.id);
      });
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          [college]: collegeArrayToSet
        },
        dataToShowForCollegeMultiSelect: collegeData
      }));
    }
  };

  /** Setting educations and qualifications */
  useEffect(() => {
    setLoaderStatus(true);
    let paramsForPageSize = {
      pageSize: -1
    };

    if (formState.isCollegeAdmin) {
      setStates([collegeInfo.state]);
    } else {
      serviceProvider
        .serviceProviderForGetRequest(STATES_URL, paramsForPageSize)
        .then(res => {
          res.data.result.map(s => {
            if (s.name === "Uttar Pradesh") {
              formState.stateId = s.id;
            }
          });
          setStates(res.data.result);
        })
        .catch(error => {
          console.log("error", error);
        });
    }

    let educationDataForEdit = [
      { id: 1, value: "First" },
      { id: 2, value: "Second" },
      { id: 3, value: "Third" }
    ];
    if (formState.isEditEvent) {
      let tempEducationData = educationDataForEdit;
      let educationPercentageArray = props["dataForEdit"]["educations"];
      for (let i in educationPercentageArray) {
        let id = educationPercentageArray[i]["education_year"];
        for (let j in tempEducationData) {
          if (tempEducationData[j]["value"] === id)
            tempEducationData.splice(j, 1);
        }
      }
      setEducations(tempEducationData);
    }

    let dataForEditing = [
      { id: 1, value: "secondary", name: "Secondary" },
      { id: 2, value: "graduation", name: "Graduation" },
      { id: 3, value: "senior_secondary", name: "Senior Secondary" },
      { id: 4, value: "undergraduate", name: "Undergraduate" },
      { id: 5, value: "postgraduate", name: "Postgraduate" },
      { id: 6, value: "other", name: "Other" }
    ];
    if (formState.isEditEvent) {
      let tempQualificationData = dataForEditing;
      let qualificationPercentageArray = props["dataForEdit"]["qualifications"];
      for (let i in qualificationPercentageArray) {
        let id = qualificationPercentageArray[i]["qualification"];
        for (let j in tempQualificationData) {
          if (tempQualificationData[j]["value"] === id)
            tempQualificationData.splice(j, 1);
        }
      }
      setQualifications(tempQualificationData);
    }

    if (!formState.isCollegeAdmin) {
      serviceProvider
        .serviceProviderForGetRequest(STREAM_URL, paramsForPageSize)
        .then(res => {
          setStreams(res.data.result);
          prePopulateStreamsData(res.data.result);
        })

        .catch(error => {
          console.log("errorstream", error);
        });
    } else if (formState.isCollegeAdmin) {
      let streamData = [];
      auth.getUserInfo().studentInfo.organization.stream_strength.map(data => {
        streamData.push(data["stream"]);
      });
      setStreams(streamData);
      prePopulateStreamsData(streamData);
    }
    setLoaderStatus(false);
  }, []);

  /** Setting rpc, zone on state change */
  useEffect(() => {
    if (
      formState.values.hasOwnProperty(state) &&
      formState.values[state] !== null &&
      formState.values[state] !== undefined
    ) {
      fetchZoneRpcData();
    }
  }, [formState.values[state]]);

  /** Common function to get zones, rpcs after changing state */
  async function fetchZoneRpcData() {
    setLoaderStatus(true);
    if (
      formState.values.hasOwnProperty(state) &&
      formState.values[state] !== null &&
      formState.values[state] !== undefined &&
      formState.values[state] !== ""
    ) {
      let zones_url =
        STATES_URL +
        "/" +
        formState.values[state] +
        "/" +
        strapiApiConstants.STRAPI_ZONES;

      if (!formState.isCollegeAdmin) {
        await serviceProvider
          .serviceProviderForGetRequest(zones_url)
          .then(res => {
            setZones(res.data.result);
          })
          .catch(error => {
            console.log("error", error);
          });
      } else if (formState.isCollegeAdmin) {
        setZones([collegeInfo.zone]);
      }

      let rpcs_url =
        STATES_URL +
        "/" +
        formState.values[state] +
        "/" +
        strapiApiConstants.STRAPI_RPCS;

      if (!formState.isCollegeAdmin) {
        await serviceProvider
          .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);
          });
      } else if (formState.isCollegeAdmin) {
        setRpcs([collegeInfo.rpc]);
      }
    }
    setLoaderStatus(false);
  }

  useEffect(() => {}, []);

  useEffect(() => {
    fetchCollegeData();
  }, []);

  /** Function to get college data after selcting zones and rpc's */
  async function fetchCollegeData() {
    setLoaderStatus(true);
    let params = {
      pageSize: -1
    };
    if (!formState.isCollegeAdmin) {
      await serviceProvider
        .serviceProviderForGetRequest(COLLEGE_URL, params)
        .then(res => {
          setColleges(res.data.result);
          prePopulateCollegeData(res.data.result);
        })
        .catch(error => {
          console.log("error", error);
        });
    } else if (formState.isCollegeAdmin) {
      setColleges([collegeInfo.college]);
      prePopulateCollegeData([collegeInfo.college]);
    }
    setLoaderStatus(false);
  }

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

  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];
    }
  };

  const checkErrorInDynamicBar = (field, currentDynamicBarValue) => {
    if (field === "qualification" || field === "percentage") {
      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;
    } else if (field === "education" || field === "educationpercentage") {
      let errorEducationData = { error: false, value: "" };

      if (formState.dynamicEducationBarError.length) {
        formState.dynamicEducationBarError.map(barErrorValue => {
          if (barErrorValue["index"] === currentDynamicBarValue["index"]) {
            if (barErrorValue.hasOwnProperty(field)) {
              errorEducationData.error = true;
              errorEducationData.value = barErrorValue[field];
            }
          }
        });
      }
      return errorEducationData;
    }
  };

  /** Adding a new row in dynamic bar */
  const addNewRow = (e, extendBarName) => {
    e.persist();
    if (extendBarName === "qualification") {
      setFormState(formState => ({
        ...formState,
        dynamicBar: [...formState.dynamicBar, { index: Math.random() }]
      }));
    } else if (extendBarName === "education") {
      setFormState(formState => ({
        ...formState,
        dynamicEducationBar: [
          ...formState.dynamicEducationBar,
          { index: Math.random() }
        ]
      }));
    }
  };

  /** To delete a value from dynamic bar */
  const clickOnDelete = (record, index) => {
    setFormState(formState => ({
      ...formState,
      dynamicBar: formState.dynamicBar.filter(r => r !== record)
    }));
    setFormState(formState => ({
      ...formState,
      dynamicEducationBar: formState.dynamicEducationBar.filter(
        r => r !== record
      )
    }));

    if (record[qualification]) {
      let qualificationsTempArray = [];
      qualificationsTempArray = qualifications;
      qualificationsDataBackup.map(qualificationData => {
        if (record["qualification"] === qualificationData["value"]) {
          qualificationsTempArray.push(qualificationData);
        }
      });
      setQualifications(qualificationsTempArray);
    }
    if (record[education]) {
      let qualificationsTempArray = [];
      qualificationsTempArray = educations;
      educationsDataBackup.map(qualificationData => {
        if (record["education"] === qualificationData["value"]) {
          qualificationsTempArray.push(qualificationData);
        }
      });
      setEducations(qualificationsTempArray);
    }
  };

  /** Handling multi select values for dynamic bar */
  const handleChangeForDynamicGrid = (
    eventName,
    event,
    selectedValueForAutoComplete,
    dynamicGridValue,
    isAutoComplete,
    isTextBox
  ) => {
    event.persist();
    if (eventName === "qualification" || eventName === "percentage") {
      /**TO SET VALUES OF AUTOCOMPLETE */
      if (isAutoComplete) {
        if (selectedValueForAutoComplete !== null) {
          setFormState(formState => ({
            ...formState,
            dynamicBar: formState.dynamicBar.map(r => {
              if (r["index"] === dynamicGridValue["index"]) {
                let qualificationsTempArray = [];
                qualifications.map(qualificationData => {
                  if (
                    qualificationData["id"] !==
                    selectedValueForAutoComplete["id"]
                  ) {
                    qualificationsTempArray.push(qualificationData);
                  }
                });
                setQualifications(qualificationsTempArray);
                r["id"] = selectedValueForAutoComplete["id"];
                r[eventName] = selectedValueForAutoComplete["value"];
                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 qualificationsTempArray = [];
                qualificationsTempArray = qualifications;
                qualificationsDataBackup.map(qualificationData => {
                  if (r[eventName] === qualificationData["value"]) {
                    qualificationsTempArray.push(qualificationData);
                  }
                });
                setQualifications(qualificationsTempArray);
                delete r[eventName];
                return r;
              } else {
                return r;
              }
            })
          }));
        }
      }
      if (isTextBox) {
        if (
          event.target.value === "" ||
          regexForPercentage.test(event.target.value)
        ) {
          if (event.target.value.length <= 2) {
            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];
        }
      });
    } else if (
      eventName === "education" ||
      eventName === "educationpercentage"
    ) {
      if (isAutoComplete) {
        if (selectedValueForAutoComplete !== null) {
          setFormState(formState => ({
            ...formState,
            dynamicEducationBar: formState.dynamicEducationBar.map(r => {
              if (r["index"] === dynamicGridValue["index"]) {
                let educationsTempArray = [];
                educations.map(educationData => {
                  if (
                    educationData["id"] !== selectedValueForAutoComplete["id"]
                  ) {
                    educationsTempArray.push(educationData);
                  }
                });
                setEducations(educationsTempArray);
                r["id"] = selectedValueForAutoComplete["id"];
                r[eventName] = selectedValueForAutoComplete["value"];
                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,
            dynamicEducationBar: formState.dynamicEducationBar.map(r => {
              if (r["index"] === dynamicGridValue["index"]) {
                let educationsTempArray = [];
                educationsTempArray = educations;
                educationsDataBackup.map(educationData => {
                  if (r[eventName] === educationData["value"]) {
                    educationsTempArray.push(educationData);
                  }
                });
                setQualifications(educationsTempArray);
                delete r[eventName];
                return r;
              } else {
                return r;
              }
            })
          }));
        }
      }
      if (isTextBox) {
        if (
          event.target.value === "" ||
          regexForPercentage.test(event.target.value)
        ) {
          if (event.target.value.length <= 2) {
            setFormState(formState => ({
              ...formState,
              dynamicEducationBar: formState.dynamicEducationBar.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 dynamikc bar */
      if (
        value.hasOwnProperty(qualification) &&
        !value.hasOwnProperty(percentage)
      ) {
        valueToPutInDynmicBarError[percentage] =
          "Percentage is required as Qualification is present";
        validationCounter += 1;
      } else if (
        value.hasOwnProperty(percentage) &&
        !value.hasOwnProperty(qualification)
      ) {
        valueToPutInDynmicBarError[qualification] =
          "Qualification is required as percentage is present";
        validationCounter += 1;
      }
      formState.dynamicBarError.push(valueToPutInDynmicBarError);
    });
    formState.dynamicEducationBarError = [];
    formState.dynamicEducationBar.map(value => {
      let valueToPutInDynmicBarError = {};
      valueToPutInDynmicBarError["index"] = value["index"];
      /** Validate dynamikc bar */
      if (
        value.hasOwnProperty(education) &&
        !value.hasOwnProperty(educationpercentage)
      ) {
        valueToPutInDynmicBarError[educationpercentage] =
          "Percentage is required as Education is present";
        validationCounter += 1;
      } else if (
        value.hasOwnProperty(educationpercentage) &&
        !value.hasOwnProperty(education)
      ) {
        valueToPutInDynmicBarError[education] =
          "Education is required as percentage is present";
        validationCounter += 1;
      }
      formState.dynamicEducationBarError.push(valueToPutInDynmicBarError);
    });
    if (validationCounter > 0) {
      return false;
    } else {
      return true;
    }
  };

  const getDynamicBarData = () => {
    let qualificationsPercentageArrayValues = [];
    formState.dynamicBar.map(field => {
      let qualificationPercentageValue = {};
      if (
        field.hasOwnProperty(qualification) &&
        field.hasOwnProperty(percentage)
      ) {
        qualificationPercentageValue["qualification"] = field[qualification];
        qualificationPercentageValue["percentage"] = parseInt(
          field[percentage]
        );
        qualificationsPercentageArrayValues.push(qualificationPercentageValue);
      }
    });

    return qualificationsPercentageArrayValues;
  };

  const getDynamicEducationData = () => {
    let educationsPercentageArrayValues = [];
    formState.dynamicEducationBar.map(field => {
      let educationPercentageValue = {};
      if (
        field.hasOwnProperty(education) &&
        field.hasOwnProperty(educationpercentage)
      ) {
        educationPercentageValue["education_year"] = field[education];
        educationPercentageValue["percentage"] = parseInt(
          field[educationpercentage]
        );
        educationsPercentageArrayValues.push(educationPercentageValue);
      }
    });

    return educationsPercentageArrayValues;
  };

  /** Handle change for autocomplete fields */
  const handleChangeAutoComplete = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (formState.errors.hasOwnProperty(eventName)) {
      delete formState.errors[eventName];
    }
    if (value !== null) {
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          [eventName]: value.id
        },
        touched: {
          ...formState.touched,
          [eventName]: true
        },
        isStateClearFilter: false
      }));
    } 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([]);
        setColleges([]);
        // setStreams([]);
        delete formState.values[zone];
        delete formState.values[rpc];
        formState.dataToShowForCollegeMultiSelect = [];
      } else if (eventName === rpc || eventName === zone) {
        setColleges([]);
        formState.dataToShowForCollegeMultiSelect = [];
      }
      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 handleCheckBox = event => {
    /** If the checkbox is checked */
    if (!formState.setAllColleges) {
      /** Delete current value */
      delete formState.values[college];
      /** Set validations */
      EventSchema.college.required = false;
      EventSchema.college.validations = {};
      /** Delete if errors present */
      delete formState.errors[college];
      /** Set college list when all collgees check box is checked */
      let collegeArrayToSet = [];
      colleges.map(c => {
        collegeArrayToSet.push(c.id);
      });
      setFormState(formState => ({
        ...formState,
        setAllColleges: !formState.setAllColleges,
        values: {
          ...formState.values,
          [college]: collegeArrayToSet
        },
        dataToShowForCollegeMultiSelect: colleges
      }));
    } else {
      delete formState.values[college];
      EventSchema.college.required = true;
      EventSchema.college.validations = {
        required: {
          value: "true",
          message: "College is required"
        }
      };
      /** Delete if errors present */
      delete formState.errors[college];
      setFormState(formState => ({
        ...formState,
        setAllColleges: !formState.setAllColleges,
        dataToShowForCollegeMultiSelect: []
      }));
    }
  };

  const handleSubmit = event => {
    event.preventDefault();
    setBackDrop(true);
    let isValid = false;
    if (formState.isCollegeAdmin && !formState.isEditEvent) {
      setDataForCollegeAdmin();
    } else {
      formState.values[state] = formState.stateId;
    }
    /** Validate DynamicGrid */
    let isDynamicBarValid;
    /** Check validity of dynamic bar */
    isDynamicBarValid = validateDynamicGridValues();
    let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
      formState.values,
      EventSchema
    );
    if (checkAllFieldsValid) {
      /** Evaluated only if all keys are valid inside formstate */
      formState.errors = formUtilities.setErrors(
        formState.values,
        EventSchema,
        true,
        dateFrom,
        dateTo
      );
      /** Check date validation */

      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,
        EventSchema
      );
      formState.errors = formUtilities.setErrors(
        formState.values,
        EventSchema,
        true,
        dateFrom,
        dateTo
      );
    }
    formState.descriptionError = false;
    if (
      convertToRaw(editorState.getCurrentContent()).blocks &&
      convertToRaw(editorState.getCurrentContent()).blocks.length
    ) {
      let arrayToCheckIn = convertToRaw(editorState.getCurrentContent()).blocks;
      let validationCounter = 0;
      let validationMinCounter = 0;
      for (let i in arrayToCheckIn) {
        if (
          arrayToCheckIn[i]["text"] &&
          arrayToCheckIn[i]["text"].trim().length !== 0
        ) {
          validationCounter += 1;
          break;
        }
      }
      if (validationCounter === 0) {
        formState.descriptionError = true;
      }
      for (let i in arrayToCheckIn) {
        if (
          arrayToCheckIn[i]["text"] &&
          arrayToCheckIn[i]["text"].trim().length > 320
        ) {
          validationMinCounter += 1;
          break;
        }
      }

      if (validationMinCounter !== 0) {
        formState.discriptionMinLengthError = true;
      }
    }
    if (
      isValid &&
      !formState.descriptionError &&
      !formState.discriptionMinLengthError &&
      isDynamicBarValid
    ) {
      /** CALL POST FUNCTION */
      postEventData();
      /** Call axios from here */
      setFormState(formState => ({
        ...formState,
        isValid: true
      }));
    } else {
      setFormState(formState => ({
        ...formState,
        isValid: false
      }));
      setBackDrop(false);
    }
  };

  const setDataForCollegeAdmin = () => {
    formState.values[zone] = collegeInfo.zone.id;
    formState.values[rpc] = collegeInfo.rpc.id;
    formState.values[college] = [collegeInfo.college.contact.id];
    formState.values[state] = collegeInfo.state.id;
  };

  const postEventData = () => {
    /** Setting quaalifications */
    let qualificationPercentageArray = [];
    qualificationPercentageArray = getDynamicBarData();

    /** Setting educations */
    let educationPercentageArray = [];
    educationPercentageArray = getDynamicEducationData();

    /** Data to post */
    let postData = databaseUtilities.addEvent(
      formState.values[eventName],
      draftToHtml(convertToRaw(editorState.getCurrentContent())),
      formState.values[dateFrom],
      formState.values[dateTo],
      formState.values[address],
      formState.values[zone] ? formState.values[zone] : null,
      formState.values[rpc] ? formState.values[rpc] : null,
      qualificationPercentageArray,
      educationPercentageArray,
      formState.values[college] ? formState.values[college] : null,
      formState.values[stream] ? formState.values[stream] : null,
      formState.values[state] ? formState.values[state] : null,
      formState.values[questionSet] ? formState.values[questionSet] : null
    );
    if (formState.isEditEvent) {
      serviceProvider
        .serviceProviderForPutRequest(
          EVENTS_URL,
          formState.dataForEdit["id"],
          postData
        )
        .then(res => {
          if (formState.files.name) {
            postImage(res.data.id);
          } else {
            history.push({
              pathname: routeConstants.MANAGE_EVENT,
              fromeditEvent: true,
              isDataEdited: true,
              editedEventData: res.data,
              addResponseMessage: "",
              editedData: {}
            });
          }
          setBackDrop(false);
        })
        .catch(error => {
          console.log("puterror", error);
          history.push({
            pathname: routeConstants.MANAGE_EVENT,
            fromeditEvent: true,
            isDataEdited: false,
            editResponseMessage: "",
            editedData: {}
          });
          setBackDrop(false);
        });
    } else {
      serviceProvider
        .serviceProviderForPostRequest(EVENTS_URL, postData)
        .then(res => {
          if (formState.files.name) {
            postImage(res.data.id);
          } else {
            history.push({
              pathname: routeConstants.MANAGE_EVENT,
              fromAddEvent: true,
              isDataAdded: true,
              addedEventData: res.data,
              addResponseMessage: "",
              addedData: {}
            });
          }
          setBackDrop(false);
        })
        .catch(error => {
          console.log("posterror", error);
          history.push({
            pathname: routeConstants.MANAGE_EVENT,
            fromeditEvent: true,
            isDataEdited: false,
            editResponseMessage: "",
            editedData: {}
          });
          setBackDrop(false);
        });
    }
  };

  const postImage = id => {
    let postImageData = databaseUtilities.uploadDocument(
      formState.files,
      ref,
      id,
      field
    );
    serviceProvider
      .serviceProviderForPostRequest(DOCUMENT_URL, postImageData)
      .then(res => {
        history.push({
          pathname: routeConstants.MANAGE_EVENT,
          fromAddEvent: true,
          isDataAdded: true,
          addResponseMessage: "",
          addedData: {}
        });
      })
      .catch(err => {
        console.log("error", err);
      });
  };

  const handleFileChange = event => {
    event.persist();
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [event.target.name]: event.target.value
      },
      touched: {
        ...formState.touched,
        [event.target.name]: true
      },
      files: event.target.files[0],
      previewFile: URL.createObjectURL(event.target.files[0]),
      showPreviewEditImage: false,
      showPreviewNoImage: false,
      showPreviewImage: true,
      showAddPreviewNoImage: false
    }));

    /** 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];
    }
  };

  const handleDateChange = (dateObject, event) => {
    if (formState.errors.hasOwnProperty(dateObject)) {
      delete formState.errors[dateObject];
    }
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [dateObject]: event
      },
      touched: {
        ...formState.touched,
        [dateObject]: true
      },
      isStateClearFilter: false
    }));
  };

  const handleMultiSelectChange = (eventName, event, value) => {
    let multiarray = [];
    delete formState.errors[eventName];

    if (eventName === college) {
      formState.dataToShowForCollegeMultiSelect = value;
      for (var i = 0; i < value.length; i++) {
        multiarray.push(value[i]["contact"].id);
      }
    }
    if (eventName === stream) {
      formState.dataToShowForStreamMultiSelect = value;
      for (var i = 0; i < value.length; i++) {
        multiarray.push(value[i].id);
      }
    }

    if (value !== null) {
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          [eventName]: multiarray
        },
        touched: {
          ...formState.touched,
          [eventName]: true
        },
        isStateClearFilter: false
      }));
    } else {
      delete formState.values[eventName];
    }
  };
  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        <Typography variant="h4" gutterBottom>
          {props["editEvent"] ? "Edit Event" : genericConstants.ADD_EVENT_TEXT}
        </Typography>
      </Grid>
      <Grid spacing={3}>
        <Card>
          <form autoComplete="off" noValidate onSubmit={handleSubmit} id="form">
            <CardContent>
              <Grid item xs={12} md={6} xl={3}>
                <Grid container className={classes.formgridInputFile}>
                  <Grid item md={10} xs={12}>
                    <div className={classes.imageDiv}>
                      {
                        formState.showPreviewImage ? (
                          <Img
                            src={formState.previewFile}
                            alt="abc"
                            loader={<Spinner />}
                            className={classes.UploadImage}
                          />
                        ) : null
                        // <div class={classes.DefaultNoImage}></div>
                      }

                      {formState.showPreviewEditImage &&
                      formState.dataForEdit["upload_logo"] !== null &&
                      formState.dataForEdit["upload_logo"] !== undefined &&
                      formState.dataForEdit["upload_logo"] !== {} ? (
                        <Img
                          src={
                            strapiApiConstants.STRAPI_DB_URL_WITHOUT_HASH +
                            formState.dataForEdit["upload_logo"]["url"]
                          }
                          loader={<Spinner />}
                          className={classes.UploadImage}
                        />
                      ) : null}
                      {formState.showPreviewNoImage ? (
                        <Img
                          src={"../"}
                          loader={<Spinner />}
                          className={classes.UploadImage}
                        />
                      ) : null}
                      {formState.showAddPreviewNoImage ? (
                        <div className={classes.DefaultNoImage}></div>
                      ) : null}
                    </div>
                  </Grid>
                </Grid>
                <Grid container className={classes.MarginBottom}>
                  <Grid item md={10} xs={12}>
                    <TextField
                      fullWidth
                      id={get(EventSchema[files], "id")}
                      name={files}
                      onChange={handleFileChange}
                      required
                      type={get(EventSchema[files], "type")}
                      value={formState.values[files] || ""}
                      error={hasError(files)}
                      inputProps={{ accept: "image/*" }}
                      helperText={
                        hasError(files)
                          ? formState.errors[files].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                      variant="outlined"
                      className={classes.inputFile}
                    />
                    <label htmlFor={get(EventSchema[files], "id")}>
                      <Button
                        variant="contained"
                        color="primary"
                        component="span"
                        fullWidth
                        className={classes.InputFileButton}
                        startIcon={<AddOutlinedIcon />}
                      >
                        ADD NEW EVENT LOGO
                      </Button>
                    </label>
                  </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
                      label={get(EventSchema[eventName], "label")}
                      id={get(EventSchema[eventName], "id")}
                      name={eventName}
                      placeholder={get(EventSchema[eventName], "placeholder")}
                      value={formState.values[eventName] || ""}
                      error={hasError(eventName)}
                      variant="outlined"
                      required
                      fullWidth
                      onChange={handleChange}
                      helperText={
                        hasError(eventName)
                          ? formState.errors[eventName].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12} className={"descriptionBox"}>
                    <Grid
                      className={
                        formState.descriptionError ||
                        formState.discriptionMinLengthError
                          ? classes.descriptionBoxError
                          : classes.descriptionBox
                      }
                    >
                      <Card className={classes.streamoffer}>
                        <InputLabel
                          htmlFor="outlined-stream-card"
                          fullwidth={true.toString()}
                          error={
                            formState.descriptionError ||
                            formState.discriptionMinLengthError
                          }
                        >
                          {genericConstants.DESCRIPTION}
                        </InputLabel>
                        <div className="rdw-root">
                          <Editor
                            editorState={editorState}
                            toolbarClassName="rdw-toolbar"
                            wrapperClassName="rdw-wrapper"
                            editorClassName="rdw-editor"
                            onEditorStateChange={data => {
                              formState.descriptionError = false;
                              formState.discriptionMinLengthError = false;
                              setEditorState(data);
                            }}
                          />
                        </div>
                        {formState.descriptionError ? (
                          <FormHelperText error={true}>
                            Description is required
                          </FormHelperText>
                        ) : null}
                        {formState.discriptionMinLengthError ? (
                          <FormHelperText error={true}>
                            Description length should be less than 320
                            characters
                          </FormHelperText>
                        ) : null}
                      </Card>
                    </Grid>
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={6} xs={12}>
                    <CustomDateTimePicker
                      id={get(EventSchema[dateFrom], "id")}
                      onChange={event => {
                        handleDateChange(dateFrom, event);
                      }}
                      value={formState.values[dateFrom] || null}
                      name={dateFrom}
                      label={get(EventSchema[dateFrom], "label")}
                      placeholder={get(EventSchema[dateFrom], "placeholder")}
                      fullWidth
                      error={hasError(dateFrom)}
                      helperText={
                        hasError(dateFrom)
                          ? formState.errors[dateFrom].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <CustomDateTimePicker
                      id={get(EventSchema[dateTo], "id")}
                      onChange={event => {
                        handleDateChange(dateTo, event);
                      }}
                      value={formState.values[dateTo] || null}
                      name={dateTo}
                      label={get(EventSchema[dateTo], "label")}
                      placeholder={get(EventSchema[dateTo], "placeholder")}
                      fullWidth
                      error={hasError(dateTo)}
                      helperText={
                        hasError(dateTo)
                          ? formState.errors[dateTo].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                </Grid>

                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12}>
                    <TextField
                      label={get(EventSchema[address], "label")}
                      id={get(EventSchema[address], "id")}
                      name={address}
                      placeholder={get(EventSchema[address], "placeholder")}
                      value={formState.values[address] || ""}
                      error={hasError(address)}
                      variant="outlined"
                      required
                      multiline
                      fullWidth
                      onChange={handleChange}
                      helperText={
                        hasError(address)
                          ? formState.errors[address].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                </Grid>
                <Grid
                  container
                  spacing={3}
                  className={classes.MarginBottom}
                ></Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  {!formState.isCollegeAdmin ? (
                    <Grid item md={12} xs={12}>
                      <FormControlLabel
                        control={
                          <Checkbox
                            checked={formState.setAllColleges}
                            onChange={handleCheckBox}
                            name="selectAllColleges"
                            color="yellow"
                          />
                        }
                        label="Select All Colleges"
                      />
                    </Grid>
                  ) : null}

                  <Grid item md={12} xs={12}>
                    {formState.isCollegeAdmin && !formState.isEditEvent ? (
                      <ReadOnlyTextField
                        id={get(EventSchema[college], "id")}
                        label={get(EventSchema[college], "label")}
                        defaultValue={collegeInfo.college.name}
                      />
                    ) : (
                      <Autocomplete
                        id={get(EventSchema[college], "id")}
                        multiple
                        limitTags={2}
                        options={colleges}
                        getOptionLabel={option => option.name}
                        onChange={(event, value) => {
                          handleMultiSelectChange(college, event, value);
                        }}
                        filterSelectedOptions
                        name={college}
                        disabled={
                          (formState.isCollegeAdmin && formState.isEditEvent) ||
                          formState.setAllColleges
                            ? true
                            : false
                        }
                        value={
                          formState.dataToShowForCollegeMultiSelect || null
                        }
                        renderInput={params => (
                          <TextField
                            {...params}
                            error={hasError(college)}
                            helperText={
                              hasError(college)
                                ? formState.errors[college].map(error => {
                                    return error + " ";
                                  })
                                : null
                            }
                            placeholder={get(
                              EventSchema[college],
                              "placeholder"
                            )}
                            value={option => option.id}
                            name={college}
                            key={option => option.id}
                            label={get(EventSchema[college], "label")}
                            variant="outlined"
                          />
                        )}
                      />
                    )}
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id={get(EventSchema[stream], "id")}
                      multiple
                      options={streams}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleMultiSelectChange(stream, event, value);
                      }}
                      disabled={
                        formState.isCollegeAdmin &&
                        formState.isEditEvent &&
                        formState.isCollegeAdminDoesNotHaveEditPreviliges
                          ? true
                          : false
                      }
                      filterSelectedOptions
                      name={stream}
                      value={formState.dataToShowForStreamMultiSelect || null}
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError(stream)}
                          helperText={
                            hasError(stream)
                              ? formState.errors[stream].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                          placeholder={get(EventSchema[stream], "placeholder")}
                          value={option => option.id}
                          name={stream}
                          key={option => option.id}
                          label={get(EventSchema[stream], "label")}
                          variant="outlined"
                        />
                      )}
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id={get(EventSchema[questionSet], "id")}
                      className={classes.root}
                      options={questionSetData}
                      placeholder={get(EventSchema[questionSet], "placeholder")}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete(questionSet, event, value);
                      }}
                      value={
                        questionSetData[
                          questionSetData.findIndex(function (item, i) {
                            return item.id === formState.values[questionSet];
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          label={get(EventSchema[questionSet], "label")}
                          variant="outlined"
                          placeholder={get(
                            EventSchema[questionSet],
                            "placeholder"
                          )}
                          error={hasError(questionSet)}
                          helperText={
                            hasError(questionSet)
                              ? formState.errors[questionSet].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
              </Grid>
              <Divider className={classes.divider} />

              <Grid item xs={12} md={6} xl={3}>
                <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.QUALIFICATIONANDPERCENTAGE}
                      </InputLabel>

                      {formState.dynamicBar.map((val, idx) => {
                        let qualificationId = `qualification-${idx}`,
                          percentageId = `percentage-${idx}`;

                        return (
                          <Card
                            id="outlined-stream-card"
                            fullwidth={true.toString()}
                            className={classes.streamcardcontent}
                            key={idx}
                          >
                            <CardContent>
                              <Grid container spacing={1}>
                                <Grid item xs={5}>
                                  <FormControl
                                    variant="outlined"
                                    fullWidth
                                    className={classes.formControl}
                                  >
                                    <InputLabel
                                      ref={inputLabel}
                                      id="demo-simple-select-outlined-label"
                                    ></InputLabel>
                                    <Autocomplete
                                      id={qualificationId}
                                      options={qualifications}
                                      disabled={
                                        formState.isCollegeAdmin &&
                                        formState.isEditEvent &&
                                        formState.isCollegeAdminDoesNotHaveEditPreviliges
                                          ? true
                                          : false
                                      }
                                      getOptionLabel={option => option.name}
                                      onChange={(event, value) => {
                                        handleChangeForDynamicGrid(
                                          qualification,
                                          event,
                                          value,
                                          val,
                                          true,
                                          false
                                        );
                                      }}
                                      data-id={idx}
                                      name={qualificationId}
                                      value={
                                        qualificationsDataBackup[
                                          qualificationsDataBackup.findIndex(
                                            function (item, i) {
                                              return (
                                                item.value ===
                                                formState.dynamicBar[idx][
                                                  qualification
                                                ]
                                              );
                                            }
                                          )
                                        ] || null
                                      }
                                      renderInput={params => (
                                        <TextField
                                          {...params}
                                          value={option => option.id}
                                          name={qualificationId}
                                          error={
                                            checkErrorInDynamicBar(
                                              qualification,
                                              val
                                            )["error"]
                                          }
                                          helperText={
                                            checkErrorInDynamicBar(
                                              qualification,
                                              val
                                            )["error"]
                                              ? checkErrorInDynamicBar(
                                                  qualification,
                                                  val
                                                )["value"]
                                              : null
                                          }
                                          placeholder={get(
                                            EventSchema[qualification],
                                            "placeholder"
                                          )}
                                          key={option => option.id}
                                          label={get(
                                            EventSchema[qualification],
                                            "label"
                                          )}
                                          variant="outlined"
                                        />
                                      )}
                                    />
                                  </FormControl>
                                </Grid>

                                <Grid item xs={5}>
                                  <TextField
                                    label="Percentage"
                                    name={percentageId}
                                    variant="outlined"
                                    fullWidth
                                    disabled={
                                      formState.isCollegeAdmin &&
                                      formState.isEditEvent &&
                                      formState.isCollegeAdminDoesNotHaveEditPreviliges
                                        ? true
                                        : false
                                    }
                                    data-id={idx}
                                    id={percentageId}
                                    value={
                                      formState.dynamicBar[idx][percentage] ||
                                      ""
                                    }
                                    error={
                                      checkErrorInDynamicBar(percentage, val)[
                                        "error"
                                      ]
                                    }
                                    helperText={
                                      checkErrorInDynamicBar(percentage, val)[
                                        "error"
                                      ]
                                        ? checkErrorInDynamicBar(
                                            percentage,
                                            val
                                          )["value"]
                                        : null
                                    }
                                    placeholder={get(
                                      EventSchema[percentage],
                                      "placeholder"
                                    )}
                                    onChange={event => {
                                      handleChangeForDynamicGrid(
                                        percentage,
                                        event,
                                        null,
                                        val,
                                        false,
                                        true
                                      );
                                    }}
                                  />
                                </Grid>
                                <Grid item xs={2}>
                                  {idx > 0 ? (
                                    <DeleteForeverOutlinedIcon
                                      onClick={e =>
                                        formState.isCollegeAdmin &&
                                        formState.isEditEvent &&
                                        formState.isCollegeAdminDoesNotHaveEditPreviliges
                                          ? null
                                          : clickOnDelete(val, idx)
                                      }
                                      style={
                                        formState.isCollegeAdmin &&
                                        formState.isEditEvent &&
                                        formState.isCollegeAdminDoesNotHaveEditPreviliges
                                          ? { color: "gray", fontSize: "24px" }
                                          : { color: "red", fontSize: "24px" }
                                      }
                                    />
                                  ) : (
                                    ""
                                  )}
                                </Grid>
                              </Grid>
                            </CardContent>
                          </Card>
                        );
                      })}
                      <div className={classes.btnspaceadd}>
                        <Grid item xs={12} md={3} lg={3} xl={3}>
                          <YellowButton
                            type="button"
                            color="primary"
                            variant="contained"
                            disabled={
                              formState.isCollegeAdmin &&
                              formState.isEditEvent &&
                              formState.isCollegeAdminDoesNotHaveEditPreviliges
                                ? true
                                : qualifications.length
                                ? false
                                : true
                            }
                            className={classes.add_more_btn}
                            onClick={e => {
                              addNewRow(e, qualification);
                            }}
                          >
                            {genericConstants.ADD_MORE_TEXT}
                          </YellowButton>
                        </Grid>
                      </div>
                    </Card>
                  </Grid>
                </Grid>
              </Grid>
              <Divider className={classes.divider} />

              <Grid item xs={12} md={6} xl={3}>
                <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.EDUCATIONANDPERCENTAGE}
                      </InputLabel>

                      {formState.dynamicEducationBar.map((val, idx) => {
                        let qualificationId = `education-${idx}`,
                          percentageId = `percentage-${idx}`;

                        return (
                          <Card
                            id="outlined-stream-card"
                            fullwidth={true.toString()}
                            className={classes.streamcardcontent}
                            key={idx}
                          >
                            <CardContent>
                              <Grid container spacing={1}>
                                <Grid item xs={5}>
                                  <FormControl
                                    variant="outlined"
                                    fullWidth
                                    className={classes.formControl}
                                  >
                                    <InputLabel
                                      ref={inputLabel}
                                      id="demo-simple-select-outlined-label"
                                    ></InputLabel>
                                    <Autocomplete
                                      id={qualificationId}
                                      options={educations}
                                      disabled={
                                        formState.isCollegeAdmin &&
                                        formState.isEditEvent &&
                                        formState.isCollegeAdminDoesNotHaveEditPreviliges
                                          ? true
                                          : false
                                      }
                                      getOptionLabel={option => option.value}
                                      onChange={(event, value) => {
                                        handleChangeForDynamicGrid(
                                          education,
                                          event,
                                          value,
                                          val,
                                          true,
                                          false
                                        );
                                      }}
                                      data-id={idx}
                                      name={qualificationId}
                                      value={
                                        educationsDataBackup[
                                          educationsDataBackup.findIndex(
                                            function (item, i) {
                                              return (
                                                item.value ===
                                                formState.dynamicEducationBar[
                                                  idx
                                                ][education]
                                              );
                                            }
                                          )
                                        ] || null
                                      }
                                      renderInput={params => (
                                        <TextField
                                          {...params}
                                          value={option => option.id}
                                          name={qualificationId}
                                          error={
                                            checkErrorInDynamicBar(
                                              education,
                                              val
                                            )["error"]
                                          }
                                          helperText={
                                            checkErrorInDynamicBar(
                                              education,
                                              val
                                            )["error"]
                                              ? checkErrorInDynamicBar(
                                                  education,
                                                  val
                                                )["value"]
                                              : null
                                          }
                                          placeholder={get(
                                            EventSchema[education],
                                            "placeholder"
                                          )}
                                          key={option => option.id}
                                          label={get(
                                            EventSchema[education],
                                            "label"
                                          )}
                                          variant="outlined"
                                        />
                                      )}
                                    />
                                  </FormControl>
                                </Grid>

                                <Grid item xs={5}>
                                  <TextField
                                    label="Percentage"
                                    name={percentageId}
                                    variant="outlined"
                                    fullWidth
                                    disabled={
                                      formState.isCollegeAdmin &&
                                      formState.isEditEvent &&
                                      formState.isCollegeAdminDoesNotHaveEditPreviliges
                                        ? true
                                        : false
                                    }
                                    data-id={idx}
                                    id={percentageId}
                                    value={
                                      formState.dynamicEducationBar[idx][
                                        educationpercentage
                                      ] || ""
                                    }
                                    error={
                                      checkErrorInDynamicBar(
                                        educationpercentage,
                                        val
                                      )["error"]
                                    }
                                    helperText={
                                      checkErrorInDynamicBar(
                                        educationpercentage,
                                        val
                                      )["error"]
                                        ? checkErrorInDynamicBar(
                                            educationpercentage,
                                            val
                                          )["value"]
                                        : null
                                    }
                                    placeholder={get(
                                      EventSchema[educationpercentage],
                                      "placeholder"
                                    )}
                                    onChange={event => {
                                      handleChangeForDynamicGrid(
                                        educationpercentage,
                                        event,
                                        null,
                                        val,
                                        false,
                                        true
                                      );
                                    }}
                                  />
                                </Grid>
                                <Grid item xs={2}>
                                  {idx > 0 ? (
                                    <DeleteForeverOutlinedIcon
                                      onClick={e =>
                                        formState.isCollegeAdmin &&
                                        formState.isEditEvent &&
                                        formState.isCollegeAdminDoesNotHaveEditPreviliges
                                          ? null
                                          : clickOnDelete(val, idx)
                                      }
                                      style={
                                        formState.isCollegeAdmin &&
                                        formState.isEditEvent &&
                                        formState.isCollegeAdminDoesNotHaveEditPreviliges
                                          ? { color: "gray", fontSize: "24px" }
                                          : { color: "red", fontSize: "24px" }
                                      }
                                    />
                                  ) : (
                                    ""
                                  )}
                                </Grid>
                              </Grid>
                            </CardContent>
                          </Card>
                        );
                      })}
                      <div className={classes.btnspaceadd}>
                        <Grid item xs={12} md={3} lg={3} xl={3}>
                          <YellowButton
                            type="button"
                            color="primary"
                            disabled={
                              formState.isCollegeAdmin &&
                              formState.isEditEvent &&
                              formState.isCollegeAdminDoesNotHaveEditPreviliges
                                ? true
                                : educations.length
                                ? false
                                : true
                            }
                            variant="contained"
                            className={classes.add_more_btn}
                            onClick={e => {
                              addNewRow(e, education);
                            }}
                          >
                            {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
                          type="submit"
                          color="primary"
                          variant="contained"
                          disabled={
                            formState.isCollegeAdmin &&
                            formState.isEditEvent &&
                            formState.isCollegeAdminDoesNotHaveEditPreviliges
                              ? true
                              : false
                          }
                        >
                          {genericConstants.SAVE_BUTTON_TEXT}
                        </YellowButton>
                      </Grid>
                      <Grid item md={2} xs={12}>
                        <GrayButton
                          type="button"
                          color="primary"
                          variant="contained"
                          to={routeConstants.MANAGE_EVENT}
                        >
                          {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 #20
Source File: AddEditStudent.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditStudent = props => {
  let history = useHistory();
  const [user, setUser] = useState({
    firstName: "",
    middleName: "",
    lastName: "",
    fatherFulltName: "",
    motherFullName: "",
    address: "",
    district: null,
    state: null,
    email: "",
    contactNumber: "",
    userName: "",
    password: "",
    gender: "",
    physicallyHandicapped: null,
    college: null,
    stream: null,
    currentAcademicYear: null,
    collegeRollNumber: null,
    otp: "",
    futureAspirations: null
  });

  const [formState, setFormState] = useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    isDateOfBirthPresent: true,
    isdateOfBirthValid: true,
    isSuccess: false,
    showPassword: false,
    editStudent: props.location.editStudent
      ? props.location.editStudent
      : false,
    dataForEdit: props.location.dataForEdit
      ? props.location.dataForEdit
      : false,
    counter: 0,
    flag: 0,
    files: null,
    previewFile: {},
    showPreview: false,
    showEditPreview: props.location.editStudent
      ? props.location.dataForEdit.profile_photo
        ? true
        : false
      : false,
    showNoImage: props.location.editStudent
      ? false
      : props.location.editStudent,
    addressSameAsLocal: false,
    addresses: genericConstants.ADDRESSES
  });

  const [selectedDate, setSelectedDate] = useState(
    props.forTesting ? new Date("1999-03-25") : null
  );

  const genderlist = [
    { name: "Male", id: "male" },
    { name: "Female", id: "female" },
    { name: "Other", id: "other" }
  ];
  const [futureAspirationsList, setFutureAspirationsList] = useState(
    props.mockFutureAspiration ? props.mockFutureAspiration : []
  );
  const physicallyHandicappedlist = [
    { name: "Yes", id: true },
    { name: "No", id: false }
  ];
  const [isFailed, setIsFailed] = useState(false);
  const [backDrop, setBackDrop] = useState(false);

  const classes = useStyles();
  const [statelist, setstatelist] = useState(
    props.mockStateList ? props.mockStateList : []
  );
  const [districtlist, setdistrictlist] = useState(
    props.mockdistrictList ? props.mockdistrictList : []
  );
  const [collegelist, setcollegelist] = useState(
    props.mockCollegeData ? props.mockCollegeData : []
  );
  const [streamlist, setstreamlist] = useState(
    props.streamsList ? props.streamsList : []
  );
  const [collegeStreamList, setCollegeStreamList] = useState(
    props.mockCollegeStreamList ? props.mockCollegeStreamList : []
  );
  const [stream, setStream] = useState(null);

  const [validateAddress, setValidateAddress] = useState([]);

  useEffect(() => {
    if (
      props.location.pathname !== "/registration" &&
      props.location &&
      !props.location.dataForEdit
    ) {
      history.push({
        pathname: routeConstants.VIEW_PROFILE
      });
    }
    getStates();
    getFutureAspirations();
    getDistrict();
    getColleges();
    getStreams();
    // setLabelWidth(inputLabel.current.offsetWidth);
  }, []);

  useEffect(() => {
    if (
      formState.values.hasOwnProperty("college") &&
      formState.values["college"] &&
      collegelist.length > 0
    ) {
      const college = collegelist.find(
        college => college.id == formState.values["college"]
      );

      const collegeStreamIds = college.stream_strength.map(s => s.stream.id);
      const list = streamlist.filter(stream => {
        if (_.includes(collegeStreamIds, stream.id)) {
          return stream;
        }
      });

      setCollegeStreamList(list);
    }
  }, [formState.values["college"]]);

  useEffect(() => {
    if (!formState.editStudent) {
      if (formState.addressSameAsLocal) {
        const address = formState.addresses.find(
          addr => addr.address_type == "Temporary"
        );
        const copyAddresses = formState.addresses.map(addr => {
          if (addr.address_type == "Permanent") {
            return { ...address, address_type: "Permanent" };
          } else {
            return addr;
          }
        });

        setFormState(formState => ({
          ...formState,
          addresses: copyAddresses
        }));
      } else {
        const address = genericConstants.ADDRESSES.find(
          addr => addr.address_type == "Permanent"
        );

        const resetPermanentAddress = formState.addresses.map(addr => {
          if (addr.address_type == "Permanent") {
            return address;
          } else {
            return addr;
          }
        });
        setFormState(formState => ({
          ...formState,
          addresses: resetPermanentAddress
        }));
      }
    }
  }, [formState.addressSameAsLocal]);

  if (formState.dataForEdit && !formState.counter) {
    if (props.location["dataForEdit"]) {
      if (props.location["dataForEdit"]["first_name"]) {
        formState.values["firstname"] =
          props.location["dataForEdit"]["first_name"];
      }
      if (props.location["dataForEdit"]["middle_name"]) {
        formState.values["middlename"] =
          props.location["dataForEdit"]["middle_name"];
      }
      if (props.location["dataForEdit"]["last_name"]) {
        formState.values["lastname"] =
          props.location["dataForEdit"]["last_name"];
      }
      if (
        props.location["dataForEdit"]["contact"] &&
        props.location["dataForEdit"]["contact"]["user"] &&
        props.location["dataForEdit"]["contact"]["user"]["email"]
      ) {
        formState.values["email"] =
          props.location["dataForEdit"]["contact"]["user"]["email"];
      }
      if (
        props.location["dataForEdit"]["contact"] &&
        props.location["dataForEdit"]["contact"]["phone"]
      ) {
        formState.values["contact"] =
          props.location["dataForEdit"]["contact"]["phone"];
      }
      if (
        props.location["dataForEdit"]["contact"] &&
        props.location["dataForEdit"]["contact"]["user"] &&
        props.location["dataForEdit"]["contact"]["user"]["username"]
      ) {
        formState.values["username"] =
          props.location["dataForEdit"]["contact"]["user"]["username"];
      }
      if (
        props.location["dataForEdit"]["organization"] &&
        props.location["dataForEdit"]["organization"]["id"]
      ) {
        formState.values["college"] =
          props.location["dataForEdit"]["organization"]["id"];
      }
      // if (
      //   props.location["dataForEdit"]["contact"] &&
      //   props.location["dataForEdit"]["contact"]["state"]
      // ) {
      //   formState.values["state"] =
      //     props.location["dataForEdit"]["contact"]["state"]["id"];
      // }
      if (
        props.location["dataForEdit"]["stream"] &&
        props.location["dataForEdit"]["stream"]["id"]
      ) {
        formState.values["stream"] = props.location["dataForEdit"]["stream"];
      }

      // if (
      //   props.location["dataForEdit"]["contact"]["district"] &&
      //   props.location["dataForEdit"]["contact"]["district"]["id"]
      // ) {
      //   formState.values["district"] =
      //     props.location["dataForEdit"]["contact"]["district"]["id"];
      // }

      if (props.location["dataForEdit"]["father_full_name"]) {
        formState.values["fatherFullName"] =
          props.location["dataForEdit"]["father_full_name"];
      }
      if (props.location["dataForEdit"]["mother_full_name"]) {
        formState.values["motherFullName"] =
          props.location["dataForEdit"]["mother_full_name"];
      }
      // if (props.location["dataForEdit"]["contact"]["address_1"]) {
      //   formState.values["address"] =
      //     props.location["dataForEdit"]["contact"]["address_1"];
      // }
      if (props.location["dataForEdit"]["gender"]) {
        formState.values["gender"] = props.location["dataForEdit"]["gender"];
      }

      if (props.location["dataForEdit"]["roll_number"]) {
        formState.values["rollnumber"] =
          props.location["dataForEdit"]["roll_number"];
      }
      if (props.location["dataForEdit"]["future_aspirations"]) {
        formState.values["futureAspirations"] =
          props.location["dataForEdit"]["future_aspirations"];
        formState["futureAspirations"] = props.location["dataForEdit"][
          "future_aspirations"
        ].map(value => value.id);
      }

      if (props.location["dataForEdit"]) {
        formState.values["physicallyHandicapped"] =
          props.location["dataForEdit"]["is_physically_challenged"];
      }
      if (
        props.location["dataForEdit"]["organization"] &&
        props.location["dataForEdit"]["organization"]["id"]
      ) {
        formState.values["college"] =
          props.location["dataForEdit"]["organization"]["id"];
      }
      if (props.location["dataForEdit"]["date_of_birth"]) {
        setSelectedDate(
          new Date(props.location["dataForEdit"]["date_of_birth"])
        );
      }
      if (
        props.location["dataForEdit"]["profile_photo"] &&
        props.location["dataForEdit"]["profile_photo"]["id"]
      ) {
        formState.previewFile = props.location["dataForEdit"]["profile_photo"];
        //      formState.values["files"] =
        //        props.location["dataForEdit"]["upload_logo"]["name"];
      }

      if (
        props.location["dataForEdit"]["contact"] &&
        props.location["dataForEdit"]["contact"]["addresses"] &&
        props.location["dataForEdit"]["contact"]["addresses"].length > 0
      ) {
        formState.addresses =
          props.location["dataForEdit"]["contact"]["addresses"];
      } else {
        formState.addresses = genericConstants.ADDRESSES;
      }
    }
    formState.counter += 1;
  }

  if (props.location.state && !formState.counter) {
    if (props.location.state.contactNumber && props.location.state.otp) {
      formState.values["contact"] = props.location.state.contactNumber;
      formState.values["otp"] = props.location.state.otp;
      formState.values["username"] = props.location.state.contactNumber;
    }
    formState.counter += 1;
  }

  const handleSubmit = event => {
    event.preventDefault();
    const isValidAddress = validateAddresses();
    setBackDrop(true);
    let schema;
    if (formState.editStudent) {
      schema = Object.assign(
        {},
        _.omit(registrationSchema, ["password", "otp"])
      );
    } else {
      schema = registrationSchema;
    }
    let isValid = false;
    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);

      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
      );
      formState.errors = formUtilities.setErrors(formState.values, schema);
    }

    if (selectedDate === null) {
      formState.isDateOfBirthPresent = false;
    } else {
      formState.isDateOfBirthPresent = true;
      if (props.forTesting) {
        formState.isdateOfBirthValid = true;
      } else {
        formState.isdateOfBirthValid = formUtilities.validateDateOfBirth(
          selectedDate
        );
      }
    }

    console.log(formState);
    if (
      isValid &&
      formState.isDateOfBirthPresent &&
      formState.isdateOfBirthValid &&
      isValidAddress
    ) {
      /** CALL POST FUNCTION */
      postStudentData();

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

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

  const postStudentData = () => {
    let postData;
    const addresses = formState.addresses;
    if (formState.editStudent) {
      postData = databaseUtilities.editStudent(
        formState.values["firstname"],
        formState.values["middlename"],
        formState.values["lastname"],
        formState.values["fatherFullName"],
        formState.values["motherFullName"],
        formState.values["email"],
        formState.values["contact"],
        formState.values["contact"],
        formState.values["gender"],
        selectedDate.getFullYear() +
          "-" +
          (selectedDate.getMonth() + 1) +
          "-" +
          selectedDate.getDate(),
        formState.values["physicallyHandicapped"] !== undefined
          ? formState.values["physicallyHandicapped"]
          : null,
        formState.values["college"],
        formState.values["stream"].id,
        formState.values["rollnumber"],
        formState.dataForEdit.id,
        formState.values["futureAspirations"]
          ? formState["futureAspirations"]
          : null,
        formState.files,
        null,
        addresses
      );
      let EDIT_STUDENT_URL =
        strapiApiConstants.STRAPI_DB_URL +
        strapiApiConstants.STRAPI_CONTACT_URL;
      let EDIT_URL = strapiApiConstants.STRAPI_EDIT_STUDENT;
      serviceProvider
        .serviceProviderForPutRequest(
          EDIT_STUDENT_URL,
          formState.dataForEdit.contact.id,
          postData,
          EDIT_URL
        )
        .then(response => {
          if (auth.getUserInfo().role.name === roleConstants.STUDENT) {
            commonUtilities.updateUser();
          }
          let studentName =
            props.location["dataForEdit"]["first_name"] +
            " " +
            props.location["dataForEdit"]["middlename"] +
            " " +
            props.location["dataForEdit"]["last_name"];
          if (
            auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
            auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
          ) {
            history.push({
              pathname: routeConstants.MANAGE_STUDENT,
              fromeditStudent: true,
              isDataEdited: true,
              editedStudentName: studentName
            });
          } else {
            if (formState.flag === 1) {
              history.push({
                pathname: routeConstants.VIEW_EDUCATION
              });
            } else {
              history.push({
                pathname: routeConstants.VIEW_PROFILE,
                success: true
              });
            }
          }

          setBackDrop(false);
        })
        .catch(err => {
          setIsFailed(true);
          let studentName =
            props.location["dataForEdit"]["first_name"] +
            " " +
            props.location["dataForEdit"]["middlename"] +
            " " +
            props.location["dataForEdit"]["last_name"];
          if (
            auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
            auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
          ) {
            history.push({
              pathname: routeConstants.MANAGE_STUDENT,
              fromeditStudent: true,
              isDataEdited: true,
              editedStudentName: studentName
            });
          } else {
            history.push({
              pathname: routeConstants.VIEW_PROFILE,
              success: false
            });
          }
          setBackDrop(false);
        });
    } else {
      postData = databaseUtilities.addStudent(
        formState.values["firstname"],
        formState.values["middlename"],
        formState.values["lastname"],
        formState.values["fatherFullName"],
        formState.values["motherFullName"],
        formState.values["email"],
        formState.values["contact"],
        formState.values["contact"],
        formState.values["password"],
        formState.values["gender"],
        selectedDate.getFullYear() +
          "-" +
          (selectedDate.getMonth() + 1) +
          "-" +
          selectedDate.getDate(),
        formState.values["physicallyHandicapped"],
        formState.values["college"],
        formState.values["stream"].id,
        formState.values["rollnumber"],
        formState.values.otp,
        formState.files,
        formState.values["futureAspirations"]
          ? formState["futureAspirations"]
          : null,
        true,
        addresses
      );

      axios
        .post(
          strapiApiConstants.STRAPI_DB_URL +
            strapiApiConstants.STRAPI_CREATE_USERS,
          postData
        )
        .then(response => {
          if (auth.getToken() === null || auth.getUserInfo() === null) {
            history.push(routeConstants.REGISTERED);
          } else {
            if (
              auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
              auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
            ) {
              history.push(routeConstants.MANAGE_STUDENT);
            }
          }
          setBackDrop(false);
        })
        .catch(err => {
          console.log(err);
          setBackDrop(false);
        });
    }
  };

  const getFutureAspirations = () => {
    axios
      .get(
        strapiApiConstants.STRAPI_DB_URL +
          strapiApiConstants.STRAPI_FUTURE_ASPIRATIONS +
          "?pageSize=-1"
      )
      .then(res => {
        const list = res.data.result.map(({ id, name }) => ({ id, name }));
        setFutureAspirationsList(list);
        if (formState.dataForEdit) {
          const id = props.location["dataForEdit"]["future_aspirations"].map(
            value => value.id
          );
          const ids = list.filter(value => {
            if (includes(id, value.id)) {
              return value;
            }
          });
          formState.values["futureAspirations"] = ids;
        }
      });
  };
  const getColleges = () => {
    axios
      .get(
        strapiApiConstants.STRAPI_DB_URL +
          strapiApiConstants.STRAPI_COLLEGES +
          "?pageSize=-1"
      )
      .then(res => {
        setcollegelist(
          res.data.result.map(({ id, name, stream_strength }) => ({
            id,
            name,
            stream_strength
          }))
        );
      });
  };

  const getStreams = () => {
    axios
      .get(
        strapiApiConstants.STRAPI_DB_URL +
          strapiApiConstants.STRAPI_STREAMS +
          "?pageSize=-1"
      )
      .then(res => {
        const list = res.data.map(({ id, name }) => ({
          id,
          name
        }));
        setstreamlist(list);

        if (formState.dataForEdit && props.location["dataForEdit"]["stream"]) {
          const selectedStream = list.find(
            stream => stream.id == props.location["dataForEdit"]["stream"]["id"]
          );

          setStream(selectedStream);
        }
      });
  };

  const getStates = () => {
    axios
      .get(
        strapiApiConstants.STRAPI_DB_URL +
          strapiApiConstants.STRAPI_STATES +
          "?pageSize=-1"
      )
      .then(res => {
        setstatelist(res.data.result.map(({ id, name }) => ({ id, name })));
      });
  };

  const getDistrict = () => {
    axios
      .get(
        strapiApiConstants.STRAPI_DB_URL +
          strapiApiConstants.STRAPI_DISTRICTS +
          "?pageSize=-1"
      )
      .then(res => {
        setdistrictlist(
          res.data.result.map(({ id, name, state }) => ({
            id,
            name,
            state: state.id
          }))
        );
      });
  };

  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];
    }
  };

  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
        }
      }));
      if (formState.errors.hasOwnProperty(eventName)) {
        delete formState.errors[eventName];
      }
    } else {
      if (eventName === "state") {
        delete formState.values["district"];
      }
      delete formState.values[eventName];
      setFormState(formState => ({
        ...formState
      }));
    }
  };

  const handleStreamChange = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (value !== null) {
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          [eventName]: value
        },
        touched: {
          ...formState.touched,
          [eventName]: true
        }
      }));
      if (formState.errors.hasOwnProperty(eventName)) {
        delete formState.errors[eventName];
      }
      setStream(value);
    } else {
      if (eventName === "state") {
        delete formState.values["district"];
      }
      delete formState.values[eventName];
      setFormState(formState => ({
        ...formState
      }));
    }
  };

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

  const handleFutureAspirationChange = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (value !== null) {
      const id = value.map(value => value.id).filter(c => c);
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          [eventName]: value
        },
        touched: {
          ...formState.touched,
          [eventName]: true
        },
        futureAspirations: id
      }));
      if (formState.errors.hasOwnProperty(eventName)) {
        delete formState.errors[eventName];
      }
    }
  };

  const handleChangefile = e => {
    e.persist();
    setFormState(formState => ({
      ...formState,

      values: {
        ...formState.values,
        [e.target.name]: e.target.files[0].name
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      },
      files: e.target.files[0],
      previewFile: URL.createObjectURL(e.target.files[0]),
      showPreview: true,
      showEditPreview: false,
      showNoImage: false
    }));
    if (formState.errors.hasOwnProperty(e.target.name)) {
      delete formState.errors[e.target.name];
    }
  };

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

  const changeContactNumber = () => {
    history.push(routeConstants.CHANGE_CONTACT_NUMBER, {
      contactNumber: formState.values["contact"]
    });
  };

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

  const handleAddressChange = (idx, e, type) => {
    e.persist();
    console.log(e.target.value);

    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;
  };

  console.log(formState.addresses);
  console.log(validateAddress);
  return (
    // <Layout>
    <Grid>
      <Grid item xs={12} className={classes.title}>
        {formState.editStudent ? null : (
          <Typography variant="h4" gutterBottom>
            {genericConstants.STUDENT_REGISTRATION}
          </Typography>
        )}

        {isFailed && formState.editStudent ? (
          <Collapse in={isFailed}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setIsFailed(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {genericConstants.ALERT_ERROR_DATA_EDITED_MESSAGE}
            </Alert>
          </Collapse>
        ) : null}
        {isFailed && !formState.editStudent ? (
          <Collapse in={isFailed}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setIsFailed(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {genericConstants.ALERT_ERROR_DATA_ADDED_MESSAGE}
            </Alert>
          </Collapse>
        ) : null}
      </Grid>
      <Card>
        <form autoComplete="off" noValidate>
          <CardContent>
            <Grid item xs={12} md={6} xl={3}>
              <Grid container className={classes.formgridInputFile}>
                <Grid item md={10} xs={12}>
                  <div className={classes.imageDiv}>
                    {formState.showPreview ? (
                      <Img
                        alt="abc"
                        loader={<Spinner />}
                        className={classes.UploadImage}
                        src={formState.previewFile}
                      />
                    ) : null}
                    {!formState.showPreview && !formState.showEditPreview ? (
                      <div className={classes.DefaultNoImage}></div>
                    ) : null}
                    {/* {formState.showEditPreview&&formState.dataForEdit.upload_logo===null? <div class={classes.DefaultNoImage}></div>:null} */}
                    {formState.showEditPreview &&
                    formState.dataForEdit["profile_photo"] !== null &&
                    formState.dataForEdit["profile_photo"] !== undefined &&
                    formState.dataForEdit["profile_photo"] !== {} ? (
                      <Img
                        src={
                          strapiApiConstants.STRAPI_DB_URL_WITHOUT_HASH +
                          formState.dataForEdit["profile_photo"]["url"]
                        }
                        loader={<Spinner />}
                        className={classes.UploadImage}
                      />
                    ) : null}
                    {formState.showNoImage ? (
                      <Img
                        src="/images/noImage.png"
                        loader={<Spinner />}
                        className={classes.UploadImage}
                      />
                    ) : null}
                  </div>
                </Grid>
              </Grid>
              <Grid container className={classes.MarginBottom}>
                <Grid item md={10} xs={12}>
                  <TextField
                    fullWidth
                    id="files"
                    margin="normal"
                    name="files"
                    placeholder="Upload Logo"
                    onChange={handleChangefile}
                    required
                    type="file"
                    inputProps={{ accept: "image/*" }}
                    //value={formState.values["files"] || ""}
                    error={hasError("files")}
                    helperText={
                      hasError("files")
                        ? formState.errors["files"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    variant="outlined"
                    className={classes.inputFile}
                  />
                  <label htmlFor={get(registrationSchema["files"], "id")}>
                    <Button
                      variant="contained"
                      color="primary"
                      component="span"
                      fullWidth
                      className={classes.InputFileButton}
                      startIcon={<AddOutlinedIcon />}
                    >
                      ADD PROFILE PHOTO
                    </Button>
                  </label>
                </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
                    id="firstName"
                    label="First Name"
                    name="firstname"
                    value={formState.values["firstname"] || ""}
                    variant="outlined"
                    required
                    fullWidth
                    onChange={handleChange}
                    error={hasError("firstname")}
                    helperText={
                      hasError("firstname")
                        ? formState.errors["firstname"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                </Grid>
              </Grid>
              <Grid container spacing={3} className={classes.MarginBottom}>
                <Grid item md={6} xs={12}>
                  <TextField
                    id="middlename"
                    label="Middle Name"
                    name="middlename"
                    value={formState.values["middlename"]}
                    variant="outlined"
                    error={hasError("middlename")}
                    fullWidth
                    onChange={handleChange}
                    helperText={
                      hasError("middlename")
                        ? formState.errors["middlename"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <TextField
                    id="lastname"
                    label="Last Name"
                    name="lastname"
                    value={formState.values["lastname"]}
                    variant="outlined"
                    required
                    fullWidth
                    error={hasError("lastname")}
                    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={6} xs={12}>
                  <TextField
                    id="fatherFullName"
                    label="Father's Full Name"
                    name="fatherFullName"
                    value={formState.values["fatherFullName"] || ""}
                    variant="outlined"
                    required
                    fullWidth
                    onChange={handleChange}
                    error={hasError("fatherFullName")}
                    helperText={
                      hasError("fatherFullName")
                        ? formState.errors["fatherFullName"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <TextField
                    id="motherFullName"
                    label="Mother's Full Name"
                    name="motherFullName"
                    value={formState.values["motherFullName"] || ""}
                    variant="outlined"
                    required
                    fullWidth
                    onChange={handleChange}
                    error={hasError("motherFullName")}
                    helperText={
                      hasError("motherFullName")
                        ? formState.errors["motherFullName"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                </Grid>
              </Grid>
              <Divider className={classes.divider} />
              <Grid container spacing={3} className={classes.MarginBottom}>
                {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"
                              : "Permanent Address"}
                          </InputLabel>
                          <Grid
                            container
                            spacing={3}
                            className={classes.MarginBottom}
                          >
                            <Grid
                              item
                              md={12}
                              xs={12}
                              style={{ marginTop: "8px" }}
                            >
                              <TextField
                                label="Address"
                                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="combo-box-demo"
                                className={classes.root}
                                options={statelist}
                                getOptionLabel={option => option.name}
                                onChange={(event, value) => {
                                  handleStateAndDistrictChange(
                                    "state",
                                    value,
                                    idx
                                  );
                                }}
                                value={
                                  statelist[
                                    statelist.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}>
                              <Autocomplete
                                id="combo-box-demo"
                                className={classes.root}
                                options={districtlist.filter(
                                  district =>
                                    district.state ===
                                    formState.addresses[idx].state
                                )}
                                getOptionLabel={option => option.name}
                                onChange={(event, value) => {
                                  handleStateAndDistrictChange(
                                    "district",
                                    value,
                                    idx
                                  );
                                }}
                                value={
                                  districtlist[
                                    districtlist.findIndex(function (item, i) {
                                      return (
                                        item.id ===
                                        formState.addresses[idx].district
                                      );
                                    })
                                  ] || null
                                }
                                renderInput={params => (
                                  <TextField
                                    {...params}
                                    label="District"
                                    variant="outlined"
                                    name="tester"
                                    error={
                                      (validateAddress[idx] &&
                                        validateAddress[idx]["district"][
                                          "error"
                                        ]) ||
                                      false
                                    }
                                    helperText={
                                      (validateAddress[idx] &&
                                        validateAddress[idx]["district"][
                                          "message"
                                        ]) ||
                                      null
                                    }
                                  />
                                )}
                              />
                            </Grid>
                            <Grid item md={6} xs={12}>
                              <TextField
                                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
                                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>
                          <Grid item md={12} xs={12}>
                            {!formState.editStudent &&
                            addr.address_type == "Temporary" ? (
                              <FormControlLabel
                                control={
                                  <Checkbox
                                    checked={formState.addressSameAsLocal}
                                    onChange={event => {
                                      setFormState(formState => ({
                                        ...formState,
                                        addressSameAsLocal: event.target.checked
                                      }));
                                    }}
                                    name="addressSameAsLocal"
                                    color="primary"
                                  />
                                }
                                label="Permanent Address same as local Address?"
                              />
                            ) : null}
                          </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={6} xs={12}>
                  <TextField
                    id="contact"
                    label="Contact Number"
                    name="contact"
                    value={formState.values["contact"] || ""}
                    variant="outlined"
                    required
                    fullWidth
                    readOnly
                    disabled
                    error={hasError("contact")}
                    helperText={
                      hasError("contact")
                        ? formState.errors["contact"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                  {formState.editStudent ? (
                    <Link
                      href="javascript:void(0);"
                      variant="body2"
                      className={classes.linkColor}
                      onClick={changeContactNumber}
                    >
                      {authPageConstants.CHANGE_CONTACT_NUMBER}
                    </Link>
                  ) : null}
                </Grid>

                <Grid
                  item
                  md={6}
                  xs={12}
                  style={formState.editStudent ? { marginTop: "-22px" } : null}
                >
                  <InlineDatePicker
                    // variant="inline"
                    format="dd/MM/yyyy"
                    margin="normal"
                    id="date-picker-inline"
                    label="Date of Birth"
                    value={selectedDate}
                    className={classes.date}
                    onChange={date => {
                      formState.isDateOfBirthPresent = true;
                      formState.isdateOfBirthValid = true;
                      setSelectedDate(date);
                    }}
                    error={
                      !formState.isDateOfBirthPresent ||
                      !formState.isdateOfBirthValid
                    }
                    helperText={
                      !formState.isDateOfBirthPresent
                        ? "Date of Birth is required"
                        : !formState.isdateOfBirthValid
                        ? "Date of birth cannot be greater than current date"
                        : null
                    }
                    KeyboardButtonProps={{
                      "aria-label": "change date"
                    }}
                  />
                </Grid>
              </Grid>
              <Grid container spacing={3} className={classes.formgrid}>
                <Grid item md={6} xs={12}>
                  <Autocomplete
                    id="gender-filter"
                    className={classes.root}
                    options={genderlist}
                    getOptionLabel={option => option.name}
                    onChange={(event, value) => {
                      handleChangeAutoComplete("gender", event, value);
                    }}
                    value={
                      genderlist[
                        genderlist.findIndex(function (item, i) {
                          return item.id === formState.values.gender;
                        })
                      ] || null
                    }
                    renderInput={params => (
                      <TextField
                        {...params}
                        error={hasError("gender")}
                        label="Gender"
                        required
                        variant="outlined"
                        name="tester"
                        helperText={
                          hasError("gender")
                            ? formState.errors["gender"].map(error => {
                                return error + " ";
                              })
                            : null
                        }
                      />
                    )}
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <TextField
                    id="email"
                    label="Email-Id"
                    name="email"
                    value={formState.values["email"] || ""}
                    variant="outlined"
                    required
                    fullWidth
                    onChange={handleChange}
                    error={hasError("email")}
                    helperText={
                      hasError("email")
                        ? formState.errors["email"].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}>
                  <Autocomplete
                    id="college-filter"
                    className={classes.root}
                    options={collegelist}
                    disabled={formState.editStudent ? true : false}
                    getOptionLabel={option => option.name}
                    onChange={(event, value) => {
                      handleChangeAutoComplete("college", event, value);
                    }}
                    value={
                      collegelist[
                        collegelist.findIndex(function (item, i) {
                          return item.id === formState.values.college;
                        })
                      ] || null
                    }
                    renderInput={params => (
                      <TextField
                        {...params}
                        error={hasError("college")}
                        label="College"
                        variant="outlined"
                        required
                        name="tester"
                        helperText={
                          hasError("college")
                            ? formState.errors["college"].map(error => {
                                return error + " ";
                              })
                            : null
                        }
                      />
                    )}
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <Autocomplete
                    id="stream-filter"
                    className={classes.root}
                    options={collegeStreamList || []}
                    disabled={formState.editStudent ? true : false}
                    getOptionLabel={option => option.name}
                    onChange={(event, value) => {
                      handleStreamChange("stream", event, value);
                    }}
                    value={stream || null}
                    renderInput={params => (
                      <TextField
                        {...params}
                        error={hasError("stream")}
                        label="Stream"
                        variant="outlined"
                        name="tester"
                        helperText={
                          hasError("stream")
                            ? formState.errors["stream"].map(error => {
                                return error + " ";
                              })
                            : null
                        }
                      />
                    )}
                  />
                </Grid>
              </Grid>
              <Grid container spacing={3} className={classes.formgrid}>
                <Grid item md={6} xs={12}>
                  <TextField
                    id="rollnumber"
                    label="Enrollment Number "
                    name="rollnumber"
                    value={formState.values["rollnumber"] || ""}
                    variant="outlined"
                    fullWidth
                    required
                    onChange={handleChange}
                    error={hasError("rollnumber")}
                    helperText={
                      hasError("rollnumber")
                        ? formState.errors["rollnumber"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <Autocomplete
                    id="physically-handicapped-id"
                    className={classes.root}
                    options={physicallyHandicappedlist}
                    getOptionLabel={option => option.name}
                    onChange={(event, value) => {
                      handleChangeAutoComplete(
                        "physicallyHandicapped",
                        event,
                        value
                      );
                    }}
                    value={
                      physicallyHandicappedlist[
                        physicallyHandicappedlist.findIndex(function (item, i) {
                          return (
                            item.id === formState.values.physicallyHandicapped
                          );
                        })
                      ] || null
                    }
                    renderInput={params => (
                      <TextField
                        {...params}
                        error={hasError("physicallyHandicapped")}
                        label="Physically Handicapped"
                        variant="outlined"
                        name="tester"
                        helperText={
                          hasError("physicallyHandicapped")
                            ? formState.errors["physicallyHandicapped"].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.MarginBottom}>
                <Grid item md={12} xs={12}>
                  <Autocomplete
                    multiple={true}
                    id="futureAspirations"
                    className={classes.root}
                    options={futureAspirationsList}
                    getOptionLabel={option => option.name}
                    onChange={(event, value) => {
                      handleFutureAspirationChange(
                        "futureAspirations",
                        event,
                        value
                      );
                    }}
                    value={formState.values.futureAspirations}
                    filterSelectedOptions={true}
                    renderInput={params => (
                      <TextField
                        {...params}
                        error={hasError("futureAspirations")}
                        label="Future Aspirations"
                        variant="outlined"
                        name="tester"
                        helperText={
                          hasError("futureAspirations")
                            ? formState.errors["futureAspirations"].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}>
                  <TextField
                    id="username"
                    label="Username"
                    name="username"
                    value={formState.values["username"] || ""}
                    variant="outlined"
                    required
                    fullWidth
                    disabled
                    readOnly
                    error={hasError("username")}
                    helperText={
                      hasError("username")
                        ? formState.errors["username"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                </Grid>

                {formState.editStudent ? null : (
                  <Grid item md={6} xs={12}>
                    <FormControl fullWidth variant="outlined">
                      <InputLabel
                        htmlFor="outlined-adornment-password"
                        fullWidth
                        error={hasError("password")}
                      >
                        Password
                      </InputLabel>
                      <OutlinedInput
                        id="password"
                        label="Password"
                        name="password"
                        type={formState.showPassword ? "text" : "password"}
                        value={formState.values["password"]}
                        required
                        fullWidth
                        onChange={handleChange}
                        error={hasError("password")}
                        helpertext={
                          hasError("password")
                            ? formState.errors["password"].map(error => {
                                return error + " ";
                              })
                            : null
                        }
                        endAdornment={
                          <InputAdornment
                            position="end"
                            error={hasError("password")}
                          >
                            <IconButton
                              aria-label="toggle password visibility"
                              onClick={handleClickShowPassword}
                              edge="end"
                            >
                              {formState.showPassword ? (
                                <Visibility />
                              ) : (
                                <VisibilityOff />
                              )}
                            </IconButton>
                          </InputAdornment>
                        }
                      />
                      <FormHelperText error={hasError("password")}>
                        {hasError("password")
                          ? formState.errors["password"].map(error => {
                              return error + " ";
                            })
                          : null}
                      </FormHelperText>
                    </FormControl>
                  </Grid>
                )}
              </Grid>
            </Grid>
            {formState.editStudent ? (
              <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
                            color="primary"
                            type="submit"
                            id="submit"
                            mfullWidth
                            variant="contained"
                            style={{ marginRight: "18px" }}
                            onClick={handleSubmit}
                          >
                            <span>{genericConstants.SAVE_BUTTON_TEXT}</span>
                          </YellowButton>
                        </Grid>
                        <Grid item md={3} xs={12}>
                          <YellowButton
                            id="submitandnext"
                            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
                            id="cancel"
                            color="primary"
                            type="submit"
                            mfullWidth
                            variant="contained"
                            onClick={() => {
                              auth.getUserInfo().role.name ===
                              roleConstants.COLLEGEADMIN
                                ? history.push(routeConstants.MANAGE_STUDENT)
                                : history.push(routeConstants.VIEW_PROFILE);
                            }}
                          >
                            <span>{genericConstants.CANCEL_BUTTON_TEXT}</span>
                          </GrayButton>
                        </Grid>
                      </Grid>
                    </Grid>
                  </Grid>
                </CardActions>
              </Grid>
            ) : (
              <Grid item md={12} 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"
                            color="primary"
                            type="submit"
                            mfullWidth
                            variant="contained"
                            onClick={handleSubmit}
                          >
                            <span>{authPageConstants.REGISTER}</span>
                          </YellowButton>
                        </Grid>

                        <Grid item md={2} xs={12}>
                          <GrayButton
                            id="cancel"
                            color="primary"
                            type="submit"
                            mfullWidth
                            variant="contained"
                            onClick={() => {
                              history.push(routeConstants.SIGN_IN_URL);
                            }}
                          >
                            <span>{genericConstants.CANCEL_BUTTON_TEXT}</span>
                          </GrayButton>
                        </Grid>
                      </Grid>
                    </Grid>
                  </Grid>
                </CardActions>
              </Grid>
            )}
          </CardContent>
        </form>
      </Card>
      <Backdrop className={classes.backDrop} open={backDrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </Grid>
    // </Layout>
  );
}
Example #21
Source File: AddEditStudentForCollegeAdmin.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditStudentForCollegeAdmin = props => {
  const [selectedDate, setSelectedDate] = useState(
    props.forTestingDate ? new Date("1999-03-25") : null
  );
  const [backDrop, setBackDrop] = useState(false);

  const defaultParams = {
    pageSize: -1
  };

  const genderlist = [
    { name: "Male", id: "male" },
    { name: "Female", id: "female" },
    { name: "Other", id: "other" }
  ];

  const physicallyHandicappedlist = [
    { name: "Yes", id: true },
    { name: "No", id: false }
  ];

  let history = useHistory();
  const [user, setUser] = useState({
    firstName: "",
    lastName: "",
    fatherFirstName: "",
    fatherLastName: "",
    address: "",
    district: null,
    state: null,
    email: "",
    contactNumber: "",
    password: "",
    gender: "",
    physicallyHandicapped: null,
    college: null,
    stream: null,
    currentAcademicYear: null,
    collegeRollNumber: null,
    otp: "",
    futureAspirations: null
  });

  const [formState, setFormState] = useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    dataToShowForMultiSelect: [],
    isDateOfBirthPresent: true,
    isdateOfBirthValid: true,
    isSuccess: false,
    showPassword: false,
    isStateClearFilter: false,
    addStudent: props.location.addStudent ? props.location.addStudent : false,
    editStudent: props.location.editStudent
      ? props.location.editStudent
      : false,
    dataForEdit: props.location.dataForEdit ? props.location.dataForEdit : [],
    counter: 0,
    flag: 0,
    files: null,
    previewFile: {},
    showPreview: false,
    showEditPreview: props.location.editStudent
      ? props.location.dataForEdit.profile_photo
        ? true
        : false
      : false,
    showNoImage: props.location.editStudent
      ? false
      : props.location.editStudent,
    addressSameAsLocal: false,
    addresses: genericConstants.ADDRESSES
  });

  const { layout: Layout } = props;
  const classes = useStyles();

  const [statelist, setstatelist] = useState(
    props.mockStateList ? props.mockStateList : []
  );
  const [districtlist, setdistrictlist] = useState(
    props.mockdistrictList ? props.mockdistrictList : []
  );
  const [streamlist, setStreamlist] = useState(
    props.mockstreamList ? props.mockstreamList : []
  );
  const [futureAspirant, setFutureAspirant] = useState(
    props.mockFutureAspiration ? props.mockFutureAspiration : []
  );
  const [collegelist] = useState([auth.getUserInfo().studentInfo.organization]);
  const [validateAddress, setValidateAddress] = useState([]);

  useEffect(() => {
    if (!formState.editStudent) {
      if (formState.addressSameAsLocal) {
        const address = formState.addresses.find(
          addr => addr.address_type == "Temporary"
        );
        const copyAddresses = formState.addresses.map(addr => {
          if (addr.address_type == "Permanent") {
            return { ...address, address_type: "Permanent" };
          } else {
            return addr;
          }
        });

        setFormState(formState => ({
          ...formState,
          addresses: copyAddresses
        }));
      } else {
        const address = genericConstants.ADDRESSES.find(
          addr => addr.address_type == "Permanent"
        );

        const resetPermanentAddress = formState.addresses.map(addr => {
          if (addr.address_type == "Permanent") {
            return address;
          } else {
            return addr;
          }
        });
        setFormState(formState => ({
          ...formState,
          addresses: resetPermanentAddress
        }));
      }
    }
  }, [formState.addressSameAsLocal]);

  useEffect(() => {
    if (!formState.editStudent && !formState.addStudent) {
      history.push({
        pathname: routeConstants.MANAGE_STUDENT
      });
    } else if (formState.addStudent) {
      formState.values[
        "college"
      ] = auth.getUserInfo().studentInfo.organization.id;
    }

    if (formState.editStudent) {
      registrationSchema["password"]["required"] = false;
      registrationSchema["password"]["validations"] = {
        validatePasswordMinLength: {
          value: "true",
          message: "Password is too short"
        }
      };
    } else if (formState.addStudent) {
      registrationSchema["password"]["required"] = true;
      registrationSchema["password"]["validations"] = {
        required: {
          value: "true",
          message: "Password is required"
        },
        validatePasswordMinLength: {
          value: "true",
          message: "Password is too short"
        }
      };
    }
    getFutureAspirant();
    getStates();
    getStreams();
    getDistrict();
  }, []);

  const getFutureAspirant = () => {
    let futureAspirationsUrl =
      strapiApiConstants.STRAPI_DB_URL +
      strapiApiConstants.STRAPI_FUTURE_ASPIRATIONS;
    serviceProvider
      .serviceProviderForGetRequest(futureAspirationsUrl)
      .then(res => {
        setFutureAspirant(res.data.result);
        prePopulateFutureAspirant(res.data.result);
      })
      .catch(error => {
        console.log("errorfuture", error);
      });
  };

  const prePopulateFutureAspirant = data => {
    if (formState.editStudent) {
      if (
        formState["dataForEdit"]["future_aspirations"] &&
        formState["dataForEdit"]["future_aspirations"].length !== 0
      ) {
        let array = [];
        data.map(aspirantData => {
          for (let i in formState["dataForEdit"]["future_aspirations"]) {
            if (
              formState["dataForEdit"]["future_aspirations"][i]["id"] ===
              aspirantData["id"]
            ) {
              array.push(aspirantData);
            }
          }
        });
        setFormState(formState => ({
          ...formState,
          dataToShowForMultiSelect: array
        }));
        let finalData = [];
        for (let i in formState["dataForEdit"]["future_aspirations"]) {
          finalData.push(
            formState["dataForEdit"]["future_aspirations"][i]["id"]
          );
        }
        formState.values["futureAspirations"] = finalData;
      }
    }
  };

  const getStreams = () => {
    let streamsArray = [];
    for (let i in auth.getUserInfo().studentInfo.organization.stream_strength) {
      streamsArray.push(
        auth.getUserInfo().studentInfo.organization.stream_strength[i]["stream"]
      );
    }
    setStreamlist(streamsArray);
  };

  const getStates = () => {
    serviceProvider
      .serviceProviderForGetRequest(
        STATES_URL,
        {
          pageSize: -1
        },
        {}
      )
      .then(res => {
        setstatelist(res.data.result.map(({ id, name }) => ({ id, name })));
      });
  };

  const getDistrict = () => {
    Axios.get(
      strapiApiConstants.STRAPI_DB_URL +
        strapiApiConstants.STRAPI_DISTRICTS +
        "?pageSize=-1"
    ).then(res => {
      setdistrictlist(
        res.data.result.map(({ id, name, state }) => ({
          id,
          name,
          state: state.id
        }))
      );
    });
  };

  if (formState.dataForEdit && !formState.counter) {
    if (props.location["dataForEdit"]) {
      if (props.location["dataForEdit"]["first_name"]) {
        formState.values["firstname"] =
          props.location["dataForEdit"]["first_name"];
      }
      if (props.location["dataForEdit"]["middle_name"]) {
        formState.values["middlename"] =
          props.location["dataForEdit"]["middle_name"];
      }
      if (props.location["dataForEdit"]["last_name"]) {
        formState.values["lastname"] =
          props.location["dataForEdit"]["last_name"];
      }
      if (
        props.location["dataForEdit"]["contact"] &&
        props.location["dataForEdit"]["contact"]["user"] &&
        props.location["dataForEdit"]["contact"]["user"]["email"]
      ) {
        formState.values["email"] =
          props.location["dataForEdit"]["contact"]["user"]["email"];
      }
      if (
        props.location["dataForEdit"]["contact"] &&
        props.location["dataForEdit"]["contact"]["phone"]
      ) {
        formState.values["contact"] =
          props.location["dataForEdit"]["contact"]["phone"];
      }
      // if (
      //   props.location["dataForEdit"]["contact"] &&
      //   props.location["dataForEdit"]["contact"]["state"]
      // ) {
      //   formState.values["state"] =
      //     props.location["dataForEdit"]["contact"]["state"]["id"];
      // }
      if (props.location["dataForEdit"]["stream"]) {
        formState.values["stream"] =
          props.location["dataForEdit"]["stream"]["id"];
      }

      // if (
      //   props.location["dataForEdit"]["contact"] &&
      //   props.location["dataForEdit"]["contact"]["district"]
      // ) {
      //   formState.values["district"] =
      //     props.location["dataForEdit"]["contact"]["district"]["id"];
      // }
      if (props.location["dataForEdit"]["father_full_name"]) {
        formState.values["fatherFullName"] =
          props.location["dataForEdit"]["father_full_name"];
      }
      if (props.location["dataForEdit"]["mother_full_name"]) {
        formState.values["motherFullName"] =
          props.location["dataForEdit"]["mother_full_name"];
      }
      // if (props.location["dataForEdit"]["contact"]["address_1"]) {
      //   formState.values["address"] =
      //     props.location["dataForEdit"]["contact"]["address_1"];
      // }
      if (props.location["dataForEdit"]["gender"]) {
        formState.values["gender"] = props.location["dataForEdit"]["gender"];
      }

      if (props.location["dataForEdit"]["roll_number"]) {
        formState.values["rollnumber"] =
          props.location["dataForEdit"]["roll_number"];
      }
      if (props.location["dataForEdit"]["is_physically_challenged"] !== null) {
        formState.values["physicallyHandicapped"] =
          props.location["dataForEdit"]["is_physically_challenged"];
      }
      if (
        props.location["dataForEdit"]["organization"] &&
        props.location["dataForEdit"]["organization"]["id"]
      ) {
        formState.values["college"] =
          props.location["dataForEdit"]["organization"]["id"];
      }
      if (props.location["dataForEdit"]["date_of_birth"]) {
        setSelectedDate(
          new Date(props.location["dataForEdit"]["date_of_birth"])
        );
      }
      if (
        props.location["dataForEdit"]["profile_photo"] &&
        props.location["dataForEdit"]["profile_photo"]["id"]
      ) {
        formState.previewFile = props.location["dataForEdit"]["profile_photo"];
        //      formState.values["files"] =
        //        props.location["dataForEdit"]["upload_logo"]["name"];
      }

      if (
        props.location["dataForEdit"]["contact"] &&
        props.location["dataForEdit"]["contact"]["addresses"] &&
        props.location["dataForEdit"]["contact"]["addresses"].length > 0
      ) {
        formState.addresses =
          props.location["dataForEdit"]["contact"]["addresses"];
      } else {
        formState.addresses = genericConstants.ADDRESSES;
      }
    }
    formState.counter += 1;
  }

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

  const handleSubmit = event => {
    setBackDrop(true);
    let schema;
    if (formState.editStudent) {
      schema = Object.assign({}, _.omit(registrationSchema, ["otp"]));
    } else {
      schema = Object.assign(
        {},
        _.omit(registrationSchema, ["futureAspirations"])
      );
    }
    formState.values = Object.assign(
      {},
      _.omit(formState.values, ["username"])
    );
    let isValid = false;
    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);

      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
      );
      formState.errors = formUtilities.setErrors(formState.values, schema);
    }

    if (selectedDate === null) {
      formState.isDateOfBirthPresent = false;
    } else {
      formState.isDateOfBirthPresent = true;
      if (props.forTestingDate) {
        formState.isdateOfBirthValid = true;
      } else {
        formState.isdateOfBirthValid = formUtilities.validateDateOfBirth(
          selectedDate
        );
      }
    }

    const isValidAddress = validateAddresses();
    if (
      isValid &&
      formState.isDateOfBirthPresent &&
      formState.isdateOfBirthValid &&
      !isValidAddress
    ) {
      /** CALL POST FUNCTION */
      postStudentData();

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

  const postStudentData = () => {
    let postData;
    const addresses = formState.addresses;

    if (formState.editStudent) {
      postData = databaseUtilities.editStudent(
        formState.values["firstname"],
        formState.values["middlename"],
        formState.values["lastname"],
        formState.values["fatherFullName"],
        formState.values["motherFullName"],
        formState.values["email"],
        formState.values["contact"],
        formState.values["contact"],
        formState.values["gender"],
        selectedDate.getFullYear() +
          "-" +
          (selectedDate.getMonth() + 1) +
          "-" +
          selectedDate.getDate(),
        formState.values["physicallyHandicapped"] ? true : false,
        formState.values["college"],
        formState.values["stream"],
        formState.values["rollnumber"],
        formState.dataForEdit.id,
        formState.values["futureAspirations"],
        formState.files,
        formState.values["password"] ? formState.values["password"] : undefined,
        addresses
      );

      let studentName =
        props.location["dataForEdit"]["first_name"] +
        " " +
        props.location["dataForEdit"]["middlename"] +
        " " +
        props.location["dataForEdit"]["last_name"];

      let EDIT_STUDENT_URL =
        strapiApiConstants.STRAPI_DB_URL +
        strapiApiConstants.STRAPI_CONTACT_URL;
      let EDIT_URL = strapiApiConstants.STRAPI_EDIT_STUDENT;
      serviceProvider
        .serviceProviderForPutRequest(
          EDIT_STUDENT_URL,
          formState.dataForEdit.contact.id,
          postData,
          EDIT_URL
        )
        .then(response => {
          setBackDrop(false);
          if (formState.flag === 1) {
            history.push({
              pathname: routeConstants.VIEW_EDUCATION
            });
          } else {
            history.push({
              pathname: routeConstants.MANAGE_STUDENT,
              fromEditStudent: true,
              isStudentEdited: true,
              messageForEditStudent:
                "Student " + studentName + " has been edited successfully."
            });
          }
        })
        .catch(err => {
          setBackDrop(false);
          console.log(JSON.stringify(err));
          history.push({
            pathname: routeConstants.MANAGE_STUDENT,
            fromEditStudent: true,
            isStudentEdited: false,
            messageForEditStudent:
              "An error has occured while updating student " +
              studentName +
              ". Kindly, try again."
          });
        });
    } else {
      postData = databaseUtilities.addStudentFromCollege(
        formState.values["firstname"],
        formState.values["middlename"],
        formState.values["lastname"],
        formState.values["fatherFullName"],
        formState.values["motherFullName"],
        formState.values["email"],
        formState.values["contact"],
        formState.values["contact"],
        formState.values["password"],
        formState.values["gender"],
        selectedDate.getFullYear() +
          "-" +
          (selectedDate.getMonth() + 1) +
          "-" +
          selectedDate.getDate(),
        formState.values["physicallyHandicapped"] ? true : false,
        formState.values["college"],
        formState.values["stream"],
        formState.values["rollnumber"],
        formState.files,
        formState.values["futureAspirations"]
          ? formState["futureAspirations"]
          : null,
        addresses
      );
      let url =
        strapiApiConstants.STRAPI_DB_URL +
        strapiApiConstants.STRAPI_CREATE_USERS;
      serviceProvider
        .serviceProviderForPostRequest(url, postData)
        .then(response => {
          setBackDrop(false);
          history.push({
            pathname: routeConstants.MANAGE_STUDENT,
            fromAddStudent: true,
            isStudentAdded: true,
            messageForAddStudent:
              "Student " +
              formState.values["firstname"] +
              " " +
              formState.values["middlename"] +
              " " +
              formState.values["lastname"] +
              " has been added successfully"
          });
        })
        .catch(error => {
          setBackDrop(false);
          let errorMessage;

          if (
            error.response !== undefined &&
            error.response.status !== undefined &&
            error.response.status === 400
          ) {
            if (error.response.data["message"]) {
              errorMessage = error.response.data["message"];
            }
          }
          console.log("err", error, error.response);
          history.push({
            pathname: routeConstants.MANAGE_STUDENT,
            fromAddStudent: true,
            isStudentAdded: false,
            messageForAddStudent: errorMessage
              ? errorMessage
              : "An error has occured while adding student " +
                formState.values["firstname"] +
                " " +
                formState.values["middlename"] +
                " " +
                formState.values["lastname"] +
                ". Kindly, try again. "
          });
        });
    }
  };

  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];
    }
  };

  const handleChangeAutoComplete = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (eventName === "futureAspirations") {
      formState.dataToShowForMultiSelect = value;
    }
    if (get(registrationSchema[eventName], "type") === "multi-select") {
      let finalValues = [];
      for (let i in value) {
        finalValues.push(value[i]["id"]);
      }
      value = {
        id: finalValues
      };
    }
    if (value !== null) {
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          [eventName]: value.id
        },
        touched: {
          ...formState.touched,
          [eventName]: true
        },
        isStateClearFilter: false
      }));
      if (formState.errors.hasOwnProperty(eventName)) {
        delete formState.errors[eventName];
      }
    } else {
      let setStateFilterValue = false;
      /** If we click cross for state the district should clear off! */
      if (eventName === "state") {
        /** 
        This flag is used to determine that state is cleared which clears 
        off district by setting their value to null 
        */
        setStateFilterValue = true;
        /** 
        When state is cleared then clear district
        */
        setdistrictlist([]);
        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];
    }
  };

  const handleChangefile = e => {
    e.persist();
    setFormState(formState => ({
      ...formState,

      values: {
        ...formState.values,
        [e.target.name]: e.target.files[0].name
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      },
      files: e.target.files[0],
      previewFile: URL.createObjectURL(e.target.files[0]),
      showPreview: true,
      showEditPreview: false,
      showNoImage: false
    }));
    if (formState.errors.hasOwnProperty(e.target.name)) {
      delete formState.errors[e.target.name];
    }
  };

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

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

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

  const handleAddressChange = (idx, e, type) => {
    e.persist();
    console.log(e.target.value);

    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;
  };

  console.log(formState.addresses);
  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        {formState.editStudent ? null : (
          <Typography variant="h4" gutterBottom>
            Add Student
          </Typography>
        )}
      </Grid>
      <Grid>
        <Card>
          <form autoComplete="off">
            <CardContent>
              <Grid item xs={12} md={6} xl={3}>
                <Grid container className={classes.formgridInputFile}>
                  <Grid item md={10} xs={12}>
                    <div className={classes.imageDiv}>
                      {formState.showPreview ? (
                        <Img
                          alt="abc"
                          loader={<Spinner />}
                          className={classes.UploadImage}
                          src={formState.previewFile}
                        />
                      ) : null}
                      {!formState.showPreview && !formState.showEditPreview ? (
                        <div className={classes.DefaultNoImage}></div>
                      ) : null}
                      {/* {formState.showEditPreview&&formState.dataForEdit.upload_logo===null? <div class={classes.DefaultNoImage}></div>:null} */}
                      {formState.showEditPreview &&
                      formState.dataForEdit["profile_photo"] !== null &&
                      formState.dataForEdit["profile_photo"] !== undefined &&
                      formState.dataForEdit["profile_photo"] !== {} ? (
                        <Img
                          src={
                            strapiApiConstants.STRAPI_DB_URL_WITHOUT_HASH +
                            formState.dataForEdit["profile_photo"]["url"]
                          }
                          loader={<Spinner />}
                          className={classes.UploadImage}
                        />
                      ) : null}
                      {formState.showNoImage ? (
                        <Img
                          src="/images/noImage.png"
                          loader={<Spinner />}
                          className={classes.UploadImage}
                        />
                      ) : null}
                    </div>
                  </Grid>
                </Grid>
                <Grid container className={classes.MarginBottom}>
                  <Grid item md={10} xs={12}>
                    <TextField
                      fullWidth
                      id="files"
                      margin="normal"
                      name="files"
                      placeholder="Upload Logo"
                      onChange={handleChangefile}
                      required
                      type="file"
                      inputProps={{ accept: "image/*" }}
                      //value={formState.values["files"] || ""}
                      error={hasError("files")}
                      helperText={
                        hasError("files")
                          ? formState.errors["files"].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                      variant="outlined"
                      className={classes.inputFile}
                    />
                    <label htmlFor={get(registrationSchema["files"], "id")}>
                      <Button
                        variant="contained"
                        color="primary"
                        component="span"
                        fullWidth
                        className={classes.InputFileButton}
                        startIcon={<AddOutlinedIcon />}
                      >
                        ADD PROFILE PHOTO
                      </Button>
                    </label>
                  </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
                      label={get(registrationSchema["firstname"], "label")}
                      name="firstname"
                      placeholder={get(
                        registrationSchema["firstname"],
                        "placeholder"
                      )}
                      id="firstName"
                      value={formState.values["firstname"] || ""}
                      variant="outlined"
                      error={hasError("firstname")}
                      required
                      fullWidth
                      onChange={handleChange}
                      helperText={
                        hasError("firstname")
                          ? formState.errors["firstname"].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>{" "}
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={6} xs={12}>
                    <TextField
                      label="Middle Name"
                      name="middlename"
                      id="middlename"
                      value={formState.values["middlename"]}
                      variant="outlined"
                      error={hasError("middlename")}
                      fullWidth
                      onChange={handleChange}
                      helperText={
                        hasError("middlename")
                          ? formState.errors["middlename"].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <TextField
                      label={get(registrationSchema["lastname"], "label")}
                      name="lastname"
                      placeholder={get(
                        registrationSchema["lastname"],
                        "placeholder"
                      )}
                      id="lastname"
                      value={formState.values["lastname"] || ""}
                      variant="outlined"
                      required
                      fullWidth
                      error={hasError("lastname")}
                      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={6} xs={12}>
                    <TextField
                      label={get(registrationSchema["fatherFullName"], "label")}
                      name="fatherFullName"
                      placeholder={get(
                        registrationSchema["fatherFullName"],
                        "placeholder"
                      )}
                      id="fatherFullName"
                      value={formState.values["fatherFullName"] || ""}
                      variant="outlined"
                      required
                      fullWidth
                      onChange={handleChange}
                      error={hasError("fatherFullName")}
                      helperText={
                        hasError("fatherFullName")
                          ? formState.errors["fatherFullName"].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <TextField
                      label={get(registrationSchema["motherFullName"], "label")}
                      name="motherFullName"
                      placeholder={get(
                        registrationSchema["motherFullName"],
                        "placeholder"
                      )}
                      id="motherFullName"
                      value={formState.values["motherFullName"] || ""}
                      variant="outlined"
                      required
                      fullWidth
                      onChange={handleChange}
                      error={hasError("motherFullName")}
                      helperText={
                        hasError("motherFullName")
                          ? formState.errors["motherFullName"].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                </Grid>
                <Divider className={classes.divider} />
                <Grid container spacing={3} className={classes.MarginBottom}>
                  {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"
                                : "Permanent Address"}
                            </InputLabel>
                            <Grid
                              container
                              spacing={3}
                              className={classes.MarginBottom}
                            >
                              <Grid
                                item
                                md={12}
                                xs={12}
                                style={{ marginTop: "8px" }}
                              >
                                <TextField
                                  label="Address"
                                  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="combo-box-demo"
                                  className={classes.root}
                                  options={statelist}
                                  getOptionLabel={option => option.name}
                                  onChange={(event, value) => {
                                    handleStateAndDistrictChange(
                                      "state",
                                      value,
                                      idx
                                    );
                                  }}
                                  value={
                                    statelist[
                                      statelist.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}>
                                <Autocomplete
                                  id="combo-box-demo"
                                  className={classes.root}
                                  options={districtlist.filter(
                                    district =>
                                      district.state ===
                                      formState.addresses[idx].state
                                  )}
                                  getOptionLabel={option => option.name}
                                  onChange={(event, value) => {
                                    handleStateAndDistrictChange(
                                      "district",
                                      value,
                                      idx
                                    );
                                  }}
                                  value={
                                    districtlist[
                                      districtlist.findIndex(function (
                                        item,
                                        i
                                      ) {
                                        return (
                                          item.id ===
                                          formState.addresses[idx].district
                                        );
                                      })
                                    ] || null
                                  }
                                  renderInput={params => (
                                    <TextField
                                      {...params}
                                      label="District"
                                      variant="outlined"
                                      name="tester"
                                      error={
                                        (validateAddress[idx] &&
                                          validateAddress[idx]["district"][
                                            "error"
                                          ]) ||
                                        false
                                      }
                                      helperText={
                                        (validateAddress[idx] &&
                                          validateAddress[idx]["district"][
                                            "message"
                                          ]) ||
                                        null
                                      }
                                    />
                                  )}
                                />
                              </Grid>
                              <Grid item md={6} xs={12}>
                                <TextField
                                  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
                                  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
                                  }
                                  inputProps={{ maxLength: 6, minLength: 6 }}
                                />
                              </Grid>
                            </Grid>
                            <Grid item md={12} xs={12}>
                              {!formState.editStudent &&
                              addr.address_type == "Temporary" ? (
                                <FormControlLabel
                                  control={
                                    <Checkbox
                                      checked={formState.addressSameAsLocal}
                                      onChange={event => {
                                        setFormState(formState => ({
                                          ...formState,
                                          addressSameAsLocal:
                                            event.target.checked
                                        }));
                                      }}
                                      name="addressSameAsLocal"
                                      color="primary"
                                    />
                                  }
                                  label="Permanent Address same as local Address?"
                                />
                              ) : null}
                            </Grid>
                          </Card>
                        </Grid>
                      </Grid>
                    );
                  })}
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={6} xs={12}>
                    <InlineDatePicker
                      className={classes.dateField}
                      format="dd/MM/yyyy"
                      id="date-picker-inline"
                      placeholder="DD/MM//YYYY"
                      label={get(registrationSchema["dateofbirth"], "label")}
                      value={selectedDate}
                      onChange={date => {
                        formState.isDateOfBirthPresent = true;
                        formState.isdateOfBirthValid = true;
                        setSelectedDate(date);
                      }}
                      error={
                        !formState.isDateOfBirthPresent ||
                        !formState.isdateOfBirthValid
                      }
                      helperText={
                        !formState.isDateOfBirthPresent
                          ? "Date of Birth is required"
                          : !formState.isdateOfBirthValid
                          ? "Date of birth cannot be greater than current date"
                          : null
                      }
                      KeyboardButtonProps={{
                        "aria-label": "change date"
                      }}
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id="gender-filter"
                      className={classes.root}
                      options={genderlist}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete("gender", event, value);
                      }}
                      value={
                        genderlist[
                          genderlist.findIndex(function (item, i) {
                            return item.id === formState.values.gender;
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError("gender")}
                          label={get(registrationSchema["gender"], "label")}
                          placeholder={get(
                            registrationSchema["gender"],
                            "placeholder"
                          )}
                          required
                          variant="outlined"
                          name="tester"
                          helperText={
                            hasError("gender")
                              ? formState.errors["gender"].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={6} xs={12}>
                    <TextField
                      label={get(registrationSchema["contact"], "label")}
                      placeholder={get(
                        registrationSchema["contact"],
                        "placeholder"
                      )}
                      id="contact"
                      name="contact"
                      value={formState.values["contact"] || ""}
                      variant="outlined"
                      required
                      fullWidth
                      onChange={handleChange}
                      error={hasError("contact")}
                      helperText={
                        hasError("contact")
                          ? formState.errors["contact"].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id="physically-handicapped-id"
                      className={classes.root}
                      options={physicallyHandicappedlist}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete(
                          "physicallyHandicapped",
                          event,
                          value
                        );
                      }}
                      value={
                        physicallyHandicappedlist[
                          physicallyHandicappedlist.findIndex(function (
                            item,
                            i
                          ) {
                            return (
                              item.id === formState.values.physicallyHandicapped
                            );
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError("physicallyHandicapped")}
                          label={get(
                            registrationSchema["physicallyHandicapped"],
                            "label"
                          )}
                          placeholder={get(
                            registrationSchema["physicallyHandicapped"],
                            "placeholder"
                          )}
                          variant="outlined"
                          name="tester"
                          helperText={
                            hasError("physicallyHandicapped")
                              ? formState.errors["physicallyHandicapped"].map(
                                  error => {
                                    return error + " ";
                                  }
                                )
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12}>
                    <TextField
                      label={get(registrationSchema["email"], "label")}
                      placeholder={get(
                        registrationSchema["email"],
                        "placeholder"
                      )}
                      id="email"
                      name="email"
                      value={formState.values["email"] || ""}
                      variant="outlined"
                      required
                      fullWidth
                      onChange={handleChange}
                      error={hasError("email")}
                      helperText={
                        hasError("email")
                          ? formState.errors["email"].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12}>
                    <Autocomplete
                      id="college-filter"
                      className={classes.root}
                      options={collegelist}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete("college", event, value);
                      }}
                      value={
                        collegelist[
                          collegelist.findIndex(function (item, i) {
                            return item.id === formState.values.college;
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError("college")}
                          label={get(registrationSchema["college"], "label")}
                          placeholder={get(
                            registrationSchema["college"],
                            "placeholder"
                          )}
                          variant="outlined"
                          required
                          name="college"
                          helperText={
                            hasError("college")
                              ? formState.errors["college"].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id="stream-filter"
                      className={classes.root}
                      options={streamlist}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete("stream", event, value);
                      }}
                      value={
                        streamlist[
                          streamlist.findIndex(function (item, i) {
                            return item.id === formState.values.stream;
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError("stream")}
                          label={get(registrationSchema["stream"], "label")}
                          placeholder={get(
                            registrationSchema["stream"],
                            "placeholder"
                          )}
                          variant="outlined"
                          name="stream"
                          helperText={
                            hasError("stream")
                              ? formState.errors["stream"].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <TextField
                      label={get(registrationSchema["rollnumber"], "label")}
                      placeholder={get(
                        registrationSchema["rollnumber"],
                        "placeholder"
                      )}
                      id="rollnumber"
                      name="rollnumber"
                      value={formState.values["rollnumber"] || ""}
                      variant="outlined"
                      fullWidth
                      required
                      onChange={handleChange}
                      error={hasError("rollnumber")}
                      helperText={
                        hasError("rollnumber")
                          ? formState.errors["rollnumber"].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={6} xs={12}>
                    <FormControl fullWidth variant="outlined">
                      <InputLabel
                        htmlFor="outlined-adornment-password"
                        fullWidth
                        error={hasError("password")}
                      >
                        Password
                      </InputLabel>
                      <OutlinedInput
                        label={get(registrationSchema["password"], "label")}
                        placeholder={get(
                          registrationSchema["password"],
                          "placeholder"
                        )}
                        id="password"
                        name="password"
                        type={formState.showPassword ? "text" : "password"}
                        value={formState.values["password"]}
                        required
                        fullWidth
                        onChange={handleChange}
                        error={hasError("password")}
                        helperText={
                          hasError("password")
                            ? formState.errors["password"].map(error => {
                                return error + " ";
                              })
                            : null
                        }
                        endAdornment={
                          <InputAdornment
                            position="end"
                            error={hasError("password")}
                          >
                            <IconButton
                              aria-label="toggle password visibility"
                              onClick={handleClickShowPassword}
                              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>
                  {formState.editStudent ? (
                    <Grid item md={6} xs={12}>
                      <Autocomplete
                        id="futureAspirations"
                        multiple
                        options={futureAspirant}
                        getOptionLabel={option => option.name}
                        onChange={(event, value) => {
                          handleChangeAutoComplete(
                            "futureAspirations",
                            event,
                            value
                          );
                        }}
                        name={"futureAspirations"}
                        filterSelectedOptions
                        value={formState.dataToShowForMultiSelect || null}
                        renderInput={params => (
                          <TextField
                            {...params}
                            error={hasError("futureAspirations")}
                            helperText={
                              hasError("futureAspirations")
                                ? formState.errors["futureAspirations"].map(
                                    error => {
                                      return error + " ";
                                    }
                                  )
                                : null
                            }
                            placeholder={get(
                              registrationSchema["futureAspirations"],
                              "placeholder"
                            )}
                            label={get(
                              registrationSchema["futureAspirations"],
                              "label"
                            )}
                            variant="outlined"
                          />
                        )}
                      />
                    </Grid>
                  ) : null}
                </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
                          color="primary"
                          type="submit"
                          id="submit"
                          mfullWidth
                          variant="contained"
                          style={{ marginRight: "18px" }}
                          onClick={event => {
                            event.preventDefault();
                            handleSubmit(event);
                          }}
                        >
                          <span>{genericConstants.SAVE_BUTTON_TEXT}</span>
                        </YellowButton>
                      </Grid>
                      <Grid item md={3} xs={12}>
                        <YellowButton
                          color="primary"
                          type="submit"
                          id="submitandnext"
                          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
                          color="primary"
                          type="submit"
                          mfullWidth
                          variant="contained"
                          onClick={() => {
                            history.push(routeConstants.MANAGE_STUDENT);
                          }}
                        >
                          <span>{genericConstants.CANCEL_BUTTON_TEXT}</span>
                        </GrayButton>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </CardActions>
            </Grid>
          </form>
        </Card>
      </Grid>
      <Backdrop className={classes.backDrop} open={backDrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </Grid>
    // </Layout>
  );
}
Example #22
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 #23
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 #24
Source File: AddGroupMembers.jsx    From zubhub with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @function AddGroupMembers
 * @author Raymond Ndibe <[email protected]>
 *
 * @todo - describe function's signature
 */
function AddGroupMembers(props) {
  const refs = {
    add_group_members_el: React.useRef(null),
    drag_drop_el: React.useRef(null),
  };
  const classes = useStyles();
  const common_classes = useCommonStyles();

  const [state, setState] = React.useState({
    loading: true,
    error: null,
    csv: null,
    upload_dialog: false,
    bulk_add_checked: false,
  });

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

  const { upload_dialog, bulk_add_checked, csv } = state;
  const { t } = props;
  vars.csv_not_added = !csv;
  if (!props.auth.token) {
    return <ErrorPage error={t('addGroupMembers.errors.notLoggedIn')} />;
  } else if (props.auth.members_count === null) {
    return <ErrorPage error={t('addGroupMembers.errors.unauthorized')} />;
  } else {
    return (
      <Box className={classes.root}>
        <Container className={classes.containerStyle}>
          <Card className={classes.cardStyle}>
            <CardActionArea>
              <CardContent>
                <form
                  className="project-create-form"
                  name="create_project"
                  noValidate="noValidate"
                  onSubmit={e => handleSubmit(e, state, handleSetState, props)}
                >
                  <Typography
                    className={classes.titleStyle}
                    gutterBottom
                    variant="h5"
                    component="h2"
                    color="textPrimary"
                  >
                    {t('addGroupMembers.welcomeMsg.primary')}
                  </Typography>
                  <Typography
                    variant="body2"
                    color="textSecondary"
                    component="p"
                    className={classes.descStyle}
                  >
                    {t('addGroupMembers.welcomeMsg.secondary')}
                  </Typography>

                  <Grid container spacing={3}>
                    <Grid item xs={12}>
                      <Box
                        component="p"
                        className={
                          props.status &&
                          props.status['non_field_errors'] &&
                          classes.errorBox
                        }
                      >
                        {props.status && props.status['non_field_errors'] && (
                          <Box component="span" className={classes.error}>
                            {props.status['non_field_errors']}
                          </Box>
                        )}
                      </Box>
                    </Grid>

                    <Grid item xs={12} className={common_classes.marginTop1em}>
                      <FormControl
                        variant="outlined"
                        size="small"
                        fullWidth
                        margin="small"
                        error={
                          (props.status && props.status['group_members']) ||
                          (props.touched['group_members'] &&
                            props.errors['group_members'])
                        }
                      >
                        <label htmlFor="add_group_members">
                          <Typography
                            color="textSecondary"
                            className={clsx(
                              classes.customLabelStyle,
                              common_classes.marginBottom1em,
                            )}
                          >
                            {t('addGroupMembers.inputs.groupMembers.label')}
                          </Typography>
                        </label>

                        <Grid container spacing={1} alignItems="flex-end">
                          {!bulk_add_checked ? (
                            <>
                              <Grid item xs={12} sm={8}>
                                <Box ref={refs.add_group_members_el}>
                                  {buildGroupMembersNodes({
                                    props,
                                    refs,
                                    classes,
                                    common_classes,
                                  })}
                                </Box>
                              </Grid>
                              <Grid item xs={12} sm={4}>
                                <CustomButton
                                  variant="outlined"
                                  size="large"
                                  onClick={e => addGroupMembersNode(e, props)}
                                  secondaryButtonStyle
                                  customButtonStyle
                                  fullWidth
                                >
                                  <AddIcon />{' '}
                                  {t(
                                    'addGroupMembers.inputs.groupMembers.addMore',
                                  )}
                                </CustomButton>
                              </Grid>
                              <FormHelperText
                                error
                                className={classes.fieldHelperTextStyle}
                              >
                                {(props.status &&
                                  props.status['group_members']) ||
                                  (props.touched['group_members'] &&
                                    props.errors['group_members'] &&
                                    t(
                                      `addGroupMembers.inputs.groupMembers.errors.${props.errors['group_members']}`,
                                    ))}
                              </FormHelperText>
                            </>
                          ) : (
                            <label
                              htmlFor="addcsv"
                              className={classes.addCSVStyles}
                            >
                              <Box
                                className={classes.CSVBoxStyles}
                                ref={refs.drag_drop_el}
                                onDragLeave={e => {
                                  refs.drag_drop_el.current.style.border =
                                    '1px dashed rgb(196, 194, 194)';
                                }}
                                onDragOver={e => {
                                  e.preventDefault();
                                  refs.drag_drop_el.current.style.border =
                                    '1px solid #878dcd';
                                }}
                                onDrop={e =>
                                  handleSetState(handleAddCSV(e, refs))
                                }
                              >
                                <img
                                  src={csvLogo}
                                  alt={
                                    csv
                                      ? csv.name
                                      : t(
                                          'addGroupMembers.inputs.groupMembers.addCSV',
                                        )
                                  }
                                />
                                <br />
                                {csv
                                  ? csv.name
                                  : t(
                                      'addGroupMembers.inputs.groupMembers.addCSV',
                                    )}
                                <FormHelperText
                                  error
                                  className={classes.fieldHelperTextStyle}
                                >
                                  {(props.status &&
                                    props.status['group_members']) ||
                                    (props.touched['group_members'] &&
                                      props.errors['group_members'] &&
                                      t(
                                        `addGroupMembers.inputs.groupMembers.errors.${props.errors['group_members']}`,
                                      ))}
                                </FormHelperText>
                                <input
                                  type="file"
                                  accept=".csv"
                                  style={{ display: 'none' }}
                                  id="addcsv"
                                  onChange={e =>
                                    handleSetState({
                                      csv: e.target.files[0],
                                    })
                                  }
                                />
                              </Box>
                            </label>
                          )}
                        </Grid>
                      </FormControl>
                    </Grid>
                    <Grid item xs={12} sm={8}>
                      <FormControlLabel
                        className={common_classes.floatLeft}
                        control={
                          <Switch
                            className={classes.bulkAddStyles}
                            checked={bulk_add_checked}
                            onChange={e =>
                              handleSetState(
                                handleBulkAddCheck(bulk_add_checked),
                              )
                            }
                          />
                        }
                        label={
                          <Typography
                            color="textSecondary"
                            className={classes.customLabelStyle}
                          >
                            {t('addGroupMembers.inputs.groupMembers.bulkAdd')}
                          </Typography>
                        }
                      />
                    </Grid>
                    <Grid item xs={12} sm={4}>
                      <CustomButton
                        variant="contained"
                        size="large"
                        type="submit"
                        primaryButtonStyle
                        customButtonStyle
                        fullWidth
                        className={common_classes.floatRight}
                      >
                        {t('addGroupMembers.inputs.submit')}
                      </CustomButton>
                    </Grid>
                  </Grid>
                </form>
                <Dialog
                  PaperProps={{
                    style: {
                      backgroundColor: 'transparent',
                      boxShadow: 'none',
                      overflow: 'hidden',
                    },
                  }}
                  open={upload_dialog}
                  aria-label={t('addGroupMembers.ariaLabels.submitting')}
                >
                  <Box position="relative" display="inline-flex">
                    <CircularProgress
                      className={classes.uploadProgressStyle}
                      size={70}
                      thickness={6}
                    />
                  </Box>
                </Dialog>
              </CardContent>
            </CardActionArea>
          </Card>
        </Container>
      </Box>
    );
  }
}
Example #25
Source File: App.js    From covid-vaccine-notification-system with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/*
  *	Author:- Rahul Malhotra
  *	Description:- This method is used to render the UI
  */
  render() {
    const { classes } = this.props;
    const {
      states,
      districts,
      vaccines,
      prices,
      ages,
      centreIdsToSkip,
      searchOptions,
      hasSearched,
      vaccinesData,
      notify,
      selectedSearchBy,
      pincode,
      hasError,
      selectedState,
      selectedDistrict,
      selectedAge,
      selectedVaccine,
      selectedVaccinePrice,
      minDose1,
      minDose2,
      showBookVaccineConfirmationModal
    } = this.state;
    let showHiddenVaccineCentersButton, notifyButton, clearNotifyButton;

    // * Setting up show hidden vaccination centres button
    if (centreIdsToSkip.length) {
      showHiddenVaccineCentersButton = (
        <FormControl className={classes.formControl}>
          <Button
            variant="contained"
            color="secondary"
            onClick={this.clearCentreIdsToSkip.bind(this)}
            startIcon={<Visibility />}
          >
            Show Hidden Vaccination Centres
          </Button>
        </FormControl>
      );
    }

    // * Setting up notifications button
    if (
      hasSearched &&
      vaccinesData.length === 0 &&
      !notify &&
      (
        (
          selectedSearchBy === 'district' &&
          this.stateSelected() &&
          this.districtSelected()
        ) ||
        (
          selectedSearchBy === 'pincode' &&
          this.pincodeEntered()
        )
      )
    ) {
      notifyButton = (
        <FormControl className={classes.formControl}>
          <Button
            variant="contained"
            color="primary"
            onClick={this.notifyVaccineAvailability.bind(this)}
            endIcon={<Notifications />}
          >
            Notify me when vaccines are available
          </Button>
        </FormControl>
      );
    }

    // * Setting up stop notifications button
    if (notify) {
      clearNotifyButton = (
        <FormControl className={classes.formControl}>
          <Button
            variant="contained"
            color="secondary"
            onClick={this.clearNotificationSearch.bind(this)}
            endIcon={<Close />}
          >
            Stop Notifications
          </Button>
        </FormControl>
      )
    }

    // * Setting up the UI
  return (
      <div>
        <Card style={{ margin: '1rem' }}>
          <CardContent>
            <Typography gutterBottom variant="h5" component="h2">
              COVID-19 Vaccine Notification System
            </Typography>
            {/* Form Inputs */}
            <FormControl variant="outlined" className={classes.formControl}>
              <InputLabel id="searchBy-label">Search by</InputLabel>
              <Select
                labelId="searchBy-label"
                id="searchBy-input"
                value={selectedSearchBy}
                onChange={this.selectSearchBy}
                label="Search by"
                autoFocus
                >
                {searchOptions.map((searchOption) => (
                  <MenuItem key={searchOption.id} value={searchOption.value}>
                    {searchOption.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            {
              (selectedSearchBy === 'pincode') && (
                <FormControl required variant="outlined" className={classes.formControl} error={pincode && !this.pincodeEntered()}>
                  <TextField
                    required
                    id="outlined-pincode"
                    label="Enter pincode"
                    variant="outlined"
                    value={pincode}
                    type="number"
                    onChange={this.setPincode}
                    error={hasError && !this.pincodeEntered()}
                    helperText={
                      hasError && !this.pincodeEntered() &&
                      (
                        "Please enter pincode"
                      )
                    }
                  />
                </FormControl>
              )
            }
            {
              (selectedSearchBy === 'district') && (
                <span>
                  <FormControl required variant="outlined" className={classes.formControl} error={hasError && !this.stateSelected()}>
                  <InputLabel id="state-label">Select state</InputLabel>
                  <Select
                    labelId="state-label"
                    id="state-input"
                    value={selectedState}
                    onChange={this.selectState}
                    label="Select state"
                    error={hasError && !this.stateSelected()}
                  >
                    {states.map((state) => (
                      <MenuItem key={state.state_id} value={state.state_id}>
                        {state.state_name}
                      </MenuItem>
                    ))}
                  </Select>
                  {
                    hasError && !this.stateSelected() &&
                    (
                      <FormHelperText>Please select a state</FormHelperText>
                    )
                  }
                </FormControl>
                  <FormControl required variant="outlined" className={classes.formControl} error={hasError && !this.districtSelected()}>
                    <InputLabel id="district-label">Select district</InputLabel>
                    <Select
                      labelId="district-label"
                      id="district-input"
                      value={selectedDistrict}
                      onChange={this.selectDistrict}
                      label="Select district"
                      error={hasError && !this.districtSelected()}
                    >
                      {districts.map((district) => (
                        <MenuItem
                          key={district.district_id}
                          value={district.district_id}
                        >
                          {district.district_name}
                        </MenuItem>
                      ))}
                    </Select>
                    {
                      hasError && !this.districtSelected() &&
                      (
                        <FormHelperText>Please select a district</FormHelperText>
                      )
                    }
                  </FormControl>
                </span>
              )
            }
            <FormControl variant="outlined" className={classes.formControl}>
              <InputLabel id="vaccine-label">Select vaccine</InputLabel>
              <Select
                labelId="vaccine-label"
                id="vaccine-input"
                value={selectedVaccine}
                onChange={this.selectVaccine}
                label="Select vaccine"
              >
                {vaccines.map((vaccine) => (
                  <MenuItem key={vaccine.id} value={vaccine.value}>
                    {vaccine.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <FormControl variant="outlined" className={classes.formControl}>
              <InputLabel id="price-label">Select price</InputLabel>
              <Select
                labelId="price-label"
                id="price-input"
                value={selectedVaccinePrice}
                onChange={this.selectVaccinePrice}
                label="Select price"
              >
                {prices.map((price) => (
                  <MenuItem key={price.id} value={price.value}>
                    {price.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <FormControl variant="outlined" className={classes.formControl}>
              <InputLabel id="age-label">Minimum age</InputLabel>
              <Select
                labelId="age-label"
                id="age-input"
                value={selectedAge}
                onChange={this.selectAge}
                label="Minimum age"
              >
                {ages.map((age) => (
                  <MenuItem key={age.id} value={age.value}>
                    {age.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <FormControl variant="outlined" className={classes.formControl}>
              <TextField
                id="outlined-min-vaccine-dose-1"
                label="Quantity required - 1st dose"
                variant="outlined"
                value={minDose1}
                type="number"
                onChange={this.setMinimumDose1}
                onFocus={this.focusMinimumDose1}
              />
            </FormControl>
            <FormControl variant="outlined" className={classes.formControl}>
              <TextField
                id="outlined-min-vaccine-dose-2"
                label="Quantity required - 2nd dose"
                variant="outlined"
                value={minDose2}
                type="number"
                onChange={this.setMinimumDose2}
                onFocus={this.focusMinimumDose2}
              />
            </FormControl>
            <br />
            <FormControl className={classes.formControl}>
              <Button
                variant="contained"
                color="primary"
                onClick={this.fetchVaccineCentres.bind(this)}
                startIcon={<Search />}
              >
                Search Vaccination Centres
              </Button>
            </FormControl>
            {showHiddenVaccineCentersButton}
            {notifyButton}
            {clearNotifyButton}
            <FormControl className={classes.formControl}>
              <Button
                variant="contained"
                color="primary"
                onClick={this.displayBookVaccineModal.bind(this)}
                endIcon={<ArrowForward />}
              >
                Book Vaccination Slot
              </Button>
              <ConfirmModal open={showBookVaccineConfirmationModal} onConfirm={this.bookVaccineSlot.bind(this)} onReject={this.closeBookVaccineModal.bind(this)} onClose={this.closeBookVaccineModal.bind(this)} heading="Book Vaccination Slot?" description="Please make sure that you take a note of the center details before proceeding" confirmButtonText="Yes" rejectButtonText="No" />
            </FormControl>
          </CardContent>
        </Card>
        {/* Data Table */}
        <div style={{ maxWidth: "100%", margin: '1rem' }}>
          <MaterialTable
            icons={tableIcons}
            columns={[
              { title: "Date", field: "date" },
              { title: "Center Name", field: "name" },
              { title: "Center Address", field: "address" },
              { title: "Vaccine Name", field: "vaccineName" },
              { title: "Minimum Age Required", field: "minAge" },
              { title: "Price", field: "price" },
              { title: "1st Dose Availability", field: "dose1Availability", type: "numeric" },
              { title: "2nd Dose Availability", field: "dose2Availability", type: "numeric" }
            ]}
            data={vaccinesData}
            title="Vaccination Centres"
            options={{ selection: true }}
            actions={[
              {
                tooltip: "Remove centres from search results",
                icon: () => {
                  return <VisibilityOff />;
                },
                onClick: (event, centres) => {
                  // * Removing selected centres from search results
                  let currentCentreIdsToSkip = [...centreIdsToSkip];
                  centres.forEach((centre) =>
                    currentCentreIdsToSkip.push(centre.center_id)
                  );
                  // * Setting up unique centre ids to skip
                  this.setState({
                    centreIdsToSkip: currentCentreIdsToSkip.filter(this.getUnique),
                  });
                  // * Removing centres from search results
                  this.setState({
                    vaccinesData: vaccinesData.filter((vaccine) => !currentCentreIdsToSkip.includes(vaccine.center_id))
                  });
                },
              },
            ]}
          />
        </div>
        {/* Hit Counter */}
        <br />
        <center><b>Total Views Worldwide</b></center>
        <br />
        <center>
          <a href="https://www.hitwebcounter.com" target="_blank" rel="noreferrer">
            <img src="https://hitwebcounter.com/counter/counter.php?page=7816923&style=0005&nbdigits=9&type=page&initCount=0" title="Free Counter" Alt="web counter" border="0" />
        </a>
        </center>
        <br />
    </div>
  );
}
Example #26
Source File: index.jsx    From product-collector with MIT License 4 votes vote down vote up
export default function Filters() {
  const { filter, setFilter, countries, setCountries } = useContext(
    TrendContext
  );
  const { control, errors, setValue } = useForm();

  const query = `
    {
      countries
    }
  `;

  const requestData = useRequestData(query);

  useEffect(() => {
    if (requestData.countries) {
      const values = ['Todos', ...requestData.countries];
      setCountries(values);
    }
  }, [JSON.stringify(requestData)]);

  useEffect(() => {
    Object.entries(filter).map(([key, value]) => {
      setValue(key, value);
    });
  }, [filter.toString()]);

  const handleChange = ([event]) => {
    const {
      target: { name, value },
    } = event;
    const currentFilter = { [name]: value };
    setFilter({ ...filter, ...currentFilter });
    return value;
  };

  return (
    <section className={styles.filters}>
      <FormControl
        className={styles.formControl}
        error={Boolean(errors.country)}
      >
        <InputLabel>Por paĆ­s</InputLabel>
        <Controller
          as={
            <Select>
              {countries.map((item, index) => (
                <MenuItem key={index} value={index}>
                  {item}
                </MenuItem>
              ))}
            </Select>
          }
          name='country'
          rules={{ required: 'Valor requerido' }}
          control={control}
          defaultValue={0}
          onChange={handleChange}
        />
        <FormHelperText>
          {errors.country && errors.country.message}
        </FormHelperText>
      </FormControl>
      <FormControl className={styles.formControl} error={Boolean(errors.date)}>
        <InputLabel>Por fecha</InputLabel>
        <Controller
          as={
            <Select>
              {dateFilters.map(({ label }, index) => (
                <MenuItem key={index} value={index}>
                  {label}
                </MenuItem>
              ))}
            </Select>
          }
          name='date'
          rules={{ required: 'Valor requerido' }}
          control={control}
          defaultValue={0}
          onChange={handleChange}
        />
        <FormHelperText>{errors.date && errors.date.message}</FormHelperText>{' '}
      </FormControl>
    </section>
  );
}
Example #27
Source File: App.js    From cloud-dapr-demo with MIT License 4 votes vote down vote up
export default function App() {
  const classes = useStyles();
  const [activeStep, setActiveStep] = useState(0);
  const [food, setFood] = useState('');
  const [drink, setDrink] = useState('');
  const [loading, setLoading] = useState(false);
  const [orderId, setOrderId] = useState(null);
  const [status, setStatus] = useState(null);

  const steps = getSteps();

  function submitOrder() {
    setLoading(true);
    axios.post(`${baseUrl}/order`, {
      food, drink
    }).then((res) => {
      setOrderId(res.data.id);
    }).finally(() => setLoading(false));
  }

  useEffect(() => {
    if (orderId) {
      pollStatus(orderId);
    }
  }, [orderId]);

  useEffect(() => {
    if (status) {
      let activeIndex = 0;
      switch (status) {
        case 'OrderReceived':
          activeIndex = 0;
          break;
        case 'Processing':
          activeIndex = 1;
          break;
        case 'ReadyToPickup':
          activeIndex = 2;
          break;
        case 'DeliveryOnWay':
          activeIndex = 3;
          break;
        case 'Delivered':
          activeIndex = 4;
          break;
      }
      setActiveStep(activeIndex);
    }
  }, [status]);

  function pollStatus(id) {
    setTimeout(async () => {
      const status = await fetchStatus(id);
      setStatus(status);
      if (status !== 'Delivered') {
        pollStatus(id);
      }
    }, 500);
  }

  async function fetchStatus(id) {
    return axios.get(`${baseUrl}/order/${id}`)
      .then(res => res.data)
      .then(data => data.status)
      .catch((e) => console.error(e));
  }

  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Toolbar>
          <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" className={classes.title}>
            Demo: Event Driven Apps with Dapr in Kubernetes
          </Typography>
        </Toolbar>
      </AppBar>
      <Container maxWidth="sm">
        <Grid container style={{ marginTop: 40 }}>
          <Grid item xs={6} spacing={3}>
            <FormControl component="fieldset" className={classes.formControl}>
              <FormLabel component="legend">Food</FormLabel>
              <RadioGroup aria-label="food" name="food" value={food}
                onChange={(e) => setFood(e.target.value)}>
                <FormControlLabel value="pizza" control={<Radio />} label="Pizza ?" />
                <FormControlLabel value="burger" control={<Radio />} label="Burger ?" />
                <FormControlLabel value="sandwich" control={<Radio />} label="Sandwich ?" />
                <FormControlLabel value="hotdog" control={<Radio />} label="HotDog ?" />
                <FormControlLabel value="fries" control={<Radio />} label="Fries ?" />
              </RadioGroup>
            </FormControl>
          </Grid>
          <Grid item xs={6}>
            <FormControl component="fieldset" className={classes.formControl}>
              <FormLabel component="legend">Drink</FormLabel>
              <RadioGroup aria-label="drink" name="drink" value={drink}
                onChange={(e) => setDrink(e.target.value)}>
                <FormControlLabel value="drink1" control={<Radio />} label="Diet Coke" />
                <FormControlLabel value="drink2" control={<Radio />} label="Coke" />
                <FormControlLabel value="drink3" control={<Radio />} label="Coffee" />
                <FormControlLabel value="drink4" control={<Radio />} label="Iced Tea" />
                <FormControlLabel value="drink5" control={<Radio />} label="Beer" />
                <FormControlLabel value="drink6" control={<Radio />} label="Orange Juice" />
              </RadioGroup>
              <FormHelperText></FormHelperText>
            </FormControl>
          </Grid>
          <Button type="submit" variant="outlined" disabled={!(food && drink)}
            color="primary" className={classes.button}
            onClick={submitOrder}>
            {loading && <CircularProgress
              className={classes.spinner}
              size={20}
            />}
            Submit Order
          </Button>
        </Grid>
        {orderId && <Grid container style={{ marginTop: 50 }}>
          <Grid item>
            <Typography variant="h6" className={classes.title}>
              Order ID: {orderId}
            </Typography>
          </Grid>
          <Grid item>
            <Stepper activeStep={activeStep} alternativeLabel>
              {steps.map((label) => (
                <Step key={label}>
                  <StepLabel StepIconComponent={QontoStepIcon}>{label}</StepLabel>
                </Step>
              ))}
            </Stepper>
          </Grid>
        </Grid>
        }
      </Container>
    </div >
  );
}
Example #28
Source File: NewRequestPage.js    From app with MIT License 4 votes vote down vote up
function NewRequestPage() {
  const classes = useStyles();
  const location = useLocation();
  const qs = queryString.parse(location.search);
  const defaultValues = {
    needs: {},
    immediacy: '1',
    needFinancialAssistance: 'false',
  };

  // Append needs from query string type
  if (qs && qs.type) {
    defaultValues.needs = { [qs.type]: true };
  }

  const {
    register,
    handleSubmit,
    errors,
    watch,
    control,
    formState: { isValid, isSubmitting, dirty },
  } = useForm({
    validationSchema: requestValidationSchema,
    defaultValues,
  });

  const {
    submitRequest,
    handleLocationChange,
    requestLocation,
    requestLocationLoading,
  } = useNewRequestPage();
  const currentNeeds = watch('needs');
  const groceryPickup = currentNeeds && currentNeeds['grocery-pickup'];

  return (
    <Container maxWidth="md">
      <Helmet>
        <title>Request Assistance</title>
      </Helmet>
      <Typography variant="h5" color="textPrimary" gutterBottom>
        Request Help
      </Typography>
      <Paper className={classes.paper} data-test="request-form">
        <div className={classes.heroContent}>
          <Container maxWidth="md">
            <form onSubmit={handleSubmit(submitRequest)}>
              <Container>
                <FormGroup>
                  <Typography
                    variant="h5"
                    gutterBottom
                    className={classes.otherComments}>
                    What do you need help with?
                  </Typography>
                  {Object.keys(activeCategoryMap).map((optionKey) => (
                    <FormControlLabel
                      key={optionKey}
                      control={
                        <Checkbox
                          inputRef={register}
                          name={`needs.${optionKey}`}
                          data-test={`need-${optionKey}`}
                          defaultChecked={defaultValues.needs[optionKey]}
                        />
                      }
                      label={
                        activeCategoryMap[optionKey].inputCaption
                          ? activeCategoryMap[optionKey].inputCaption
                          : activeCategoryMap[optionKey].description
                      }
                    />
                  ))}
                </FormGroup>
                {!!errors.needs && (
                  <FormHelperText error>{errors.needs.message}</FormHelperText>
                )}

                <Typography
                  variant="h5"
                  className={classes.otherComments}
                  gutterBottom={!groceryPickup}>
                  Details
                </Typography>
                <Zoom in={groceryPickup} unmountOnExit>
                  <Typography variant="subtitle1" gutterBottom>
                    For grocery pickup, please provide the list of groceries
                    that you would like the volunteer to get. Please be as
                    specific as possible.
                  </Typography>
                </Zoom>
                <Grid container spacing={3}>
                  <Grid item xs={12}>
                    <TextField
                      name="otherDetails"
                      data-test="otherDetails"
                      multiline
                      placeholder="Please be as specific as possible."
                      fullWidth
                      rows="4"
                      variant="outlined"
                      inputRef={register}
                    />
                  </Grid>
                </Grid>

                {/* <Zoom in={hasFinancialComponent} unmountOnExit> */}
                <div>
                  <Divider className={classes.optionalDivider} />
                  <Typography variant="h5" gutterBottom>
                    Will you be able to pay for your items?
                  </Typography>
                  <Typography variant="body1" gutterBottom>
                    This service is free, but the items still cost money. Are
                    you able to pay for your items? If not, we will do our best
                    to match you with organizations and volunteers who can also
                    provide financial assistance.
                  </Typography>
                  <Controller
                    as={
                      <RadioGroup
                        aria-label="Need Financial Assistance"
                        component="fieldset">
                        <FormControlLabel
                          value="false"
                          control={<Radio />}
                          label="Yes, I can pay and only need help with the delivery."
                        />
                        <FormControlLabel
                          value="true"
                          control={<Radio />}
                          label="No, I need help paying for the items."
                        />
                      </RadioGroup>
                    }
                    control={control}
                    onChange={([event]) => event.target.value}
                    name="needFinancialAssistance"
                  />
                  {!!errors.needFinancialAssistance && (
                    <FormHelperText error>
                      {errors.needFinancialAssistance}
                    </FormHelperText>
                  )}
                </div>
                {/* </Zoom> */}

                <Divider className={classes.optionalDivider} />
                <Typography variant="h5" gutterBottom>
                  Immediacy of Need
                </Typography>
                <Typography variant="body1" gutterBottom>
                  Please let us know how urgently you need us to fulfill the
                  request. We will do our best to connect you with a volunteer
                  as soon as possible, however, we cannot guarantee anything
                  because we are dependent on volunteer availability.
                </Typography>
                <Controller
                  as={
                    <RadioGroup>
                      <FormControlLabel
                        value="1"
                        control={<Radio />}
                        label="Low"
                      />
                      <FormControlLabel
                        value="5"
                        control={<Radio />}
                        label="Medium - Not very urgent"
                      />
                      <FormControlLabel
                        value="10"
                        control={<Radio />}
                        label="High - Urgent"
                      />
                    </RadioGroup>
                  }
                  control={control}
                  name="immediacy"
                />

                {!!errors.immediacy && (
                  <FormHelperText error>
                    {errors.immediacy.message}
                  </FormHelperText>
                )}

                <Divider className={classes.optionalDivider} />
                <Typography variant="h5" gutterBottom>
                  Your Location
                </Typography>
                <Typography className={classes.intro}>
                  A rough location is needed to allow us to efficiently and
                  quickly find a match for your need. You can do this in three
                  ways: by entering your address in the address field, by
                  clicking the &quot;Detect Location&quot; button, or by
                  clicking on the map. If you decide to enter the address, we
                  will not save the actual address and instead use it to get the
                  location.
                </Typography>
                <Grid container spacing={3}>
                  <Grid item xs={12}>
                    <Card>
                      {requestLocationLoading ? (
                        <LoadingSpinner />
                      ) : (
                        <ClickableMap
                          locationInfo={requestLocation}
                          onLocationChange={handleLocationChange}
                        />
                      )}
                    </Card>
                  </Grid>
                </Grid>
                <Divider className={classes.optionalDivider} />
                <Typography variant="h5" gutterBottom>
                  Contact Information
                </Typography>
                <Typography gutterBottom>
                  To minimize exposing your contact information, we do not
                  display it unless a volunteer specifically requests to see it.
                  To further discourage any abuse, we do not display your last
                  name and also keep track of all the volunteers who have looked
                  up your contact information.
                </Typography>

                <Grid container spacing={2}>
                  <Grid item xs={12} sm={6}>
                    <TextField
                      name="firstName"
                      data-test="firstName"
                      type="text"
                      label="First Name"
                      variant="outlined"
                      inputRef={register}
                      error={!!errors.firstName}
                      fullWidth
                      helperText={errors?.firstName?.message}
                    />
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <TextField
                      name="lastName"
                      data-test="lastName"
                      type="text"
                      label="Last Name"
                      variant="outlined"
                      fullWidth
                      inputRef={register}
                      error={!!errors.lastName}
                      helperText={errors?.firstName?.message}
                    />
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <TextField
                      name="phone"
                      data-test="phone"
                      type="text"
                      label="Phone Number"
                      variant="outlined"
                      fullWidth
                      inputRef={register}
                      error={!!errors.phone}
                      helperText={errors?.phone?.message}
                    />
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <TextField
                      name="email"
                      type="text"
                      data-test="email"
                      label="Email"
                      variant="outlined"
                      fullWidth
                      inputRef={register}
                      error={!!errors.email}
                      helperText={errors?.email?.message}
                    />
                  </Grid>
                </Grid>

                <Typography className={classes.warrantyInfo}>
                  Note: This website and all related work products are provided
                  &quot;AS IS&quot;. The provider of this service makes no other
                  warranties, express or implied, and hereby disclaims all
                  implied warranties, including any warranty of merchantability
                  and warranty of fitness for a particular purpose.
                </Typography>

                {dirty && !!Object.keys(errors).length && !isValid && (
                  <Typography variant="body2" className={classes.errorText}>
                    Please fix the errors above.
                  </Typography>
                )}

                <div className={classes.buttons}>
                  <Button
                    type="submit"
                    variant="contained"
                    color="primary"
                    data-test="submit-request"
                    disabled={isSubmitting}>
                    Submit Request
                  </Button>
                </div>
              </Container>
            </form>
          </Container>
        </div>
      </Paper>
    </Container>
  );
}
Example #29
Source File: images-constructor.js    From horondi_client_fe with MIT License 4 votes vote down vote up
ImagesConstructor = () => {
  const {
    constructorValues,
    setConstructorValues,
    constructorModel,
    setConstructorModel,
    currentConstructorModel,
    allPrices,
    allModels,
    setAllPrice,
    constructorsError,
    constructorError,
    valuesLoading
  } = useConstructorLoader();

  const { getPriceWithCurrency, getCurrencySign } = useCurrency();
  const { currency } = useContext(CurrencyContext);

  const { basePrice } = constructorValues;

  const defaultPrice = getPriceWithCurrency(basePrice);

  const [modalVisibility, setModalVisibility] = useState(false);
  const styles = useStyles();
  const appStyles = useAppStyles();
  const { t } = useTranslation();

  const canvasH = 768;
  const canvasW = 768;

  const showModal = () => {
    setModalVisibility(true);
  };

  const onModalAction = () => {
    setModalVisibility(false);
  };

  useEffect(() => {
    const getPrice = (key) => getPriceWithCurrency(constructorValues[key].absolutePrice);

    setAllPrice(
      Object.keys(constructorValues).reduce((acc, key) => {
        if (key === 'pattern' && constructorValues.pattern !== undefined) {
          acc.pattern = getPrice(key);
        }

        if (key === 'bottom') {
          acc.bottom = getPrice(key);
        }

        return acc;
      }, {})
    );
  }, [constructorValues, currency, setAllPrice]);

  const { isError } = useIsLoadingOrError([], [constructorsError, constructorError]);
  if (valuesLoading) {
    return errorOrLoadingHandler(isError, valuesLoading);
  }

  function price() {
    if (allPrices.pattern) {
      return constructorEndPrice(defaultPrice + allPrices.pattern + allPrices.bottom);
    }
    return constructorEndPrice(defaultPrice + allPrices.bottom);
  }

  const costPattern = constructorValues.pattern ? constructorValues.pattern.absolutePrice : null;

  const sizeAndPrice = {
    price: basePrice + costPattern + constructorValues.bottom.absolutePrice,
    size: {
      available: constructorValues.size.available,
      name: constructorValues.size.name,
      _id: constructorValues.size._id
    }
  };

  return (
    <div className={appStyles.rootApp}>
      <div className={`${appStyles.containerApp} ${styles.constructorWrapper}`}>
        <div className={styles.headingWrapper}>
          <h1>{t('common.title')}</h1>
        </div>
        <hr />
        <div className={styles.contentWrapper}>
          <form className={styles.formWrapper}>
            <FormControl>
              <p className={styles.headerWrapperH1}>{t('common.backpack')}</p>
              <Select
                className={styles.selectItem}
                label='title'
                data-cy='model'
                name='model'
                value={constructorModel}
                onChange={(e) => setConstructorModel(e.target.value)}
                data-testid='model'
              >
                {allModels.current.map((model) => (
                  <MenuItem className={styles.menuItem} key={model._id} value={model._id}>
                    {t(`${model.translationsKey}.name`)}
                  </MenuItem>
                ))}
              </Select>
              <FormHelperText className={styles.formHelper}>{t('common.models')}</FormHelperText>
            </FormControl>

            <FormControl>
              <Select
                className={styles.selectItem}
                label='title'
                data-cy='basics'
                name='basic'
                value={constructorValues.basic._id}
                onChange={(e) =>
                  setConstructorValues({
                    ...constructorValues,
                    basic: currentConstructorModel.current.basics.find(
                      (basic) => basic._id === e.target.value
                    )
                  })
                }
              >
                {currentConstructorModel.current.basics.map((basic) => (
                  <MenuItem className={styles.menuItem} key={basic._id} value={basic._id}>
                    {t(`${basic.translationsKey}.name`)}
                  </MenuItem>
                ))}
              </Select>
              <FormHelperText className={styles.formHelper}>{t('common.basis')}</FormHelperText>
            </FormControl>

            <FormControl>
              <Select
                className={styles.selectItem}
                label='title'
                name='patern'
                value={constructorValues.pattern?._id || ''}
                onChange={(e) => {
                  setConstructorValues({
                    ...constructorValues,
                    pattern: currentConstructorModel.current.patterns.find(
                      (pattern) => pattern._id === e.target.value
                    )
                  });
                  setAllPrice((prevState) => ({
                    ...prevState,
                    pattern: constructorValues.pattern.absolutePrice
                  }));
                }}
              >
                {currentConstructorModel.current.patterns.map((pattern) => (
                  <MenuItem className={styles.menuItem} key={pattern._id} value={pattern._id}>
                    {t(`${pattern.translationsKey}.name`)}
                  </MenuItem>
                ))}
              </Select>
              <FormHelperText className={styles.formHelper}>{t('common.patterns')}</FormHelperText>
            </FormControl>

            <FormControl>
              <Select
                className={styles.selectItem}
                label='title'
                data-cy='bottom'
                name='bottom'
                value={constructorValues.bottom._id}
                onChange={(e) => {
                  setConstructorValues({
                    ...constructorValues,
                    bottom: currentConstructorModel.current.bottoms.find(
                      (bottom) => bottom._id === e.target.value
                    )
                  });
                  setAllPrice((prevState) => ({
                    ...prevState,
                    bottom: constructorValues.bottom.absolutePrice
                  }));
                }}
              >
                {currentConstructorModel.current.bottoms.map((bottom) => (
                  <MenuItem className={styles.menuItem} key={bottom._id} value={bottom._id}>
                    {t(`${bottom.translationsKey}.name`)}
                  </MenuItem>
                ))}
              </Select>
              <FormHelperText className={styles.formHelper}>{t('common.bottom')}</FormHelperText>
            </FormControl>

            <FormControl>
              <Select
                className={styles.selectItem}
                label='title'
                data-cy='size'
                name='size'
                value={constructorValues.size._id}
                onChange={(e) =>
                  setConstructorValues({
                    ...constructorValues,
                    size: currentConstructorModel.current.model.sizes.find(
                      (size) => size._id === e.target.value
                    )
                  })
                }
              >
                {currentConstructorModel.current.model.sizes.map((size) => (
                  <MenuItem className={styles.menuItem} key={size.name} value={size._id}>
                    {size.name}
                  </MenuItem>
                ))}
              </Select>
              <FormHelperText className={styles.formHelper}>{t('common.size')}</FormHelperText>
            </FormControl>

            <Button className={styles.buttonOptions} onClick={showModal} data-testid='modalButton'>
              <span className={styles.pluse}>+</span> {t('buttons.moreOptions')}
            </Button>

            {modalVisibility && (
              <Modal
                className={styles.modal}
                setModalVisibility={setModalVisibility}
                onAction={onModalAction}
                isOpen={modalVisibility}
                isEmpty
                isFullscreen
                content={<h3>MODAL FOR CONSTRUCTOR</h3>}
              />
            )}
          </form>

          <div className={styles.imageContainer}>
            {!constructorValues.basic && <Loader />}
            <ConstructorCanvas
              className={styles.image}
              item={constructorValues}
              width={canvasW}
              height={canvasH}
            />
          </div>

          <div className={styles.pricesInfoWrapper}>
            <p className={styles.headerWrapperH1}>{t('common.totalPrice')}</p>
            <div className={styles.textWrapper}>
              <ul>
                <div className={`${styles.line} ${styles.bottomLine}`} />
                <li className={styles.priceItem}>
                  <span>{t('common.defaultPrice')}</span>
                  <span className={styles.currencySign}>
                    {defaultPrice}
                    {getCurrencySign()}
                  </span>
                </li>
                <div className={`${styles.line} ${styles.topLine}`} />
                {constructorPartPrice(allPrices.pattern, allPrices.bottom).map((item, index) =>
                  item ? (
                    <li key={index} className={styles.priceItem}>
                      <span>
                        {t(`common.constructorAdditionals`, { returnObjects: true })[index]}
                      </span>
                      <span className={styles.currencySign}>
                        {item} {getCurrencySign()}
                      </span>
                    </li>
                  ) : (
                    <div key={index} />
                  )
                )}
                <div className={`${styles.line} ${styles.bottomLine}`} />
              </ul>
            </div>
            <h2 className={styles.headerWrapper}>
              {t('common.endPrice')}
              <span className={styles.currencySign}>
                {price()}
                {getCurrencySign()}
              </span>
            </h2>
            <ConstructorSubmit
              constructorValues={constructorValues}
              sizeAndPrice={sizeAndPrice}
              allSizes={currentConstructorModel.current.sizes}
            />
          </div>
        </div>
      </div>
    </div>
  );
}