@material-ui/core#CardMedia JavaScript Examples

The following examples show how to use @material-ui/core#CardMedia. 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: Gravatars.jsx    From Gameplayer with MIT License 6 votes vote down vote up
Gravatar = ({ classes, id, displayName, imageUrl, owner }) => (
  <Grid item>
    <Card>
      <CardActionArea className={classes.actionArea}>
        {imageUrl && (
          <CardMedia className={classes.image} image={imageUrl} title={displayName} />
        )}
        <CardContent>
          <Typography variant="h6" component="h3" className={classes.displayName}>
            {displayName || '—'}
          </Typography>
          <Typography color="textSecondary">ID</Typography>
          <Typography component="p" className={classes.id}>
            {id}
          </Typography>
          <Typography color="textSecondary">Owner</Typography>
          <Typography component="p" className={classes.owner}>
            {owner}
          </Typography>
        </CardContent>
      </CardActionArea>
    </Card>
  </Grid>
)
Example #2
Source File: ProjectCard.js    From eSim-Cloud with GNU General Public License v3.0 6 votes vote down vote up
export default function ProjectCard ({ pub, is_review }) {
  const classes = useStyles()
  return (
    <>
      <Card>
        <ButtonBase
          target="_blank"
          component={RouterLink}
          to={'/project?save_id=' + pub.save_id + '&version=' + pub.active_version + '&branch=' + pub.active_branch + '&project_id=' + pub.project_id}
          style={{ width: '100%' }}>
          <CardActionArea>
            <CardHeader title={pub.title} />
            <CardMedia
              className={classes.media}
              image={pub.active_save.base64_image} />
            <CardContent>
              <Typography variant="body2" component="p" noWrap={true}>
                {pub.description}
              </Typography>
              <br/>
              <Typography variant='body2' color='textSecondary' component='p'>
              Status: {pub.status_name}
              </Typography>
              {/* <Typography variant='body2' component='p' color='textSecondary' style={{ margin: '5px 0px 0px 0px' }}>
              Updated at {timeSince(pub.save_time)} ago...
            </Typography> */}
            </CardContent>
          </CardActionArea>
        </ButtonBase>
      </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: Categories.jsx    From scholar-front-end with MIT License 6 votes vote down vote up
categoriesCard = data.map(item => (
    <Grid item sm={3}>
    <Card className="cardActions">
        <CardActionArea >
            <CardMedia className="card"
                image={require(`../../data/Images/${item.name}`).default}
                style={{ height: 300 }} />
            <CardContent>
                <Typography variant="h5"><span className="categoryName">{item.category}</span></Typography>
            </CardContent>
        </CardActionArea>
    </Card>
</Grid>
))
Example #5
Source File: team-member.js    From turinghut-website with BSD Zero Clause License 6 votes vote down vote up
export default function TeamMember() {
  const classes = teamMemberStyles();
  return (
    <div>
      <Typography variant="h3" className={classes.heading}>our team</Typography>
      <div className={classes.root}>
        <Grid container spacing={4} className={classes.gridContainer}>
          {team.map((member, i) => (
            <Grid item xs={12} md={4} key={i}>
              <Card className={classes.card}>
                <CardActionArea >
                  <CardMedia className={classes.media} image={member.imageUrl} title={member.name} />
                  <DialogDisplay person={member} />
                </CardActionArea>
              </Card>
            </Grid>
          ))}
        </Grid>
      </div>
    </div>
  );
}
Example #6
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 #7
Source File: VideoCard.js    From course-manager with MIT License 6 votes vote down vote up
export default function VideoCard({ video }) {
  const classes = useStyles();
  const { id, title, description, thumbnailUrl } = video;

  return (
    <Card className={classes.root}>
      <CardMedia image={thumbnailUrl} title={title} className={classes.media} />
      <CardContent style={{ padding: '12px' }}>
        <Link
          to={`/dashboard/videos/${id}`}
          color="inherit"
          underline="hover"
          component={RouterLink}
        >
          <Typography variant="h6" noWrap>
            {title}
          </Typography>
        </Link>
        <Typography variant="body2" noWrap>
          {description}
        </Typography>
      </CardContent>
    </Card>
  );
}
Example #8
Source File: CourseCard.js    From course-manager with MIT License 6 votes vote down vote up
export default function CourseCard({ course }) {
  const classes = useStyles();
  const { id, title, description, thumbnailUrl, videoCount } = course;

  return (
    <Card className={classes.root}>
      <CardMedia image={thumbnailUrl} title={title} className={classes.media} />
      <CardContent style={{ padding: '12px' }}>
        <Link
          to={`/dashboard/courses/${id}`}
          color="inherit"
          underline="hover"
          component={RouterLink}
        >
          <Typography variant="h6" noWrap>
            {title}
          </Typography>
        </Link>
        <Typography variant="body2" noWrap>
          {description}
        </Typography>
        <Typography variant="body2" noWrap>
          {videoCount} videos
        </Typography>
      </CardContent>
    </Card>
  );
}
Example #9
Source File: Home.js    From deno-seed with MIT License 5 votes vote down vote up
render() {
    return (
      <div className={ styles.home }>
        <Grid
          item
          xs={ 12 }
          sm={ 6 }
          md={ 4 }
        >
          <Card className={ styles.card }>
            <CardMedia
              component="img"
              image="https://camo.githubusercontent.com/7fb1ce3c4d77a02b0508d05865ec667798a1dd0e/68747470733a2f2f692e6962622e636f2f324b74677143762f4e65772d50726f6a6563742d342d312e706e67"
              title="Deno Seed"
              style={{ 'padding-bottom': '15px' }}
            />
            <hr/>
            <CardContent>
              <Typography component="p">
                <GitHubButton
                  href="https://github.com/tamasszoke/deno-seed"
                  data-icon="octicon-star"
                  data-size="large"
                  data-show-count="true"
                  aria-label="Star tamasszoke/deno-seed on GitHub"
                >
                  Star
                </GitHubButton>
              </Typography>
              <Typography component="p">
                <GitHubButton
                  href="https://github.com/tamasszoke"
                  data-size="large"
                  aria-label="Follow @tamasszoke on GitHub"
                >
                  Follow @tamasszoke
                </GitHubButton>
              </Typography>
            </CardContent>
          </Card>
        </Grid>
      </div>
    )
  }
Example #10
Source File: gifs.js    From js-miniapp with MIT License 5 votes vote down vote up
function GIFComponent() {
  const classes = useStyles();
  const images = [
    {
      label: 'Loop Count: Once',
      iconSrc: require('../assets/images/gif/road.gif'),
      altLabel: 'road',
    },
    {
      label: 'Loop Count: Infinite',
      iconSrc: require('../assets/images/gif/road_infinite.gif'),
      altLabel: 'infinite_road',
    },
    {
      label: 'Loop Count: Infinite (WebP)',
      // $FlowFixMe
      iconSrc: require('../assets/images/webp/road_webp.gif'),
      altLabel: 'infinite_road_webp',
    },
  ];
  return (
    <div className={classes.scrollable}>
      <Grid
        container
        direction="column"
        justify="flex-start"
        alignItems="center"
        className={classes.grid}
      >
        {images.map((it, i) => (
          <React.Fragment item key={i}>
            <GreyCard height="auto" className={`${classes.greyCard}`}>
              <Typography className={`app-typography ${classes.typography}`}>
                {it.label}
              </Typography>
              <CardContent>
                <CardMedia
                  component="img"
                  className={classes.gif}
                  src={it.iconSrc}
                  alt={it.altLabel}
                />
              </CardContent>
            </GreyCard>
          </React.Fragment>
        ))}
      </Grid>
    </div>
  );
}
Example #11
Source File: LinkContent.js    From covid19ph.net with MIT License 5 votes vote down vote up
LinkContent = ({
  image,
  title,
  url,
}) => {
  const classes = useStyles()

  return (
    <CardActionArea
      component="a"
      href={url}
      rel="noreferrer noopener"
      target="_blank"
    >
      <CardMedia
        component="img"
        height="256"
        image={image}
        alt={title}
        title={title}
        className={classes.linkImage}
      />
      <CardContent>
        <Typography
          gutterBottom
          variant="h5"
          component="h2"
          className={classes.linkTitle}
        >
          {title}
        </Typography>
        <Typography
          variant="body2"
          color="textSecondary"
          component="p"
          className={classes.linkUrl}
        >
          {url}
        </Typography>
      </CardContent>
    </CardActionArea>
  )
}
Example #12
Source File: news-item.js    From horondi_client_fe with MIT License 5 votes vote down vote up
NewsItem = ({ date, image, id, slug, translationsKey }) => {
  const { t, i18n } = useTranslation();
  const dateLanguage = i18n.language === 'ua' ? 'ukr-UA' : 'en-US';
  const styles = useStyles();
  if (!t(`${translationsKey}.text`)) {
    return null;
  }
  return (
    <div className={styles.container}>
      <Card className={styles.root}>
        <div className={styles.imagesContainer}>
          <CardMedia
            className={styles.media}
            image={IMG_URL + image}
            title={translationsKey ? t(`${translationsKey}.title`) : t('newsDetail.noTitle')}
            component='div'
            data-cy='image'
          />
        </div>
        <div className={styles.newsAuthorFooter}>
          <Typography variant='h5' component='div' className={styles.newsDateAutor}>
            <span>{new Date(parseInt(date)).toLocaleString(dateLanguage, TIME_OPTIONS)}</span>
            <span>{translationsKey ? t(`${translationsKey}.name`) : t('newsDetail.noAuthor')}</span>
          </Typography>
        </div>
        <CardContent className={styles.ArticleTitleContainer}>
          <Typography
            className={styles.ArticleTitle}
            gutterBottom
            variant='h5'
            component='h2'
            data-cy='newsTitle'
          >
            {translationsKey ? t(`${translationsKey}.title`) : t('newsDetail.noTitle')}
          </Typography>
        </CardContent>
        <CardContent className={styles.newsItemContent}>
          <Typography
            variant='body2'
            color='textSecondary'
            component='div'
            className={styles.newsText}
            data-cy='newsText'
          >
            {translationsKey
              ? parse(t(`${translationsKey}.text`).slice(0, 299))
              : t('newsDetail.noText')}
          </Typography>
        </CardContent>
        <div className={styles.newsFooter}>
          <Link to={`/news/${id}-${slug}`}>
            <Button variant='outlined' className={styles.newsButton} data-cy='readMoreButton'>
              {t('buttons.readMore')}
            </Button>
          </Link>
        </div>
      </Card>
    </div>
  );
}
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: 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 #15
Source File: ResultCard.js    From qasong with ISC License 5 votes vote down vote up
export default function ResultCard({
  video,
  setNowPlaying,
  nowPlaying,
  queue,
  setQueue,
}) {
  const classes = useStyles();
  const [playing, setPlaying] = useState(false);

  useEffect(() => {
    if (nowPlaying && nowPlaying.videoId === video.videoId) {
      setPlaying(true);
    } else {
      setPlaying(false);
    }
  }, [nowPlaying]);

  function handlePlayButton(event) {
    event.stopPropagation();

    if (!playing) {
      setNowPlaying(video);
      setPlaying(true);
    } else {
      setNowPlaying({});
      setPlaying(false);
    }
  }

  function handleAddQueue(event) {
    event.stopPropagation();
    setQueue(
      queue.concat({
        ...video,
        qid: uuid(),
      })
    );
  }

  return (
    <Card
      className={classes.card}
      style={{ backgroundColor: playing && qasongOrange }}
      onClick={handlePlayButton}
    >
      <CardActionArea>
        <CardMedia className={classes.media} image={video.image} />
        <Box p={1}>
          <Grid container direction="column">
            <Grid item>
              <Typography className={classes.truncate} variant="caption">
                {video.title}
              </Typography>
            </Grid>
            <Grid item container justify="space-between">
              <Grid item>
                <Typography className={classes.truncate} variant="caption">
                  {video.author.name}
                </Typography>
              </Grid>
              <Grid item>
                <Typography className={classes.truncate} variant="caption">
                  {video.timestamp}
                </Typography>
              </Grid>
            </Grid>
          </Grid>
        </Box>
      </CardActionArea>

      <Box className={classes.overlay}>
        <AddToQueueButton {...{ handleAddQueue }} />
      </Box>
    </Card>
  );
}
Example #16
Source File: ResultRow.js    From qasong with ISC License 5 votes vote down vote up
export default function ResultRow({ video, setNowPlaying, nowPlaying, queue, setQueue }) {
  const classes = useStyles();
  const [playing, setPlaying] = useState(false);

  useEffect(() => {
    if (nowPlaying && nowPlaying.videoId === video.videoId) {
      setPlaying(true);
    } else {
      setPlaying(false);
    }
  }, [nowPlaying]);

  function handlePlayButton(event) {
    event.stopPropagation();

    if (!playing) {
      setNowPlaying(video);
      setPlaying(true);
    } else {
      setNowPlaying({});
      setPlaying(false);
    }
  }

  function handleAddQueue(event) {
    event.stopPropagation();
    setQueue(
      queue.concat({
        ...video,
        qid: uuid(),
      })
    );
  }

  return (
    <TableRow
      className={classes.row}
      key={video.videoId}
      style={{ backgroundColor: playing && qasongOrange }}
    >
      <TableCell>
        <IconButton onClick={handlePlayButton} aria-label="Play">
          <PlayArrowIcon />
        </IconButton>
      </TableCell>
      <TableCell>
        <AddToQueueButton {...{ handleAddQueue }} />
      </TableCell>
      <TableCell>{video.title}</TableCell>
      <TableCell>{video.author.name}</TableCell>
      <TableCell>{numberWithCommas(video.views)}</TableCell>
      <TableCell>
        <CardMedia
          onClick={handlePlayButton}
          className={classes.media}
          image={video.thumbnail}
        />
      </TableCell>
    </TableRow>
  );
}
Example #17
Source File: index.js    From iiitt with MIT License 5 votes vote down vote up
export default function Director() {
  useEffect(() => {
    document.getElementsByTagName("title")[0].innerHTML = "Administration";
  }, []);

  useEffect(() => {
    return () => {
      document.getElementsByTagName("title")[0].innerHTML = "IIIT Trichy";
    };
  }, []);

  const classes = createStyles();
  return (
    <div className="page-container">
      <Navbar />
      <Grid container className={classes.container}>
        <Grid item xs={false} sm={1} />
        <Grid item xs={12} sm={10}>
          <Grid item xs={12} sm={4} className={classes.info}>
            <Card className={classes.card}>
              <CardMedia
                className={classes.media}
                image={require(`../../images/Dr_Seetharaman.jpg`)}
                title="Registrar"
              />
              <CardContent>
                <Typography variant="body" gutterBottom>
                  <Box component="span" fontSize="1.5rem" gutterBottom>
                    Dr. G.Seetharaman
                  </Box>
                  <br />
                  <Box fontSize="1.2rem">
                    Registrar i/c
                    <br />
                    Indian Institute of Information Technology Tiruchirappalli
                    Tiruchirappalli-620012 Tamilnadu
                  </Box>
                  <br />
                  <a href={`mailto:[email protected]`} fontSize="1.2rem">
                    [email protected]
                  </a>
                  <br />

                  <br />
                  <br />
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          <Typography className={classes.text} gutterBottom>
            The Registrar is one of the Principle Officers of the Institute. He
            is entrusted with the statutory functions as per IIITT-Act and the
            Statutes framed there under. He is in-charge of the Administration
            of the Institute. He is an ex-officio Secretary to the statutory
            bodies of the Institute, such as, the Board of Governors, the
            Senate, the Finance Committee and the Building Works Committee.
            Apart from the above statutory functions, he is also enjoined to
            assist the Director on all matters pertaining to the administration
            of the Institute.
          </Typography>
        </Grid>
        <Grid item xs={false} sm={1} />
      </Grid>

      <Footer />
    </div>
  );
}
Example #18
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 #19
Source File: About.jsx    From Corona-tracker with MIT License 5 votes vote down vote up
About = () => {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <Grid>
        <main>
          <div className={classes.heroContent}>
            <Container maxWidth="sm">
              <Typography component="h1" variant="h3" align="center" color="textPrimary" gutterBottom>
                For the community, by the community
              </Typography>
              <Typography variant="body1" align="center" color="textSecondary" paragraph>
                CoronaTracker is an easy-to-use, private-by-design, open-source application for monitoring your health
                and staying informed during the COVID-19 crisis. Here&apos;s what we&apos;ve accomplished so far
              </Typography>
            </Container>
          </div>
          <Link className={classes.color} href="https://forms.gle/PrD1QY2z3a7htB5W9" color="inherit">
            Take our Beta Survey!
          </Link>
          <Container className={classes.cardGrid} maxWidth="md">
            {/* End hero unit */}
            <Grid container spacing={4}>
              {cards.map(card => (
                <Grid item key={card.id} xs={12} sm={6} md={4}>
                  <Link href={card.link}>
                    <Card className={classes.card}>
                      <CardMedia className={classes.cardMedia} image={card.img} title="Image title" />
                      <CardContent className={classes.cardContent}>
                        <Typography gutterBottom variant="subtitle1" component="h2">
                          {card.title}
                        </Typography>
                        <Typography variant="body2">{card.about}</Typography>
                      </CardContent>
                    </Card>
                  </Link>
                </Grid>
              ))}
            </Grid>
          </Container>
        </main>
        <footer className={classes.footer}>
          <Typography variant="h6" align="center" gutterBottom>
            Support Us!
          </Typography>
          <Typography variant="body1" align="center" color="textSecondary" component="p">
            Star our GitHub, fill out our user survey, anything counts! CoronaTracker is made with{' '}
            <span role="img" aria-label="heart">
              ❤️
            </span>{' '}
            in NYC and across the globe
          </Typography>
          {/* <Copyright /> */}
        </footer>
      </Grid>
    </div>
  );
}
Example #20
Source File: ProjectCard.jsx    From Design-Initiative-Dashboard-frontend with GNU General Public License v3.0 5 votes vote down vote up
export default function ProjectCard() {
  const classes = useStyles();
  const history = useHistory();

  function handleChange(){
    history.push('./ProjectDetails');
  }
  

  return (
    <React.Fragment>
      {cardData.map((data) => (
        <Card className={classes.root}>
          <CardActionArea>
            <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>
          </CardActionArea>
          <div>
            <CardActions>
              <Button size="small" color="primary" className={classes.btn} onClick={handleChange}>
                View more
              </Button>
            </CardActions>
          </div>
        </Card>
      ))}
    </React.Fragment>
  );
}
Example #21
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 #22
Source File: ProposalDetail.jsx    From Design-Initiative-Dashboard-frontend with GNU General Public License v3.0 5 votes vote down vote up
ProposalDetail = () => {
  const classes = useStyles();
  return (
    <div>
      {selectedProposal.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 Proposal
              </Button>
              <Button size="small" color="primary" className={classes.btn}>
                View Project
              </Button>
            </CardActions>
          </div>
        </Card>
      ))}
    </div>
  );
}
Example #23
Source File: EligibleEvents.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
EligibleEvents = props => {
  const history = useHistory();
  const [open, setOpen] = useState(true);

  const classes = useStyles();
  const [formState, setFormState] = useState({
    eventDetails: [],
    greenButtonChecker: true,
    showRegisterModel: false,
    registerUserId: "",
    eventtitle: "",
    isStudentRegister: false,
    registrationFail: false,
    authUserRegistering: null,
    NoEventsData: false,
    registeredEventsIds: []
  });

  /** This use effect is called at the very begining and only once */
  useEffect(() => {
    if (
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.STUDENT &&
      auth.getUserInfo().studentInfo !== null &&
      auth.getUserInfo().studentInfo.id !== null
    ) {
      getEventDetails();
    } else {
      history.push({
        pathname: routeConstants.NOT_FOUND_URL
      });
    }
  }, []);

  /** This gets events details */
  async function getEventDetails() {
    let studentId = null;
    if (
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.STUDENT &&
      auth.getUserInfo().studentInfo !== null &&
      auth.getUserInfo().studentInfo.contact !== null &&
      auth.getUserInfo().studentInfo.contact.id !== null
    ) {
      studentId = auth.getUserInfo().studentInfo.contact.id;
      formState.authUserRegistering = studentId;
      if (studentId !== null && studentId !== undefined) {
        /** This will give all the eligible events for a student */
        const ELIGIBLE_EVENTS =
          strapiConstants.STRAPI_DB_URL +
          strapiConstants.STRAPI_INDIVIDUAL_URL +
          "/" +
          auth.getUserInfo().studentInfo.contact.id +
          "/" +
          strapiConstants.STRAPI_EVENTS;

        let params = {
          pageSize: -1,
          _sort: "start_date_time"
        };

        await serviceProviders
          .serviceProviderForGetRequest(ELIGIBLE_EVENTS, params)
          .then(res => {
            let viewData = [];
            if (res.data.result.length === 0) {
              setFormState(formState => ({
                ...formState,
                NoEventsData: true
              }));
            } else {
              viewData = res.data.result;
            }
            setFormState(formState => ({
              ...formState,
              eventDetails: viewData
            }));
          })
          .catch(error => {
            console.log("error", error);
          });
      } else {
        auth.clearAppStorage();
        history.push({
          pathname: routeConstants.SIGN_IN_URL
        });
      }
    } else {
      auth.clearAppStorage();
      history.push({
        pathname: routeConstants.SIGN_IN_URL
      });
    }
  }

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

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

  const getVenue = data => {
    return data["address"];
  };

  const routeToDisplayEvent = id => {
    history.push({
      pathname: routeConstants.VIEW_EVENT,
      dataForView: id
    });
  };

  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        <Typography variant="h4" gutterBottom>
          Upcoming Events
        </Typography>
      </Grid>
      <Grid item xs={12}>
        {props.location.fromAddEvent && props.location.isRegistered ? (
          <Collapse in={open}>
            <Alert
              severity="success"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {props.location.registeredEventMessage}
            </Alert>
          </Collapse>
        ) : null}
        {props.location.fromAddEvent && !props.location.isRegistered ? (
          <Collapse in={open}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {props.location.registeredEventMessage}
            </Alert>
          </Collapse>
        ) : null}
        <Grid container spacing={3}>
          {formState.eventDetails.length ? (
            formState.eventDetails.map(data => {
              return (
                <Grid key={data.id} item xs={12} sm={6} md={4}>
                  <Card>
                    {/* <CardHeader className={classes.CardHeaderFooter}> */}
                    <Grid
                      container
                      direction="row"
                      justify="flex-end"
                      alignItems="center"
                      className={classes.CardHeaderFooter}
                    >
                      {data["isRegistered"] ? (
                        <React.Fragment>
                          <Grid item xs={2}>
                            <IconButton aria-label="is student registered">
                              <CheckCircleIcon style={{ color: green[500] }} />
                            </IconButton>
                          </Grid>
                          <Grid item xs={10}>
                            <Typography style={{ color: green[500] }}>
                              Registered
                            </Typography>
                          </Grid>
                        </React.Fragment>
                      ) : (
                        <div className={classes.successTickDiv}></div>
                      )}
                    </Grid>
                    {/* </CardHeader> */}
                    <Box className={classes.BoxPadding}>
                      {data["upload_logo"] !== null &&
                      data["upload_logo"] !== undefined &&
                      data["upload_logo"] !== {} ? (
                        <CardMedia
                          image={
                            strapiConstants.STRAPI_DB_URL_WITHOUT_HASH +
                            data["upload_logo"]["url"]
                          }
                          className={classes.EligibleEventsStyling}
                        />
                      ) : (
                        <CardMedia
                          image={noImage}
                          className={classes.NoEventsStyling}
                        />
                      )}
                      <Box className={classes.DivHeight}>
                        <Typography
                          variant="h5"
                          className={classes.TextAlign}
                          color="textPrimary"
                        >
                          {data.title}
                        </Typography>
                      </Box>
                      <Box>
                        <Grid container spacing={1} justify="center">
                          <Grid item md={3} xs={3}>
                            <Typography variant="h5" color="textPrimary">
                              Date
                            </Typography>
                          </Grid>
                          <Grid item md={9} xs={9}>
                            <Typography color="textSecondary">
                              {getDate(data)}
                            </Typography>
                          </Grid>
                          <Grid item md={3} xs={3}>
                            <Typography variant="h5" color="textPrimary">
                              Time
                            </Typography>
                          </Grid>
                          <Grid item md={9} xs={9}>
                            <Typography color="textSecondary">
                              {getTime(data)}
                            </Typography>
                          </Grid>
                          <Grid
                            item
                            md={3}
                            xs={3}
                            className={classes.GridHeight}
                          >
                            <Typography variant="h5" color="textPrimary">
                              Venue
                            </Typography>
                          </Grid>
                          <Grid item md={9} xs={9}>
                            <Typography color="textSecondary">
                              {getVenue(data)}
                            </Typography>
                          </Grid>
                        </Grid>
                      </Box>
                    </Box>
                    <Divider />
                    <Box className={classes.CardHeaderFooter}>
                      <Grid item xs={12} md={11} justify="center">
                        <Button
                          variant="contained"
                          greenButtonChecker={formState.greenButtonChecker}
                          disableElevation
                          onClick={() => {
                            routeToDisplayEvent(data.id);
                          }}
                          fullWidth
                          className={classes.ReadMoreButton}
                        >
                          Read More
                        </Button>
                      </Grid>
                    </Box>
                  </Card>
                </Grid>
              );
            })
          ) : (
            <React.Fragment>
              {formState.NoEventsData === true ? (
                <p className={classes.alignCenter}>No upcoming events</p>
              ) : (
                <Spinner />
              )}
            </React.Fragment>
          )}
        </Grid>
      </Grid>
    </Grid>
  );
}
Example #24
Source File: GrowerDetail.js    From treetracker-admin-client with GNU Affero General Public License v3.0 4 votes vote down vote up
GrowerDetail = ({ open, growerId, onClose }) => {
  // console.log('render: grower detail');
  const classes = useStyle();
  const appContext = useContext(AppContext);
  const { growers } = useContext(GrowerContext);
  const { sendMessageFromGrower } = useContext(MessagingContext);
  const [growerRegistrations, setGrowerRegistrations] = useState(null);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [grower, setGrower] = useState({});
  const [deviceIdentifiers, setDeviceIdentifiers] = useState([]);
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarLabel, setSnackbarLabel] = useState('');
  const [verificationStatus, setVerificationStatus] = useState({});
  const [loading, setLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState(null);

  useEffect(() => {
    setErrorMessage(null);
    async function loadGrowerDetail() {
      if (grower && grower.growerAccountUuid !== growerId) {
        setGrower({});
        setDeviceIdentifiers([]);
      }
      if (growerId) {
        let match;
        if (isNaN(Number(growerId))) {
          match = await getGrower({
            id: undefined,
            growerAccountUuid: growerId,
          });
        } else {
          match = await getGrower({
            id: growerId,
            growerAccountUuid: undefined,
          });
        }

        if (match.error) {
          setErrorMessage(match.message);
        }

        setGrower(match);

        if (
          match.id &&
          (!growerRegistrations ||
            (growerRegistrations.length > 0 &&
              growerRegistrations[0].planter_id !== match.id))
        ) {
          setGrowerRegistrations(null);
          api.getGrowerRegistrations(match.id).then((registrations) => {
            if (registrations && registrations.length) {
              const sortedReg = registrations.sort((a, b) =>
                a.created_at > b.created_at ? 1 : -1
              );
              const uniqueDevices = {};
              const devices = sortedReg.reduce((result, reg) => {
                if (!reg.device_identifier) {
                  return result;
                }
                if (!uniqueDevices[reg.device_identifier]) {
                  uniqueDevices[reg.device_identifier] = true;
                  // if manufacturer isn't 'apple' it's an android phone
                  result.push({
                    id: reg.device_identifier,
                    os:
                      reg.manufacturer?.toLowerCase() === 'apple'
                        ? 'iOS'
                        : 'Android',
                  });
                }
                return result;
              }, []);

              setDeviceIdentifiers(devices);
              setGrowerRegistrations(sortedReg);
            }
          });
        }
      }
    }
    loadGrowerDetail();
    // eslint-disable-next-line
  }, [growerId, growers]);

  useEffect(() => {
    async function loadCaptures() {
      if (grower.id) {
        setLoading(true);
        const [
          approvedCount,
          awaitingCount,
          rejectedCount,
        ] = await Promise.all([
          getCaptureCountGrower(true, true, grower.id),
          getCaptureCountGrower(true, false, grower.id),
          getCaptureCountGrower(false, false, grower.id),
        ]);
        setVerificationStatus({
          approved: approvedCount,
          awaiting: awaitingCount,
          rejected: rejectedCount,
        });
        setLoading(false);
      }
    }
    loadCaptures();
  }, [grower]);

  async function getCaptureCountGrower(active, approved, growerId) {
    let filter = new FilterModel();
    filter.planterId = growerId?.toString();
    filter.active = active;
    filter.approved = approved;
    const countResponse = await treeTrackerApi.getCaptureCount(filter);
    return countResponse && countResponse.count ? countResponse.count : 0;
  }

  async function getGrower(payload) {
    const { id, growerAccountUuid } = payload;
    let grower = growers?.find(
      (p) =>
        (growerAccountUuid && p.growerAccountUuid === growerAccountUuid) ||
        p.id === id
    ); // Look for a match in the context first

    if (!grower && !id) {
      const filter = new FilterGrower();
      filter.growerAccountUuid = growerAccountUuid;
      [grower] = await api.getGrowers({ filter }); // Otherwise query the API
    }

    if (!grower && !growerAccountUuid) {
      grower = await api.getGrower(id);
    }
    // throw error if no match at all
    return grower || { error: true, message: 'Sorry! No grower info found' };
  }

  function handleEditClick() {
    setEditDialogOpen(true);
  }

  function handleEditClose() {
    setEditDialogOpen(false);
    setSnackbarOpen(false);
    setSnackbarLabel('');
  }

  function confirmCopy(label) {
    setSnackbarOpen(false);
    setSnackbarLabel(label);
    setSnackbarOpen(true);
  }

  return (
    <>
      <Drawer anchor="right" open={open} onClose={onClose}>
        <Grid
          style={{
            width: GROWER_IMAGE_SIZE,
          }}
        >
          {errorMessage ? (
            <Grid container direction="column">
              <Grid item>
                <Grid container justify="space-between" alignItems="center">
                  <Grid item>
                    <Box m={4}>
                      <Typography color="primary" variant="h6">
                        Grower Detail
                      </Typography>
                      <Typography variant="h4">{errorMessage}</Typography>
                    </Box>
                  </Grid>
                  <Grid item>
                    <IconButton onClick={() => onClose()}>
                      <Close />
                    </IconButton>
                  </Grid>
                </Grid>
              </Grid>
              <Grid item className={classes.imageContainer}>
                <CardMedia className={classes.cardMedia}>
                  <Grid container className={classes.personBox}>
                    <Person className={classes.person} />
                  </Grid>
                </CardMedia>
              </Grid>
            </Grid>
          ) : (
            <Grid container direction="column">
              <Grid item>
                <Grid container justify="space-between" alignItems="center">
                  <Grid item>
                    <Box m={4}>
                      <Typography color="primary" variant="h6">
                        Grower Detail
                      </Typography>
                    </Box>
                  </Grid>
                  <Grid item>
                    <IconButton onClick={() => onClose()}>
                      <Close />
                    </IconButton>
                  </Grid>
                </Grid>
              </Grid>
              <Grid item className={classes.imageContainer}>
                {grower?.imageUrl && (
                  <OptimizedImage
                    src={grower.imageUrl}
                    width={GROWER_IMAGE_SIZE}
                    height={GROWER_IMAGE_SIZE}
                    className={classes.cardMedia}
                    fixed
                    rotation={grower.imageRotation}
                    alertTitleSize="1.6rem"
                    alertTextSize="1rem"
                    alertHeight="50%"
                  />
                )}
                {!grower.imageUrl && (
                  <CardMedia className={classes.cardMedia}>
                    <Grid container className={classes.personBox}>
                      <Person className={classes.person} />
                    </Grid>
                  </CardMedia>
                )}
                {hasPermission(appContext.user, [
                  POLICIES.SUPER_PERMISSION,
                  POLICIES.MANAGE_GROWER,
                ]) && (
                  <Fab
                    data-testid="edit-grower"
                    className={classes.editButton}
                    onClick={() => handleEditClick()}
                  >
                    <EditIcon />
                  </Fab>
                )}
              </Grid>
              <Grid item className={classes.box}>
                <Typography
                  variant="h5"
                  color="primary"
                  className={classes.name}
                >
                  {grower.firstName} {grower.lastName}
                </Typography>
                <Typography variant="body2">
                  ID: <LinkToWebmap value={grower.id} type="user" />
                </Typography>
              </Grid>
              {process.env.REACT_APP_ENABLE_MESSAGING === 'true' &&
                hasPermission(appContext.user, [POLICIES.SUPER_PERMISSION]) && (
                  <Grid item>
                    <Button
                      className={classes.messageButton}
                      onClick={() => sendMessageFromGrower(grower)}
                      component={Link}
                      to={'/messaging'}
                    >
                      Send Message
                    </Button>
                  </Grid>
                )}
              <Divider />
              <Grid container direction="column" className={classes.box}>
                <Typography variant="subtitle1">Captures</Typography>
                {loading ? (
                  <LinearProgress color="primary" />
                ) : (
                  <List className={classes.listCaptures}>
                    <Box
                      borderColor="grey.300"
                      borderRadius={10}
                      border={0.5}
                      m={0.5}
                    >
                      <ListItem>
                        <ListItemAvatar>
                          <Avatar className={classes.approvedChip}>
                            <Done />
                          </Avatar>
                        </ListItemAvatar>
                        <ListItemText
                          primary={
                            <Typography variant="h5">
                              {verificationStatus.approved || 0}
                            </Typography>
                          }
                          secondary="Approved"
                        />
                      </ListItem>
                    </Box>
                    <Box
                      borderColor="grey.300"
                      borderRadius={10}
                      border={0.5}
                      m={0.5}
                    >
                      <ListItem>
                        <ListItemAvatar>
                          <Avatar className={classes.awaitingChip}>
                            <HourglassEmptyOutlined />
                          </Avatar>
                        </ListItemAvatar>
                        <ListItemText
                          primary={
                            <Typography variant="h5">
                              {verificationStatus.awaiting || 0}
                            </Typography>
                          }
                          secondary="Awaiting"
                        />
                      </ListItem>
                    </Box>
                    <Box
                      borderColor="grey.300"
                      borderRadius={10}
                      border={0.5}
                      m={0.5}
                    >
                      <ListItem>
                        <ListItemAvatar>
                          <Avatar className={classes.rejectedChip}>
                            <Clear />
                          </Avatar>
                        </ListItemAvatar>
                        <ListItemText
                          primary={
                            <Typography variant="h5">
                              {verificationStatus.rejected || 0}
                            </Typography>
                          }
                          secondary="Rejected"
                        />
                      </ListItem>
                    </Box>
                  </List>
                )}
              </Grid>
              <Divider />
              <Grid container direction="column" className={classes.box}>
                <Typography variant="subtitle1">Email address</Typography>
                <Typography variant="body1">{grower.email || '---'}</Typography>
              </Grid>
              <Divider />
              <Grid container direction="column" className={classes.box}>
                <Typography variant="subtitle1">Phone number</Typography>
                <Typography variant="body1">{grower.phone || '---'}</Typography>
              </Grid>
              <Divider />
              <Grid container direction="column" className={classes.box}>
                <Typography variant="subtitle1">Person ID</Typography>
                <Typography variant="body1">
                  {grower.personId || '---'}
                </Typography>
              </Grid>
              <Divider />
              <Grid container direction="column" className={classes.box}>
                <Typography variant="subtitle1">Organization</Typography>
                {grower.organization || grower.organizationId ? (
                  <GrowerOrganization
                    organizationName={grower.organization}
                    assignedOrganizationId={grower.organizationId}
                  />
                ) : (
                  <Typography variant="body1">---</Typography>
                )}
              </Grid>
              <Divider />
              <Grid container direction="column" className={classes.box}>
                <Typography variant="subtitle1">Country</Typography>
                <Typography variant="body1">
                  {(growerRegistrations &&
                    growerRegistrations
                      .map((item) => item.country)
                      .filter(
                        (country, i, arr) =>
                          country && arr.indexOf(country) === i
                      )
                      .join(', ')) ||
                    '---'}
                </Typography>
              </Grid>
              <Divider />
              <Grid container direction="column" className={classes.box}>
                <Typography variant="subtitle1">Registered</Typography>
                <Typography variant="body1">
                  {(growerRegistrations &&
                    growerRegistrations.length > 0 &&
                    getDateTimeStringLocale(
                      growerRegistrations[0].created_at
                    )) ||
                    '---'}
                </Typography>
              </Grid>
              <Divider />
              <Grid container direction="column" className={classes.box}>
                <Typography variant="subtitle1">
                  Device Identifier{deviceIdentifiers.length >= 2 ? 's' : ''}
                </Typography>
                {(deviceIdentifiers.length && (
                  <table>
                    <tbody>
                      {deviceIdentifiers.map((device, i) => (
                        <tr key={i}>
                          <td>
                            <Typography variant="body1">
                              {device.id}
                              <CopyButton
                                label={'Device Identifier'}
                                value={device.id}
                                confirmCopy={confirmCopy}
                              />
                            </Typography>
                          </td>
                          <td>
                            <Typography variant="body1">
                              ({device.os})
                            </Typography>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                )) || <Typography variant="body1">---</Typography>}
              </Grid>
            </Grid>
          )}
        </Grid>
      </Drawer>
      <CopyNotification
        snackbarLabel={snackbarLabel}
        snackbarOpen={snackbarOpen}
        setSnackbarOpen={setSnackbarOpen}
      />
      <EditGrower
        isOpen={editDialogOpen}
        grower={grower}
        onClose={handleEditClose}
      ></EditGrower>
    </>
  );
}
Example #25
Source File: Project.jsx    From zubhub with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @function Project Component
 * @author Raymond Ndibe <[email protected]>
 *
 * @todo - describe function's signature
 */
function Project(props) {
  const classes = useStyles();
  const common_classes = useCommonStyles();

  const { project, t } = props;
  return (
    <Link to={`/projects/${project.id}`} className={classes.textDecorationNone}>
      <Card className={classes.root}>
        <CardMedia className={classes.mediaBoxStyle} title={project.title}>
          <Tooltip
            title={getPublishTypeLabel(project.publish.type)}
            placement="right-start"
            arrow
          >
            <Box className={classes.publishStyle}>
              {project.publish.type === publish_type.Draft
                ? t('project.publish.draft')
                : ''}
              {project.publish.type === publish_type.Preview
                ? t('project.publish.preview')
                : ''}
              {project.publish.type ===
              publish_type['Authenticated Creators'] ? (
                <LockIcon />
              ) : (
                ''
              )}
              {project.publish.type === publish_type.Public ? (
                <PublicIcon />
              ) : (
                ''
              )}
            </Box>
          </Tooltip>
          {project.video ? (
            <>
              <img
                className={classes.mediaImageStyle}
                src={buildVideoThumbnailURL(project.video)}
                alt={project.title}
              />
              <img className={classes.playIconStyle} src={playIcon} alt="" />
            </>
          ) : project.images.length > 0 ? (
            <img
              className={classes.mediaImageStyle}
              src={project.images[0].image_url}
              alt={project.title}
            />
          ) : null}
        </CardMedia>
        <CardActionArea className={classes.actionAreaStyle}>
          <CardContent
            className={clsx(classes.contentStyle, classes.positionRelative)}
          >
            <Fab
              className={classes.fabButtonStyle}
              size="small"
              aria-label="save button"
              onClick={(e, id = project.id) => toggleSave(e, id, props)}
            >
              {project.saved_by.includes(props.auth.id) ? (
                <BookmarkIcon aria-label="unsave" />
              ) : (
                <BookmarkBorderIcon aria-label="save" />
              )}
            </Fab>
            <Fab
              className={clsx(classes.fabButtonStyle, classes.likeButtonStyle)}
              size="small"
              aria-label="like button"
              variant="extended"
              onClick={(e, id = project.id) => toggleLike(e, id, props)}
            >
              {project.likes.includes(props.auth.id) ? (
                <ClapIcon arial-label="unlike" />
              ) : (
                <ClapBorderIcon arial-label="like" />
              )}
              {nFormatter(project.likes.length)}
            </Fab>
            <Typography
              className={classes.titleStyle}
              variant="h5"
              component="h2"
            >
              {project.title}
            </Typography>
            <Box className={classes.descriptionStyle}>
              <Typography
                variant="subtitle2"
                color="textSecondary"
                component="p"
              >
                {formatProjectDescription(project.description)}
              </Typography>
            </Box>
            <Link
              to={`/creators/${project.creator.username}`}
              className={classes.textDecorationNone}
            >
              <Box className={classes.creatorBoxStyle}>
                <Avatar
                  className={classes.creatorAvatarStyle}
                  src={project.creator.avatar}
                  alt={project.creator.username}
                />
                <Typography
                  color="textSecondary"
                  variant="caption"
                  component="p"
                >
                  {project.creator.username}
                </Typography>
                <Link
                  className={common_classes.textDecorationNone}
                  to={`/search/?q=${project.creator.tags[0]}&tab=creators`}
                >
                  <Typography
                    className={clsx(common_classes.baseTagStyle, {
                      [common_classes.extendedTagStyle]: !isBaseTag(
                        project.creator.tags[0],
                      ),
                    })}
                    component="h2"
                  >
                    {project.creator.tags[0]}
                  </Typography>
                </Link>
              </Box>
            </Link>
            <Box className={classes.captionStyle}>
              <Box className={classes.captionStyle}>
                <Typography
                  className={clsx(
                    classes.captionIconStyle,
                    classes.VisibilityIconStyle,
                  )}
                  color="textSecondary"
                  variant="caption"
                  component="span"
                >
                  <VisibilityIcon /> {project.views_count}
                </Typography>
                <Typography
                  className={classes.captionIconStyle}
                  color="textSecondary"
                  variant="caption"
                  component="span"
                >
                  <CommentIcon /> {project.comments_count}
                </Typography>
              </Box>
              <Typography
                color="textSecondary"
                variant="caption"
                component="span"
              >
                {`${dFormatter(project.created_on).value} ${t(
                  `date.${dFormatter(project.created_on).key}`,
                )} ${t('date.ago')}`}
              </Typography>
            </Box>
          </CardContent>
        </CardActionArea>
      </Card>
    </Link>
  );
}
Example #26
Source File: EligibleActivity.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
EligibleActivity = props => {
  const history = useHistory();
  const classes = useStyles();
  const [formState, setFormState] = useState({
    activityDetails: {},
    galleryItems: [1, 2, 3, 4, 5],
    greenButtonChecker: true,
    showRegisterModel: false,
    registerUserId: "",
    NoActivityData: false,
    isStudentRegister: false,
    authUserRegistering: auth.getUserInfo().id
  });
  useEffect(() => {
    getactivityDetails();
  }, []);

  async function getactivityDetails() {
    let paramsForStudent = null;
    if (
      auth.getUserInfo().role.name === roleConstants.STUDENT &&
      auth.getUserInfo().studentInfo !== null
    ) {
      paramsForStudent = auth.getUserInfo().contact.id;
    } else {
      localStorage.clear();
      history.push({
        pathname: routeConstants.SIGN_IN_URL
      });
    }
    if (paramsForStudent !== null && paramsForStudent !== undefined) {
      const COLLEGES_URL =
        strapiConstants.STRAPI_DB_URL +
        strapiConstants.STRAPI_STUDENTS_INDIVIDUAL_URL +
        "/" +
        paramsForStudent +
        "/activities";
      let params = {
        pageSize: -1,
        _sort: "start_date_time"
      };
      await serviceProviders
        .serviceProviderForGetRequest(COLLEGES_URL, params)
        .then(res => {
          let viewData = res.data.result;
          if (res.data.result.length === 0) {
            setFormState(formState => ({
              ...formState,
              activityDetails: viewData,
              NoActivityData: true
            }));
          } else {
            setFormState(formState => ({
              ...formState,
              activityDetails: viewData
            }));
          }
        })
        .catch(error => {
          console.log("error", error);
        });
    } else {
      if (auth.getUserInfo().role.name === roleConstants.STUDENT) {
        history.push({
          pathname: routeConstants.VIEW_PROFILE
        });
      } else {
        localStorage.clear();
        history.push({
          pathname: routeConstants.SIGN_IN_URL
        });
      }
    }
  }

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

  const getVenue = data => {
    return data["address"];
  };
  const getBatch = data => {
    return data.activity_batch.name;
  };

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

  const routeToDisplayActivity = data => {
    history.push({
      pathname: routeConstants.VIEW_ACTIVITY,
      dataForView: data
    });
  };
  const getRemainingDays = data => {
    // let currentDate = new Date();
    // let startDate = new Date(data["activity_batch"]["start_date_time"]);
    // let remainingDays = startDate.getDay() - currentDate.getDay();
    let currentDate = moment();
    let startDate = moment(data["activity_batch"]["start_date_time"]);
    let remainingDays = startDate.diff(currentDate, "days");
    if (remainingDays >= 1) return parseInt(remainingDays) + " Days to go";
    else return "Today";
  };
  /** Show event registration model */

  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        <Typography variant="h4" gutterBottom>
          Upcoming Activity
        </Typography>
      </Grid>
      <Grid item xs={12}>
        <Grid container spacing={3}>
          {formState.activityDetails.length ? (
            formState.activityDetails.map(data => {
              return (
                <Grid item xs={12} sm={6} md={4}>
                  <Card>
                    {/* <CardHeader className={classes.CardHeaderFooter}> */}
                    <Grid
                      container
                      direction="row"
                      justify="flex-end"
                      alignItems="center"
                      className={classes.CardHeaderFooter}
                    >
                      <Grid item xs={2}>
                        <IconButton aria-label="is student registered">
                          <Clock style={{ color: green[500] }} />
                        </IconButton>
                      </Grid>

                      <Grid item xs={10}>
                        <Typography
                          className={classes.header}
                          style={{
                            color: green[500]
                          }}
                        >
                          {getRemainingDays(data)}
                        </Typography>
                      </Grid>
                    </Grid>
                    {/* </CardHeader> */}
                    <Box className={classes.BoxPadding}>
                      {data["upload_logo"] !== null &&
                      data["upload_logo"] !== undefined &&
                      data["upload_logo"] !== {} ? (
                        <CardMedia
                          image={
                            strapiConstants.STRAPI_DB_URL_WITHOUT_HASH +
                            data["upload_logo"]["url"]
                          }
                          className={classes.EligibleEventsStyling}
                        />
                      ) : (
                        <CardMedia
                          image={noImage}
                          className={classes.NoEventsStyling}
                        />
                      )}
                      <Box className={classes.DivHeight}>
                        <Typography
                          variant="h5"
                          className={classes.TextAlign}
                          color="textPrimary"
                        >
                          {data.title}
                        </Typography>
                      </Box>
                      <Box>
                        <Grid container spacing={1} justify="center">
                          <Grid item md={3} xs={3}>
                            <Typography variant="h5" color="textPrimary">
                              Date
                            </Typography>
                          </Grid>
                          <Grid item md={9} xs={9}>
                            <Typography color="textSecondary">
                              {getDate(data)}
                            </Typography>
                          </Grid>
                          <Grid item md={3} xs={3}>
                            <Typography variant="h5" color="textPrimary">
                              Venue
                            </Typography>
                          </Grid>
                          <Grid item md={9} xs={9}>
                            <Typography color="textSecondary">
                              {getVenue(data)}
                            </Typography>
                          </Grid>
                          <Grid item md={3} xs={3}>
                            <Typography variant="h5" color="textPrimary">
                              Batch
                            </Typography>
                          </Grid>
                          <Grid item md={9} xs={9}>
                            <Typography color="textSecondary">
                              {getBatch(data)}
                            </Typography>
                          </Grid>
                          <Grid item md={3} xs={3}>
                            <Typography variant="h5" color="textPrimary">
                              Time
                            </Typography>
                          </Grid>
                          <Grid item md={9} xs={9}>
                            <Typography color="textSecondary">
                              {getBatchTime(data)}
                            </Typography>
                          </Grid>
                        </Grid>
                      </Box>
                    </Box>
                    <Divider />
                    <Box className={classes.CardHeaderFooter}>
                      <Grid item xs={12} md={11} justify="center">
                        <Button
                          variant="contained"
                          disableElevation
                          onClick={() => {
                            routeToDisplayActivity(data);
                          }}
                          fullWidth
                          className={classes.ReadMoreButton}
                        >
                          Read More
                        </Button>
                      </Grid>
                    </Box>
                  </Card>
                </Grid>
              );
            })
          ) : (
            <React.Fragment>
              {formState.NoActivityData === true ? (
                <p className={classes.alignCenter}>No upcoming Activity</p>
              ) : (
                <Spinner />
              )}
            </React.Fragment>
          )}
        </Grid>
      </Grid>
    </Grid>
  );
}
Example #27
Source File: ForgotPassword.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
ForgotPassword = props => {
  const [openBackdrop, setOpenBackdrop] = React.useState(false);
  const [open, setOpen] = React.useState(true);
  const theme = useTheme();
  const history = useHistory();
  const classes = useStyles();
  const [isOtpVerificationFailed, setIsOtpVerificationFailed] = React.useState(
    false
  );

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

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

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

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

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

  function checkAllKeysPresent(obj) {
    let areFieldsValid = false;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return <div style={{padding: 16, margin: 'auto', maxWidth: 800}}>
            <CssBaseline/>
            <Grid container>
                <Grid item xs={12}>
                    <Typography variant="h4" component="h1" >
                        Algorand {NETWORK} Dispenser
                    </Typography>
                </Grid>
                <Grid container item xs={6}>
                    <ReCAPTCHA
                        ref={this._reCaptchaRef}
                        onChange={this.onCaptchaChange}
                        sitekey={TEST_SITE_KEY}
                        size="normal"
                        asyncScriptOnLoad={this.asyncScriptOnLoad}
                    >
                    </ReCAPTCHA>
                </Grid>
                <Grid container item xs={6}>
                    <CardMedia
                        component="img"
                        alt="Algorand Logo"
                        height="150"
                        image={algorandImage}
                        title="Algorand"
                    />
                </Grid>
            </Grid>


            <Typography xs={6} gutterBottom>
                {`Fund your Algorand ${NETWORK} Account`}
            </Typography>
            <Form
                onSubmit={this.onSubmit}
                initialValues={{account: this.providedAccount}}
                validate={this.validate}

                render={({handleSubmit, reset, submitting, pristine, values}) => (
                    <form onSubmit={handleSubmit} noValidate>
                        <Paper style={{padding: 16}}>

                            <Grid container alignItems="flex-start" spacing={2}>

                                <Grid container item xs={5}>
                                    <RadioButtonsGroup {...this.state} onAssetChange={this.updateAsset.bind(this)}/>
                                </Grid>
                                <Grid item xs={2}>
                                    <CircularProgress variant={this.state.progressVariant} progress={0}/>
                                </Grid>
                                <Grid container item xs={5}>
                                    <Grid container alignItems="flex-start" spacing={2}>
                                        <Grid container item xs={12}>
                                            <Typography gutterBottom>
                                                {this.state.algoAccountBalance}
                                            </Typography>
                                        </Grid>
                                        <Grid container item xs={12}>
                                            <Typography gutterBottom>
                                                {this.state.usdcAccountBalance}
                                            </Typography>
                                        </Grid>
                                    </Grid>
                                </Grid>
                                <Grid container item xs={12}>
                                    <Field
                                        fullWidth
                                        name="account"
                                        component={TextField}
                                        label="Algorand Account"
                                        variant="outlined"
                                        value={this.state.account}
                                    />
                                </Grid>

                                <Grid container item xs={12}>
                                    <Button
                                        variant="contained"
                                        color="primary"
                                        type="submit"
                                        disabled={!(this.state.captchaOK && this.state.formValid && this.state.active)}
                                    >
                                        Dispense
                                    </Button>
                                </Grid>

                            </Grid>
                        </Paper>
                    </form>
                )}
            />
            <Grid container>
                <Grid container item xs={12}>
                    <Typography gutterBottom>
                        {"Account Address: "}
                        <Link
                            href={`https://${NETWORK}.algoexplorer.io/address/${this.state.account}`}
                            variant="inherit"
                            color="primary"
                            target="_blank"
                            rel="noreferrer"
                        >
                            {this.state.account}
                        </Link>
                    </Typography>
                </Grid>
                <Grid container item xs={12}>
                    <Typography gutterBottom>
                        {"Transaction ID: "}
                        <Link
                            href={`https://${NETWORK}.algoexplorer.io/tx/${this.state.transactionId}`}
                            variant="inherit"
                            color="primary"
                            target="_blank"
                            rel="noreferrer"
                        >
                            {this.state.transactionId}
                        </Link>
                    </Typography>
                </Grid>
            </Grid>
        </div>
    }