@material-ui/core#CardActions JavaScript Examples

The following examples show how to use @material-ui/core#CardActions. 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: index.js    From dineforward with MIT License 6 votes vote down vote up
BlockItem = ({ classes = {}, Icon, title, subtext, btnText, btnUrl }) => {
  const local = useStyles();
  const cn = key => classNames(classes[key], local[key]);

  return (
    <Card className={cn('root')} elevation={0}>
      <CardContent>
        <div className={cn('icon')}>
          <Icon className={cn('iconItem')} />
        </div>
        <Typography variant="h3" className={cn('title')} gutterBottom>
          {title}
        </Typography>
        <Typography variant="body1" className={cn('subtitle')}>
          {subtext}
        </Typography>
      </CardContent>
      <CardActions className={cn('actions')}>
        {btnUrl || btnText ? (
          <Link href={btnUrl}>
            <a className={cn('link')}>
              <Button variant="contained" size="large" color="secondary" className={cn('ctaButton')}>
                {btnText}
              </Button>
            </a>
          </Link>
        ) : null}
      </CardActions>
    </Card>
  );
}
Example #2
Source File: SchematicsList.js    From eSim-Cloud with GNU General Public License v3.0 6 votes vote down vote up
// Card displaying user my schematics page header.
function MainCard () {
  const classes = useStyles()

  return (
    <Card className={classes.mainHead}>
      <CardContent>
        <Typography className={classes.title} gutterBottom>
          All schematics are Listed Below
        </Typography>
        <Typography variant="h5" component="h2">
          My Schematics
        </Typography>
      </CardContent>
      <CardActions>
        <Button
          target="_blank"
          component={RouterLink}
          to="/editor"
          size="small"
          color="primary"
        >
          Create New
        </Button>
        <Button size="small" color="secondary">
          Load More
        </Button>
      </CardActions>
    </Card>
  )
}
Example #3
Source File: Sliders.jsx    From scholar-front-end with MIT License 6 votes vote down vote up
function CourseCard({data}){
  var image = require("./CourseLogo.jpg").default;

  const classes = useStyles();
  return (
<Card className={classes.root}>
  <CardActionArea>
  <CardMedia alt="course" component="img" height="140" title={data} image={image}/>
  <CardContent>
    <Typography gutterBottom variant="h5" component="h2">
      Course Title
    </Typography>
    <Typography variant="body2" color="textSecondary" component="p">
      Course Number {data}
    </Typography>
  </CardContent>
  </CardActionArea>
  <CardActions>
    <Button size="small" color="primary">Open</Button>
  </CardActions>
</Card>
  )

}
Example #4
Source File: Post.js    From clone-instagram-ui with MIT License 6 votes vote down vote up
Post = ({ post, onCommentChange, onLike }) => {
  const firstCharacter = post.userName[0].toUpperCase();
  return (
    <Card className="ins-post">
      <Link
        to={`/profile/${post.userName}`}
        className="profile-navigation-link"
      >
        <CardHeader
          avatar={
            <Avatar style={{ background: getBackgroundColor(firstCharacter) }}>
              {firstCharacter || '-'}
            </Avatar>
          }
          title={post.userName}
        />
      </Link>
      <img
        className="ins-post-media"
        src={post.media}
        title={post.content}
        alt={post.title}
      />
      <CardActions disableSpacing>
        <IconButton aria-label="add to favorites" onClick={onLike}>
          <FavoriteBorderOutlined />
        </IconButton>
      </CardActions>
      <CardContent className="comments-section">
        <b>{`${post.likes || 0} Likes`}</b>
        {post.comment.map((c) => (
          <Comment {...c} />
        ))}
      </CardContent>
      <AddComment onCommentChange={onCommentChange} />
    </Card>
  );
}
Example #5
Source File: GitCoin.js    From spells-fyi with MIT License 6 votes vote down vote up
GitCoin = () => {
    const classes = useStyles();
    return (
        <Grid container justify="center" className={classes.subtitle}>
            <Grid item xs={12} sm={9} md={6}>
                <Card variant="outlined">
                    <CardContent>
                        <Typography variant="h4" color="textSecondary" paragraph>GitCoin Grants CLR Round 6</Typography>
                        <Typography variant="h6" paragraph>Spells.fyi is a community good that gets better with your support.</Typography>
                    </CardContent>
                    <CardActions>
                        <Button variant="contained" color="primary" href="https://gitcoin.co/grants/601/spellsfyi-see-the-future" target="_blank">Contribute to Spells.fyi</Button>
                    </CardActions>
                </Card>
            </Grid>
        </Grid>
    )
}
Example #6
Source File: About.js    From Dog-Book with MIT License 6 votes vote down vote up
About = () => {
  const classes = useStyle();
  return (
    <Container>
      <Typography variant="h4" className={classes.contributers} component="h2">
        Contributers
      </Typography>
      {data.contributers.map((contributer) => (
        <Card className={classes.root} elevation={4}>
          <CardContent className={classes.content}>
            <Avatar alt="avatar" src={contributer.avatar_url}></Avatar>
            <Typography variant="h5" className={classes.name}>
              {contributer.name}
            </Typography>
          </CardContent>
          <CardActions className={classes.actions}>
            <IconButton href={contributer.username}>
              <GitHub className={classes.avatar} />
            </IconButton>
          </CardActions>
        </Card>
      ))}
    </Container>
  );
}
Example #7
Source File: ChallengeCard.js    From dscbppimt-official-website with MIT License 6 votes vote down vote up
ChallengeCard = (props) => {
    const classes = useStyles();

    return (
        <Card className={classes.root}>
        <CardActionArea>
          <CardMedia
            className={classes.media}
            image="/static/images/cards/contemplative-reptile.jpg"
            title="Contemplative Reptile"
          />
          <CardContent>
            <Typography gutterBottom variant="h5" component="h2">
              Lizard
            </Typography>
            <Typography variant="body2" color="textSecondary" component="p">
              Lizards are a widespread group of squamate reptiles, with over 6,000 species, ranging
              across all continents except Antarctica
            </Typography>
          </CardContent>
        </CardActionArea>
        <CardActions>
          <Button size="small" color="primary">
            Share
          </Button>
          <Button size="small" color="primary">
            Learn More
          </Button>
        </CardActions>
      </Card>
    )
}
Example #8
Source File: team-member-dialog-display.js    From turinghut-website with BSD Zero Clause License 6 votes vote down vote up
DialogDisplay = ({ person: { name, designation, phoneNumber, emailId, githubProfile, linkedinProfile } }) => {
    const classes = teamMemberStyles();
    const [open, setOpen] = useState(false);
    return (
        <div className={`${classes.tilebar} ${classes.tilebarRootTitle} ${classes.tilebarBottom}`}>
            <div className={`${classes.titlePosRight} ${classes.titleWrap}`}>
                <div className={classes.title}>{name}</div>
                <div><span>{designation}</span></div>
            </div>
            <CardActions onClick={() => setOpen(true)} className={classes.actionItem}><Info /></CardActions>
            <Dialog
                aria-labelledby="simple-dialog-title"
                aria-describedby="simple-dialog-description"
                open={open}
                onClose={() => { setOpen(false) }}
            >
                <DialogContent style={{minWidth:'38vh',minHeight:'25vh'}}>
                    {name ? <DialogContentText className={classes.dialogHeading}>{name}</DialogContentText> : null}
                    {phoneNumber ? <DialogContentText className={classes.dialogContent}><LocalPhone className={classes.icon}/> {phoneNumber}</DialogContentText> : null}
                    {emailId ? <DialogContentText className={classes.dialogContent}><Mail className={classes.icon}/> {emailId}</DialogContentText> : null}
                    {githubProfile ? <a href={githubProfile} alt={"githubProfile"} ><GitHub className={classes.githubIcon} /></a> : null}
                    {linkedinProfile ? <a href={linkedinProfile} alt={"linkedinProfile"}><LinkedIn className={classes.linkedinIcon} /></a> : null}
                </DialogContent>
            </Dialog>
        </div>
    )
}
Example #9
Source File: local-storage.js    From js-miniapp with MIT License 5 votes vote down vote up
function LocalStorage() {
  const classes = useStyles();
  const [inputValue, setInputValue] = useState('');
  const [storedValue, setStoredValue] = useLocalStorage('input-value', '');

  const handleInput = (e: SyntheticInputEvent<HTMLInputElement>) => {
    e.preventDefault();
    setInputValue(e.currentTarget.value);
  };

  const handleLoad = () => {
    setInputValue(storedValue);
  };

  const handleSave = () => {
    setStoredValue(inputValue);
  };

  return (
    <GreyCard>
      <CardContent className={classes.content}>
        <TextField
          type="text"
          className={classes.textfield}
          value={inputValue}
          onChange={handleInput}
          variant="outlined"
          color="primary"
          inputProps={{
            'data-testid': 'input-field',
          }}
        />
      </CardContent>
      <CardActions className={classes.actions}>
        <Button
          color="primary"
          className={classes.button}
          onClick={handleLoad}
          variant="contained"
        >
          Load text from Local Storage
        </Button>
        <Button
          color="primary"
          className={classes.button}
          onClick={handleSave}
          variant="contained"
        >
          Save text to Local Storage
        </Button>
      </CardActions>
    </GreyCard>
  );
}
Example #10
Source File: CardUrls.js    From FireShort with MIT License 5 votes vote down vote up
export default function CardUrls(props) {
    const history = useHistory();
    const classes = useStyles();

    return (
        <Container className={classes.cardGrid} maxWidth="lg">
            <Grid container spacing={4}>
                {props.shortUrls.map((card) => (
                    <Grid item key={card.id} xs={12} sm={6} md={4}>
                        <Card className={classes.card}>
                            <CardHeader
                                action={
                                    <Tooltip title={"Copy to clipboard"}>
                                        <IconButton color="primary" className={classes.copyButton} onClick={() => { navigator.clipboard.writeText(window.location.origin + "/" + card.data.curl) }}>
                                            <FileCopyOutlinedIcon />
                                        </IconButton>
                                    </Tooltip>
                                }
                                title={
                                    <Tooltip title={card.data.track === true ? "Link Tracking ON" : "Link Tracking OFF"}>
                                        <Badge color={card.data.track === true ? "primary" : "error"} variant="dot">
                                            <Typography>{card.data.curl}</Typography>
                                        </Badge>
                                    </Tooltip>
                                }
                                titleTypographyProps={{
                                    variant: "subtitle1"
                                }}
                            >

                            </CardHeader>
                            <CardContent className={classes.cardContent}>
                                <Box bgcolor="text.primary" color="background.paper" p={2} style={{ overflowX: 'auto', overflowY: 'hidden', whiteSpace: "nowrap" }}>
                                    {card.data.lurl}
                                </Box>
                            </CardContent>
                            <CardActions className={classes.cardActions}>
                                <Tooltip title={"Preview link"}>
                                    <IconButton size="small" color="primary" href={card.data.lurl} target="_blank">
                                        <VisibilityIcon />
                                    </IconButton>
                                </Tooltip>
                                <Tooltip title={"Edit link"}>
                                    <IconButton size="small" onClick={() => props.handleEditShortUrl(card.data.curl)}>
                                        <EditIcon />
                                    </IconButton>
                                </Tooltip>
                                <Tooltip title={"Analytics"}>
                                    <IconButton size="small" disabled={!card.data.track} onClick={() => history.push(`/analytics/${card.data.curl}`)}>
                                        <AnalyticsIcon />
                                    </IconButton>
                                </Tooltip>
                                <Tooltip title={"Delete link"}>
                                    <IconButton size="small" color="secondary" onClick={() => props.handleDeleteShortUrl(card.data.curl)}>
                                        <DeleteForeverIcon />
                                    </IconButton>
                                </Tooltip>
                                <Tooltip title={card.data.hits + " Hits"}>
                                    <IconButton onClick={() => { props.openHits(card.data.curl) }} style={{ cursor: "pointer" }}>
                                        <Badge badgeContent={card.data.hits} color="secondary" max={Infinity} showZero>
                                            <OpenInBrowser />
                                        </Badge>
                                    </IconButton>
                                </Tooltip>
                                <Tooltip title={"Password protect"}>
                                    <IconButton size='small' color='default' onClick={() => props.toggleSecurity(card.data.curl)}>
                                        {card.data.locked ? <LockIcon /> : <LockOpenIcon />}
                                    </IconButton>
                                </Tooltip>
                            </CardActions>
                        </Card>
                    </Grid>
                ))}
            </Grid>
        </Container>
    );
}
Example #11
Source File: media.js    From js-miniapp with MIT License 5 votes vote down vote up
Media = () => {
  const [showAutoplayVideo, setShowAutoplayVideo] = useState(false);
  const classes = useStyles();

  return (
    <GreyCard className={classes.card}>
      <CardContent className={classes.content}>
        Autoplay Fullscreen Video
      </CardContent>
      <CardContent className={classes.content}>
        <ReactPlayerLoader
          accountId="1752604059001"
          videoId="5819230967001"
          onSuccess={onSuccess}
        ></ReactPlayerLoader>
      </CardContent>

      <CardContent className={classes.content}>Normal Video</CardContent>
      <CardActions className={classes.actions}>
        <Button
          variant="contained"
          color="primary"
          onClick={() => setShowAutoplayVideo(!showAutoplayVideo)}
        >
          {showAutoplayVideo ? 'Hide' : 'Show'} Video
        </Button>
      </CardActions>

      {showAutoplayVideo && (
        <CardContent className={classes.content}>
          <ReactPlayerLoader
            accountId="1752604059001"
            videoId="5819230967001"
            onSuccess={(success) => {
              onSuccess(success);
              success.ref.requestFullscreen();
            }}
            options={{ autoplay: true }}
          ></ReactPlayerLoader>
        </CardContent>
      )}
    </GreyCard>
  );
}
Example #12
Source File: CardUrls.js    From fireshort with MIT License 5 votes vote down vote up
export default function CardUrls(props) {
    const classes = useStyles();

    return (
        <Container className={classes.cardGrid} maxWidth="md">
            <Grid container spacing={4}>
                {props.shortUrls.map((card) => (
                    <Grid item key={card.id} xs={12} sm={6} md={4}>
                        <Card className={classes.card}>
                            <CardHeader 
                                action={
                                    <IconButton color="primary" className={classes.copyButton} onClick={() => { navigator.clipboard.writeText(window.location.hostname + "/" + card.data.curl) }}>
                                        <FileCopyOutlinedIcon />
                                    </IconButton>
                                }
                                title={ card.data.curl }
                                titleTypographyProps={{
                                    variant: "subtitle1"
                                }}
                            />
                            <CardContent className={classes.cardContent}>
                                <Box bgcolor="text.primary" color="background.paper" p={2} style={{ overflowX: 'auto', overflowY: 'hidden', whiteSpace: "nowrap" }}>
                                    {card.data.lurl}
                                </Box>
                            </CardContent>
                            <CardActions>
                                <Button size="small" color="primary" href={card.data.lurl} target="_blank">
                                    Open
                                </Button>
                                <Button size="small" onClick={() => props.handleEditShortUrl(card.data.curl)}>
                                    Edit
                                </Button>
                                <Button size="small" color="secondary" onClick={() => props.handleDeleteShortUrl(card.data.curl)}>
                                    Delete
                                </Button>
                            </CardActions>
                        </Card>
                    </Grid>
                ))}
            </Grid>
        </Container>
    );
}
Example #13
Source File: EventCard.js    From AdaptivApps-fe with MIT License 5 votes vote down vote up
export default function EventCard({ event }) {
  const classes = useStyles();
  const [updateEvent] = useMutation(REGISTER_EVENT);

  const { user } = useAuth0();
  const navigate = useNavigate();

  const registerEvent = async () => {
    await updateEvent({
      variables: { id: event.id, email: user.email },
    });
    await navigate(`/calendar/${event.id}`);
  };

  return (
    <Card className={classes.root}>
      <CardActionArea className={classes.card}>
        <Box>
          <div className={classes.banner}>{event.type}</div>
          <CardMedia
            className={classes.cardImg}
            component="img"
            alt="Event"
            width="15rem"
            image={event?.imgUrl}
            title="Angel City Event"
          />
        </Box>
        <CardContent className={classes.content}>
          <Typography
            className={classes.cardDate}
            variant="body2"
            color="textSecondary"
            component="p"
          >
            {event.startDate} - {event.endDate}
          </Typography>
          <Typography
            className={classes.cardTitle}
            gutterBottom
            variant="h5"
            component="h2"
          >
            {event.title}
          </Typography>
          <Typography
            className={classes.cardLoc}
            variant="body2"
            color="textSecondary"
            component="p"
          >
            {event.location}
          </Typography>
        </CardContent>
      </CardActionArea>
      <CardActions className={classes.btnContainer}>
        <SimpleModal event={event} registerEvent={registerEvent} />
      </CardActions>
    </Card>
  );
}
Example #14
Source File: Rules.js    From gitlab-lint-react with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
Rules = () => {
  const classes = useStyles();
  const [rows, setData] = useState({});
  const fetchData = () => {
    GitlabLintHttpClient("GET_ALL", { entity: "rules" })
      .then((data) => {
        setData(data.data);
      })
      .catch((err) => console.error(err));
  };

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

  if (Object.keys(rows).length === 0 && rows.constructor === Object) {
    return <Loading />;
  }

  return (
    <React.Fragment>
      <Typography variant="h4" paragraph>
        Rules
      </Typography>

      <Grid container spacing={4}>
        {rows.map((row) => {
          return (
            <Grid item key={row.ruleId} xs={12} sm={6} md={4}>
              <Card className={classes.root}>
                <CardActionArea component={Link} to={`rules/${row.ruleId}`}>
                  <CardHeader
                    className={classes[row.level]}
                    classes={{ title: classes["title"] }}
                    title={row.level}
                  />
                  <CardContent>
                    <Typography gutterBottom variant="h5" component="h2">
                      {row.name}
                    </Typography>
                    {row.description && (
                      <Typography
                        variant="body2"
                        color="textSecondary"
                        component="p"
                      >
                        {row.description}
                      </Typography>
                    )}
                  </CardContent>
                </CardActionArea>
                <CardActions>
                  <Button
                    component={Link}
                    size="small"
                    color="secondary"
                    to={`/rules/${row.ruleId}`}
                  >
                    Show projects
                  </Button>
                </CardActions>
              </Card>
            </Grid>
          );
        })}
      </Grid>
    </React.Fragment>
  );
}
Example #15
Source File: RepoPicker.js    From git-insights with MIT License 5 votes vote down vote up
export default function RepoPickerList(props) {
  const classes = useStyles();
  const { repos, fetchRepos, pickPrimaryRepo, isLoading } = props;

  const selectPrimaryRepo = (repoId) => {
    // TODO: err if no repo found
    const repo = repos.data.find((repo) => repo.id === repoId);
    pickPrimaryRepo({
      owner: repo.owner.login,
      repo: repo.name
    });
  }

  const getNextPage = () => {
    fetchRepos(repos.nextPage);
  }

  const getPreviousPage = () => {
    fetchRepos(repos.prevPage);
  }

  return (
    !isLoading ?
      <Grid container spacing={1} direction="column" alignItems="center">
        <Grid item container spacing={4}>
          {repos.data.map(repo => {
            return (
              <Grid item xs={12} sm={6} md={4} lg={3} key={repo.id}>
                <Card className={classes.cardRoot}>
                  <CardContent className={classes.cardContent}>
                    <Typography gutterBottom variant="h5" component="h2">
                      {repo.full_name}
                    </Typography>
                    <Typography variant="body2" color="textSecondary"
                      component="p" className={classes.textBlock}>
                        {repo.description}
                    </Typography>
                  </CardContent>
                  <Divider variant="middle" />
                  <CardActions>
                    <Button size="small" color="primary" variant="outlined"
                      startIcon={<LaunchIcon />} href={repo.html_url} target="_blank">
                      Visit
                    </Button>
                    <Button size="small" color="primary" variant="outlined"
                      onClick={() => selectPrimaryRepo(repo.id)}
                    >
                      Connect
                    </Button>
                  </CardActions>
                </Card>
              </Grid>
            );
          })}
        </Grid>
        <Grid item className={classes.buttonGrid}>
          <ButtonGroup>
            {repos.prevPage ? (
              <Button onClick={getPreviousPage}>Previous</Button>
            ) : (
              <Button disabled>Previous</Button>
            )}
            {repos.nextPage ? (
              <Button onClick={getNextPage}>Next</Button>
            ) : (
              <Button disabled>Next</Button>
            )}
          </ButtonGroup>
        </Grid>
      </Grid>
    :
      <Grid container className={classes.loadingContainer}>
        <CircularProgress />
        <br />
        <Typography>Loading...</Typography>
      </Grid>
  );
}
Example #16
Source File: share.js    From js-miniapp with MIT License 5 votes vote down vote up
function Share() {
  const classes = useStyles();
  const defaultInputValue = 'This is JS-SDK-Sample.';
  let inputValue = defaultInputValue;

  const handleInput = (e: SyntheticInputEvent<HTMLInputElement>) => {
    e.preventDefault();
    inputValue = e.currentTarget.value;
  };

  const shareContent = () => {
    const info = { content: inputValue }; //see js-miniapp-bridge/types/share-info
    MiniApp.shareInfo(info)
      .then((success) => {
        console.log(success);
      })
      .catch((error) => {
        console.error(error);
      });
  };

  return (
    <GreyCard>
      <CardContent className={classes.content}>
        <TextField
          type="text"
          className={classes.textfield}
          onChange={handleInput}
          placeholder="Content"
          defaultValue={defaultInputValue}
          variant="outlined"
          color="primary"
          multiline="true"
          rowsMax="5"
          inputProps={{
            'data-testid': 'input-field',
          }}
        />
      </CardContent>
      <CardActions className={classes.actions}>
        <Button
          color="primary"
          className={classes.button}
          onClick={shareContent}
          variant="contained"
        >
          Share
        </Button>
      </CardActions>
    </GreyCard>
  );
}
Example #17
Source File: Gallery.js    From eSim-Cloud with GNU General Public License v3.0 5 votes vote down vote up
// Card displaying overview of gallery sample schematics.
function SchematicCard ({ sch }) {
  const classes = useStyles()
  const auth = useSelector(state => state.authReducer)
  const dispatch = useDispatch()
  const [snacOpen, setSnacOpen] = React.useState(false)

  const handleSnacClick = () => {
    setSnacOpen(true)
  }
  const handleSnacClose = (event, reason) => {
    if (reason === 'clickaway') {
      return
    }
    setSnacOpen(false)
  }
  useEffect(() => {
    dispatch(fetchRole())
  }, [dispatch])

  return (
    <>
      <Card>
        <ButtonBase
          target="_blank"
          component={RouterLink}
          to={'/editor?id=' + sch.save_id}
          style={{ width: '100%' }}
        >
          <CardActionArea>
            <CardMedia
              className={classes.media}
              image={sch.media}
              title={sch.name}
            />
            <CardContent>
              <Typography gutterBottom variant="h5" component="h2">
                {sch.name}
              </Typography>
              <Typography variant="body2" component="p">
                {sch.description}
              </Typography>
            </CardContent>
          </CardActionArea>
        </ButtonBase>

        <CardActions>
          <Button
            target="_blank"
            component={RouterLink}
            to={'/editor?id=' + sch.save_id}
            size="small"
            color="primary"
          >
            Launch in Editor
          </Button>
          {console.log(auth.roles)}
          {auth.roles && auth.roles.is_type_staff &&
            <Button onClick={() => { handleSnacClick() }}>
              <Tooltip title="Delete" placement="bottom" arrow>
                <DeleteIcon
                  color="secondary"
                  fontSize="small"
                />
              </Tooltip>
            </Button>}
          <SimpleSnackbar open={snacOpen} close={handleSnacClose} sch={sch} confirmation={deleteGallerySch} />
        </CardActions>
      </Card>
    </>
  )
}
Example #18
Source File: web-location.js    From js-miniapp with MIT License 5 votes vote down vote up
Location = (props: any) => {
  const classes = useStyles();
  const [state, watch, unwatch] = useGeoLocation();

  return (
    <GreyCard>
      <CardContent className={classes.content}>
        {state.error && <div>Error: {state.error}</div>}

        {state.isLoading && (
          <CircularProgress size={20} className={classes.buttonProgress} />
        )}

        {state.location && state.isWatching && (
          <div
            className={classes.locationContainer}
            data-testid="location-container"
          >
            <div>
              <span className="label">Longitude:</span>
              {state.location.longitude}
            </div>
            <div>
              <span className="label">Latitude:</span>
              {state.location.latitude}
            </div>
          </div>
        )}
      </CardContent>
      <CardActions className={classes.actions}>
        <Button
          data-testid="turn-on"
          startIcon={<LocationSearchingIcon />}
          variant="contained"
          color="primary"
          disabled={state.isWatching}
          className={clsx(classes.button, {
            [classes.disabled]: state.isWatching,
          })}
          onClick={watch}
        >
          TURN ON
        </Button>
        <Button
          data-testid="turn-off"
          startIcon={<LocationOffIcon />}
          variant="contained"
          color="primary"
          onClick={unwatch}
          disabled={!state.isWatching}
          className={clsx(classes.button, {
            [classes.disabled]: !state.isWatching,
          })}
        >
          TURN OFF
        </Button>
      </CardActions>
    </GreyCard>
  );
}
Example #19
Source File: MissionDeliveredCard.jsx    From resilience-app with GNU General Public License v3.0 5 votes vote down vote up
MissionDeliveredCard = ({ completeMission, missionUid, onClose }) => {
  const classes = useStyles();
  const [deliveryConfirmationImage, setDeliveryConfirmationImage] = useState(selectImage);
  const [deliveryConfirmationImageWasSelected, setDeliveryConfirmationImageWasSelected] = useState(
    false
  );

  function onImageChanged(image) {
    setDeliveryConfirmationImageWasSelected(true);
    setDeliveryConfirmationImage(image);
  }

  return (
    <Card>
      <Grid className={classes.content} direction="column" container>
        <Grid align="right" item>
          <CloseIcon align="right" className={classes.closeIcon} onClick={onClose} />
        </Grid>
        <Grid align="left" item>
          <CardHeader
            title="Take a photo of your delivery"
            titleTypographyProps={{
              variant: "h1",
              component: "span",
              className: classes.cardTitle,
            }}
            className={classes.cardHeader}
            align="center"
          />
          <MissionDeliveredImagePicker
            defaultImage={deliveryConfirmationImage}
            setCurrentImage={onImageChanged}
          />
          <CardContent>
            <H5 align="left" color="textPrimary" className={classes.infoText}>
              Make sure the photo is clear so the recipient can locate it easily!
            </H5>
          </CardContent>
          <CardActions className={classes.submitContainer}>
            <StyledButton
              color="primary"
              variant="contained"
              disableElevation
              disabled={!deliveryConfirmationImageWasSelected}
              onClick={() => completeMission(missionUid, deliveryConfirmationImage)}
            >
              Submit & Complete Mission
            </StyledButton>
          </CardActions>
        </Grid>
      </Grid>
    </Card>
  );
}
Example #20
Source File: Projects.js    From Design-Initiative-Dashboard-frontend with GNU General Public License v3.0 5 votes vote down vote up
Projects = () => {
  const classes = useStyles();
  return (
    <div>
      {projectsMentoring.map((data) => (
        <Card className={classes.root}>
          <div className={classes.details}>
            <CardMedia
              className={classes.im}
              component="img"
              alt="org-logo"
              height="140"
              src={data.image}
              title="Organisation card"
            />
            <CardContent className={classes.content}>
              <Typography
                variant="h5"
                component="h2"
                align="left"
                className={classes.pos1}
              >
                {data.title}
                {data.features.map((f) => (
                  <Button
                    variant="contained"
                    color="primary"
                    size="small"
                    className={classes.cap}
                  >
                    {f.name}
                  </Button>
                ))}
              </Typography>
              <Typography
                variant="body2"
                color="textSecondary"
                component="p"
                align="left"
                className={classes.pos2}
              >
                {data.desc}
              </Typography>
            </CardContent>
          </div>
          <div>
            <CardActions>
              <Button size="small" color="primary" className={classes.btn}>
                View More
              </Button>
            </CardActions>
          </div>
        </Card>
      ))}
    </div>
  );
}
Example #21
Source File: MentorCard.js    From mentors-website with MIT License 5 votes vote down vote up
MentorCard = (props) => {
  const classes = useStyles();
  const {
    mentor,
    choseCountry,
    choseSkill,
    heartedMentor,
    toggleHeartedMentor,
  } = props;

  const handleFlagClick = () => {
    choseCountry(mentor.countryAlpha2Code)
  }

  const handleSkillChipClick = (e) => {
    choseSkill(e.target.textContent)
  }
  return (
    <Card className={classes.root}>
      <CardHeader
        avatar={
          <Avatar
            src={`https://unavatar.now.sh/twitter/${mentor.twitter}`}
            aria-label="mentor"
            className={classes.avatar}
          >
            {mentor.name[0]}
          </Avatar>
        }
        action={
          <IconButton onClick={handleFlagClick}>
            <img
              src={`https://www.countryflags.io/${mentor.countryAlpha2Code}/flat/32.png`}
              alt={mentor.country}
            />
          </IconButton>
        }
        title={mentor.name}
        subheader={mentor.title}
      />
      <CardContent className={classes.MessageCardContent}>
        <Typography variant="body2">"{mentor.message}"</Typography>
      </CardContent>
      <CardContent className={classes.SkillsCardContent}>
        <Grid container justify="center" spacing={1}>
          {mentor.skills.map((skill, index) => (
            <Grid key={index} item>
              <Chip label={skill} variant="outlined" onClick={handleSkillChipClick} />
            </Grid>
          ))}
        </Grid>
      </CardContent>
      <Divider variant="fullWidth" />
      <CardActions className={classes.cardAction} disableSpacing>
        <Button href="#connect-mentor" color="primary">
          Connect
        </Button>
        <IconButton onClick={() => toggleHeartedMentor(mentor.id)}>
          {heartedMentor ? (
            <FavoriteOutlinedIcon color="secondary" />
          ) : (
            <FavoriteBorderOutlinedIcon />
          )}
        </IconButton>
      </CardActions>
    </Card>
  );
}
Example #22
Source File: Password.js    From telar-cli with MIT License 5 votes vote down vote up
Password = props => {
  const { className, ...rest } = props;

  const classes = useStyles();

  const [values, setValues] = useState({
    password: '',
    confirm: ''
  });

  const handleChange = event => {
    setValues({
      ...values,
      [event.target.name]: event.target.value
    });
  };

  return (
    <Card
      {...rest}
      className={clsx(classes.root, className)}
    >
      <form>
        <CardHeader
          subheader="Update password"
          title="Password"
        />
        <Divider />
        <CardContent>
          <TextField
            fullWidth
            label="Password"
            name="password"
            onChange={handleChange}
            type="password"
            value={values.password}
            variant="outlined"
          />
          <TextField
            fullWidth
            label="Confirm password"
            name="confirm"
            onChange={handleChange}
            style={{ marginTop: '1rem' }}
            type="password"
            value={values.confirm}
            variant="outlined"
          />
        </CardContent>
        <Divider />
        <CardActions>
          <Button
            color="primary"
            variant="outlined"
          >
            Update
          </Button>
        </CardActions>
      </form>
    </Card>
  );
}
Example #23
Source File: CommentList.js    From ra-data-django-rest-framework with MIT License 5 votes vote down vote up
CommentGrid = ({ ids, data, basePath }) => {
    const translate = useTranslate();
    const classes = useListStyles();

    return (
        <Grid spacing={2} container>
            {ids.map(id => (
                <Grid item key={id} sm={12} md={6} lg={4}>
                    <Card className={classes.card}>
                        <CardHeader
                            className="comment"
                            title={
                                <TextField
                                    record={data[id]}
                                    source="author.name"
                                />
                            }
                            subheader={
                                <DateField
                                    record={data[id]}
                                    source="created_at"
                                />
                            }
                            avatar={
                                <Avatar>
                                    <PersonIcon />
                                </Avatar>
                            }
                        />
                        <CardContent className={classes.cardContent}>
                            <TextField record={data[id]} source="body" />
                        </CardContent>
                        <CardContent className={classes.cardLink}>
                            {translate('comment.list.about')}&nbsp;
                            <ReferenceField
                                resource="comments"
                                record={data[id]}
                                source="post"
                                reference="posts"
                                basePath={basePath}
                            >
                                <TextField
                                    source="title"
                                    className={classes.cardLinkLink}
                                />
                            </ReferenceField>
                        </CardContent>
                        <CardActions className={classes.cardActions}>
                            <EditButton
                                resource="posts"
                                basePath={basePath}
                                record={data[id]}
                            />
                            <ShowButton
                                resource="posts"
                                basePath={basePath}
                                record={data[id]}
                            />
                        </CardActions>
                    </Card>
                </Grid>
            ))}
        </Grid>
    );
}
Example #24
Source File: Image.js    From Dog-Book with MIT License 5 votes vote down vote up
Image = (props) => {
  const { breedName } = props;
  const [loaded, setLoaded] = useState(false);
  const [imgUrl, setImgUrl] = useState(undefined);
  useEffect(() => {
    if (breedName !== null) {
      trackPromise(
        axios
          .get(`https://dog.ceo/api/breed/${breedName}/images/random`)
          .then((response) => {
            const url = response.data.message.toString();
            setImgUrl(url);
          })
      );
    }
  }, [breedName]);
  const manageRefresh = () => {
    trackPromise(
      axios
        .get(`https://dog.ceo/api/breed/${breedName}/images/random`)
        .then((response) => {
          const url = response.data.message.toString();
          setImgUrl(url);
        })
    );
  };

  return (
    <Card>
      <CardMedia
        title="Dogs Image"
        style={{ display: loaded ? "block" : "none" }}
      >
        <LoadingIndicator />
        <img
          src={imgUrl}
          onLoad={() => setLoaded(true)}
          alt={breedName}
          style={({ height: "300px" }, { width: "100%" })}
        />
      </CardMedia>
      <Skeleton
        height={300}
        variant="rect"
        style={{ display: !loaded ? "block" : "none" }}
      />
      <CardContent>
        <Typography
          gutterBottom
          variant="h5"
          component="h2"
          style={{ textTransform: "capitalize" }}
        >
          {breedName === null ? "No Breed Selected" : breedName}
        </Typography>
      </CardContent>
      <CardActions>
        <Button
          variant="contained"
          color="secondary"
          onClick={manageRefresh}
          startIcon={<NavigateNext />}
        >
          Next Image
        </Button>
      </CardActions>
    </Card>
  );
}
Example #25
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 #26
Source File: LoanEditTask.js    From SESTA-FMS with GNU Affero General Public License v3.0 4 votes vote down vote up
render() {
    const { classes } = this.props;
    let loanTaskStatus = constants.LOAN_TASK_STATUS;
    let statusValue = this.state.values.editStatus;

    return (
      <Layout breadcrumbs={EDIT_LOAN_TASK_BREADCRUMBS}>
        {!this.state.isLoader ? (
          <Card style={{ maxWidth: "45rem" }}>
            <form
              autoComplete="off"
              noValidate
              onSubmit={this.handleSubmit}
              method="post"
            >
              <CardHeader
                title={"Edit Loan task"}
                subheader={"You can edit loan task here!"}
              />
              <Divider />

              <CardContent>
                <Grid container spacing={3}>
                  <Grid item md={6} xs={12}>
                    <Autotext
                      id="combo-box-demo"
                      options={loanTaskStatus}
                      variant="outlined"
                      label="Select Status*"
                      getOptionLabel={(option) => option.name}
                      onChange={(event, value) => {
                        this.handleStatusChange(value);
                      }}
                      value={
                        statusValue
                          ? this.state.loanTaskStatus[
                              this.state.loanTaskStatus.findIndex(function (
                                item,
                                i
                              ) {
                                return item.id === statusValue;
                              })
                            ] || null
                          : null
                      }
                      error={this.hasError("editStatus")}
                      helperText={
                        this.hasError("editStatus")
                          ? this.state.errors.editStatus[0]
                          : null
                      }
                      renderInput={(params) => (
                        <Input
                          fullWidth
                          label="Select Status*"
                          name="editStatus"
                          variant="outlined"
                        />
                      )}
                    />
                  </Grid>

                  <Grid item md={6} xs={12}>
                    <Datepicker
                      label="Date*"
                      name="editDate"
                      error={this.hasError("editDate")}
                      helperText={
                        this.hasError("editDate")
                          ? this.state.errors.editDate[0]
                          : null
                      }
                      value={this.state.values.editDate || ""}
                      format={"dd MMM yyyy"}
                      onChange={(value) =>
                        this.setState({
                          values: { ...this.state.values, editDate: value },
                        })
                      }
                    />
                  </Grid>

                  <Grid item md={9} xs={12}>
                    <Input
                      fullWidth
                      label="Comments"
                      name="comments"
                      value={this.state.values.comments || ""}
                      onChange={this.handleChange}
                      variant="outlined"
                    />
                  </Grid>
                </Grid>
              </CardContent>
              <Divider />

              <CardActions style={{ padding: "15px" }}>
                <Button type="submit">Save</Button>
                <Button color="secondary" clicked={this.cancelForm}>
                  cancel
                </Button>
              </CardActions>
            </form>
          </Card>
        ) : (
          <Spinner />
        )}
      </Layout>
    );
  }
