@material-ui/core#Backdrop JavaScript Examples

The following examples show how to use @material-ui/core#Backdrop. 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: Modal.js    From web-wallet with Apache License 2.0 6 votes vote down vote up
function _Modal ({
  children,
  open,
  onClose,
  light
}) {
  const classes = useStyles();

  return (
    <Modal
      aria-labelledby='transition-modal-title'
      aria-describedby='transition-modal-description'
      className={classes.modal}
      open={open}
      onClose={onClose}
      closeAfterTransition
      BackdropComponent={Backdrop}
      BackdropProps={{
        timeout: 500
      }}
    >
      <Fade in={open}>
        <div
          className={[
            classes.paper,
            light ? classes.light : ''
          ].join(' ')}
        >
          {children}
        </div>
      </Fade>
    </Modal>
  );
}
Example #2
Source File: index.js    From AED-Map with MIT License 6 votes vote down vote up
ModalWrapper = ({ ButtonOpen, ModalContent }) => {
  const classes = useStyles();
  const [open, setOpen] = useState(false);

  const handleOpen = event => {
    event.preventDefault();
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  return (
    <>
      <ButtonOpen handleOpen={handleOpen} />

      <Modal
        className={classes.modal}
        open={open}
        onClose={handleClose}
        closeAfterTransition
        BackdropComponent={Backdrop}
        BackdropProps={{
          timeout: 500
        }}
      >
        <Fade in={open}>
          <div className={classes.paper}>
            <ModalContent handleClose={handleClose} />
          </div>
        </Fade>
      </Modal>
    </>
  );
}
Example #3
Source File: Spinner.js    From inventory-management-web with MIT License 6 votes vote down vote up
export default function Spinner() {
  const classes = useStyles();

  return (
    <Backdrop className={classes.backdrop} open>
      <CircularProgress color='inherit' />
    </Backdrop>
  );
}
Example #4
Source File: metrics.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
Metrics = () => {
  const {loading, error, data} = useQuery(query);
  const [newMetricName, setNewMetricName] = useState("");
  const [addMetric, { loading: mutationLoading }] = useMutation(addMetricMutation, {
    awaitRefetchQueries: true,
    refetchQueries: [{query}],
  });

  const metrics = data?.queryMetric || []

  return <>
    <Navbar title="Metrics" color="primary" />
    <Content>
      {loading && <Backdrop open={loading || mutationLoading} >
        <CircularProgress />
      </Backdrop>}
      {error && <Alert severity="error">Something Went Horribly Wrong</Alert>}
      <Card style={{ padding: 30 }}>
        <Typography>Here are the metrics currently configured:</Typography>
        <List>
          {metrics.map(({ name }, index) => <ListItem item key={index} sm={12} md={6} lg={3}>
            <Typography>{name}</Typography>
          </ListItem>)}
        </List>

        <TextField
          label="Add Metric"
          defaultValue={newMetricName}
          onChange={e => setNewMetricName(e.target.value)}
        />
        <UglyButton onClick={() => addMetric({ variables: { newMetricName } })} disabled={newMetricName === ""}>
          Add Metric
        </UglyButton>
      </Card>
    </Content>
  </>
}
Example #5
Source File: Agents.js    From voicemail-for-amazon-connect with Apache License 2.0 5 votes vote down vote up
render() {
        let classes = this.props.classes;
        if (this.props.role === "") {
            return (
                <div>
                    <NavigationBar/>
                    <p> The user you logged in with is not in the "Manager" Cognito User Pool group. You must be a member of this group to view this page.</p>
                </div>
            )
        }

        return (
            <div>
                <NavigationBar/>
                <AgentsTable className={classes.agentsTable}/>
                <Dialog
                    scroll="paper"
                    disableAutoFocus={true}
                    open={this.props.showGlobalSettingsModal}
                    closeAfterTransition
                    BackdropComponent={Backdrop}
                    onClose={() => {
                        this.props.showSettings(false)
                    }}>
                    <Fade in={this.props.showGlobalSettingsModal}>
                        <DialogContent>
                            <GlobalSettings/>
                        </DialogContent>
                    </Fade>
                </Dialog>
                <Dialog
                    scroll="paper"
                    disableAutoFocus={true}
                    open={this.props.showAgentSettings}
                    closeAfterTransition
                    BackdropComponent={Backdrop}
                    onClose={() => {
                        this.props.showAgentModal(false)
                    }}>
                    <Fade in={this.props.showAgentSettings}>
                        <DialogContent>
                            <AgentSettings/>
                        </DialogContent>
                    </Fade>
                </Dialog>
                <Dialog
                    scroll="paper"
                    disableAutoFocus={true}
                    open={this.props.showContactFlowModal}
                    closeAfterTransition
                    BackdropComponent={Backdrop}
                    onClose={() => {
                        this.props.showContactFlow(false)
                    }}>
                    <Fade in={this.props.showContactFlowModal}>
                        <DialogContent>
                            <ContactFlow/>
                        </DialogContent>
                    </Fade>
                </Dialog>
            </div>
        )
    }
Example #6
Source File: Layout.js    From medha-STPC with GNU Affero General Public License v3.0 5 votes vote down vote up
Layout = props => {
  const { children } = props;

  const classes = useStyles();
  const theme = useTheme();
  const isDesktop = useMediaQuery(theme.breakpoints.up("lg"), {
    defaultMatches: true
  });
  const { loaderStatus } = useContext(LoaderContext);
  if (auth.getToken() != null && isDesktop) {
    return (
      <React.Fragment>
        <div
          className={clsx({
            [classes.root]: true,
            [classes.shiftContent]: isDesktop
          })}
        >
          <SideAndTopNavBar />
          <main className={classes.content}>{children}</main>
        </div>
        <Backdrop className={classes.backdrop} open={loaderStatus}>
          <CircularProgress color="inherit" />
        </Backdrop>
      </React.Fragment>
    );
  } else {
    return (
      <React.Fragment>
        <div
          className={clsx({
            [classes.root]: true,
            [classes.shiftContent]: false
          })}
        >
          <SideAndTopNavBar />
          <main className={classes.content}>{children}</main>
        </div>
        <Backdrop className={classes.backdrop} open={loaderStatus}>
          <CircularProgress color="inherit" />
        </Backdrop>
      </React.Fragment>
    );
  }
}
Example #7
Source File: index.js    From yi-note with GNU General Public License v3.0 5 votes vote down vote up
SupportExtension = () => {
  const { t } = useTranslation('notesView');
  const { open } = useStoreState(state => state.videoNotes.support);
  const { setOpen } = useStoreActions(actions => actions.videoNotes.support);
  const containerRef = useRef(null);
  const [message, setMessage] = useState({});

  useEffect(() => {
    containerRef.current = document.getElementById(APP_ID);
  }, []);

  const clearState = () => {
    setMessage({});
  };

  const handleClose = () => {
    clearState();
    setOpen(false);
  };

  return (
    <StyledModal
      container={containerRef.current}
      open={open}
      onClose={handleClose}
      closeAfterTransition
      BackdropComponent={Backdrop}
      BackdropProps={{
        timeout: 500
      }}
    >
      <Fade in={open}>
        <StyledPaper>
          <Grid container direction="column" spacing={3}>
            {message.status && (
              <Grid item>
                <Alert severity={message.status}>{message.message}</Alert>
              </Grid>
            )}
            <Grid item container justify="center">
              <Typography>{t('support.text')}</Typography>
            </Grid>
            <Grid item>
              <Sponsor />
            </Grid>
            <Grid item>
              <Star />
            </Grid>
            <Grid item>
              <Share />
            </Grid>
          </Grid>
        </StyledPaper>
      </Fade>
    </StyledModal>
  );
}
Example #8
Source File: generate-data.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
Home = ({currentTime = new Date()}) => {
  const [endDate, setEndDate] = useState(currentTime.toISOString().substr(0, 10))
  const [startDate, setStartDate] = useState(new Date(currentTime.getTime() - 28 * 3600 * 1000 * 24).toISOString().substr(0, 10))

  const {loading, error, data} = useQuery(query);

  const results = [];
  for (let date = Date.parse(startDate); date <= Date.parse(endDate); date = date + 3600 * 1000 * 24) {
    results.push({
      timestamp: new Date(date).toISOString().substr(0, 10),
      readings: (data?.queryMetric || []).map(({name}) => ({
        value: ((date - Date.parse(startDate)) / (3600 * 1000 * 24)) + Math.random() * 4,
        name
      }))
    })
  }

  return <>
    <Navbar title="Home" color="primary" />
    <Content>
      {loading && <Backdrop open={loading} >
        <CircularProgress />
      </Backdrop>}
      {error && <Alert severity="error">Something Went Horribly Wrong</Alert>}
      <Grid container spacing={3}>
        <Grid item sm={12}>
          <Card style={{ padding: 30 }}>
            <TextField
              label="From"
              type="date"
              defaultValue={startDate}
              InputLabelProps={{
                shrink: true,
              }}
              style={{marginRight: 20}}
              onChange={e => setStartDate(e.target.value)}
            />
            <TextField
              label="To"
              type="date"
              defaultValue={endDate}
              InputLabelProps={{
                shrink: true,
              }}
              onChange={e => setEndDate(e.target.value)}
            />
          </Card>
        </Grid>
        <Grid item sm={12}>
          <Card style={{ padding: 30 }}>
            <pre>{`mutation {
  addCollection(input: [
    ${results.map(({timestamp, readings}) => `{
      timestamp: "${timestamp}",
      readings: [
        ${readings.map(({value, name}) => `{value: ${value}, metric: { name: "${name}" } }`).join(",\n        ")}
      ]
    }`).join(",\n    ")}
  ]) {
    collection {
      readings {
        value
        metric { name }
      }
    }
  }
}`}</pre>
          </Card>
        </Grid>
      </Grid>
    </Content>
  </>
}
Example #9
Source File: add-data.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
AddData = ({currentTime = new Date()}) => {
  const {loading, error, data} = useQuery(query);
  const [date, setDate] = useState(currentTime.toISOString().substr(0, 10))
  const [values, setValues] = useState({})
  const [addCollectionMutation] = useMutation(addCollection);

  const metrics = data?.queryMetric || []

  const submitMetrics = async () => {
    const readings = Object.entries(values).map(([name, value]) => ({ value, metric: { name } }))
    await addCollectionMutation({ variables: {readings, date} })
    history.push("/");
  }

  return <>
    <Navbar title="Home" color="primary" />
    <Content>
      {loading && <Backdrop open={loading} >
        <CircularProgress />
      </Backdrop>}
      {error && <Alert severity="error">Something Went Horribly Wrong</Alert>}
      <Grid container spacing={3}>
        <Grid item sm={12}>
          <Card style={{ padding: 30 }}>
            <TextField
              label="Date"
              type="date"
              defaultValue={date}
              InputLabelProps={{
                shrink: true,
              }}
              style={{ marginRight: 20 }}
              onChange={e => setDate(e.target.value)}
            />
          </Card>
        </Grid>
        {metrics.map(({ name }, index) => <Grid item key={index} sm={12} md={6} lg={3}>
          <Card style={{ textAlign: "center" }}>
            <CardContent>
              <TextField
                label={name}
                type="number"
                defaultValue={0}
                InputLabelProps={{
                  shrink: true,
                }}
                style={{ marginRight: 20 }}
                onChange={e => setValues({...values, [name]: e.target.value})}
              />
            </CardContent>
          </Card>
        </Grid>)}
        <Grid item sm={12} style={{textAlign: "right"}}>
          <UglyButton onClick={submitMetrics}>Add Readings</UglyButton>
        </Grid>
      </Grid>
    </Content>
  </>
}
Example #10
Source File: home.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
Home = ({currentTime = new Date()}) => {
  const [endTime] = useState(currentTime)
  const oneMonthAgo = new Date(endTime.getTime() -  28 * 3600 * 1000 * 24);
  const startDate = oneMonthAgo.toISOString().substr(0, 10)
  const endDate = endTime.toISOString().substr(0, 10)

  const {loading, error, data, refetch} = useQuery(query, {
    variables: {
      timestampGE: startDate,
      timestampLT: endDate,
    }
  });
  const graphData = useMemo(() => {
    if(!data) { return [] }
    return (data.queryMetric || []).map(({name, readings}) => ({
      name,
      data: [
        ["Timestamp", name],
        ...readings.map(({ value, collection }) => [new Date(collection.timestamp), value]).sort(([k1], [k2]) => k1 < k2 ? -1 : 1)
      ]
    }));
  }, [data])

  return <>
    <Navbar title="Home" color="primary" />
    <Content>
      {loading && <Backdrop open={loading} >
        <CircularProgress />
      </Backdrop>}
      {error && <Alert severity="error">Something Went Horribly Wrong</Alert>}
      <Grid container spacing={3}>
        <Grid item sm={12}>
          <Card style={{ padding: 30 }}>
            <TextField
              label="From"
              type="date"
              defaultValue={startDate}
              InputLabelProps={{
                shrink: true,
              }}
              style={{marginRight: 20}}
              onChange={e => refetch({ timestampGE: e.target.value })}
            />
            <TextField
              label="To"
              type="date"
              defaultValue={endDate }
              InputLabelProps={{
                shrink: true,
              }}
              onChange={e => refetch({ timestampLT: e.target.value })}
            />
          </Card>
        </Grid>
        {graphData.map(({name, data}, index) => <Grid item key={index} sm={12} lg={6}>
          <Card style={{textAlign: "center"}}>
            <CardContent>
              <h3>{name}</h3>
              {data.length > 1
                ? <Chart
                    chartType="LineChart"
                    width="100%"
                    loader={<CircularProgress />}
                    data={data}
                    options={{
                      pointSize: 5,
                      curveType: "function",
                      legend: { position: "none" }
                    }} />
                : <Typography>Not enough Data to show this chart</Typography>}

            </CardContent>
          </Card>
        </Grid>)}
      </Grid>
    </Content>
  </>
}
Example #11
Source File: ClickableMap.js    From app with MIT License 4 votes vote down vote up
function ClickableMap({ onLocationChange, locationInfo }) {
  let generalLocation = null;
  let generalLocationName = null;
  let preciseLocation = null;

  if (locationInfo) {
    ({ generalLocation, generalLocationName, preciseLocation } = locationInfo);
  }
  // console.log(
  //   'ClickableMap',
  //   generalLocation,
  //   generalLocationName,
  //   preciseLocation,
  // );
  const classes = useStyles();
  const { showSuccess, showError } = useNotifications();
  const [map, setMap] = useState(null);
  const [detectingLocation, setDetectingLocation] = useState(false);
  const [currentPlaceLabel, setCurrentPlaceLabel] = useState('');

  async function setLocation(location) {
    const scrambledLocation = scrambleLocation(location, 300); // Roughly within 1,000 feet.
    // Detect locality
    try {
      const response = await reverseGeocode(
        location.latitude,
        location.longitude,
      );
      if (response.status === window.google.maps.GeocoderStatus.ZERO_RESULTS) {
        showError('Could not find the locality.');
        return;
      }
      const [result] = response.results;

      // Find city and state.
      let locality = null;
      let administrativeAreaLevel1 = null;
      let administrativeAreaLevel3 = null;
      result.address_components.forEach((addressComp) => {
        if (addressComp.types.indexOf('locality') !== -1) {
          locality = addressComp.long_name;
        }
        if (addressComp.types.indexOf('administrative_area_level_1') !== -1) {
          administrativeAreaLevel1 = addressComp.short_name;
        }
        if (addressComp.types.indexOf('administrative_area_level_3') !== -1) {
          administrativeAreaLevel3 = addressComp.short_name;
        }
      });

      const city = locality || administrativeAreaLevel3;
      let locationName = `${city}, ${administrativeAreaLevel1}`;
      if (!city) {
        locationName = administrativeAreaLevel1;
      }

      // console.log(result);
      // console.log(locality, administrative_area_level_1);

      onLocationChange({
        generalLocation: scrambledLocation,
        generalLocationName: locationName,
        preciseLocation: {
          latitude: location.latitude,
          longitude: location.longitude,
        },
        lookedUpAddress: result,
      });
      // setMarkerLocation(location);
    } catch (err) {
      console.error(`Error detecting locality: ${err.message}`, err); // eslint-disable-line no-console
      showError(err.message);
      throw err;
    }
  }

  function handleLocationClick(args) {
    const newLoc = {
      latitude: args.latLng.lat(),
      longitude: args.latLng.lng(),
    };
    // console.log("handle click", args);
    // console.log("handle click", newLoc);
    setLocation(newLoc);
  }

  function handleDetectLocation() {
    setDetectingLocation(true);
    if (!navigator.geolocation) {
      showError(
        'Sorry, your browser does not support detecting your location.',
      );
      setDetectingLocation(false);
      return;
    }

    navigator.geolocation.getCurrentPosition(
      (position) => {
        const loc = {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
        };
        map.panTo({
          lat: position.coords.latitude,
          lng: position.coords.longitude,
        });
        map.setZoom(15);
        setLocation(loc);
        showSuccess('Location detected');
        setDetectingLocation(false);
      },
      (err) => {
        // eslint-disable-next-line no-console
        console.log(err);
        showError(
          `Unable to retrieve your location, please click on your location manually.`,
        );
        setDetectingLocation(false);
      },
    );
  }

  function onGoogleMapLoad(googleMap) {
    setMap(googleMap);
    if (generalLocation) {
      googleMap.panTo({
        lat: generalLocation.latitude,
        lng: generalLocation.longitude,
      });
    } else {
      googleMap.panTo({
        lat: DEFAULT_LATITUDE,
        lng: DEFAULT_LONGITUDE,
      });
    }
  }

  function handlePlaceChange(address) {
    setCurrentPlaceLabel(address);
  }

  // function handlePlaceSelect(_event, selection) {
  //   if (!selection) return;

  //   geocodeByAddress(selection.description)
  //     .then((results) => getLatLng(results[0]))
  //     .then((latLng) => {
  //       map.setZoom(15);
  //       setLocation({ latitude: latLng.lat, longitude: latLng.lng });
  //     })
  //     .catch((error) => {
  //       showError('Failed to get the location from address.');
  //       // eslint-disable-next-line no-console
  //       console.error('Error', error);
  //     });
  // }

  async function handlePlaceSelect(_event, selection) {
    if (!selection) return;
    try {
      const [address] = await geocodeByAddress(selection.description);
      const loc = await getLatLng(address);
      map.setZoom(15);
      map.panTo(loc);
      setLocation({ latitude: loc.lat, longitude: loc.lng });
    } catch (err) {
      // eslint-disable-next-line no-console
      console.error('Failed to get the location from address:', err.message);
      showError('Failed to get the location from address.');
      Sentry.captureException(err);
    }
  }

  return (
    <LoadScript
      id="script-loader"
      libraries={USED_GOOGLE_MAPS_LIBRARIES}
      googleMapsApiKey={process.env.REACT_APP_FIREBASE_API_KEY}>
      <Backdrop
        open={detectingLocation}
        className={classes.backdrop}
        color="inherit">
        <CircularProgress
          color="inherit"
          size="2em"
          className={classes.progress}
        />
        <Typography variant="h5" gutterBottom color="inherit" display="block">
          Detecting Location...
        </Typography>
      </Backdrop>
      <div className={classes.entryOptions}>
        <PlacesAutocomplete
          value={currentPlaceLabel}
          onChange={handlePlaceChange}>
          {({ getInputProps, suggestions, loading }) => (
            <>
              {/* {console.log(suggestions)} */}
              <Autocomplete
                data-test="places-autocomplete"
                className={classes.autocomplete}
                onChange={handlePlaceSelect}
                options={suggestions}
                loading={loading}
                getOptionLabel={(sug) => sug.description}
                noOptionsText="No matches"
                renderInput={(params) => (
                  <TextField
                    className={classes.autocompleteInputContainer}
                    data-test="address-entry"
                    {...getInputProps({
                      ...params,
                      placeholder: 'Enter Address',
                    })}
                    InputProps={{
                      ...params.InputProps,
                      className: classes.autocompleteInput,
                      endAdornment: loading && (
                        <CircularProgress color="inherit" size={20} />
                      ),
                    }}
                  />
                )}
              />
            </>
          )}
        </PlacesAutocomplete>
        <div className={classes.entryOptionsSeparator}>
          <Typography>- OR -</Typography>
        </div>
        <Button
          size="small"
          variant="outlined"
          onClick={handleDetectLocation}
          startIcon={<DetectLocationIcon fontSize="small" />}
          className={classes.detectButton}>
          Detect Location
        </Button>
      </div>
      <GoogleMap
        onLoad={onGoogleMapLoad}
        mapContainerClassName={classes.map}
        zoom={4}
        options={{ streetViewControl: false, mapTypeControl: false }}
        onClick={handleLocationClick}>
        {preciseLocation && (
          <SelectedLocationMarker
            position={preciseLocation}
            title={generalLocationName}
          />
        )}
      </GoogleMap>
    </LoadScript>
  );
}
Example #12
Source File: ManageZone.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
ViewZone = props => {
  const [open, setOpen] = React.useState(true);
  const history = useHistory();
  const [selectedRows, setSelectedRows] = useState([]);
  const [zonesFilter, setZonesFilter] = useState([]);
  const [backDrop, setBackDrop] = useState(false);
  const [formState, setFormState] = useState({
    filterZone: "",
    dataToShow: props.testingZoneData ? props.testingZoneData : [],
    tempData: [],
    zones: [],
    zonesFilter: [],
    states: [],
    filterDataParameters: {},
    isFilterSearch: false,
    /** This is when we return from edit page */
    isDataEdited: props["location"]["fromEditZone"]
      ? props["location"]["isDataEdited"]
      : false,
    editedData: props["location"]["fromEditZone"]
      ? props["location"]["editedData"]
      : {},
    fromEditZone: props["location"]["fromEditZone"]
      ? props["location"]["fromEditZone"]
      : false,
    editedZoneName: props["location"]["editedZoneData"]
      ? props["location"]["editedZoneData"]["name"]
      : "",
    /** This is when we return from add page */
    isDataAdded: props["location"]["fromAddZone"]
      ? props["location"]["isDataAdded"]
      : false,
    addedData: props["location"]["fromAddZone"]
      ? props["location"]["addedData"]
      : {},
    fromAddZone: props["location"]["fromAddZone"]
      ? props["location"]["fromAddZone"]
      : false,
    addedZoneName: props["location"]["addedZoneData"]
      ? props["location"]["addedZoneData"]["name"]
      : "",
    isClearResetFilter: false,
    /** This is for delete */
    isDataDeleted: false,
    dataToEdit: {},
    dataToDelete: {},
    showModalDelete: false,
    isMultiDelete: false,
    MultiDeleteID: [],
    selectedRowFilter: true,
    greenButtonChecker: true,
    /** Pagination and sortinig data */
    isDataLoading: false,
    pageSize: "",
    totalRows: "",
    page: "",
    pageCount: "",
    sortAscending: true,
    resetPagination: false,
    /** Message to show */
    fromDeleteModal: false,
    messageToShow: "",
    toggleCleared: false
  });

  /** Pre-populate the data with zones data and state data. State data is used while editing the data */
  useEffect(() => {
    /** Seperate function to get zone data */
    getZoneData(10, 1);
  }, []);

  /** This seperate function is used to get the zone data*/
  const getZoneData = async (pageSize, page, paramsForZones = null) => {
    if (paramsForZones !== null && !formUtilities.checkEmpty(paramsForZones)) {
      let defaultParams = {};
      if (paramsForZones.hasOwnProperty(SORT_FIELD_KEY)) {
        defaultParams = {
          page: page,
          pageSize: pageSize
        };
      } else {
        defaultParams = {
          page: page,
          pageSize: pageSize,
          [SORT_FIELD_KEY]: "name:asc"
        };
      }
      Object.keys(paramsForZones).map(key => {
        defaultParams[key] = paramsForZones[key];
      });
      paramsForZones = defaultParams;
    } else {
      paramsForZones = {
        page: page,
        pageSize: pageSize,
        [SORT_FIELD_KEY]: "name:asc"
      };
    }
    setFormState(formState => ({
      ...formState,
      isDataLoading: true
    }));
    await serviceProviders
      .serviceProviderForGetRequest(ZONES_URL, paramsForZones)
      .then(res => {
        formState.dataToShow = [];
        formState.tempData = [];
        let temp = [];
        /** As zones data is in nested form we first convert it into
         * a float structure and store it in data
         */
        temp = convertZoneData(res.data.result);
        setFormState(formState => ({
          ...formState,
          zones: res.data.result,
          dataToShow: temp,
          tempData: temp,
          pageSize: res.data.pageSize,
          totalRows: res.data.rowCount,
          page: res.data.page,
          pageCount: res.data.pageCount,
          isDataLoading: false
        }));
      })
      .catch(error => {
        console.log("error", error);
      });
  };

  const convertZoneData = data => {
    let x = [];
    if (data.length > 0) {
      for (let i in data) {
        var temp = {};
        temp["id"] = data[i]["id"];
        temp["name"] = data[i]["name"];
        temp["state"] = data[i]["state"] ? data[i]["state"]["name"] : "";
        x.push(temp);
      }
      return x;
    }
  };

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

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

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

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

  const restoreData = () => {
    getZoneData(formState.pageSize, 1);
  };

  /** Restoring the data basically resets all te data i.e it gets all the data in view zones
   * i.e the nested zones data and also resets the data to []
  
  const restoreData = () => {
    getZoneData();
  };
  */

  const getDataForEdit = async id => {
    setBackDrop(true);
    let paramsForZones = {
      id: id
    };
    await serviceProviders
      .serviceProviderForGetRequest(ZONES_URL, paramsForZones)
      .then(res => {
        let editData = res.data.result[0];
        history.push({
          pathname: routeConstants.EDIT_ZONES,
          editZone: true,
          dataForEdit: editData
        });
      })
      .catch(error => {
        console.log("error", error);
      });
    setBackDrop(false);
  };
  const editCell = event => {
    getDataForEdit(event.target.id);
  };

  const deleteCell = event => {
    setFormState(formState => ({
      ...formState,
      dataToDelete: {
        id: event.target.id,
        name: event.target.getAttribute("value")
      },
      showModalDelete: true,
      isDataDeleted: false,
      fromDeleteModal: false,
      messageToShow: "",
      fromAddZone: false,
      fromEditZone: false,
      isMultiDelete: false
    }));
  };

  /** This is used to handle the close modal event */
  const handleCloseDeleteModal = (status, statusToShow = "") => {
    /** This restores all the data when we close the modal */
    //restoreData();
    setOpen(true);
    setFormState(formState => ({
      ...formState,
      isDataDeleted: status,
      showModalDelete: false,
      fromDeleteModal: true,
      messageToShow: statusToShow,
      isMultiDelete: false,
      dataToDelete: {}
    }));
    if (status) {
      getZoneData(formState.pageSize, 1, formState.filterDataParameters);
    }
  };

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

  /** Multi Delete */
  /** Get multiple user id for delete */
  const deleteMulUserById = () => {
    let arrayId = [];

    selectedRows.forEach(d => {
      arrayId.push(d.id);
    });

    setFormState(formState => ({
      ...formState,
      showEditModal: false,
      showModalDelete: true,
      isMultiDelete: true,
      MultiDeleteID: arrayId,
      isDataDeleted: false,
      fromDeleteModal: false,
      fromAddZone: false,
      fromEditZone: false
    }));
  };

  /** On select multiple rows */
  const handleRowSelected = useCallback(state => {
    if (state.selectedCount >= 1) {
      setFormState(formState => ({
        ...formState,
        selectedRowFilter: false,
        toggleCleared: false
      }));
    } else {
      setFormState(formState => ({
        ...formState,
        selectedRowFilter: true
      }));
    }
    setSelectedRows(state.selectedRows);
  }, []);

  const handleFilterChange = event => {
    setZonesFilter(event.target.value);
  };

  const filterZoneData = () => {
    let params = "?name_contains=" + zonesFilter;

    let FilterZoneURL =
      strapiConstants.STRAPI_DB_URL + strapiConstants.STRAPI_ZONES + params;

    serviceProviders
      .serviceProviderForGetRequest(FilterZoneURL)
      .then(res => {
        formState.dataToShow = [];
        formState.tempData = [];
        let temp = [];
        /** As zones data is in nested form we first convert it into
         * a float structure and store it in data
         */
        temp = convertZoneData(res.data.result);
        setFormState(formState => ({
          ...formState,
          zones: res.data.result,
          dataToShow: temp,
          tempData: temp,
          pageSize: res.data.pageSize,
          totalRows: res.data.rowCount,
          page: res.data.page,
          pageCount: res.data.pageCount,
          isDataLoading: false
        }));
      })
      .catch(error => {
        console.log("error", error);
      });
  };

  const selectedRowCleared = data => {
    formState.toggleCleared = data;
    setTimeout(() => {
      setFormState(formState => ({
        ...formState,
        toggleCleared: false
      }));
    }, 2000);
  };

  /** Columns to show in table */
  const column = [
    { name: "Name", sortable: true, selector: "name" },
    { name: "State", sortable: true, selector: "state" },
    {
      name: "Actions",
      cell: cell => (
        <div className={classes.DisplayFlex}>
          <div className={classes.PaddingFirstActionButton}>
            <Tooltip title="Edit" placement="top">
              <i
                className="material-icons"
                id={cell.id}
                value={cell.name}
                onClick={editCell}
                style={{ color: "green", fontSize: "21px" }}
              >
                edit
              </i>
            </Tooltip>
          </div>
          <div className={classes.PaddingActionButton}>
            <Tooltip title="Delete" placement="top">
              <i
                className="material-icons tableicons"
                id={cell.id}
                onClick={deleteCell}
                value={cell.name}
                style={{ color: "red", fontSize: "21px" }}
              >
                delete_outline
              </i>
            </Tooltip>
          </div>
        </div>
      ),
      width: "20%",
      cellStyle: {
        width: "auto",
        maxWidth: "auto"
      }
    }
  ];

  /** Set zone data to data in formState */

  /** Empty the initial nested zones array as we have already added our data in the formState.data array*/
  //formState.zones = [];

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

  const classes = useStyles();
  return (
    <Grid>
      <Grid
        container
        spacing={3}
        justify="space-between"
        className={classes.title}
      >
        <Grid item>
          <Typography variant="h4" gutterBottom>
            {genericConstants.VIEW_ZONE_TEXT}
          </Typography>
        </Grid>
        <Grid item>
          <GreenButton
            id="deleteMulUsers"
            variant="contained"
            color="secondary"
            onClick={() => deleteMulUserById()}
            startIcon={<DeleteIcon />}
            greenButtonChecker={formState.greenButtonChecker}
            buttonDisabled={formState.selectedRowFilter}
            style={{ margin: "2px", marginRight: "15px" }}
          >
            Delete Selected Zones
          </GreenButton>
          <GreenButton
            id="addZones"
            variant="contained"
            color="primary"
            disableElevation
            to={routeConstants.ADD_ZONES}
            startIcon={<AddCircleOutlineOutlinedIcon />}
            style={{ margin: "2px" }}
          >
            {genericConstants.ADD_ZONE_TEXT}
          </GreenButton>
        </Grid>
      </Grid>
      <Grid item xs={12} className={classes.formgrid}>
        {/** Error/Success messages to be shown for edit */}
        {formState.fromEditZone && formState.isDataEdited ? (
          <Collapse in={open}>
            <Alert
              severity="success"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              Zone {formState.editedZoneName} has been updated successfully.
            </Alert>
          </Collapse>
        ) : null}
        {formState.fromEditZone && !formState.isDataEdited ? (
          <Collapse in={open}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {props.location.editResponseMessage
                ? props.location.editResponseMessage
                : "An error has occured while updating Zone. Kindly, try again."}
            </Alert>
          </Collapse>
        ) : null}

        {/** Error/Success messages to be shown for add */}
        {formState.fromAddZone && formState.isDataAdded ? (
          <Collapse in={open}>
            <Alert
              severity="success"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              Zone {formState.addedZoneName} has been added successfully.
            </Alert>
          </Collapse>
        ) : null}
        {formState.fromAddZone && !formState.isDataAdded ? (
          <Collapse in={open}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {props.location.addResponseMessage
                ? props.location.addResponseMessage
                : "An error has occured while adding zone.  Kindly, try again."}
            </Alert>
          </Collapse>
        ) : null}

        {formState.fromDeleteModal &&
        formState.isDataDeleted &&
        formState.messageToShow !== "" ? (
          <Collapse in={open}>
            <Alert
              severity="success"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {formState.messageToShow}
            </Alert>
          </Collapse>
        ) : null}

        {formState.fromDeleteModal &&
        !formState.isDataDeleted &&
        formState.messageToShow !== "" ? (
          <Collapse in={open}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {formState.messageToShow}
            </Alert>
          </Collapse>
        ) : null}

        <Card className={classes.root} variant="outlined">
          <CardContent className={classes.Cardtheming}>
            <Grid className={classes.filterOptions} container spacing={1}>
              <Grid item>
                <TextField
                  id="name"
                  label={"Name"}
                  placeholder="Name"
                  variant="outlined"
                  value={zonesFilter}
                  onChange={handleFilterChange}
                />
              </Grid>
              <Grid className={classes.filterButtonsMargin}>
                <YellowButton
                  id="submitFilter"
                  variant="contained"
                  color="primary"
                  disableElevation
                  onClick={filterZoneData}
                >
                  {genericConstants.SEARCH_BUTTON_TEXT}
                </YellowButton>
              </Grid>
              <Grid className={classes.filterButtonsMargin}>
                <GrayButton
                  id="cancelFilter"
                  variant="contained"
                  color="primary"
                  onClick={clearFilter}
                  disableElevation
                >
                  {genericConstants.RESET_BUTTON_TEXT}
                </GrayButton>
              </Grid>
            </Grid>
          </CardContent>
        </Card>
        <Card className={classes.tabledata} variant="outlined">
          {formState.dataToShow ? (
            formState.dataToShow.length ? (
              <Table
                id="ManageTableID"
                data={formState.dataToShow}
                column={column}
                defaultSortField="name"
                onSelectedRowsChange={handleRowSelected}
                defaultSortAsc={formState.sortAscending}
                paginationResetDefaultPage={formState.resetPagination}
                editEvent={editCell}
                deleteEvent={deleteCell}
                progressPending={formState.isDataLoading}
                paginationDefaultPage={formState.page}
                paginationPerPage={formState.pageSize}
                paginationTotalRows={formState.totalRows}
                paginationRowsPerPageOptions={[10, 20, 50]}
                onChangeRowsPerPage={handlePerRowsChange}
                onChangePage={handlePageChange}
                onSort={handleSort}
                sortServer={true}
                clearSelectedRows={formState.toggleCleared}
              />
            ) : (
              <Spinner />
            )
          ) : (
            <div className={classes.noDataMargin}>No data to show</div>
          )}
          {formState.showModalDelete ? (
            <DeleteZone
              showModal={formState.showModalDelete}
              closeModal={handleCloseDeleteModal}
              id={
                formState.isMultiDelete
                  ? formState.MultiDeleteID
                  : formState.dataToDelete["id"]
              }
              modalClose={modalClose}
              isMultiDelete={formState.isMultiDelete ? true : false}
              dataToDelete={formState.dataToDelete}
              clearSelectedRow={selectedRowCleared}
            />
          ) : null}
        </Card>
      </Grid>
      <Backdrop className={classes.backDrop} open={backDrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </Grid>
  );
}
Example #13
Source File: AddEditZone.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditZone = props => {
  const history = useHistory();
  const zone = "zoneName";
  const state = "stateName";
  const content = "content";
  const classes = useStyles();

  const [formState, setFormState] = useState({
    backDrop: false,
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    isSuccess: false,
    isEditZone: props["editZone"] ? props["editZone"] : false,
    dataForEdit: props["dataForEdit"] ? props["dataForEdit"] : {},
    counter: 0
  });

  const [states, setStates] = useState(props.option ? props.option : []);

  /** Part for editing college */
  if (formState.isEditZone && !formState.counter) {
    if (props["dataForEdit"]) {
      if (props["dataForEdit"]["name"]) {
        formState.values[zone] = props["dataForEdit"]["name"];
      }
      if (
        props["dataForEdit"]["state"] &&
        props["dataForEdit"]["state"]["id"]
      ) {
        formState.values[state] = props["dataForEdit"]["state"]["id"];
      }
      formState.counter += 1;
    }
  }

  useEffect(() => {
    let paramsForPageSize = {
      name_contains: "Uttar Pradesh"
    };
    serviceProviders
      .serviceProviderForGetRequest(STATES_URL, paramsForPageSize)
      .then(res => {
        setStates(res.data.result);
      })
      .catch(error => {
        console.log("error > ", error);
      });
  }, []);

  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 handleChangeAutoComplete = (eventName, event, value) => {
    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 {
      delete formState.values[eventName];
    }
  };

  const handleSubmit = event => {
    event.preventDefault();
    let isValid = false;
    let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
      formState.values,
      AddZoneForm
    );
    if (checkAllFieldsValid) {
      formState.errors = formUtilities.setErrors(formState.values, AddZoneForm);
      if (formUtilities.checkEmpty(formState.errors)) {
        isValid = true;
      }
    } else {
      formState.values = formUtilities.getListOfKeysNotPresent(
        formState.values,
        AddZoneForm
      );
      formState.errors = formUtilities.setErrors(formState.values, AddZoneForm);
    }
    if (isValid) {
      postZoneData();

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

  const postZoneData = async () => {
    let postData = databaseUtilities.addZone(
      formState.values[zone],
      formState.values[state] ? formState.values[state] : null
    );
    if (formState.isEditZone) {
      serviceProviders
        .serviceProviderForPutRequest(
          ZONE_URL,
          formState.dataForEdit["id"],
          postData
        )
        .then(res => {
          formState.backDrop = false;
          history.push({
            pathname: routeConstants.MANAGE_ZONES,
            fromEditZone: true,
            isDataEdited: true,
            editedZoneData: res.data,
            editResponseMessage: "",
            editedData: {}
          });
        })
        .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"];
            }
          }
          formState.backDrop = false;
          console.log(error, error.response);
          history.push({
            pathname: routeConstants.MANAGE_ZONES,
            fromEditZone: true,
            isDataEdited: false,
            editResponseMessage: errorMessage ? errorMessage : "",
            editedData: {}
          });
        });

      /** Set state to reload form */
      setFormState(formState => ({
        ...formState,
        isValid: true
      }));
    } else {
      serviceProviders
        .serviceProviderForPostRequest(ZONE_URL, postData)
        .then(res => {
          formState.backDrop = false;
          history.push({
            pathname: routeConstants.MANAGE_ZONES,
            fromAddZone: true,
            isDataAdded: true,
            addedZoneData: res.data,
            addResponseMessage: "",
            addedData: {}
          });
        })
        .catch(error => {
          formState.backDrop = false;
          console.log(error, error.response);
          let errorMessage;

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

      /** 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}>
        {formState.isEditZone ? (
          <Typography variant="h4" gutterBottom>
            {genericConstants.EDIT_ZONE_TEXT}
          </Typography>
        ) : (
          <Typography variant="h4" gutterBottom>
            {get(AddZoneForm[content], "title")}
          </Typography>
        )}
      </Grid>
      <Grid item xs={12} className={classes.formgrid}>
        <Card className={classes.root} variant="outlined">
          <form autoComplete="off" noValidate onSubmit={handleSubmit} id="form">
            <CardContent>
              <Grid container spacing={2}>
                <Grid item md={12} xs={12}>
                  <TextField
                    label={get(AddZoneForm[zone], "label")}
                    name={zone}
                    value={formState.values[zone] || ""}
                    error={hasError(zone)}
                    placeholder={get(AddZoneForm[zone], "placeholder")}
                    variant="outlined"
                    id="test"
                    required
                    fullWidth
                    onChange={handleChange}
                    helperText={
                      hasError(zone)
                        ? formState.errors[zone].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    className={classes.elementroot}
                  />
                </Grid>
                <Grid item md={12} xs={12}>
                  <Autocomplete
                    id="states-filter"
                    className={classes.root}
                    options={states}
                    getOptionLabel={option => option.name}
                    onChange={(event, value) => {
                      handleChangeAutoComplete(state, event, value);
                    }}
                    value={
                      states[
                        states.findIndex(function (item, i) {
                          return item.id === formState.values[state];
                        })
                      ] || null /** Please give a default " " blank value */
                    }
                    renderInput={params => (
                      <TextField
                        id="state-filter-test-id"
                        {...params}
                        label={get(AddZoneForm[state], "label")}
                        variant="outlined"
                        placeholder={get(AddZoneForm[state], "placeholder")}
                        error={hasError(state)}
                        helperText={
                          hasError(state)
                            ? formState.errors[state].map(error => {
                                return error + " ";
                              })
                            : null
                        }
                      />
                    )}
                    className={classes.elementroot}
                  />
                </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"
                          id="submit"
                          color="primary"
                          variant="contained"
                          onClick={() => {
                            formState.backDrop = true;
                          }}
                        >
                          {genericConstants.SAVE_BUTTON_TEXT}
                        </YellowButton>
                      </Grid>
                      <Grid item md={2} xs={12}>
                        <GrayButton
                          type="submit"
                          color="primary"
                          variant="contained"
                          to={routeConstants.MANAGE_ZONES}
                        >
                          {genericConstants.CANCEL_BUTTON_TEXT}
                        </GrayButton>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </CardActions>
            </Grid>
          </form>
        </Card>
      </Grid>
      <Backdrop className={classes.backDrop} open={formState.backDrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </Grid>
  );
}
Example #14
Source File: BlockUser.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
BlockUser = props => {
  const [open, setOpen] = React.useState(false);
  const [formState, setFormState] = useState({
    isDataBlockUnblock: false,
    isValid: false,
    stateCounter: 0,
    values: {}
  });

  const handleCloseModal = (message = "") => {
    setOpen(false);
    /** This event handles the scenario when the pop up is closed just by clicking outside the popup 
    to ensure that only string value is passed to message variable */
    if (typeof message !== "string") {
      message = "";
    }
    setFormState(formState => ({
      ...formState,
      values: {},
      isDataBlockUnblock: false,
      isValid: false,
      stateCounter: 0
    }));
    if (formState.isDataBlockUnblock) {
      props.closeModal(true, message);
    } else {
      props.closeModal(false, message);
    }
  };

  const handleSubmit = event => {
    setOpen(true);
    /** CALL Put FUNCTION */
    blockUser();
    props.clearSelectedRow(true);
    event.preventDefault();
  };
  const blockUser = () => {
    var body;
    if (props.isUnBlocked || props.isMultiUnblock) {
      body = {
        blocked: false
      };
    }
    if (props.isBlocked || props.isMulBlocked) {
      body = {
        blocked: true
      };
    }

    if (props.isMulBlocked || props.isMultiUnblock) {
      let MultiBlockUnblockUrl;
      if (props.isMulBlocked) {
        MultiBlockUnblockUrl = USER_URL + strapiConstants.STRAPI_BLOCK_URL;
      } else if (props.isMultiUnblock) {
        MultiBlockUnblockUrl = USER_URL + strapiConstants.STRAPI_UNBLOCK_URL;
      }
      let MultiBlockUnblockId = {
        ids: props.id
      };
      serviceProviders
        .serviceProviderForPostRequest(
          MultiBlockUnblockUrl,
          MultiBlockUnblockId
        )
        .then(res => {
          setFormState(formState => ({
            ...formState,
            isValid: true
          }));
          formState.isDataBlockUnblock = true;
          if (props.isMultiUnblock) {
            handleCloseModal("Users has been unblocked");
          } else {
            handleCloseModal("Users has been blocked");
          }
        })
        .catch(error => {
          console.log("error");
          formState.isDataBlockUnblock = false;
          if (props.isMultiUnblock) {
            handleCloseModal("Error unblocking selected Users");
          } else {
            handleCloseModal("Error blocking selected Users");
          }
        });
    } else {
      let BLOCK_URL;
      if (props.dataToBlockUnblock.isUserBlock === true) {
        BLOCK_URL = USER_URL + strapiConstants.STRAPI_BLOCK_URL;
      } else if (props.dataToBlockUnblock.isUserBlock === false) {
        BLOCK_URL = USER_URL + strapiConstants.STRAPI_UNBLOCK_URL;
      }

      let BLOCKUNBLOCKID = {
        ids: parseInt(props.id)
      };
      serviceProviders
        .serviceProviderForPostRequest(BLOCK_URL, BLOCKUNBLOCKID)
        .then(res => {
          formState.isDataBlockUnblock = true;
          if (props.dataToBlockUnblock["isUserBlock"]) {
            handleCloseModal(
              "User " + props.dataToBlockUnblock["name"] + " has been blocked"
            );
          } else {
            handleCloseModal(
              "User " + props.dataToBlockUnblock["name"] + " has been unblocked"
            );
          }
        })
        .catch(error => {
          console.log("error", error);
          formState.isDataBlockUnblock = false;
          handleCloseModal("user unblock successfully");
        });
    }
  };

  const handleBlock = async event => {
    props.clearSelectedRow(true);
    props.closeModal();
  };

  const classes = useStyles();
  return (
    <Modal
      aria-labelledby="transition-modal-title"
      aria-describedby="transition-modal-description"
      className={classes.modal}
      open={props.getModel}
      onClose={handleCloseModal}
      closeAfterTransition
      BackdropComponent={Backdrop}
      BackdropProps={{
        timeout: 500
      }}
    >
      <Fade in={props.getModel}>
        <div className={classes.paper}>
          <div className={classes.blockpanel}>
            <Typography variant={"h2"} className={classes.textMargin}>
              {props.isUnBlocked || props.isMultiUnblock ? "Unblock" : null}
              {props.isBlocked || props.isMulBlocked ? "Block" : null}
            </Typography>
            <div className={classes.crossbtn}>
              <IconButton
                aria-label="close"
                className={classes.closeButton}
                onClick={props.modalClose}
              >
                <CloseIcon />
              </IconButton>
            </div>
          </div>
          <div className={classes.edit_dialog}>
            <Grid item xs={12}>
              <Grid
                container
                spacing={2}
                alignItems="center"
                justifyContent="center"
              >
                <Grid item lg className={classes.deletemessage}>
                  {props.isUnBlocked
                    ? "Are you sure you want to unblock user " +
                      props.dataToBlockUserName
                    : null}
                  {props.isMultiUnblock
                    ? "Are you sure you want to unblock the selected users "
                    : null}
                  {props.isBlocked
                    ? "Are you sure you want to block user " +
                      props.dataToBlockUserName
                    : null}
                  {props.isMulBlocked
                    ? "Are you sure you want to block the selected users "
                    : null}
                </Grid>
              </Grid>
            </Grid>
            <Grid item xs={12}>
              <Grid
                container
                direction="row"
                justify="flex-end"
                alignItems="center"
                spacing={2}
              >
                <Grid item>
                  <YellowButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleSubmit}
                  >
                    OK
                  </YellowButton>
                </Grid>
                <Grid item>
                  <GrayButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleBlock}
                  >
                    Close
                  </GrayButton>
                </Grid>
              </Grid>
            </Grid>
          </div>
          <Backdrop className={classes.backdrop} open={open}>
            <CircularProgress color="inherit" />
          </Backdrop>
        </div>
      </Fade>
    </Modal>
  );
}
Example #15
Source File: AddEditUser.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditUser = props => {
  /** Initializing all the hooks */
  const classes = useStyles();
  const history = useHistory();
  const [formState, setFormState] = useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    isSuccess: false,
    isZoneBlocked: props.isZoneBlocked === "false" ? false : true,
    isRPCBlocked: props.isRPCBlocked === "false" ? false : true,
    isCollegeBlocked: props.isCollegeBlocked === "false" ? false : true,
    showPassword: props.showPassword ? props.showPassword : false,
    isEditUser: props["editUser"] ? props["editUser"] : false,
    dataForEdit: props["dataForEdit"] ? props["dataForEdit"] : {},
    counter: props.counter ? props.counter : 0,
    isCollegeAdmin:
      auth.getUserInfo() !== undefined &&
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name !== undefined &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
        ? true
        : false
  });
  const [states, setStates] = useState(
    props.stateOption ? props.stateOption : []
  );
  const [backdrop, setBackDrop] = useState(false);
  const [zones, setZones] = useState(props.zoneOption ? props.zoneOption : []);
  const [rpcs, setRpcs] = useState(props.rpcOption ? props.rpcOption : []);
  const [colleges, setColleges] = useState(
    props.collegeOption ? props.collegeOption : []
  );
  const [roles, setRoles] = useState(props.option ? props.option : []);
  const [isDisable, setIsDisable] = useState(false);

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

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

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

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

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

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

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

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

    let paramsForPageSize = {
      pageSize: -1
    };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

              <Grid item xs={12} md={6} xl={3}>
                <Grid container spacing={3} className={classes.formgrid}>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id={get(UserSchema[zone], "id")}
                      className={classes.root}
                      disabled={isDisable || formState.isZoneBlocked}
                      options={zones}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete(zone, event, value);
                      }}
                      value={
                        isDisable || formState.isZoneBlocked
                          ? null
                          : zones[
                              zones.findIndex(function (item, i) {
                                return item.id === formState.values[zone];
                              })
                            ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          label={get(UserSchema[zone], "label")}
                          placeholder={get(UserSchema[zone], "placeholder")}
                          variant="outlined"
                          error={hasError(zone)}
                          helperText={
                            hasError(zone)
                              ? formState.errors[zone].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id={get(UserSchema[college], "id")}
                      className={classes.root}
                      disabled={isDisable || formState.isCollegeBlocked}
                      options={colleges}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete(college, event, value);
                      }}
                      value={
                        isDisable || formState.isCollegeBlocked
                          ? null
                          : colleges[
                              colleges.findIndex(function (item, i) {
                                return item.id === formState.values[college];
                              })
                            ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          label={get(UserSchema[college], "label")}
                          placeholder={get(UserSchema[college], "placeholder")}
                          variant="outlined"
                          error={hasError(college)}
                          helperText={
                            hasError(college)
                              ? formState.errors[college].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
              </Grid>
            </CardContent>
            <Grid item xs={12} className={classes.CardActionGrid}>
              <CardActions className={classes.btnspace}>
                <Grid item xs={12}>
                  <Grid item xs={12} md={6} xl={3}>
                    <Grid container spacing={3}>
                      <Grid item md={2} xs={12}>
                        <YellowButton
                          type="submit"
                          color="primary"
                          variant="contained"
                        >
                          {genericConstants.SAVE_BUTTON_TEXT}
                        </YellowButton>
                      </Grid>
                      <Grid item md={2} xs={12}>
                        <GrayButton
                          type="submit"
                          color="primary"
                          variant="contained"
                          to={routeConstants.MANAGE_USER}
                        >
                          {genericConstants.CANCEL_BUTTON_TEXT}
                        </GrayButton>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </CardActions>
            </Grid>
          </form>
        </Card>
      </Grid>
      <Backdrop className={classes.backDrop} open={backdrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </Grid>
  );
}
Example #16
Source File: 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 #17
Source File: ViewEducation.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
ViewEducation = props => {
  const [open, setOpen] = React.useState(true);
  const classes = useStyles();
  const history = useHistory();
  const [backDrop, setBackDrop] = useState(false);
  const [formState, setFormState] = useState({
    dataToShow: [],
    educations: [],
    educationFilter: [],
    filterDataParameters: {},
    isFilterSearch: false,
    /** This is when we return from edit page */
    isDataEdited: props["location"]["fromEditEducation"]
      ? props["location"]["isDataEdited"]
      : false,
    editedData: props["location"]["fromEditEducation"]
      ? props["location"]["editedData"]
      : {},
    fromEditEducation: props["location"]["fromEditEducation"]
      ? props["location"]["fromEditEducation"]
      : false,
    /** This is when we return from add page */
    isDataAdded: props["location"]["fromAddEducation"]
      ? props["location"]["isDataAdded"]
      : false,
    addedData: props["location"]["fromAddEducation"]
      ? props["location"]["addedData"]
      : {},
    fromAddEducation: props["location"]["fromAddEducation"]
      ? props["location"]["fromAddEducation"]
      : false,
    responseError: props["location"]["error"] ? props["location"]["error"] : "",
    /** This is for delete */
    isDataDeleted: false,
    dataToEdit: {},
    dataToDelete: {},
    showModalDelete: false,
    /** Pagination and sortinig data */
    isDataLoading: false,
    pageSize: "",
    totalRows: "",
    page: "",
    pageCount: "",
    sortAscending: true
  });
  const { loaderStatus, setLoaderStatus } = useContext(LoaderContext);

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

  const studentInfo =
    Auth.getUserInfo() !== null &&
    Auth.getUserInfo().role.name === roleConstants.STUDENT
      ? Auth.getUserInfo().studentInfo.contact.id
      : Auth.getStudentIdFromCollegeAdmin();
  const STUDENT_EDUCATION_URL =
    strapiConstants.STRAPI_DB_URL +
    strapiConstants.STRAPI_STUDENTS_INDIVIDUAL_URL +
    `/${studentInfo}/` +
    strapiConstants.STRAPI_STUDENT_EDUCATION;
  const EDUCATION_FILTER = "qualification_contains";

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

  /** This seperate function is used to get the education data*/
  const getEducationData = async (pageSize, page, params = null) => {
    if (params !== null && !formUtilities.checkEmpty(params)) {
      let defaultParams = {
        page: page,
        pageSize: pageSize
      };
      Object.keys(params).map(key => {
        return (defaultParams[key] = params[key]);
      });
      params = defaultParams;
    } else {
      params = {
        page: page,
        pageSize: pageSize
      };
    }
    setFormState(formState => ({
      ...formState,
      isDataLoading: true
    }));

    await serviceProviders
      .serviceProviderForGetRequest(STUDENT_EDUCATION_URL, params)
      .then(res => {
        res.data.result.filter(education => {
          genericConstants.QUALIFICATION_LIST.filter(qualification => {
            if (qualification.id === education.qualification) {
              education.Qualification = qualification.name;
            }
            return qualification;
          });
          return education;
        });
        formState.dataToShow = [];
        setFormState(formState => ({
          ...formState,
          educations: res.data.result,
          dataToShow: res.data.result,
          pageSize: res.data.pageSize,
          totalRows: res.data.rowCount,
          page: res.data.page,
          pageCount: res.data.pageCount,
          isDataLoading: false
        }));
      })
      .catch(error => {
        console.log("error", error);
      });
  };

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

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

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

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

  const restoreData = () => {
    getEducationData(formState.pageSize, 1);
  };

  const editCell = data => {
    history.push({
      pathname: routeConstants.EDIT_EDUCATION,
      editEducation: true,
      dataForEdit: data
    });
  };

  const isDeleteCellCompleted = (status, message) => {
    formState.isDataDeleted = status;
    if (typeof message === typeof "") {
      if (status) {
        setAlert(() => ({
          isOpen: true,
          message: "Education " + message + " is deleted",
          severity: "success"
        }));
      } else {
        setAlert(() => ({
          isOpen: true,
          message: message,
          severity: "error"
        }));
      }
    }
  };

  const deleteCell = event => {
    setFormState(formState => ({
      ...formState,
      dataToDelete: {
        id: event.target.id,
        education: event.target.getAttribute("value")
      },
      showModalDelete: true
    }));
  };

  const handleFilterChangeForQualificationField = event => {
    setFormState(formState => ({
      ...formState,
      filterDataParameters: {
        ...formState.filterDataParameters,
        [EDUCATION_FILTER]: event.target.value
      }
    }));
    event.persist();
  };

  /** This is used to handle the close modal event */
  const handleCloseDeleteModal = () => {
    /** This restores all the data when we close the modal */
    //restoreData();
    setFormState(formState => ({
      ...formState,
      isDataDeleted: false,
      showModalDelete: false
    }));
    if (formState.isDataDeleted) {
      getEducationData(formState.pageSize, formState.page);
    }
  };

  /** Columns to show in table */
  const column = [
    {
      name: "Year Of Passing",
      sortable: true,
      selector: "year_of_passing.name"
    },
    {
      name: "Qualification",
      sortable: true,
      cell: cell =>
        cell.qualification == "other"
          ? cell.other_qualification
          : cell.Qualification
    },
    {
      name: "Board",
      sortable: true,
      cell: cell =>
        cell.board
          ? cell.board.name === "Other"
            ? cell.other_board
            : cell.board.name
          : "-"
    },
    { name: "Percentage", sortable: true, selector: "percentage" },
    {
      name: "Pursuing",
      sortable: true,
      selector: "pursuing",
      cell: cell => (cell.pursuing ? "Yes" : "No")
    },
    {
      name: "Institute",
      sortable: true,
      cell: cell => (cell.institute ? cell.institute : "-")
    },
    {
      name: "Actions",
      cell: cell => (
        <div className={classes.DisplayFlex}>
          <div className={classes.PaddingFirstActionButton}>
            <EditGridIcon
              id={cell.id}
              value={cell.name}
              onClick={() => editCell(cell)}
            />
          </div>
          <div className={classes.PaddingActionButton}>
            <DeleteGridIcon
              id={cell.id}
              value={cell.qualification}
              onClick={deleteCell}
            />
          </div>
        </div>
      ),
      width: "20%",
      cellStyle: {
        width: "auto",
        maxWidth: "auto"
      }
    }
  ];

  const handleAddEducationClick = () => {
    history.push({
      pathname: routeConstants.ADD_EDUCATION
    });
  };

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

  return (
    <React.Fragment>
      <Card style={{ padding: "8px" }}>
        <CardContent className={classes.Cardtheming}>
          <Grid>
            <Grid item xs={12} className={classes.title}>
              <GreenButton
                variant="contained"
                color="primary"
                onClick={handleAddEducationClick}
                disableElevation
                startIcon={<AddCircleOutlineOutlinedIcon />}
                to={routeConstants.ADD_EDUCATION}
              >
                {genericConstants.ADD_EDUCATION_TEXT}
              </GreenButton>
            </Grid>

            <Grid item xs={12} className={classes.formgrid}>
              {/** Error/Success messages to be shown for edit */}
              {formState.fromEditEducation && formState.isDataEdited ? (
                <Collapse in={open}>
                  <Alert
                    severity="success"
                    action={
                      <IconButton
                        aria-label="close"
                        color="inherit"
                        size="small"
                        onClick={() => {
                          setOpen(false);
                        }}
                      >
                        <CloseIcon fontSize="inherit" />
                      </IconButton>
                    }
                  >
                    Education edited successfully.
                    {/* {genericConstants.ALERT_SUCCESS_DATA_EDITED_MESSAGE} */}
                  </Alert>
                </Collapse>
              ) : null}
              {formState.fromEditEducation && !formState.isDataEdited ? (
                <Collapse in={open}>
                  <Alert
                    severity="error"
                    action={
                      <IconButton
                        aria-label="close"
                        color="inherit"
                        size="small"
                        onClick={() => {
                          setOpen(false);
                        }}
                      >
                        <CloseIcon fontSize="inherit" />
                      </IconButton>
                    }
                  >
                    {formState.responseError}
                    {/* {genericConstants.ALERT_ERROR_DATA_EDITED_MESSAGE} */}
                  </Alert>
                </Collapse>
              ) : null}

              {/** Error/Success messages to be shown for add */}
              {formState.fromAddEducation && formState.isDataAdded ? (
                <Collapse in={open}>
                  <Alert
                    severity="success"
                    action={
                      <IconButton
                        aria-label="close"
                        color="inherit"
                        size="small"
                        onClick={() => {
                          setOpen(false);
                        }}
                      >
                        <CloseIcon fontSize="inherit" />
                      </IconButton>
                    }
                  >
                    Education added successfully.
                    {/* {genericConstants.ALERT_SUCCESS_DATA_ADDED_MESSAGE} */}
                  </Alert>
                </Collapse>
              ) : null}
              {formState.fromAddEducation && !formState.isDataAdded ? (
                <Collapse in={open}>
                  <Alert
                    severity="error"
                    action={
                      <IconButton
                        aria-label="close"
                        color="inherit"
                        size="small"
                        onClick={() => {
                          setOpen(false);
                        }}
                      >
                        <CloseIcon fontSize="inherit" />
                      </IconButton>
                    }
                  >
                    {formState.responseError}
                    {/* {genericConstants.ALERT_ERROR_DATA_ADDED_MESSAGE} */}
                  </Alert>
                </Collapse>
              ) : null}
              <AlertAPIResponseMessage />
              <Card className={styles.filterButton}>
                <CardContent className={classes.Cardtheming}>
                  <Grid className={classes.filterOptions} container spacing={1}>
                    <Grid item>
                      <TextField
                        id="qualification"
                        label="Qualification"
                        margin="normal"
                        variant="outlined"
                        value={
                          formState.filterDataParameters[EDUCATION_FILTER] || ""
                        }
                        placeholder="Qualification"
                        className={classes.autoCompleteField}
                        onChange={handleFilterChangeForQualificationField}
                      />
                    </Grid>
                    <Grid item className={classes.filterButtonsMargin}>
                      <YellowButton
                        id="submitFilter"
                        variant="contained"
                        color="primary"
                        disableElevation
                        onClick={event => {
                          event.persist();
                          searchFilter();
                        }}
                      >
                        {genericConstants.SEARCH_BUTTON_TEXT}
                      </YellowButton>
                    </Grid>
                    <Grid item className={classes.filterButtonsMargin}>
                      <GrayButton
                        id="cancelFilter"
                        variant="contained"
                        color="primary"
                        onClick={clearFilter}
                        disableElevation
                      >
                        {genericConstants.RESET_BUTTON_TEXT}
                      </GrayButton>
                    </Grid>
                  </Grid>
                </CardContent>
              </Card>
              <Table
                id="ManageTableID"
                data={formState.dataToShow}
                column={column}
                defaultSortField="name"
                defaultSortAsc={formState.sortAscending}
                editEvent={editCell}
                deleteEvent={deleteCell}
                progressPending={formState.isDataLoading}
                paginationTotalRows={formState.totalRows}
                paginationRowsPerPageOptions={[10, 20, 50]}
                onChangeRowsPerPage={handlePerRowsChange}
                onChangePage={handlePageChange}
                noDataComponent="No education details found"
              />
              <DeleteEducation
                id="deleteEducation"
                showModal={formState.showModalDelete}
                closeModal={handleCloseDeleteModal}
                data={formState.dataToDelete}
                deleteEvent={isDeleteCellCompleted}
              />
            </Grid>
          </Grid>
        </CardContent>
      </Card>
      <Backdrop className={classes.backDrop} open={backDrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </React.Fragment>
  );
}
Example #18
Source File: AddEditState.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditState = props => {
  const history = useHistory();
  const state = "state";
  const content = "content";
  const classes = useStyles();
  const { setLoaderStatus } = useContext(LoaderContext);

  const [formState, setFormState] = useState({
    backDrop: false,
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    isSuccess: false,
    isEditState: props["editState"] ? props["editState"] : false,
    dataForEdit: props["dataForEdit"] ? props["dataForEdit"] : {},
    counter: 0
  });

  /** Part for editing state */
  if (formState.isEditState && !formState.counter) {
    if (props["dataForEdit"]) {
      if (props["dataForEdit"]["name"]) {
        formState.values[state] = props["dataForEdit"]["name"];
      }
    }
    formState.counter += 1;
  }

  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 setLoader = () => {
    formState.backDrop = true;
  };
  const handleSubmit = event => {
    event.preventDefault();
    setLoader();
    let isValid = false;
    let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
      formState.values,
      StateSchema
    );
    if (checkAllFieldsValid) {
      formState.errors = formUtilities.setErrors(formState.values, StateSchema);
      if (formUtilities.checkEmpty(formState.errors)) {
        isValid = true;
      }
    } else {
      formState.values = formUtilities.getListOfKeysNotPresent(
        formState.values,
        StateSchema
      );
      formState.errors = formUtilities.setErrors(formState.values, StateSchema);
    }
    if (isValid) {
      postStateData();

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

  const postStateData = () => {
    let postData = databaseUtilities.addState(formState.values[state]);
    if (formState.isEditState) {
      serviceProviders
        .serviceProviderForPutRequest(
          STATES_URL,
          formState.dataForEdit["id"],
          postData
        )
        .then(res => {
          setLoaderStatus(false);
          history.push({
            pathname: routeConstants.MANAGE_STATES,
            fromEditState: true,
            isDataEdited: true,
            stateDataEdited: res.data,
            editResponseMessage: "",
            editedData: {}
          });
        })
        .catch(error => {
          setLoaderStatus(false);
          history.push({
            pathname: routeConstants.MANAGE_STATES,
            fromEditState: true,
            isDataEdited: false,
            editResponseMessage: "",
            editedData: {}
          });
        });
      /** Set state to reload form */
      setFormState(formState => ({
        ...formState,
        isValid: true
      }));
    } else {
      serviceProviders
        .serviceProviderForPostRequest(STATES_URL, postData)
        .then(res => {
          setLoaderStatus(false);
          history.push({
            pathname: routeConstants.MANAGE_STATES,
            fromAddState: true,
            addedStateData: res.data,
            isDataAdded: true,
            addResponseMessage: "",
            addedData: {}
          });
        })
        .catch(error => {
          setLoaderStatus(false);
          history.push({
            pathname: routeConstants.MANAGE_STATES,
            fromAddState: true,
            isDataAdded: false,
            addResponseMessage: "",
            addedData: {}
          });
        });
      /** 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}>
        {formState.isEditState ? (
          <Typography variant="h4" gutterBottom>
            {genericConstants.EDIT_STATE_TEXT}
          </Typography>
        ) : (
          <Typography variant="h4" gutterBottom>
            {get(StateSchema[content], "title")}
          </Typography>
        )}
      </Grid>
      <Grid item xs={12} className={classes.formgrid}>
        <Card className={classes.root} variant="outlined">
          <form autoComplete="off" noValidate onSubmit={handleSubmit} id="form">
            <CardContent>
              <Grid container spacing={2}>
                <Grid item md={12} xs={12}>
                  <TextField
                    label={get(StateSchema[state], "label")}
                    name={state}
                    value={formState.values[state] || ""}
                    error={hasError(state)}
                    placeholder={get(StateSchema[state], "placeholder")}
                    variant="outlined"
                    required
                    id="test"
                    fullWidth
                    onChange={handleChange}
                    helperText={
                      hasError(state)
                        ? formState.errors[state].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    className={classes.elementroot}
                  />
                </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"
                          id="submit"
                          color="primary"
                          variant="contained"
                          onClick={() => {
                            setLoader();
                          }}
                        >
                          {genericConstants.SAVE_BUTTON_TEXT}
                        </YellowButton>
                      </Grid>
                      <Grid item md={2} xs={12}>
                        <GrayButton
                          type="submit"
                          color="primary"
                          variant="contained"
                          to={routeConstants.MANAGE_STATES}
                        >
                          {genericConstants.CANCEL_BUTTON_TEXT}
                        </GrayButton>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </CardActions>
            </Grid>
          </form>
        </Card>
      </Grid>
      <Backdrop className={classes.backDrop} open={formState.backDrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </Grid>
  );
}
Example #19
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 #20
Source File: ManageRpc.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
ViewRpc = props => {
  /** Value to set for Rpc filter */
  const classes = useStyles();
  const [open, setOpen] = React.useState(true);
  const history = useHistory();
  const [selectedRows, setSelectedRows] = useState([]);
  const [rpcsFilter, setRpcsFilter] = useState([]);
  const { setLoaderStatus } = useContext(LoaderContext);
  const [backDrop, setBackDrop] = useState(false);

  const [formState, setFormState] = useState({
    filterRpc: "",
    dataToShow: props.testingRPCData ? props.testingRPCData : [],
    tempData: [],
    zones: [],
    rpcs: [],
    rpcFilter: [],
    states: [],
    isFilterSearch: false,
    filterDataParameters: {},
    /** This is when we return from edit page */
    isDataEdited: props["location"]["fromEditRpc"]
      ? props["location"]["isDataEdited"]
      : false,
    editedData: props["location"]["fromEditRpc"]
      ? props["location"]["editedData"]
      : {},
    fromEditRpc: props["location"]["fromEditRpc"]
      ? props["location"]["fromEditRpc"]
      : false,
    editedRPCName: props["location"]["editedRPCData"]
      ? props["location"]["editedRPCData"]["name"]
      : "",
    /** This is when we return from add page */
    isDataAdded: props["location"]["fromAddRpc"]
      ? props["location"]["isDataAdded"]
      : false,
    addedData: props["location"]["fromAddRpc"]
      ? props["location"]["addedData"]
      : {},
    fromAddRpc: props["location"]["fromAddRpc"]
      ? props["location"]["fromAddRpc"]
      : false,
    addedRPCName: props["location"]["addedRPCData"]
      ? props["location"]["addedRPCData"]["name"]
      : "",
    isClearResetFilter: false,
    /** This is for delete */
    isDataDeleted: false,
    dataToEdit: {},
    dataToDelete: {},
    showModalDelete: false,
    isMultiDelete: false,
    MultiDeleteID: [],
    selectedRowFilter: true,
    greenButtonChecker: true,
    /** Pagination and sortinig data */
    isDataLoading: false,
    pageSize: "",
    totalRows: "",
    page: "",
    pageCount: "",
    sortAscending: true,
    resetPagination: false,
    /** Message to show */
    fromDeleteModal: false,
    messageToShow: "",
    isDataDeleted: false,

    /**Filter RPC's */
    rpcsFilterValueToStore: "",
    rpcsFilterData: [],
    toggleCleared: false
  });
  useEffect(() => {
    getRpcStateData(10, 1);
  }, []);

  useEffect(() => {
    if (
      formState.rpcsFilterValueToStore === null ||
      formState.rpcsFilterValueToStore === ""
    ) {
      setFormState(formState => ({
        ...formState,
        rpcsFilterData: []
      }));
    }
  }, [formState.rpcsFilterValueToStore]);

  const getRpcStateData = async (pageSize, page, paramsForRpc = null) => {
    if (paramsForRpc !== null && !formUtilities.checkEmpty(paramsForRpc)) {
      let defaultParams = {};
      if (paramsForRpc.hasOwnProperty(SORT_FIELD_KEY)) {
        defaultParams = {
          page: page,
          pageSize: pageSize
        };
      } else {
        defaultParams = {
          page: page,
          pageSize: pageSize,
          [SORT_FIELD_KEY]: "title:asc"
        };
      }
      Object.keys(paramsForRpc).map(key => {
        defaultParams[key] = paramsForRpc[key];
      });
      paramsForRpc = defaultParams;
    } else {
      paramsForRpc = {
        page: page,
        pageSize: pageSize,
        [SORT_FIELD_KEY]: "name:asc"
      };
    }
    setFormState(formState => ({
      ...formState,
      isDataLoading: true
    }));

    await serviceProviders
      .serviceProviderForGetRequest(RPC_URL, paramsForRpc)
      .then(res => {
        let currentPage = res.data.page;
        let totalRows = res.data.rowCount;
        let currentPageSize = res.data.pageSize;
        let pageCount = res.data.pageCount;
        formState.dataToShow = [];
        formState.tempData = [];
        let temp = [];
        temp = convertRpcData(res.data.result);
        setFormState(formState => ({
          ...formState,
          rpcs: res.data.result,
          dataToShow: temp,
          tempData: temp,
          pageSize: currentPageSize,
          totalRows: totalRows,
          page: currentPage,
          pageCount: pageCount,
          isDataLoading: false
        }));
      })
      .catch(error => {
        console.log("rpcerror", error);
      });
  };

  const convertRpcData = data => {
    let x = [];
    if (data.length > 0) {
      for (let i in data) {
        var temp = {};
        temp["id"] = data[i]["id"];
        temp["name"] = data[i]["name"];
        temp["state"] = data[i]["state"]["name"];
        x.push(temp);
      }
      return x;
    }
  };

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

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

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

  /**---------------------------clear filter------------------------ */
  const clearFilter = () => {
    setRpcsFilter([""]);
    setFormState(formState => ({
      ...formState,
      isFilterSearch: false,
      isClearResetFilter: true,
      /** Clear all filters */
      filterDataParameters: {},
      /** Turns on the spinner */
      isDataLoading: true,
      /** Clear filter */
      rpcsFilterValueToStore: null,
      /**Clear filters */
      rpcsFilterData: []
    }));
    selectedRowCleared(true);
    /**Need to confirm this thing for resetting the data */
    restoreData();
  };

  const restoreData = () => {
    getRpcStateData(formState.pageSize, 1);
  };

  /**-----------edit ----------- */
  const editCell = event => {
    getDataForEdit(event.target.id);
  };

  const getDataForEdit = async id => {
    setBackDrop(true);
    let paramsForRpcs = {
      id: id
    };
    await serviceProviders
      .serviceProviderForGetRequest(RPC_URL, paramsForRpcs)
      .then(res => {
        let editData = res.data.result[0];
        history.push({
          pathname: routeConstants.EDIT_RPC,
          editRpc: true,
          dataForEdit: editData
        });
      })
      .catch(error => {
        console.log("error", error);
      });
    setBackDrop(false);
  };

  /** ---------Delete -------- */

  const deleteCell = event => {
    setFormState(formState => ({
      ...formState,
      dataToDelete: {
        id: event.target.id,
        name: event.target.getAttribute("value")
      },
      showModalDelete: true,
      isDataDeleted: false,
      fromDeleteModal: false,
      messageToShow: "",
      fromAddRpc: false,
      fromEditRpc: false,
      isMultiDelete: false
    }));
  };

  /** This is used to handle the close modal event */
  const handleCloseDeleteModal = (status, statusToShow = "") => {
    /** This restores all the data when we close the modal */
    //restoreData();
    setOpen(true);
    setFormState(formState => ({
      ...formState,
      isDataDeleted: status,
      showModalDelete: false,
      fromDeleteModal: true,
      messageToShow: statusToShow,
      isMultiDelete: false,
      dataToDelete: {}
    }));
    if (status) {
      getRpcStateData(formState.pageSize, 1, formState.filterDataParameters);
    }
  };

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

  /** Multi Delete */
  /** Get multiple user id for delete */
  const deleteMulUserById = () => {
    let arrayId = [];

    selectedRows.forEach(d => {
      arrayId.push(d.id);
    });

    setFormState(formState => ({
      ...formState,
      showEditModal: false,
      showModalDelete: true,
      isMultiDelete: true,
      MultiDeleteID: arrayId,
      isDataDeleted: false,
      fromDeleteModal: false,
      fromAddRpc: false,
      fromEditRpc: false
    }));
  };

  /** On select multiple rows */
  const handleRowSelected = useCallback(state => {
    if (state.selectedCount >= 1) {
      setFormState(formState => ({
        ...formState,
        selectedRowFilter: false,
        toggleCleared: false
      }));
    } else {
      setFormState(formState => ({
        ...formState,
        selectedRowFilter: true
      }));
    }
    setSelectedRows(state.selectedRows);
  }, []);

  /** Filter methods and functions */
  const handleFilterChange = event => {
    setRpcsFilter(event.target.value);
  };

  /** Search filter is called when we select filters and click on search button */
  const filterRpcData = async (perPage = formState.pageSize, page = 1) => {
    let params = "?name_contains=" + rpcsFilter;
    let FilterRpcURL =
      strapiConstants.STRAPI_DB_URL + strapiConstants.STRAPI_RPCS + params;
    serviceProviders
      .serviceProviderForGetRequest(FilterRpcURL)
      .then(res => {
        let currentPage = res.data.page;
        let totalRows = res.data.rowCount;
        let currentPageSize = res.data.pageSize;
        let pageCount = res.data.pageCount;
        formState.dataToShow = [];
        formState.tempData = [];
        let temp = [];
        temp = convertRpcData(res.data.result);
        setFormState(formState => ({
          ...formState,
          rpcs: res.data.result,
          dataToShow: temp,
          tempData: temp,
          pageSize: currentPageSize,
          totalRows: totalRows,
          page: currentPage,
          pageCount: pageCount,
          isDataLoading: false
        }));
      })
      .catch(error => {
        console.log("filterRpcDataError", error);
      });
  };

  const selectedRowCleared = data => {
    formState.toggleCleared = data;
    setTimeout(() => {
      setFormState(formState => ({
        ...formState,
        toggleCleared: false
      }));
    }, 2000);
  };

  const column = [
    { name: "Name", sortable: true, selector: "name" },
    { name: "State", sortable: true, selector: "state" },
    {
      name: "Actions",
      cell: cell => (
        <div className={classes.DisplayFlex}>
          <div className={classes.PaddingFirstActionButton}>
            <EditGridIcon id={cell.id} value={cell.name} onClick={editCell} />
          </div>
          <div className={classes.PaddingActionButton}>
            <DeleteGridIcon
              id={cell.id}
              onClick={deleteCell}
              value={cell.name}
            />
          </div>
        </div>
      ),
      width: "20%",
      cellStyle: {
        width: "auto",
        maxWidth: "auto"
      }
    }
  ];

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

  return (
    <Grid>
      <Grid
        container
        spacing={3}
        justify="space-between"
        className={classes.title}
      >
        <Grid item>
          <Typography variant="h4" gutterBottom>
            {genericConstants.VIEW_RPC_TEXT}
          </Typography>
        </Grid>
        <Grid item>
          <GreenButton
            id="deleteMulUsers"
            variant="contained"
            color="secondary"
            onClick={() => deleteMulUserById()}
            startIcon={<DeleteIcon />}
            greenButtonChecker={formState.greenButtonChecker}
            buttonDisabled={formState.selectedRowFilter}
            style={{ margin: "2px", marginRight: "15px" }}
          >
            Delete Selected RPC's
          </GreenButton>
          <GreenButton
            variant="contained"
            color="primary"
            disableElevation
            component={CustomRouterLink}
            to={routeConstants.ADD_RPC}
            startIcon={<AddCircleOutlineOutlinedIcon />}
            style={{ margin: "2px" }}
          >
            {genericConstants.ADD_RPC_TEXT}
          </GreenButton>
        </Grid>
      </Grid>
      <Grid item xs={12} className={classes.formgrid}>
        {/** Delete rpc data */}
        {/** Error/Success messages to be shown for edit */}
        {formState.fromEditRpc && formState.isDataEdited ? (
          <Collapse in={open}>
            <Alert
              severity="success"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              RPC {formState.editedRPCName} has been updated successfully.
            </Alert>
          </Collapse>
        ) : null}
        {formState.fromEditRpc && !formState.isDataEdited ? (
          <Collapse in={open}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {props.location.editResponseMessage
                ? props.location.editResponseMessage
                : "An error has occured while updating RPC. Kindly, try again."}
            </Alert>
          </Collapse>
        ) : null}

        {/** Error/Success messages to be shown for add */}
        {formState.fromAddRpc && formState.isDataAdded ? (
          <Collapse in={open}>
            <Alert
              severity="success"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              RPC {formState.addedRPCName} has been added successfully.
            </Alert>
          </Collapse>
        ) : null}
        {formState.fromAddRpc && !formState.isDataAdded ? (
          <Collapse in={open}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {props.location.addResponseMessage
                ? props.location.addResponseMessage
                : "An error has occured while adding RPC. Kindly, try again"}
            </Alert>
          </Collapse>
        ) : null}
        {formState.fromDeleteModal &&
        formState.isDataDeleted &&
        formState.messageToShow !== "" ? (
          <Collapse in={open}>
            <Alert
              severity="success"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {formState.messageToShow}
            </Alert>
          </Collapse>
        ) : null}

        {formState.fromDeleteModal &&
        !formState.isDataDeleted &&
        formState.messageToShow !== "" ? (
          <Collapse in={open}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {formState.messageToShow}
            </Alert>
          </Collapse>
        ) : null}
        <Card>
          <CardContent>
            <Grid className={classes.filterOptions} container spacing={1}>
              <Grid item>
                <TextField
                  id="name"
                  label={"Name"}
                  placeholder="Name"
                  variant="outlined"
                  value={rpcsFilter}
                  onChange={handleFilterChange}
                />
              </Grid>
              <Grid className={classes.filterButtonsMargin}>
                <YellowButton
                  id="submitFilter"
                  variant="contained"
                  color="primary"
                  disableElevation
                  onClick={event => {
                    event.persist();
                    filterRpcData();
                  }}
                >
                  {genericConstants.SEARCH_BUTTON_TEXT}
                </YellowButton>
              </Grid>
              <Grid className={classes.filterButtonsMargin}>
                <GrayButton
                  id="cancelFilter"
                  variant="contained"
                  color="primary"
                  onClick={clearFilter}
                  disableElevation
                >
                  {genericConstants.RESET_BUTTON_TEXT}
                </GrayButton>
              </Grid>
            </Grid>
          </CardContent>
        </Card>
        <Card className={classes.tabledata} variant="outlined">
          {formState.dataToShow ? (
            formState.dataToShow.length ? (
              <Table
                id="ManageTableID"
                data={formState.dataToShow}
                column={column}
                defaultSortField="name"
                onSelectedRowsChange={handleRowSelected}
                paginationResetDefaultPage={formState.resetPagination}
                defaultSortAsc={formState.sortAscending}
                editEvent={editCell}
                deleteEvent={deleteCell}
                progressPending={formState.isDataLoading}
                paginationDefaultPage={formState.page}
                paginationPerPage={formState.pageSize}
                paginationTotalRows={formState.totalRows}
                paginationRowsPerPageOptions={[10, 20, 50]}
                onChangeRowsPerPage={handlePerRowsChange}
                onChangePage={handlePageChange}
                onSort={handleSort}
                sortServer={true}
                clearSelectedRows={formState.toggleCleared}
              />
            ) : (
              <Spinner />
            )
          ) : (
            <div className={classes.noDataMargin}>No data to show</div>
          )}
          {formState.showModalDelete ? (
            <DeleteRpc
              showModal={formState.showModalDelete}
              closeModal={handleCloseDeleteModal}
              id={
                formState.isMultiDelete
                  ? formState.MultiDeleteID
                  : formState.dataToDelete["id"]
              }
              modalClose={modalClose}
              isMultiDelete={formState.isMultiDelete ? true : false}
              dataToDelete={formState.dataToDelete}
              clearSelectedRow={selectedRowCleared}
            />
          ) : null}
        </Card>
      </Grid>
      <Backdrop className={classes.backDrop} open={backDrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </Grid>
  );
}
Example #21
Source File: AddEditRpc.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditRpc = props => {
  const history = useHistory();
  const classes = useStyles();
  const [states, setStates] = useState(props.option ? props.option : []);
  const [getColleges, setGetColleges] = useState(
    props.collegeOption ? props.collegeOption : []
  );
  const [isSuccess, setIsSuccess] = useState(false);
  const [isFailed, setIsFailed] = useState(false);
  const [formState, setFormState] = useState({
    backDrop: false,
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    isSuccess: false,
    isStateClearFilter: false,
    isEditRpc: props["editRpc"] ? props["editRpc"] : false,
    dataForEdit: props["dataForEdit"] ? props["dataForEdit"] : {},
    counter: 0
  });

  /** Part for editing college */
  if (formState.isEditRpc && !formState.counter) {
    if (props["dataForEdit"]) {
      if (props["dataForEdit"]["name"]) {
        formState.values[rpcName] = props["dataForEdit"]["name"];
      }
      if (
        props["dataForEdit"]["state"] &&
        props["dataForEdit"]["state"]["id"]
      ) {
        formState.values[stateName] = props["dataForEdit"]["state"]["id"];
      }
      if (
        props["dataForEdit"]["main_college"] &&
        props["dataForEdit"]["main_college"]["id"]
      ) {
        formState.values[collegeName] =
          props["dataForEdit"]["main_college"]["id"];
      }

      formState.counter += 1;
    }
  }

  useEffect(() => {
    /* TO GET STATES AND COLLEGE IN AUTOCOMPLETE */

    let paramsForPageSize = {
      name_contains: "Uttar Pradesh"
    };

    serviceProviders
      .serviceProviderForGetRequest(STATE_URL, paramsForPageSize)
      .then(res => {
        setStates(res.data.result);
      });
  }, []);

  useEffect(() => {
    if (formState.values[stateName]) {
      let COLLEGE_URL =
        strapiConstants.STRAPI_DB_URL +
        strapiConstants.STRAPI_STATES +
        "/" +
        formState.values[stateName] +
        "/" +
        strapiConstants.STRAPI_ORGANIZATION +
        "/" +
        formState.dataForEdit["id"] +
        "/rpc";
      serviceProviders.serviceProviderForGetRequest(COLLEGE_URL).then(res => {
        setGetColleges(res.data);
      });
    }
    return () => {};
  }, [formState.values[stateName]]);

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

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

  /** This handle change is used to handle changes to auto complete */
  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
      }));

      /** 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 college should clear off! */
      if (eventName === stateName) {
        /** 
        This flag is used to determine that state is cleared which clears 
        off college by setting their value to null 
        */
        setStateFilterValue = true;
        /** 
        When state is cleared then clear college
        */
        setGetColleges([]);
        delete formState.values[collegeName];
      }
      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];
    }
  };

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

  /** Handle submit handles the submit and performs all the validations */
  const handleSubmit = event => {
    let isValid = false;
    /** Checkif all fields are present in the submitted form */
    let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
      formState.values,
      AddRpcSchema
    );
    if (checkAllFieldsValid) {
      /** Evaluated only if all keys are valid inside formstate */
      formState.errors = formUtilities.setErrors(
        formState.values,
        AddRpcSchema
      );
      /** Checks if the form is empty */
      if (formUtilities.checkEmpty(formState.errors)) {
        isValid = true;
      }
    } else {
      /** This is used to find out which all required fields are not filled */
      formState.values = formUtilities.getListOfKeysNotPresent(
        formState.values,
        AddRpcSchema
      );
      /** This sets errors by comparing it with the json schema provided */
      formState.errors = formUtilities.setErrors(
        formState.values,
        AddRpcSchema
      );
    }
    if (isValid) {
      /** CALL POST FUNCTION */
      postRpcData();
    } else {
      setFormState(formState => ({
        ...formState,
        isValid: false
      }));
      formState.backDrop = false;
    }
    event.preventDefault();
  };

  const postRpcData = async () => {
    let postData = databaseUtilities.addRpc(
      formState.values[rpcName],
      formState.values[stateName] ? formState.values[stateName] : null,
      formState.values[collegeName] ? formState.values[collegeName] : null
    );
    if (formState.isEditRpc) {
      serviceProviders
        .serviceProviderForPutRequest(
          RPCS_URL,
          formState.dataForEdit["id"],
          postData
        )
        .then(res => {
          formState.backDrop = false;
          history.push({
            pathname: routeConstants.MANAGE_RPC,
            fromEditRpc: true,
            isDataEdited: true,
            editedRPCData: res.data,
            editResponseMessage: "",
            editedData: {}
          });
        })
        .catch(error => {
          formState.backDrop = false;
          console.log("Put ERROR", error, error.response);
          let errorMessage;

          if (
            error.response !== undefined &&
            error.response.status !== undefined &&
            error.response.status === 400
          ) {
            if (error.response.data["message"]) {
              errorMessage = error.response.data["message"];
            }
          }
          history.push({
            pathname: routeConstants.MANAGE_RPC,
            fromEditRpc: true,
            isDataEdited: false,
            editResponseMessage: errorMessage ? errorMessage : "",
            editedData: {}
          });
        });
    } else {
      serviceProviders
        .serviceProviderForPostRequest(RPCS_URL, postData)
        .then(res => {
          formState.backDrop = false;
          history.push({
            pathname: routeConstants.MANAGE_RPC,
            fromAddRpc: true,
            isDataAdded: true,
            addedRPCData: res.data,
            addResponseMessage: "",
            addedData: {}
          });
        })
        .catch(error => {
          console.log(error, error.response);
          formState.backDrop = 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"];
            }
          }
          history.push({
            pathname: routeConstants.MANAGE_RPC,
            fromAddRpc: true,
            isDataAdded: false,
            addResponseMessage: errorMessage ? errorMessage : "",
            addedData: {}
          });
        });
    }
  };

  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        {formState.isEditRpc ? (
          <Typography variant="h4" gutterBottom>
            {genericConstants.EDIT_RPC_TEXT}
          </Typography>
        ) : (
          <Typography variant="h4" gutterBottom>
            {genericConstants.ADD_RPC_TITLE}
          </Typography>
        )}
        {isSuccess ? (
          <Alert severity="success">
            {genericConstants.ALERT_SUCCESS_BUTTON_MESSAGE}
          </Alert>
        ) : null}
        {isFailed ? (
          <Alert severity="error">
            {genericConstants.ALERT_ERROR_BUTTON_MESSAGE}
          </Alert>
        ) : null}
      </Grid>
      <Grid item xs={12} className={classes.formgrid}>
        <Card className={classes.root} variant="outlined">
          <form autoComplete="off" noValidate onSubmit={handleSubmit} id="form">
            <CardContent>
              <Grid container spacing={2}>
                <Grid item md={12} xs={12}>
                  <TextField
                    fullWidth
                    id={get(AddRpcSchema[rpcName], "id")}
                    label={get(AddRpcSchema[rpcName], "label")}
                    margin="normal"
                    name={rpcName}
                    onChange={handleChange}
                    required
                    placeholder={get(AddRpcSchema[rpcName], "placeholder")}
                    type={get(AddRpcSchema[rpcName], "type")}
                    value={formState.values[rpcName] || ""}
                    error={hasError(rpcName)}
                    helperText={
                      hasError(rpcName)
                        ? formState.errors[rpcName].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    variant="outlined"
                    className={classes.elementroot}
                  />
                </Grid>
                <Grid item md={12} xs={12}>
                  <Autocomplete
                    id={get(AddRpcSchema[stateName], "id")}
                    options={states}
                    getOptionLabel={option => option.name}
                    onChange={(event, value) => {
                      handleChangeAutoComplete(stateName, event, value);
                    }}
                    name={stateName}
                    value={
                      formState.isStateClearFilter
                        ? null
                        : states[
                            states.findIndex(function (item, i) {
                              return item.id === formState.values[stateName];
                            })
                          ] || null /** Please give a default " " blank value */
                    }
                    renderInput={params => (
                      <TextField
                        {...params}
                        error={hasError(stateName)}
                        placeholder={get(
                          AddRpcSchema[stateName],
                          "placeholder"
                        )}
                        helperText={
                          hasError(stateName)
                            ? formState.errors[stateName].map(error => {
                                return error + " ";
                              })
                            : null
                        }
                        value={option => option.id}
                        name={stateName}
                        key={option => option.id}
                        label={get(AddRpcSchema[stateName], "label")}
                        variant="outlined"
                      />
                    )}
                    className={classes.elementroot}
                  />
                </Grid>
                {formState.isEditRpc ? (
                  <Grid item md={12} xs={12}>
                    <Autocomplete
                      id={get(AddRpcSchema[collegeName], "id")}
                      options={getColleges}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete(collegeName, event, value);
                      }}
                      name={collegeName}
                      value={
                        formState.isStateClearFilter
                          ? null
                          : getColleges[
                              getColleges.findIndex(function (item, i) {
                                return (
                                  item.id === formState.values[collegeName]
                                );
                              })
                            ] ||
                            null /** Please give a default " " blank value */
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError(collegeName)}
                          placeholder={get(
                            AddRpcSchema[collegeName],
                            "placeholder"
                          )}
                          helperText={
                            hasError(collegeName)
                              ? formState.errors[collegeName].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                          value={option => option.id}
                          name={collegeName}
                          key={option => option.id}
                          label={get(AddRpcSchema[collegeName], "label")}
                          variant="outlined"
                        />
                      )}
                      className={classes.elementroot}
                    />{" "}
                  </Grid>
                ) : null}
              </Grid>
            </CardContent>
            <Grid item xs={12} className={classes.CardActionGrid}>
              <CardActions className={classes.btnspace}>
                <Grid item xs={12}>
                  <Grid item xs={12} md={6} xl={3}>
                    <Grid container spacing={3}>
                      <Grid item md={2} xs={12}>
                        <YellowButton
                          type="submit"
                          color="primary"
                          variant="contained"
                          onClick={() => {
                            formState.backDrop = true;
                          }}
                        >
                          {genericConstants.SAVE_BUTTON_TEXT}
                        </YellowButton>
                      </Grid>
                      <Grid item md={2} xs={12}>
                        <GrayButton
                          type="submit"
                          color="primary"
                          variant="contained"
                          to={routeConstants.MANAGE_RPC}
                        >
                          {genericConstants.CANCEL_BUTTON_TEXT}
                        </GrayButton>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </CardActions>
            </Grid>
          </form>
        </Card>
      </Grid>
      <Backdrop className={classes.backDrop} open={formState.backDrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </Grid>
  );
}
Example #22
Source File: MarkAttaindance.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
MarkAttaindance = props => {
  const [open, setOpen] = React.useState(false);

  const [formState, setFormState] = useState({
    isAttaindanceMarked: false,
    isValid: false,
    stateCounter: 0,
    values: {}
  });

  const handleCloseModal = () => {
    setOpen(false);

    setFormState(formState => ({
      ...formState,
      values: {},
      isAttaindanceMarked: false,
      isValid: false,
      stateCounter: 0
    }));

    if (formState.isAttaindanceMarked) {
      props.closeAttaindanceModal(true);
    } else {
      props.closeAttaindanceModal(false);
    }
  };

  const handleSubmit = event => {
    setOpen(true);
    /** CALL Put FUNCTION */
    attaindanceHandler();
    event.preventDefault();
  };

  const attaindanceHandler = () => {
    var body;
    if (props.isPresent) {
      body = {
        is_attendance_verified: true
      };
    }
    if (props.isAbsent) {
      body = {
        is_attendance_verified: false
      };
    }
    serviceProviders
      .serviceProviderForPutRequest(REGISTRATION_URL, props.id, body)
      .then(res => {
        formState.isAttaindanceMarked = true;
        handleCloseModal();
      })
      .catch(error => {
        console.log("error---", error);
        formState.isAttaindanceMarked = false;
        handleCloseModal();
      });
  };
  const classes = useStyles();
  return (
    <Modal
      aria-labelledby="transition-modal-title"
      aria-describedby="transition-modal-description"
      className={classes.modal}
      open={props.showModal}
      onClose={handleCloseModal}
      closeAfterTransition
      BackdropComponent={Backdrop}
      BackdropProps={{
        timeout: 500
      }}
    >
      <Fade in={props.showModal}>
        <div className={classes.paper}>
          <div className={classes.blockpanel}>
            <Typography variant={"h2"} className={classes.textMargin}>
              {props.isPresent
                ? genericConstants.ADD_ATT_BUTTON_TEXT
                : genericConstants.REMOVE_ATT_BUTTON_TEXT}
            </Typography>
            <div className={classes.crossbtn}>
              <IconButton
                aria-label="close"
                className={classes.closeButton}
                onClick={props.modalClose}
              >
                <CloseIcon />
              </IconButton>
            </div>
          </div>
          <div className={classes.edit_dialog}>
            <Grid item xs={12}>
              <Grid container spacing={2} alignItems="center">
                <Grid item lg className={classes.deletemessage}>
                  {props.isPresent ? (
                    <p>
                      Are you sure you want to add attendence for{" "}
                      {props.studentName}?
                    </p>
                  ) : (
                    <p>
                      Are you sure you want to remove attendence for{" "}
                      {props.studentName}?
                    </p>
                  )}
                </Grid>
              </Grid>
            </Grid>
            <Grid item xs={12}>
              <Grid
                container
                direction="row"
                justify="flex-end"
                alignItems="center"
                spacing={2}
              >
                <Grid item>
                  <YellowButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleSubmit}
                  >
                    Ok
                  </YellowButton>
                </Grid>
                <Grid item>
                  <GrayButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={props.modalClose}
                  >
                    Close
                  </GrayButton>
                </Grid>
              </Grid>
            </Grid>
          </div>
          <Backdrop className={classes.backdrop} open={open}>
            <CircularProgress color="inherit" />
          </Backdrop>
        </div>
      </Fade>
    </Modal>
  );
}
Example #23
Source File: HireStudent.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
HireStudent = props => {
  const [open, setOpen] = React.useState(false);

  const [formState, setFormState] = useState({
    isStudentHired: false,
    isValid: false,
    stateCounter: 0,
    values: {}
  });

  const handleCloseModal = () => {
    setOpen(false);

    setFormState(formState => ({
      ...formState,
      values: {},
      isStudentHired: false,
      isValid: false,
      stateCounter: 0
    }));

    if (formState.isStudentHired) {
      props.closeHireModal(true);
    } else {
      props.closeHireModal(false);
    }
  };

  const handleSubmit = event => {
    setOpen(true);
    /** CALL Put FUNCTION */
    studentHired();
    event.preventDefault();
  };

  const studentHired = () => {
    var body;
    if (props.isHired) {
      body = {
        is_hired_at_event: true
      };
    }
    if (props.isUnHired) {
      body = {
        is_hired_at_event: false
      };
    }
    serviceProviders
      .serviceProviderForPutRequest(REGISTRATION_URL, props.id, body)
      .then(res => {
        formState.isStudentHired = true;
        handleCloseModal();
      })
      .catch(error => {
        console.log("error---", error);
        formState.isStudentHired = false;
        handleCloseModal();
      });
  };

  const classes = useStyles();
  return (
    <Modal
      aria-labelledby="transition-modal-title"
      aria-describedby="transition-modal-description"
      className={classes.modal}
      open={props.showModal}
      onClose={handleCloseModal}
      closeAfterTransition
      BackdropComponent={Backdrop}
      BackdropProps={{
        timeout: 500
      }}
    >
      <Fade in={props.showModal}>
        <div className={classes.paper}>
          <div className={classes.blockpanel}>
            <Typography variant={"h2"} className={classes.textMargin}>
              {props.isHired
                ? genericConstants.HIRE_BUTTON_TEXT
                : genericConstants.DEHIRE_BUTTON_TEXT}
            </Typography>
            <div className={classes.crossbtn}>
              <IconButton
                aria-label="close"
                className={classes.closeButton}
                onClick={props.modalClose}
              >
                <CloseIcon />
              </IconButton>
            </div>
          </div>
          <div className={classes.edit_dialog}>
            <Grid item xs={12}>
              <Grid container spacing={2} alignItems="center">
                <Grid item lg className={classes.deletemessage}>
                  {props.isHired ? (
                    <p>Are you sure you want to Hire {props.studentName}?</p>
                  ) : (
                    <p>Are you sure you want to Dehire {props.studentName}?</p>
                  )}
                </Grid>
              </Grid>
            </Grid>
            <Grid item xs={12}>
              <Grid
                container
                direction="row"
                justify="flex-end"
                alignItems="center"
                spacing={2}
              >
                <Grid item>
                  <YellowButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleSubmit}
                  >
                    Ok
                  </YellowButton>
                </Grid>
                <Grid item>
                  <GrayButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={props.modalClose}
                  >
                    Close
                  </GrayButton>
                </Grid>
              </Grid>
            </Grid>
          </div>
          <Backdrop className={classes.backdrop} open={open}>
            <CircularProgress color="inherit" />
          </Backdrop>
        </div>
      </Fade>
    </Modal>
  );
}
Example #24
Source File: DeleteEvent.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
DeleteUser = props => {
  const { setLoaderStatus } = useContext(LoaderContext);
  const [formState, setFormState] = useState({
    isDeleteData: false,
    isValid: false,
    stateCounter: 0,
    values: {},
    dataToDelete: {}
  });

  if (props.showModal && !formState.stateCounter) {
    formState.stateCounter = 0;
    formState.values[EVENT_ID] = props.id;
    formState.isDeleteData = false;
    formState.dataToDelete = props.dataToDelete;
  }
  const handleCloseModal = (message = "") => {
    /** This event handles the scenario when the pop up is closed just by clicking outside the popup 
    to ensure that only string value is passed to message variable */
    if (typeof message !== "string") {
      message = "";
    }
    setFormState(formState => ({
      ...formState,
      values: {},
      isDeleteData: false,
      isValid: false,
      stateCounter: 0
    }));
    if (formState.isDeleteData) {
      props.closeModal(true, message);
    } else {
      props.closeModal(false, message);
    }
  };

  const handleSubmit = event => {
    /** CALL Put FUNCTION */
    setLoaderStatus(true);
    props.clearSelectedRow(true);
    deleteData();
    event.preventDefault();
  };

  const deleteData = () => {
    if (props.isMultiDelete) {
      serviceProviders
        .serviceProviderForAllDeleteRequest(EVENT_URL, props.id)
        .then(res => {
          setLoaderStatus(false);
          setFormState(formState => ({
            ...formState,
            isValid: true
          }));
          formState.isDeleteData = true;
          handleCloseModal("Events has been deleted successfully");
        })
        .catch(error => {
          setLoaderStatus(false);
          console.log("error", error);
          formState.isDeleteData = false;
          handleCloseModal(
            "An error has occured while deleting events. Kindly, try again"
          );
        });
    } else {
      serviceProviders
        .serviceProviderForDeleteRequest(EVENT_URL, props.id)
        .then(res => {
          setLoaderStatus(false);
          setFormState(formState => ({
            ...formState,
            isValid: true
          }));
          formState.isDeleteData = true;
          handleCloseModal(
            "Event " +
              formState.dataToDelete["name"] +
              " has been deleted successfully"
          );
        })
        .catch(error => {
          setLoaderStatus(false);
          console.log("error");
          formState.isDeleteData = false;
          handleCloseModal(
            "An error has occured while deleting event" +
              formState.dataToDelete["name"] +
              ". Kindly, try again"
          );
        });
    }
  };

  const handleClose = async event => {
    props.clearSelectedRow(true);
    props.closeModal();
  };

  const classes = useStyles();
  return (
    <Modal
      aria-labelledby="transition-modal-title"
      aria-describedby="transition-modal-description"
      className={classes.modal}
      open={props.showModal}
      onClose={handleCloseModal}
      closeAfterTransition
      BackdropComponent={Backdrop}
      BackdropProps={{
        timeout: 500
      }}
    >
      <Fade in={props.showModal}>
        <div className={classes.paper}>
          <div className={classes.blockpanel}>
            <Typography variant={"h2"} className={classes.textMargin}>
              {genericConstants.DELETE_TEXT}
            </Typography>
            <div className={classes.crossbtn}>
              <IconButton
                aria-label="close"
                className={classes.closeButton}
                onClick={props.modalClose}
              >
                <CloseIcon />
              </IconButton>
            </div>
          </div>
          <div className={classes.edit_dialog}>
            <Grid item xs={12}>
              <Grid container spacing={2} alignItems="center">
                <Grid item lg className={classes.deletemessage}>
                  {props.id ? (
                    props.isMultiDelete ? (
                      <p>
                        Are you sure you want to delete "{props.seletedUser}"
                        Events?
                      </p>
                    ) : (
                      <p>
                        Are you sure you want to delete event "
                        {props.dataToDelete["name"]}"?
                      </p>
                    )
                  ) : null}
                </Grid>
              </Grid>
            </Grid>
            <Grid item xs={12}>
              <Grid
                container
                direction="row"
                justify="flex-end"
                alignItems="center"
                spacing={2}
              >
                <Grid item>
                  <YellowButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleSubmit}
                  >
                    Ok
                  </YellowButton>
                </Grid>
                <Grid item>
                  <GrayButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleClose}
                  >
                    Close
                  </GrayButton>
                </Grid>
              </Grid>
            </Grid>
          </div>
        </div>
      </Fade>
    </Modal>
  );
}
Example #25
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 #26
Source File: DeleteCollege.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
DeleteZone = props => {
  const [open, setOpen] = React.useState(false);
  const [formState, setFormState] = useState({
    isDeleteData: false,
    isValid: false,
    stateCounter: 0,
    values: {},
    dataToDelete: {}
  });

  if (props.showModal && !formState.stateCounter) {
    formState.stateCounter = 0;
    formState.values[COLLEGE_ID] = props.id;
    formState.isDeleteData = false;
    formState.dataToDelete = props.dataToDelete;
  }

  const handleCloseModal = (message = "") => {
    /** This event handles the scenario when the pop up is closed just by clicking outside the popup 
    to ensure that only string value is passed to message variable */
    if (typeof message !== "string") {
      message = "";
    }
    setFormState(formState => ({
      ...formState,
      values: {},
      isDeleteData: false,
      isValid: false,
      stateCounter: 0
    }));
    if (formState.isDeleteData) {
      props.closeModal(true, message);
    } else {
      props.closeModal(false, message);
    }
  };

  const handleSubmit = async event => {
    /** CALL Put FUNCTION */
    setOpen(true);
    event.preventDefault();
    event.persist();
    props.clearSelectedRow(true);
    let status = {};
    /** Calls checkIfStateCanBeDelete function to check whether the state can be deleted
     and returns back an opbject with status and message*/
    if (props.isMultiDelete) {
      status = await checkIfMultiCollegeCanBeDelete();
    } else {
      status = await checkIfCollegeCanBeDelete(
        formState.dataToDelete.organizationId
      );
    }
    setOpen(false);
    if (status["status"]) {
      deleteData();
    } else {
      formState.isDeleteData = false;
      handleCloseModal(
        status["message"]
      ); /** returns back a message saying state cannot be deleted */
    }
  };

  const handleClose = async event => {
    props.clearSelectedRow(true);
    props.closeModal();
  };

  const checkIfMultiCollegeCanBeDelete = async () => {
    let dataToSent = {};
    let isErrorCounter = 0;
    for (let i in props.MultiOrganizationId) {
      let status = await checkIfCollegeCanBeDelete(
        props.MultiOrganizationId[i]
      );
      if (!status["status"]) {
        isErrorCounter += 1;
        break;
      }
    }
    if (isErrorCounter > 0) {
      dataToSent = {
        status: false,
        message: "Error deleting selected Colleges"
      };
    } else {
      dataToSent = { status: true, message: "Success" };
    }
    return dataToSent;
  };

  /** This checks if the state can be deleted and returns back an array with status and message*/
  const checkIfCollegeCanBeDelete = async id => {
    let dataToReturn = {};
    let studentsCheckUrl =
      strapiConstants.STRAPI_DB_URL +
      strapiConstants.STRAPI_COLLEGES +
      "/" +
      id +
      "/" +
      strapiConstants.STRAPI_STUDENT;
    await serviceProviders
      .serviceProviderForGetRequest(studentsCheckUrl)
      .then(res => {
        if (res.data.result.length > 0) {
          dataToReturn = {
            status: false,
            message:
              "Cannot delete College " +
              formState.dataToDelete["name"] +
              " as it is linked to other Students"
          };
        } else {
          dataToReturn = {
            status: true,
            message: "Success"
          };
        }
      })
      .catch(error => {
        console.log("error", error);
        /** return error */
        dataToReturn = {
          status: false,
          message: "Error deleting College " + formState.dataToDelete["name"]
        };
      });
    return dataToReturn;
  };

  const deleteData = () => {
    if (props.isMultiDelete) {
      let deleteId = {
        ids: props.id
      };
      serviceProviders
        .serviceProviderForPostRequest(COLLEGE_URL, deleteId)
        .then(res => {
          setFormState(formState => ({
            ...formState,
            isValid: true
          }));
          formState.isDeleteData = true;
          handleCloseModal("Colleges have been deleted successfully");
        })
        .catch(error => {
          console.log("error");
          formState.isDeleteData = false;
          handleCloseModal(
            "An error has occured while deleting colleges. Kindly, try again"
          );
        });
    } else {
      let idArray = [];
      idArray.push(parseInt(props.id));
      let deleteId = {
        ids: idArray
      };
      serviceProviders
        .serviceProviderForPostRequest(COLLEGE_URL, deleteId)
        .then(res => {
          setFormState(formState => ({
            ...formState,
            isValid: true
          }));
          formState.isDeleteData = true;
          handleCloseModal(
            "College " +
              formState.dataToDelete["name"] +
              " has been deleted successfully"
          );
        })
        .catch(error => {
          console.log("error", error);
          formState.isDeleteData = false;
          handleCloseModal(
            "An error has occured while deleting college" +
              formState.dataToDelete["name"] +
              ". Kindly, try again"
          );
        });
    }
  };

  const classes = useStyles();
  return (
    <Modal
      aria-labelledby="transition-modal-title"
      aria-describedby="transition-modal-description"
      className={classes.modal}
      open={props.showModal}
      onClose={handleCloseModal}
      closeAfterTransition
      BackdropComponent={Backdrop}
      BackdropProps={{
        timeout: 500
      }}
    >
      <Fade in={props.showModal}>
        <div className={classes.paper}>
          <div className={classes.blockpanel}>
            <Typography variant={"h2"} className={classes.textMargin}>
              {genericConstants.DELETE_TEXT}
            </Typography>
            <div className={classes.crossbtn}>
              <IconButton
                aria-label="close"
                className={classes.closeButton}
                onClick={props.modalClose}
              >
                <CloseIcon />
              </IconButton>
            </div>
          </div>
          <div className={classes.edit_dialog}>
            <Grid item xs={12}>
              <Grid container spacing={2} alignItems="center">
                <Grid item lg className={classes.deletemessage}>
                  {props.isMultiDelete
                    ? "Are you sure you want to delete the selected Colleges?"
                    : "Are you sure you want to delete College " +
                      formState.dataToDelete["name"] +
                      "?"}
                </Grid>
              </Grid>
            </Grid>
            <Grid item xs={12}>
              <Grid
                container
                direction="row"
                justify="flex-end"
                alignItems="center"
                spacing={2}
              >
                <Grid item>
                  <YellowButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleSubmit}
                  >
                    Ok
                  </YellowButton>
                </Grid>
                <Grid item>
                  <GrayButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleClose}
                  >
                    Close
                  </GrayButton>
                </Grid>
              </Grid>
            </Grid>
          </div>
          <Backdrop className={classes.backdrop} open={open}>
            <CircularProgress color="inherit" />
          </Backdrop>
        </div>
      </Fade>
    </Modal>
  );
}
Example #27
Source File: BlockUnblockCollege.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
BlockUnblockCollege = props => {
  const [open, setOpen] = React.useState(false);
  const [formState, setFormState] = useState({
    isDataBlockUnblock: false,
    isValid: false,
    stateCounter: 0
  });

  /** Part for editing college */
  if (props.showModal && !formState.stateCounter) {
    formState.stateCounter = 0;
    formState.isDataBlockUnblock = false;
  }

  const handleCloseModal = (message = "") => {
    setOpen(false);
    /** This event handles the scenario when the pop up is closed just by clicking outside the popup 
    to ensure that only string value is passed to message variable */
    if (typeof message !== "string") {
      message = "";
    }
    setFormState(formState => ({
      ...formState,
      values: {},
      isDataBlockUnblock: false,
      isValid: false,
      stateCounter: 0
    }));
    if (formState.isDataBlockUnblock) {
      props.closeModal(true, message);
    } else {
      props.closeModal(false, message);
    }
  };

  const handleSubmit = async event => {
    /** CALL Put FUNCTION */
    setOpen(true);
    event.preventDefault();
    event.persist();
    props.clearSelectedRow(true);
    /** Calls checkIfStateCanBeDelete function to check whether the state can be deleted
     and returns back an opbject with status and message*/
    blockUnblockData();
  };

  const blockUnblockData = () => {
    if (props.isMultiBlock || props.isMultiUnblock) {
      let COLLEGE_URL = "";
      if (props.isMultiUnblock) {
        COLLEGE_URL = COLLEGE_UNBLOCK_URL;
      } else {
        COLLEGE_URL = COLLEGE_BLOCK_URL;
      }
      let postData = {
        ids: props.multiBlockCollegeIds
      };
      serviceProviders
        .serviceProviderForPostRequest(COLLEGE_URL, postData)
        .then(res => {
          setFormState(formState => ({
            ...formState,
            isValid: true
          }));
          formState.isDataBlockUnblock = true;
          if (props.isMultiUnblock) {
            handleCloseModal("Colleges have been unblocked successfully");
          } else {
            handleCloseModal("Colleges have been blocked successfully");
          }
        })
        .catch(error => {
          console.log("error");
          formState.isDataBlockUnblock = false;
          if (props.isMultiUnblock) {
            handleCloseModal(
              "An error has occured while unblocking colleges. Kindly, try again."
            );
          } else {
            handleCloseModal(
              "An error has occured while blocking colleges. Kindly, try again."
            );
          }
        });
    } else {
      if (props.dataToBlockUnblock["is_blocked"]) {
        let ids = [];
        ids.push(props.dataToBlockUnblock["id"]);
        let postData = {
          ids: ids
        };
        serviceProviders
          .serviceProviderForPostRequest(COLLEGE_UNBLOCK_URL, postData)
          .then(res => {
            setFormState(formState => ({
              ...formState,
              isValid: true
            }));
            formState.isDataBlockUnblock = true;
            handleCloseModal(
              "College " +
                props.dataToBlockUnblock["name"] +
                " has been unblocked."
            );
          })
          .catch(error => {
            console.log("error");
            formState.isDataBlockUnblock = false;
            handleCloseModal(
              "An error has occured while unblocking college" +
                props.dataToBlockUnblock["name"] +
                ". Kindly, try again."
            );
          });
      } else {
        let ids = [];
        ids.push(props.dataToBlockUnblock["id"]);
        let postData = {
          ids: ids
        };
        serviceProviders
          .serviceProviderForPostRequest(COLLEGE_BLOCK_URL, postData)
          .then(res => {
            setFormState(formState => ({
              ...formState,
              isValid: true
            }));
            formState.isDataBlockUnblock = true;
            handleCloseModal(
              "College " +
                props.dataToBlockUnblock["name"] +
                " has been blocked."
            );
          })
          .catch(error => {
            console.log("error");
            formState.isDataBlockUnblock = false;
            handleCloseModal(
              "An error has occured while blocking college" +
                props.dataToBlockUnblock["name"] +
                ". Kindly, try again."
            );
          });
      }
    }
  };

  const handleBlock = async event => {
    props.clearSelectedRow(true);
    props.closeModal();
  };

  const classes = useStyles();
  return (
    <React.Fragment>
      {!formUtilities.checkEmpty(props.dataToBlockUnblock) ||
      props.multiBlockCollegeIds.length ? (
        <Modal
          aria-labelledby="transition-modal-title"
          aria-describedby="transition-modal-description"
          className={classes.modal}
          open={props.showModal}
          onClose={handleCloseModal}
          closeAfterTransition
          BackdropComponent={Backdrop}
          BackdropProps={{
            timeout: 500
          }}
        >
          <Fade in={props.showModal}>
            <div className={classes.paper}>
              <div className={classes.blockpanel}>
                <Typography variant={"h2"} className={classes.textMargin}>
                  {props.isMultiBlock || props.isMultiUnblock
                    ? props.isMultiBlock
                      ? genericConstants.BLOCK_BUTTON_TEXT
                      : genericConstants.UNBLOCK_BUTTON_TEXT
                    : null}
                  {!props.isMultiBlock && !props.isMultiUnblock
                    ? props.dataToBlockUnblock["is_blocked"]
                      ? genericConstants.UNBLOCK_BUTTON_TEXT
                      : genericConstants.BLOCK_BUTTON_TEXT
                    : null}
                </Typography>
                <div className={classes.crossbtn}>
                  <IconButton
                    aria-label="close"
                    className={classes.closeButton}
                    onClick={props.modalClose}
                  >
                    <CloseIcon />
                  </IconButton>
                </div>
              </div>
              <div className={classes.edit_dialog}>
                <Grid item xs={12}>
                  <Grid container spacing={2} alignItems="center">
                    <Grid item lg className={classes.deletemessage}>
                      {props.isMultiBlock || props.isMultiUnblock
                        ? props.isMultiBlock
                          ? "Are you sure you want to block all selected colleges"
                          : "Are you sure you want to unblock all selected colleges"
                        : null}
                      {!props.isMultiBlock && !props.isMultiUnblock
                        ? props.dataToBlockUnblock["is_blocked"]
                          ? "Are you sure you want to unblock college " +
                            props.dataToBlockUnblock["name"]
                          : "Are you sure you want to block college " +
                            props.dataToBlockUnblock["name"]
                        : null}
                    </Grid>
                  </Grid>
                </Grid>
                <Grid item xs={12}>
                  <Grid
                    container
                    direction="row"
                    justify="flex-end"
                    alignItems="center"
                    spacing={2}
                  >
                    <Grid item>
                      <YellowButton
                        type="submit"
                        color="primary"
                        variant="contained"
                        onClick={handleSubmit}
                      >
                        OK
                      </YellowButton>
                    </Grid>
                    <Grid item>
                      <GrayButton
                        type="submit"
                        color="primary"
                        variant="contained"
                        onClick={handleBlock}
                      >
                        Close
                      </GrayButton>
                    </Grid>
                  </Grid>
                </Grid>
              </div>
              <Backdrop className={classes.backdrop} open={open}>
                <CircularProgress color="inherit" />
              </Backdrop>
            </div>
          </Fade>
        </Modal>
      ) : null}
    </React.Fragment>
  );
}
Example #28
Source File: AddEditCollege.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditCollege = props => {
  const history = useHistory();
  const classes = useStyles();

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

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

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

      formState.counter += 1;
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      errors.push(errorObject);
    });

    setValidateAddress(errors);
    return !isError;
  };

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

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

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

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

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

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

                    {formState.dynamicBar.map((val, idx) => {
                      let streamId = `stream-${idx}`,
                        firstYearStrengthId = `first-year-strength-${idx}`,
                        secondYearStrengthId = `second-year-strength-${idx}`,
                        thirdYearStrengthId = `third-year-strength-${idx}`;
                      return (
                        <Card
                          id="outlined-stream-card"
                          fullwidth={true.toString()}
                          className={classes.streamcardcontent}
                          key={idx}
                        >
                          <CardContent>
                            <Grid container spacing={1}>
                              <Grid item xs={12} md={3}>
                                <FormControl
                                  variant="outlined"
                                  fullWidth
                                  className={classes.formControl}
                                >
                                  <InputLabel
                                    ref={inputLabel}
                                    id="demo-simple-select-outlined-label"
                                  >
                                    {/* Streams */}
                                  </InputLabel>
                                  <Autocomplete
                                    id={streamId}
                                    options={streamsData}
                                    getOptionLabel={option => option.name}
                                    onChange={(event, value) => {
                                      handleChangeForDynamicGrid(
                                        streams,
                                        event,
                                        value,
                                        val,
                                        true,
                                        false
                                      );
                                    }}
                                    data-id={idx}
                                    name={streamId}
                                    value={
                                      streamsDataBackup[
                                        streamsDataBackup.findIndex(function (
                                          item,
                                          i
                                        ) {
                                          return (
                                            item.id ===
                                            formState.dynamicBar[idx][streams]
                                          );
                                        })
                                      ] || null
                                    }
                                    renderInput={params => (
                                      <TextField
                                        {...params}
                                        value={option => option.id}
                                        name={streamId}
                                        error={
                                          checkErrorInDynamicBar(streams, val)[
                                            "error"
                                          ]
                                        }
                                        helperText={
                                          checkErrorInDynamicBar(streams, val)[
                                            "error"
                                          ]
                                            ? checkErrorInDynamicBar(
                                                streams,
                                                val
                                              )["value"]
                                            : null
                                        }
                                        placeholder={get(
                                          CollegeFormSchema[streams],
                                          "placeholder"
                                        )}
                                        key={option => option.id}
                                        label={get(
                                          CollegeFormSchema[streams],
                                          "label"
                                        )}
                                        variant="outlined"
                                      />
                                    )}
                                  />
                                </FormControl>
                              </Grid>
                              {/** Need to map streams with strength */}
                              <Grid item xs>
                                <TextField
                                  label="1st Year Strength"
                                  name={firstYearStrengthId}
                                  variant="outlined"
                                  fullWidth
                                  data-id={idx}
                                  id={firstYearStrengthId}
                                  value={
                                    formState.dynamicBar[idx][
                                      firstYearStrength
                                    ] || ""
                                  }
                                  error={
                                    checkErrorInDynamicBar(
                                      firstYearStrength,
                                      val
                                    )["error"]
                                  }
                                  helperText={
                                    checkErrorInDynamicBar(
                                      firstYearStrength,
                                      val
                                    )["error"]
                                      ? checkErrorInDynamicBar(
                                          firstYearStrength,
                                          val
                                        )["value"]
                                      : null
                                  }
                                  placeholder={get(
                                    CollegeFormSchema[firstYearStrength],
                                    "placeholder"
                                  )}
                                  onChange={event => {
                                    handleChangeForDynamicGrid(
                                      firstYearStrength,
                                      event,
                                      null,
                                      val,
                                      false,
                                      true
                                    );
                                  }}
                                />
                              </Grid>
                              <Grid item xs>
                                <TextField
                                  label="2nd Year Strength"
                                  name={secondYearStrengthId}
                                  variant="outlined"
                                  fullWidth
                                  data-id={idx}
                                  id={secondYearStrengthId}
                                  value={
                                    formState.dynamicBar[idx][
                                      secondYearStrength
                                    ] || ""
                                  }
                                  error={
                                    checkErrorInDynamicBar(
                                      secondYearStrength,
                                      val
                                    )["error"]
                                  }
                                  helperText={
                                    checkErrorInDynamicBar(
                                      secondYearStrength,
                                      val
                                    )["error"]
                                      ? checkErrorInDynamicBar(
                                          secondYearStrength,
                                          val
                                        )["value"]
                                      : null
                                  }
                                  placeholder={get(
                                    CollegeFormSchema[secondYearStrength],
                                    "placeholder"
                                  )}
                                  onChange={event => {
                                    handleChangeForDynamicGrid(
                                      secondYearStrength,
                                      event,
                                      null,
                                      val,
                                      false,
                                      true
                                    );
                                  }}
                                />
                              </Grid>
                              <Grid item xs>
                                <TextField
                                  label="3rd Year Strength"
                                  name={thirdYearStrengthId}
                                  variant="outlined"
                                  fullWidth
                                  data-id={idx}
                                  id={thirdYearStrengthId}
                                  value={
                                    formState.dynamicBar[idx][
                                      thirdYearStrength
                                    ] || ""
                                  }
                                  error={
                                    checkErrorInDynamicBar(
                                      thirdYearStrength,
                                      val
                                    )["error"]
                                  }
                                  helperText={
                                    checkErrorInDynamicBar(
                                      thirdYearStrength,
                                      val
                                    )["error"]
                                      ? checkErrorInDynamicBar(
                                          thirdYearStrength,
                                          val
                                        )["value"]
                                      : null
                                  }
                                  placeholder={get(
                                    CollegeFormSchema[thirdYearStrength],
                                    "placeholder"
                                  )}
                                  onChange={event => {
                                    handleChangeForDynamicGrid(
                                      thirdYearStrength,
                                      event,
                                      null,
                                      val,
                                      false,
                                      true
                                    );
                                  }}
                                />
                              </Grid>
                              <Grid item xs={1}>
                                {idx > 0 ? (
                                  <DeleteForeverOutlinedIcon
                                    onClick={e => clickOnDelete(val, idx)}
                                    style={{ color: "red", fontSize: "24px" }}
                                  />
                                ) : (
                                  ""
                                )}
                              </Grid>
                            </Grid>
                          </CardContent>
                        </Card>
                      );
                    })}
                    <div className={classes.btnspaceadd}>
                      <Grid item xs={12} md={3} lg={2} xl={2}>
                        <YellowButton
                          disabled={streamsData.length ? false : true}
                          color="primary"
                          variant="contained"
                          className={classes.add_more_btn}
                          onClick={addNewRow}
                        >
                          {genericConstants.ADD_MORE_TEXT}
                        </YellowButton>
                      </Grid>
                    </div>
                  </Card>
                </Grid>
              </Grid>
            </Grid>
          </CardContent>
          <Grid item xs={12} className={classes.CardActionGrid}>
            <CardActions className={classes.btnspace}>
              <Grid item xs={12}>
                <Grid item xs={12} md={6} xl={3}>
                  <Grid container spacing={3}>
                    <Grid item md={2} xs={12}>
                      <YellowButton
                        id="submit"
                        type="submit"
                        color="primary"
                        variant="contained"
                        onClick={handleSubmit}
                        className={classes.submitbtn}
                      >
                        {genericConstants.SAVE_BUTTON_TEXT}
                      </YellowButton>
                    </Grid>
                    <Grid item md={2} xs={12}>
                      <GrayButton
                        color="primary"
                        variant="contained"
                        onClick={clickedCancelButton}
                        className={classes.resetbtn}
                      >
                        {genericConstants.CANCEL_BUTTON_TEXT}
                      </GrayButton>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
            </CardActions>
          </Grid>
          {/* </form> */}
        </Card>
      </Grid>
      <Backdrop className={classes.backDrop} open={formState.backDrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </Grid>
  );
}
Example #29
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>
  );
}