Example #27
Source File: ChangePassword.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
ChangePassword = props => {
  const classes = useStyles();
  const [open, setOpen] = React.useState(true);
  const changePasswordClasses = ChangePasswordStyles();
  const { setLoaderStatus } = useContext(LoaderContext);
  const { setIndex } = useContext(SetIndexContext);
  setIndex(null);
  const [formState, setFormState] = useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    showNewPassword: false,
    showOldPassword: false,
    isSuccessChangingPassword: false,
    isErrorChangingPassword: false
  });

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

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

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

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

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

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

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

      <Grid item xs={12} className={classes.formgrid}>
        <Card className={classes.root} variant="outlined">
          <form autoComplete="off" noValidate onSubmit={handleSubmit}>
            <CardContent>
              <Grid container spacing={2}>
                <Grid item md={12} xs={12}>
                  <FormControl
                    fullWidth
                    className={clsx(
                      changePasswordClasses.margin,
                      classes.elementroot
                    )}
                    variant="outlined"
                  >
                    <InputLabel
                      htmlFor="outlined-adornment-password"
                      fullWidth
                      error={hasError(OLDPASSWORD)}
                    >
                      Old Password
                    </InputLabel>
                    <OutlinedInput
                      id={get(ChangePasswordSchema[OLDPASSWORD], "id")}
                      name={OLDPASSWORD}
                      type={formState.showOldPassword ? "text" : "password"}
                      value={formState.values[OLDPASSWORD] || ""}
                      onChange={handleChange}
                      fullWidth
                      error={hasError(OLDPASSWORD)}
                      endAdornment={
                        <InputAdornment
                          position="end"
                          error={hasError(OLDPASSWORD)}
                        >
                          <IconButton
                            aria-label="toggle password visibility"
                            onClick={handleClickShowOldPassword}
                            onMouseDown={handleMouseDownPassword}
                            edge="end"
                          >
                            {formState.showOldPassword ? (
                              <Visibility />
                            ) : (
                              <VisibilityOff />
                            )}
                          </IconButton>
                        </InputAdornment>
                      }
                      labelWidth={90}
                      InputLabelProps={{
                        classes: {
                          root: changePasswordClasses.cssLabel,
                          focused: changePasswordClasses.cssFocused
                        }
                      }}
                      InputProps={{
                        classes: {
                          root: changePasswordClasses.cssOutlinedInput,
                          focused: changePasswordClasses.cssFocused,
                          notchedOutline: changePasswordClasses.notchedOutline
                        }
                      }}
                    ></OutlinedInput>
                    <FormHelperText error={hasError(OLDPASSWORD)}>
                      {hasError(OLDPASSWORD)
                        ? formState.errors[OLDPASSWORD].map(error => {
                            return error + " ";
                          })
                        : null}
                    </FormHelperText>
                  </FormControl>
                </Grid>
                <Grid item md={12} xs={12}>
                  <FormControl
                    fullWidth
                    className={clsx(
                      changePasswordClasses.margin,
                      classes.elementroot
                    )}
                    variant="outlined"
                  >
                    <InputLabel
                      htmlFor="outlined-adornment-password"
                      fullWidth
                      error={hasError(NEWPASSWORD)}
                    >
                      New Password
                    </InputLabel>
                    <OutlinedInput
                      id={get(ChangePasswordSchema[NEWPASSWORD], "id")}
                      name={NEWPASSWORD}
                      type={formState.showNewPassword ? "text" : "password"}
                      value={formState.values[NEWPASSWORD] || ""}
                      onChange={handleChange}
                      fullWidth
                      error={hasError(NEWPASSWORD)}
                      endAdornment={
                        <InputAdornment
                          position="end"
                          error={hasError(NEWPASSWORD)}
                        >
                          <IconButton
                            aria-label="toggle password visibility"
                            onClick={handleClickShowNewPassword}
                            onMouseDown={handleMouseDownPassword}
                            edge="end"
                          >
                            {formState.showNewPassword ? (
                              <Visibility />
                            ) : (
                              <VisibilityOff />
                            )}
                          </IconButton>
                        </InputAdornment>
                      }
                      labelWidth={90}
                      InputLabelProps={{
                        classes: {
                          root: changePasswordClasses.cssLabel,
                          focused: changePasswordClasses.cssFocused
                        }
                      }}
                      InputProps={{
                        classes: {
                          root: changePasswordClasses.cssOutlinedInput,
                          focused: changePasswordClasses.cssFocused,
                          notchedOutline: changePasswordClasses.notchedOutline
                        }
                      }}
                    ></OutlinedInput>
                    <FormHelperText error={hasError(NEWPASSWORD)}>
                      {hasError(NEWPASSWORD)
                        ? formState.errors[NEWPASSWORD].map(error => {
                            return error + " ";
                          })
                        : null}
                    </FormHelperText>
                  </FormControl>
                </Grid>
              </Grid>
            </CardContent>
            <Grid item xs={12} className={classes.CardActionGrid}>
              <CardActions className={classes.btnspace}>
                <Grid item xs={12}>
                  <Grid item xs={12} md={6} xl={3}>
                    <Grid container spacing={3}>
                      <Grid item md={2} xs={12}>
                        <YellowButton
                          type="submit"
                          color="primary"
                          variant="contained"
                        >
                          {genericConstants.SAVE_BUTTON_TEXT}
                        </YellowButton>
                      </Grid>

                      <Grid item md={2} xs={12}>
                        <GrayButton
                          type="submit"
                          color="primary"
                          variant="contained"
                          to={
                            auth.getUserInfo().role.name ===
                            roleConstants.STUDENT
                              ? routeConstants.VIEW_PROFILE
                              : routeConstants.DASHBOARD_URL
                          }
                        >
                          {genericConstants.CANCEL_BUTTON_TEXT}
                        </GrayButton>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </CardActions>
            </Grid>
          </form>
        </Card>
      </Grid>
    </Grid>
  );
}
Example #28
Source File: VoPage.js    From SESTA-FMS with GNU Affero General Public License v3.0 4 votes vote down vote up
render() {
    let fpoFilters = this.state.getFPO;
    let addFPO = this.state.values.addFPO;
    return (
      <Layout
        breadcrumbs={
          this.state.editPage[0]
            ? EDIT_VILLAGE_ORGANIZATIONS_BREADCRUMBS
            : ADD_VILLAGE_ORGANIZATIONS_BREADCRUMBS
        }
      >
        {!this.state.isLoader ? (
          <Card style={{ maxWidth: "45rem" }}>
            <form
              autoComplete="off"
              noValidate
              onSubmit={this.handleSubmit}
              method="post"
            >
              <CardHeader
                title={
                  this.state.editPage[0]
                    ? "Edit Village Organization"
                    : "Add Village Organization"
                }
                subheader={
                  this.state.editPage[0]
                    ? "You can edit village organization here!"
                    : "You can add new village organization here!"
                }
              />
              <Divider />
              <CardContent>
                <Grid container spacing={2}>
                  <Grid item md={12} xs={12}>
                    {this.state.formSubmitted === false ? (
                      <Snackbar severity="error" Showbutton={false}>
                        Network Error - Please try again!
                      </Snackbar>
                    ) : null}
                  </Grid>
                  <Grid item xs={12}>
                    <Input
                      fullWidth
                      label="Village Organization Name*"
                      name="addVo"
                      error={this.hasError("addVo")}
                      helperText={
                        this.hasError("addVo")
                          ? this.state.errors.addVo[0]
                          : null
                      }
                      value={this.state.values.addVo || ""}
                      onChange={this.handleChange}
                      variant="outlined"
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Input
                      fullWidth
                      label="Address"
                      name="addVoAddress"
                      error={this.hasError("addVoAddress")}
                      helperText={
                        this.hasError("addVoAddress")
                          ? this.state.errors.addVoAddress[0]
                          : null
                      }
                      value={this.state.values.addVoAddress || ""}
                      onChange={this.handleChange}
                      variant="outlined"
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <Input
                      fullWidth
                      label="Block"
                      name="addBlock"
                      error={this.hasError("addBlock")}
                      helperText={
                        this.hasError("addBlock")
                          ? this.state.errors.addBlock[0]
                          : null
                      }
                      value={this.state.values.addBlock || ""}
                      onChange={this.handleChange}
                      variant="outlined"
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <Input
                      fullWidth
                      label="Gaon Panchayat"
                      name="addGp"
                      error={this.hasError("addGp")}
                      helperText={
                        this.hasError("addGp")
                          ? this.state.errors.addGp[0]
                          : null
                      }
                      value={this.state.values.addGp || ""}
                      onChange={this.handleChange}
                      variant="outlined"
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <Input
                      fullWidth
                      label="Point of Contact"
                      name="addPerson"
                      error={this.hasError("addPerson")}
                      helperText={
                        this.hasError("addPerson")
                          ? this.state.errors.addPerson[0]
                          : null
                      }
                      value={this.state.values.addPerson || ""}
                      onChange={this.handleChange}
                      variant="outlined"
                    />
                  </Grid>
                  {this.state.loggedInUserRole === "Sesta Admin" ||
                  this.state.loggedInUserRole === "Superadmin" ? (
                    <Grid item md={6} xs={12}>
                      <Autotext
                        id="combo-box-demo"
                        options={fpoFilters}
                        name="addFPO"
                        variant="outlined"
                        label="Select FPO*"
                        getOptionLabel={(option) => option.name}
                        onChange={(event, value) => {
                          this.handleFpoChange(event, value);
                        }}
                        value={
                          addFPO
                            ? this.state.isCancel === true
                              ? null
                              : fpoFilters[
                                  fpoFilters.findIndex(function (item, i) {
                                    return item.id === addFPO;
                                  })
                                ] || null
                            : null
                        }
                        error={this.hasError("addFPO")}
                        helperText={
                          this.hasError("addFPO")
                            ? this.state.errors.addFPO[0]
                            : null
                        }
                        renderInput={(params) => (
                          <Input
                            fullWidth
                            label="Select FPO*"
                            name="addFPO"
                            variant="outlined"
                          />
                        )}
                      />
                    </Grid>
                  ) : null}
                </Grid>
              </CardContent>
              <Divider />
              <CardActions style={{ padding: "15px" }}>
                <Button type="submit">Save</Button>
                <Button
                  color="secondary"
                  clicked={this.cancelForm}
                  component={Link}
                  to="/village-organizations"
                >
                  cancel
                </Button>
              </CardActions>
            </form>
          </Card>
        ) : (
          <Spinner />
        )}
      </Layout>
    );
  }
Example #29
Source File: message.js    From js-miniapp with MIT License 4 votes vote down vote up
Message = (props: MessageTypeProps) => {
  const classes = useStyles();
  const messageTypes = props.messageTypes;
  const [message, setMessage] = useState({
    id: messageTypes[0] !== undefined ? messageTypes[0].id : -1,
    contactId: '',
    image: pandaLogo,
    text: defaultTexts.get(MessageTypeId.SINGLE_CONTACT),
    caption: defaultCaption,
    action: defaultAction,
    bannerMessage: 'Win 30 coins from every friends who joins from your invite',
  });
  const [validation, setValidationState] = useState({
    error: false,
    message: '',
  });
  const [messageResponse, setMessageResponse] = useState({
    show: false,
    response: '',
  });
  const validate = () => {
    if (
      messageTypes.map((it) => it.id).findIndex((it) => it === message.id) ===
      -1
    ) {
      setValidationState({ error: true, message: 'select message' });
      return false;
    } else if (message.text === undefined || message.text.trim().length === 0) {
      setValidationState({ error: true, message: 'text cannot be empty' });
      return false;
    } else if (
      message.id === 2 &&
      (message.contactId === undefined || message.contactId.trim().length === 0)
    ) {
      setValidationState({
        error: true,
        message: 'contact id cannot be empty',
      });
      return false;
    } else {
      setValidationState({ error: false, message: '' });
    }
    return true;
  };
  const handleChange = (event) => {
    message.text = defaultTexts.get(event.target.value);
    message.action = defaultAction;
    message.caption = defaultCaption;
    setMessage({ ...message, id: event.target.value });
  };
  const talkToChatbot = () => {
    if (validate()) {
      if (message.id === MessageTypeId.SINGLE_CONTACT) {
        props
          .sendMessageToContact(
            message.image.trim() ?? '',
            message.text !== undefined ? message.text.trim() : '',
            message.caption.trim() ?? '',
            message.action.trim() ?? '',
            message.bannerMessage.trim() ?? ''
          )
          .then((contactId) => {
            let respMsg = 'Message not sent';
            if (contactId !== null)
              respMsg = 'Message is sent to contact Id: ' + contactId;
            setMessageResponse({
              show: true,
              response: respMsg,
            });
          })
          .catch((e) => {
            setMessageResponse({
              show: true,
              response: e,
            });
          });
      } else if (message.id === MessageTypeId.SINGLE_CONTACT_ID) {
        props
          .sendMessageToContactId(
            message.contactId.trim(),
            message.image.trim() ?? '',
            message.text !== undefined ? message.text.trim() : '',
            message.caption.trim() ?? '',
            message.action.trim() ?? ''
          )
          .then((contactId) => {
            let respMsg = 'Message not sent';
            if (contactId !== null && contactId !== undefined)
              respMsg = 'Message is sent to contact Id: ' + contactId;
            setMessageResponse({
              show: true,
              response: respMsg,
            });
          })
          .catch((e) => {
            setMessageResponse({
              show: true,
              response: e,
            });
          });
      } else if (message.id === MessageTypeId.MULTIPLE_CONTACTS) {
        props
          .sendMessageToMultipleContacts(
            message.image.trim() ?? '',
            message.text !== undefined ? message.text.trim() : '',
            message.caption.trim() ?? '',
            message.action.trim() ?? '',
            message.bannerMessage.trim() ?? ''
          )
          .then((contactIds) => {
            let respMsg = 'Message not sent';
            if (contactIds !== null)
              respMsg = contactIds.length + ' contacts sent';
            setMessageResponse({
              show: true,
              response: respMsg,
            });
          })
          .catch((e) => {
            setMessageResponse({
              show: true,
              response: e,
            });
          });
      }
    }
  };

  const onContactIdChange = (event) => {
    setMessage({ ...message, contactId: event.target.value });
  };
  const onImageChange = (event) => {
    setMessage({ ...message, image: event.target.value });
  };
  const onTextChange = (event) => {
    setMessage({ ...message, text: event.target.value });
  };
  const onBannerMessageChange = (event) => {
    setMessage({ ...message, bannerMessage: event.target.value });
  };
  const onCaptionChange = (event) => {
    setMessage({ ...message, caption: event.target.value });
  };
  const onActionChange = (event) => {
    setMessage({ ...message, action: event.target.value });
  };

  const onChatbotClose = () => {
    setMessageResponse({ show: false, response: '' });
  };

  return (
    <div className={classes.scrollable}>
      <Fragment>
        <FormControl className={classes.formControl}>
          <InputLabel id="chatbotLabel">Send Message Type</InputLabel>
          <Select
            labelId="chatbotLabel"
            id="message"
            placeholder="Select Chatbot"
            value={message.id}
            className={classes.fields}
            onChange={handleChange}
          >
            {messageTypes.map((c) => (
              <MenuItem key={c.id} value={c.id}>
                {c.name}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        {message.id === MessageTypeId.SINGLE_CONTACT_ID && (
          <FormControl className={classes.formControl}>
            <TextField
              id="contactId"
              label="Contact ID"
              className={classes.fields}
              onChange={onContactIdChange}
              placeholder="Input contact id receiving a message"
              value={message.contactId}
            />
          </FormControl>
        )}

        <FormControl className={classes.formControl}>
          <TextField
            id="image"
            label="Image"
            className={classes.fields}
            onChange={onImageChange}
            placeholder="Image url or Base64 string"
            value={message.image}
          />
        </FormControl>
        <FormControl className={classes.formControl}>
          <TextField
            id="text"
            label="Text"
            className={classes.fields}
            onChange={onTextChange}
            value={message.text}
            multiline
            rowsMax="4"
          />
        </FormControl>
        {message.id !== MessageTypeId.SINGLE_CONTACT_ID && (
          <FormControl className={classes.formControl}>
            <TextField
              id="bannerMessage"
              label="Banner message"
              className={classes.fields}
              onChange={onBannerMessageChange}
              value={message.bannerMessage}
            />
          </FormControl>
        )}
        <FormControl className={classes.formControl}>
          <TextField
            id="caption"
            label="Caption"
            className={classes.fields}
            onChange={onCaptionChange}
            value={message.caption}
          />
        </FormControl>
        <FormControl className={classes.formControl}>
          <TextField
            id="action"
            label="Action"
            className={classes.fields}
            onChange={onActionChange}
            value={message.action}
          />
        </FormControl>
        {validation.error && (
          <div data-testid="validation-error" className={classes.errorMessage}>
            {validation.message}
          </div>
        )}
        <CardActions className={classes.actions}>
          <Button
            data-testid="send-message"
            variant="contained"
            color="primary"
            fullWidth
            onClick={talkToChatbot}
          >
            SEND MESSAGE
          </Button>
        </CardActions>
        <Dialog
          data-testid="message-response-dialog"
          open={messageResponse.show}
          onClose={onChatbotClose}
          aria-labelledby="max-width-dialog-title"
        >
          <DialogTitle id="max-width-dialog-title">Response</DialogTitle>
          <DialogContent>
            <DialogContentText>{messageResponse.response}</DialogContentText>
          </DialogContent>
          <DialogActions>
            <Button onClick={onChatbotClose} color="primary">
              Close
            </Button>
          </DialogActions>
        </Dialog>
      </Fragment>
    </div>
  );
}