recharts#Pie JavaScript Examples

The following examples show how to use recharts#Pie. 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: OrgPieChart.js    From study-chain with MIT License 6 votes vote down vote up
render() {
    const { data } = this.state;
    const { classes } = this.props;
    return (
      <div className={classes.container}>
        <PieChart width={485} height={290} className={classes.chart}>
          <Legend align="right" height={10} />
          <Pie
            data={data}
            dataKey="value"
            nameKey="name"
            cx="50%"
            cy="50%"
            outerRadius={90}
            label
            fill="fill"
          />
          <Tooltip />
        </PieChart>
      </div>
    );
  }
Example #2
Source File: Chart.js    From dnd-builder with MIT License 6 votes vote down vote up
ChartPie = () => (
  <ResponsiveContainer>
    <PieChart
      height={300}
      width={400}
    >
      <Pie
        data={data}
        dataKey="value"
        isAnimationActive={false}
      >
        {data.map((entry, index) => (
          <Cell
            key={`cell-${index.toString()}`}
            fill={COLORS[index % COLORS.length]}
          />
        ))}
      </Pie>
      <Legend height={36} />
    </PieChart>
  </ResponsiveContainer>
)
Example #3
Source File: AirlineFlightsInfo.js    From dev-example-flights with MIT License 6 votes vote down vote up
render() {
        const { airline_delays, delays_comparison } = this.state;

        return (
            <div className="charts-main">
                <div className="form-sub-header">
                    { !!(this.props.airline) ? this.props.airline.name : ''}
                </div>
                <div>
                    <div className="inline-div-50">
                        <p class="charts-title">Delay % By Type</p>
                        <PieChart className="form-content" width={400} height={300}>
                            <Pie isAnimationActive={false} data={airline_delays} cx={200} cy={125} outerRadius={80} fill="#8884d8" label>
                                {
                                    airline_delays.map((entry, index) => (
                                        <Cell key={`cell-${index}`} fill={this.colors[index]}/>
                                    ))
                                }
                            </Pie>
                            <Tooltip/>
                            <Legend align="center" />
                        </PieChart>
                    </div>
                    <div className="inline-div-50">
                        <p class="charts-title">Airline (avg minutes) delays vs. All (avg minutes) delays </p>
                        <BarChart className="Form-content" width={400} height={300} data={delays_comparison}>
                            <CartesianGrid strokeDasharray="3 3" />
                            <XAxis dataKey="name" />
                            <YAxis />
                            <Tooltip />
                            <Legend align="center" />
                            <Bar dataKey="Target" fill="#96DDCF" />
                            <Bar dataKey="Average" fill="#0E6488" />
                        </BarChart>
                    </div>
                </div>
            </div>
        );
    }
Example #4
Source File: MainSurveyPie.js    From front-app with MIT License 6 votes vote down vote up
MainSurveyPie = ({ datas, title }) => {
  const sorted = datas.slice(0).sort(function (a, b) {
    return a.count > b.count ? -1 : a.count < b.count ? 1 : 0
  })

  const getColor = (i) => {
    return i > 4 ? COLORS[4] : COLORS[i]
  }

  return (
    <div className="main-survey-pie">
      <PieChart width={374} height={200}>
        <text style={{ fontWeight: '700' }} x={105} y={105} textAnchor="middle" dominantBaseline="middle">
          {title}
        </text>
        <Pie innerRadius={30} outerRadius={80} data={datas} cx={100} cy={100} labelLine={false} fill="#8884d8" dataKey="count" valueKey="name">
          {datas.map((entry, index) => {
            const color = getColor(sorted.indexOf(entry))
            return <Cell name={entry.name} key={`cell-${index}`} fill={color} />
          })}
        </Pie>
        <Tooltip />
        <Legend />
      </PieChart>
    </div>
  )
}
Example #5
Source File: OftadehPieChart.jsx    From oftadeh-react-admin with MIT License 6 votes vote down vote up
render() {
    return (
      <div style={{ width: "99%", height: 300 }}>
        <ResponsiveContainer>
          <PieChart>
            <Pie
              data={data}
              // cx={200}
              // cy={200}
              labelLine={false}
              label={renderCustomizedLabel}
              outerRadius={80}
              fill="#8884d8"
              dataKey="value"
            >
              {data.map((entry, index) => (
                <Cell
                  key={`cell-${index}`}
                  fill={COLORS[index % COLORS.length]}
                />
              ))}
            </Pie>
          </PieChart>
        </ResponsiveContainer>
      </div>
    );
  }
Example #6
Source File: PieCharts.js    From gedge-platform with Apache License 2.0 6 votes vote down vote up
PieCharts = observer(() => {
  return (
    <div>
      <PieChart width={80} height={80}>
        <Pie
          data={data01}
          dataKey="value"
          nameKey="name"
          cx="50%"
          cy="50%"
          innerRadius={15}
          fill="#ff0000"
          // fill="#8884d8"
        />
      </PieChart>
    </div>
  );
})
Example #7
Source File: RechartsPieChart.js    From sofia-react-template with MIT License 6 votes vote down vote up
RechartsPieChart = () => {

  return (
    <div style={{ height: "316px" }}>
      <ResponsiveContainer width="100%" height={200}>
        <PieChart >
          <Pie
            data={chartsSettings.donut.data}
            innerRadius={50}
            outerRadius={80}
            dataKey="value"
          >
            {chartsSettings.donut.data.map((entry, index) => (
              <Cell key={`cell-${index}`} fill={entry.color} />
            ))}
          </Pie>
        </PieChart>
      </ResponsiveContainer>
      <div className={s.donutLabels}>
        {chartsSettings.donut.data.map((entry, index) => (
          <div key={uuidv4()} className={s.label}>
            <Dot color={entry.color} />
            <span className="body-3 ml-2">{entry.name}</span>
          </div>
        ))}
      </div>
    </div>
  )
}
Example #8
Source File: OrdersChart.js    From DMS_React with GNU Affero General Public License v3.0 6 votes vote down vote up
OrdersChart = () => (
  <ResponsiveContainer width="100%" height={350}>
    <PieChart>
      <Legend/>
      <Pie dataKey="value"
           data={data01} cx={200} cy={200} innerRadius={70} outerRadius={90} fill="#3367d6" label>
        {
          data01.map((entry, index) => <Cell key={index} fill={COLORS[index % COLORS.length]}/>)
        }
      </Pie>
    </PieChart>
  </ResponsiveContainer>
)
Example #9
Source File: VulnerabilitiesByCategoryStatsWidget.js    From web-client with Apache License 2.0 6 votes vote down vote up
VulnerabilitiesByCategoryStatsWidget = ({ projectId = null }) => {
    const url = '/vulnerabilities/stats?groupBy=category' + (null !== projectId ? '&projectId=' + encodeURIComponent(projectId) : '');
    const [vulnerabilitiesByCategoryStats] = useFetch(url)

    return <DashboardWidget title="Vulnerabilities by category">

        {vulnerabilitiesByCategoryStats && vulnerabilitiesByCategoryStats.length > 0 ?
            <PieChart width={320} height={320}>
                <Pie
                    data={vulnerabilitiesByCategoryStats}
                    dataKey="total"
                    cx={160}
                    cy={160}
                    labelLine={true}
                    innerRadius={50}
                    outerRadius={80}
                    paddingAngle={5}
                    fill="#82ca9d"
                    label={({ index }) =>
                        `${vulnerabilitiesByCategoryStats[index].category_name} (${vulnerabilitiesByCategoryStats[index].total})`
                    }
                    labelStyle={{ fill: '#ffffff' }}
                >
                </Pie>
            </PieChart> :
            <p>No enough data to generate the chart.</p>
        }
    </DashboardWidget>
}
Example #10
Source File: index.js    From tracker with MIT License 6 votes vote down vote up
export function CustomPieChart(props)
{
  const [activeIndex, setActiveIndex]= useState('0');

  const onPieEnter = (data, index) =>
  {
    setActiveIndex(index);
  };

  return (
    <div className='box-border shadow-lg bg-white m-4 w-auto inline-block'>
      <div className='bg-gray-100 p-4 text-lg text-blue-500'>
        {props.heading}
      </div>
      <div className='justify-center'>
        <PieChart width={400} height={400}>
          <Pie activeIndex={activeIndex}
               activeShape={renderActiveShape}
               data={props.data}
               cx={200}
               cy={200}
               innerRadius={60}
               outerRadius={80}
               fill="#8884d8"
               dataKey="value"
               onMouseEnter={()=> onPieEnter}/>
        </PieChart>
      </div>
    </div>
    );
}
Example #11
Source File: week.js    From stacker.news with MIT License 6 votes vote down vote up
function GrowthPieChart ({ data }) {
  return (
    <ResponsiveContainer width='100%' height={250} minWidth={200}>
      <PieChart margin={{ top: 5, right: 5, bottom: 5, left: 5 }}>
        <Pie
          dataKey='value'
          isAnimationActive={false}
          data={data}
          cx='50%'
          cy='50%'
          outerRadius={80}
          fill='var(--secondary)'
          label
        >
          {
            data.map((entry, index) => (
              <Cell key={`cell-${index}`} fill={COLORS[index]} />
            ))
          }
        </Pie>
        <Tooltip />
      </PieChart>
    </ResponsiveContainer>
  )
}
Example #12
Source File: SystemStatisticsPie.js    From SaraAlert with Apache License 2.0 6 votes vote down vote up
render() {
    return (
      <React.Fragment>
        <Card className="card-square">
          <Card.Header as="h5">System Statistics</Card.Header>
          <Card.Body className="pb-1">
            <Row className="text-center">
              <Col className="">
                <h4 className="mb-0"> Total Monitorees </h4>
                <div style={{ width: '100%', height: 250 }} className="recharts-wrapper">
                  <ResponsiveContainer>
                    <PieChart onMouseEnter={this.onPieEnter}>
                      <Pie data={this.data} innerRadius={55} outerRadius={85} fill="#8884d8" paddingAngle={2} dataKey="value">
                        {this.data.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={this.getColorForType(entry)} />
                        ))}
                        <Label className="display-5" value={this.props.stats.system_subjects} position="center" />
                      </Pie>
                      <Legend layout="vertical" align="right" verticalAlign="middle">
                        {' '}
                      </Legend>
                      <Tooltip />
                    </PieChart>
                  </ResponsiveContainer>
                </div>
                <div className="text-muted">
                  {this.percentageChange > 0
                    ? `Count is up ${this.props.stats.system_subjects_last_24} (${this.percentageChange}%) within last 24 hours`
                    : null}
                </div>
              </Col>
            </Row>
          </Card.Body>
        </Card>
      </React.Fragment>
    );
  }
Example #13
Source File: SubjectStatus.js    From SaraAlert with Apache License 2.0 6 votes vote down vote up
render() {
    const data = [...this.props.stats.subject_status];
    const COLORS = ['#39CC7D', '#FCDA4B', '#FF6868', '#6C757D'];

    return (
      <React.Fragment>
        <Card className="card-square">
          <Card.Header as="h5">Monitoree Status</Card.Header>
          <Card.Body>
            <div style={{ width: '100%', height: 260 }} className="recharts-wrapper">
              <ResponsiveContainer>
                <PieChart onMouseEnter={this.onPieEnter}>
                  <Pie data={data} innerRadius={70} outerRadius={100} fill="#8884d8" paddingAngle={2} dataKey="value" label>
                    {data.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                    <Label className="display-5" value={this.props.stats.system_subjects} position="center" />
                  </Pie>
                  <Legend layout="vertical" align="right" verticalAlign="middle" />
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            </div>
          </Card.Body>
        </Card>
      </React.Fragment>
    );
  }
Example #14
Source File: OverviewStats.js    From rhino with GNU Affero General Public License v3.0 5 votes vote down vote up
render() {
    return (
      <Column flexGrow={1} className={css(styles.container)} horizontal='center'>
        <Row horizontal='center' className={css(styles.fullwidth)}>
          <Column flexGrow={1} vertical='center' horizontal='center' className={css(styles.cards)}>
            Active tasks: {this.state.active_number}
          </Column>
          <Column className={css(styles.separatorwidth)}> </Column>
          <Column flexGrow={1} vertical='center' horizontal='center' className={css(styles.cards)}>
            Reserved tasks: {this.state.reserved_number}
          </Column>
          <Column className={css(styles.separatorwidth)}> </Column>
          <Column flexGrow={1} vertical='center' horizontal='center' className={css(styles.cards)}>
            Total tasks:  {this.state.succeed_number}
          </Column>
        </Row>
        <Row className={css(styles.separatorheight)}> </Row>
        <Row flexGrow={1} horizontal='center' className={css(styles.fullwidth)}>
          <Column flexGrow={1} vertical='center' horizontal='center' className={css(styles.with_c1)}>
            <ResponsiveContainer width="99%" aspect={3}>
              <LineChart data={this.state.data} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
                <XAxis dataKey="time" />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="tasks" stroke="#42494F" />
              </LineChart>
            </ResponsiveContainer>
          </Column>
          <Column className={css(styles.separatorwidth)}> </Column>
          <Column flexGrow={1} vertical='center' horizontal='center' className={css(styles.with_c2)}>
            <ResponsiveContainer width="99%" aspect={1} >
              <PieChart>
                <Pie dataKey="value" isAnimationActive={false} data={this.state.tasks} stroke="#444444" fill="#ffffff" />
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </Column>
        </Row>
        <Row className={css(styles.separatorheight)}> </Row>
        {this.state.results.length > 0 && this.state.results.map(function (item) {
          return (<div key={item.uuid} className={css(styles.fullwidth)}>
            <Row className={css(styles.listofrows)}>
              <Column flexGrow={1} vertical='center' horizontal='start' className={css(styles.cardinputoverflow)}>
                <ReactJson src={item} />
              </Column>
              <Column flexGrow={1} vertical='center' horizontal='end' className={css(styles.cardinput)}>
                <img src={backendurls.screenshot + item.uuid} alt="" height="140" width="220" />
              </Column>
            </Row>
            <Row className={css(styles.separatorheight)}> </Row></div>)
        })}
        {this.state.flashmessage.msg !== "" ? <LoadingSpinner close={false} key={this.state.flashmessage.random} timeout="5" msg={this.state.flashmessage.msg} keep={true} spinner={this.state.flashmessage.spinner} /> : ""}
      </Column>
    );
  }
Example #15
Source File: VulnerabilitiesByRiskStatsWidget.js    From web-client with Apache License 2.0 5 votes vote down vote up
VulnerabilitiesByRiskStatsWidget = ({ projectId = null }) => {
    const RADIAN = Math.PI / 180;

    const RISKS = {
        'none': { label: 'None', color: '#f3f3f3' },
        'low': { label: 'Low', color: 'var(--green)' },
        'medium': { label: 'Medium', color: 'var(--yellow)' },
        'high': { label: 'High', color: 'var(--purple)' },
        'critical': { label: 'Critical', color: 'var(--primary-color)' }
    };

    const renderCustomLabel = ({
        cx, cy, midAngle, innerRadius, outerRadius, percent, index,
    }) => {
        const radius = innerRadius + (outerRadius - innerRadius) * 1.2;
        const x = cx + radius * Math.cos(-midAngle * RADIAN);
        const y = cy + radius * Math.sin(-midAngle * RADIAN);

        return (
            <text x={x} y={y} fill="white" textAnchor={x > cx ? 'start' : 'end'} dominantBaseline="central">
                {`${RISKS[vulnerabilitiesByRiskStats[index].risk].label} (${vulnerabilitiesByRiskStats[index].total})`}
            </text>
        );
    };

    const url = '/vulnerabilities/stats?groupBy=risk' + (null !== projectId ? '&projectId=' + encodeURIComponent(projectId) : '');
    const [vulnerabilitiesByRiskStats] = useFetch(url)

    return <DashboardWidget title="Vulnerabilities by risk">

        {vulnerabilitiesByRiskStats && vulnerabilitiesByRiskStats.length > 0 ?
            <PieChart width={400} height={320} >
                <Pie
                    data={vulnerabilitiesByRiskStats}
                    dataKey="total"
                    cx={160}
                    cy={160}
                    labelLine={false}
                    outerRadius={100}
                    strokeOpacity='0'
                    strokeWidth='var(--borderWidth)'
                    color='var(--bg-color)'
                    fill="#8884d8"
                    label={renderCustomLabel}
                >
                    {
                        vulnerabilitiesByRiskStats && vulnerabilitiesByRiskStats.map((entry, index) =>
                            <Cell key={index} fill={RISKS[entry.risk].color} />
                        )
                    }
                </Pie>
            </PieChart> :
            <p>No enough data to generate the chart.</p>
        }
    </DashboardWidget>
}
Example #16
Source File: index.js    From bank-client with MIT License 5 votes vote down vote up
export default function Savings() {
  const dispatch = useDispatch();
  const { savings, savingsData, savingsColors, isLoading } = useSelector(
    stateSelector,
  );

  const getSavings = () => dispatch(getAccountBalanceAction());

  useEffect(() => {
    if (!savings) getSavings();
  }, []);

  const pieChart = (
    <PieChart margin={0} width={200} height={61}>
      <Pie
        data={savingsData}
        dataKey="value"
        innerRadius={75}
        outerRadius={80}
        paddingAngle={0}
      >
        {savingsData?.map((entry, index) => (
          <Cell
            key={`cell-${index}`}
            fill={savingsColors[index % savingsColors.length]}
          />
        ))}
      </Pie>
    </PieChart>
  );

  return (
    <FormattedMessage {...messages.savings}>
      {(title) => (
        <Widget
          pie="true"
          title={title}
          unit="%"
          content={savings}
          isLoading={isLoading}
          svg={pieChart}
        />
      )}
    </FormattedMessage>
  );
}
Example #17
Source File: SwapPieChart.js    From admin-web with GNU Affero General Public License v3.0 5 votes vote down vote up
render() {
    const { classes, swap, swapPercent } = this.props;

    return (
      <div>
        <Typography className={classes.chartTitle}>
          Swap: {swap.length > 0 && swap[1].value ? swapPercent + '%' : 'None'}
        </Typography>
        <ResponsiveContainer width="100%" height={180}>
          <PieChart height={150}>
            <defs>
              <linearGradient id="gradientGreen" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor={"#56ab2f"} stopOpacity={1}/>
                <stop offset="95%" stopColor={"#a8e063"} stopOpacity={1}/>
              </linearGradient>
              <linearGradient id="gradientBlue" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor={"#2980B9"} stopOpacity={1}/>
                <stop offset="95%" stopColor={"#6DD5FA"} stopOpacity={1}/>
              </linearGradient>
              <linearGradient id="gradientOrange" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor={"#FFB75E"} stopOpacity={1}/>
                <stop offset="95%" stopColor={"#ED8F03"} stopOpacity={1}/>
              </linearGradient>
              <linearGradient id="gradientGrey" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor={"#8e9eab"} stopOpacity={1}/>
                <stop offset="95%" stopColor={"#eef2f3"} stopOpacity={1}/>
              </linearGradient>
            </defs>
            <Pie
              data={swap}
              dataKey="value"
              nameKey="name"
              startAngle={180}
              endAngle={-180}
              cx="50%"
              cy="50%"
              innerRadius={30}
              outerRadius={50}
              label={data => this.formatLabel(data.payload.value)}
              minAngle={1}
              stroke={"none"}
              isAnimationActive={false}
            >
              {swap.map((entry, index) => 
                <Cell
                  key={`cell-${index}`}
                  fill={`url(#${entry.color})`}
                />
              )}
            </Pie>
            {swap.length > 0 && swap[1].value && <Tooltip
              formatter={this.formatLabel}
              isAnimationActive={true}
            />}
            {swap.length > 0 && swap[1].value && <Legend />}
          </PieChart>
        </ResponsiveContainer>
      </div>
    );
  }
Example #18
Source File: MemoryPieChart.js    From admin-web with GNU Affero General Public License v3.0 5 votes vote down vote up
function MemoryPieChart(props) {
  const { classes, memory } = props;

  const formatLabel = (value, descimals) => {
    if (value > 1000000000) return (value / 1000000000).toFixed(descimals) + 'GB';
    if (value > 1000000) return (value / 1000000).toFixed(descimals) + 'MB';
    if (value > 1000) return (value / 1000).toFixed(descimals) + 'KB';
    return value + 'B';
  };

  const formatLastMemory = (unformatted) => {
    return [
      { name: 'free', value: unformatted.free, color: "gradientBlue" },
      { name: 'used', value: unformatted.used, color: "gradientGreen" },
      { name: 'cache', value: unformatted.cache, color: "gradientOrange" },
      { name: 'buffer', value: unformatted.buffer, color: "gradientGrey" },
    ];
  };

    
  const lastMemory = memory.length > 0 ? formatLastMemory(memory[memory.length - 1]) : [];
  return (
    <div>
      <Typography className={classes.chartTitle}>
        {memory.length > 0 && `Memory: ${memory[memory.length - 1].percent}%`}
      </Typography>
      <ResponsiveContainer width="100%" height={180}>
        <PieChart height={150}>
          <defs>
            <linearGradient id="gradientGreen" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor={"#56ab2f"} stopOpacity={1}/>
              <stop offset="95%" stopColor={"#a8e063"} stopOpacity={1}/>
            </linearGradient>
            <linearGradient id="gradientBlue" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor={"#2980B9"} stopOpacity={1}/>
              <stop offset="95%" stopColor={"#6DD5FA"} stopOpacity={1}/>
            </linearGradient>
            <linearGradient id="gradientOrange" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor={"#ED8F03"} stopOpacity={1}/>
              <stop offset="95%" stopColor={"#FFB75E"} stopOpacity={1}/>
            </linearGradient>
            <linearGradient id="gradientGrey" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor={"#8e9eab"} stopOpacity={1}/>
              <stop offset="95%" stopColor={"#eef2f3"} stopOpacity={1}/>
            </linearGradient>
          </defs>
          <Pie
            data={lastMemory}
            dataKey="value"
            nameKey="name"
            startAngle={180}
            endAngle={540}
            cx="50%"
            cy="50%"
            innerRadius={30}
            outerRadius={50}
            fill={green['500']}
            stroke={"none"}
            label={data => formatLabel(data.payload.value)}
            isAnimationActive={false}
            margin={{ top: 0, right: 32, left: 10, bottom: 16 }}
          >
            {lastMemory.map((entry, index) => 
              <Cell
                className={classes.test}
                key={`cell-${index}`}
                fill={`url(#${entry.color})`}
              />
            )}
          </Pie>
          <Tooltip
            formatter={formatLabel}
            isAnimationActive={true}
          />
          <Legend />
        </PieChart>
      </ResponsiveContainer>
    </div>
  );
}
Example #19
Source File: CPUPieChart.js    From admin-web with GNU Affero General Public License v3.0 5 votes vote down vote up
function CPUPieChart(props) {
  const { classes, cpuPercent } = props;
  

  const formatLastCPU = (unformatted) => {
    return [
      { name: 'user', value: unformatted.user, color: "gradientGreen" },
      { name: 'system', value: unformatted.system, color: "gradientRed" },
      { name: 'io', value: unformatted.io, color: "gradientGrey" },
      { name: 'steal', value: unformatted.steal, color: "gradientBlue" },
      { name: 'interrupt', value: unformatted.interrupt, color: "gradientOrange" },
      { name: 'idle', value: unformatted.idle, color: "gradientBlue" },
    ].filter(obj => obj.value !== 0);
  };
    
  const lastCpu = cpuPercent.length > 0 ? formatLastCPU(cpuPercent[cpuPercent.length -1]) : [];
  return (
    <div>
      <Typography className={classes.chartTitle}>
        {cpuPercent.length > 0 && `CPU: ${(100 - cpuPercent[cpuPercent.length - 1].idle).toFixed(1)}%`}
      </Typography>
      <ResponsiveContainer width="100%" height={180}>
        <PieChart height={150}>
          <defs>
            <linearGradient id="gradientGreen" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor={"#56ab2f"} stopOpacity={1}/>
              <stop offset="95%" stopColor={"#a8e063"} stopOpacity={1}/>
            </linearGradient>
            <linearGradient id="gradientBlue" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor={"#2980B9"} stopOpacity={1}/>
              <stop offset="95%" stopColor={"#6DD5FA"} stopOpacity={1}/>
            </linearGradient>
            <linearGradient id="gradientOrange" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor={"#FFB75E"} stopOpacity={1}/>
              <stop offset="95%" stopColor={"#ED8F03"} stopOpacity={1}/>
            </linearGradient>
            <linearGradient id="gradientGrey" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor={"#8e9eab"} stopOpacity={1}/>
              <stop offset="95%" stopColor={"#eef2f3"} stopOpacity={1}/>
            </linearGradient>
            <linearGradient id="gradientRed" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor={"#FF512F"} stopOpacity={1}/>
              <stop offset="95%" stopColor={"#DD2476"} stopOpacity={1}/>
            </linearGradient>
          </defs>
          <Pie
            data={lastCpu}
            dataKey="value"
            nameKey="name"
            startAngle={180}
            endAngle={-180}
            cx="50%"
            cy="50%"
            innerRadius={30}
            outerRadius={50}
            label
            minAngle={1}
            stroke={"none"}
            isAnimationActive={false}
          >
            {lastCpu.map((entry, index) =>
              <Cell
                key={`cell-${index}`}
                fill={`url(#${entry.color}`}
              />
            )}
          </Pie>
          <Tooltip
            isAnimationActive={true}
          />
          <Legend />
        </PieChart>
      </ResponsiveContainer>
    </div>
  );
}
Example #20
Source File: PieChart.js    From gitlab-lint-react with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
WalletPieChart = ({ data, outerRadius }) => {
  const theme = useTheme();
  const RADIAN = Math.PI / 180;
  const renderCustomizedLabel = ({
    cx,
    cy,
    midAngle,
    innerRadius,
    outerRadius,
    index,
    name,
  }) => {
    const radius = 25 + innerRadius + (outerRadius - innerRadius);
    const x = cx + radius * Math.cos(-midAngle * RADIAN);
    const y = cy + radius * Math.sin(-midAngle * RADIAN);

    return (
      <text
        x={x}
        y={y}
        textAnchor={x > cx ? "start" : "end"}
        dominantBaseline="central"
        style={{ fill: theme.palette.secondary.main }}
      >
        {name}
      </text>
    );
  };

  return (
    <ResponsiveContainer>
      <PieChart>
        <Pie
          data={data}
          cx="50%"
          cy="50%"
          outerRadius={outerRadius}
          dataKey="value"
          label={renderCustomizedLabel}
        >
          {data.map((entry, index) => (
            <Cell
              key={`cell-${index}`}
              fill={chartColors[index % chartColors.length]}
            />
          ))}
        </Pie>
        <Tooltip content={<ChartTooltip />} />
      </PieChart>
    </ResponsiveContainer>
  );
}
Example #21
Source File: ourImpact.js    From Girscript-Community-Website with MIT License 5 votes vote down vote up
ourImpact = () => {
  
    const data01 = require("../../Test_data/ourImpactPiChartData.js").data01;
    return (
      <div> 
        <h1 className="our_impact" ><b>OUR IMPACT</b></h1>
        
        <div className="our_impact_outerdiv" >
        <a href="#" >
        <div className="hover_effect1 " >
          <b>Learn More</b>
        </div>
        </a>
        
        <div className="our_impact_div1" >
          <div className="our_impact_div11 our_impact_innerdiv"><b>25K</b><br/>Students</div>
          <div className="our_impact_div12 our_impact_innerdiv" ><b>25K</b><br/>Students</div>
          <div className="our_impact_div13 our_impact_innerdiv" ><b>25K</b><br/>Students</div>
          <div className="our_impact_div14 our_impact_innerdiv" ><b>25K</b><br/>Students</div>
          <div className="our_impact_div15 our_impact_innerdiv" ><b>25K</b><br/>Students</div>
          <p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p>
        </div>
        
  
        <a href="#" >
        <div className="hover_effect2 " >
          <b>Learn More</b>
        </div>
        </a>
        <div className="our_impact_div2" >
        
          <ResponsiveContainer width="100%" height="62%">
          <PieChart width={400} height={400}>
            <Pie data={data01} dataKey="value" cx="50%" cy="50%" outerRadius={60} fill="#9844d8" />
          </PieChart>
        </ResponsiveContainer>
  
          <p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p>
        </div>
     
        </div>
        
        </div>
    );
  }
Example #22
Source File: PieChart.jsx    From cosmoscan-front with Apache License 2.0 5 votes vote down vote up
PieChart = ({
  isLoading,
  data,
  valFormatter,
  labelFormatter,
  height,
  isAnimationActive,
  minAngle,
  displayLegend,
  cellColors,
  growOnMobile,
  displayTooltip,
}) => (
  <ChartWrapper defaultHeight={height} growOnMobile={growOnMobile}>
    {/* eslint-disable-next-line no-nested-ternary */}
    {isLoading ? (
      <div className="d-flex justify-content-center align-items-center h-100">
        <Spinner />
      </div>
    ) : data && data.length ? (
      <ResponsiveContainer>
        <PieChartStyled>
          {displayTooltip && <Tooltip formatter={valFormatter} />}
          {displayLegend && (
            <Legend
              align="left"
              iconType="circle"
              verticalAlign="top"
              wrapperStyle={{
                fontWeight: 700,
                textTransform: 'uppercase',
              }}
            />
          )}
          <Pie
            data={data}
            dataKey="value"
            nameKey="title"
            minAngle={minAngle}
            label={labelFormatter}
            unit=" %"
            isAnimationActive={isAnimationActive}
          >
            {data.map((entry, index) => (
              <Cell
                key={entry.title}
                fill={cellColors[index % cellColors.length]}
              />
            ))}
          </Pie>
        </PieChartStyled>
      </ResponsiveContainer>
    ) : (
      <div className="d-flex justify-content-center align-items-center h-100">
        No data
      </div>
    )}
  </ChartWrapper>
)
Example #23
Source File: DashboardPieChart.js    From crypto-red.github.io with MIT License 5 votes vote down vote up
render() {

        const { classes, logged_account, coins_markets, _pie_chart_active_index, balance, portfolio } = this.state;

        let pie_data = [ ];

        if(Boolean(logged_account) && coins_markets.length) {

            Object.entries(balance).forEach(entry => {

                const [key, value] = entry;

                let coin_market = null;
                for (let i = 0; i < coins_markets.length; i++) {

                    if(coins_markets[i].id === key) {
                        coin_market = coins_markets[i];
                    }
                }

                if(coin_market !== null && value > 0) {

                    pie_data.push({
                        name: coin_market.name,
                        value: value * coin_market.current_price
                    });
                }
            });
        }

        return (
            <div className={classes.cardContainer}>
                <Fade in>
                    <Card className={classes.balanceCard}>
                        <CardHeader title={t( "components.dashboard_pie_chart.title")} />
                        <CardContent className={classes.cardContent}>
                            {coins_markets.length > 0 && portfolio ?
                                <Fade in>
                                    <div className={classes.pieChart}>
                                        {pie_data.length !== 0 ?
                                            <ResponsiveContainer>
                                                <PieChart width={400} height={400}>
                                                    <Pie
                                                        activeIndex={_pie_chart_active_index}
                                                        activeShape={(props) => this._render_active_shape(props, portfolio.total_balance_currency)}
                                                        data={pie_data}
                                                        cx="50%"
                                                        cy="50%"
                                                        innerRadius={75}
                                                        outerRadius={100}
                                                        fill="#1c1882"
                                                        dataKey="value"
                                                        onMouseEnter={this._on_pie_enter}
                                                    />
                                                </PieChart>
                                            </ResponsiveContainer>
                                            : Boolean(pie_data.length <= 0) ?
                                                <div className={classes.noTransactionCardContent}>
                                                    <img className={classes.noTransactionImage} src="/src/images/segment.svg"/>
                                                    <p>{t( "sentences.no transaction maid portfolio")}</p>
                                                </div>
                                                :null
                                        }
                                    </div>
                                </Fade>
                                :
                                <div className={classes.pieChartSkeletonContainer}>
                                    <Skeleton variant={"circle"} className={classes.pieChartSkeleton}/>
                                </div>
                            }
                        </CardContent>
                    </Card>
                </Fade>
            </div>
        );
    }
Example #24
Source File: index.js    From tracker with MIT License 5 votes vote down vote up
//TWO LEVEL PIE Chart

export function TwoLevelPieChart(props)
{
  const [COLORSONE, setCOLORSONE] = useState(props.colors01);
  const [COLORSTWO, setCOLORSTWO] = useState(props.colors02);

  const totalNumber = (data) =>
  {
    let count=0;
    data.forEach((item, i) => {
      count= count+item.value
    });
    return count;
  }
  const renderLegend = (legendName, data, colors) => {
   return (
     <div class="justify-center">
       <div class="m-4 mb-0">
          <div class="text-left">{legendName}</div>
          <div class='flex'>
            {data.map((legend, index) =>
            index <= data.length &&
            <div class="mr-4">
              <div class="inline-block rounded-full h-3 w-3 items-center justify-center mr-2"
                   style={{backgroundColor : colors[index]}}></div>
              <div class="inline-block">{legend.name}</div>
            </div>)}
          </div>
       </div>
    </div>
   );}

   return (
      <div className='box-border shadow-lg bg-white w-full max-w-sm sm:max-w-sm md:max-w-md lg:max-w-sm xl:max-w-xl ml-auto mr-auto'>
        <div className='bg-gray-100 p-4 text-lg font-serif text-blue-500 h-20'>
          {props.heading}
        </div>
        <div className='justify-center'>
          <div className='-mt-3'>
            <PieChart width={400} height={350} style={{marginLeft:"auto", marginRight: "auto"}}>
              <Pie data={props.data02} dataKey="value" cx={200} cy={200} innerRadius={70} outerRadius={90} fill="#82ca9d" label>
                  {props.data02.map((entry, index) =>
                  <Cell key={`cell-${index}`} fill={COLORSTWO[index % COLORSTWO.length]} />)}
              </Pie>
              <Tooltip />
              <Legend content={renderLegend(props.legend02, props.data02, props.colors02)} verticalAlign="top" height={10}/>
            </PieChart>
          </div>
          <div className='-mt-3'>
            <PieChart width={400} height={350} style={{marginLeft:"auto", marginRight: "auto"}}>
              <Pie data={props.data01} dataKey="value" cx={200} cy={200} innerRadius={70} outerRadius={90} fill="#82ca9d" label>
                  {props.data01.map((entry, index) =>
                  <Cell key={`cell-${index}`} fill={COLORSONE[index % COLORSONE.length]} />)}
              </Pie>
              <Tooltip />
              <Legend content={renderLegend(props.legend01, props.data01, props.colors01)} verticalAlign="top" height={10}/>
            </PieChart>
          </div>
        </div>
      </div>
  );}
Example #25
Source File: OverAllWidget.js    From covid-19 with MIT License 5 votes vote down vote up
WorldData = props => {
    const loading = props.loading;
    const data = props.data;

    let refinedData = [];
    if (!loading) {
        let keys = Object.keys(data);
        keys.forEach((elem) => {
            if (elem === 'deaths' || elem === 'recovered' || elem === 'active') {
                let obj = {};
                obj['name'] = elem;
                obj['value'] = data[elem];
                refinedData.push(obj);
            }
        });
    }
    const COLORS = ['#DC3545', '#28A745', '#FFC107'];
    return (
        <div className="worldData">
            <Card >
                <Card.Body>
                    <Card.Title>
                        Total Cases: <CurrencyFormat value={data.cases} displayType={'text'} thousandSeparator={true} /> as on <Moment format="YYYY/MM/DD">{data.updated}</Moment>
                    </Card.Title>
                    <Card.Subtitle className="mb-2 text-muted">Recovery, Deaths and Still Infected</Card.Subtitle>
                    <div>
                    {loading ? 
                        <Loader
                            type="ThreeDots"
                            color="#00BFFF"
                            height={100}
                            width={100}
                        /> 
                        :
                        <div>
                            <ResponsiveContainer width='100%' height={308}>
                                <PieChart>
                                    <Pie
                                        dataKey="value"
                                        isAnimationActive={true}
                                        data={refinedData}
                                        cx={180}
                                        cy={150}
                                        outerRadius={100}
                                        fill="#8884d8"
                                        label>
                                        {
                                            refinedData.map((entry, index) => <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />)
                                        }
                                    </Pie>
                                    <Tooltip />
                                </PieChart>
                            </ResponsiveContainer>
                            <div className="legends">
                                <Badge variant="success" className="recovered">
                                    {`Recovered - ${Math.round((data.recovered * 100) / data.cases)}%`}
                                </Badge>
                                <Badge variant="warning" className="medication">
                                    {`Active - ${Math.round(((data.active) * 100) / data.cases)}%`}
                                </Badge>
                                <Badge variant="danger" className="deaths">
                                    {`Deaths - ${Math.round((data.deaths * 100) / data.cases)}%`}
                                </Badge>
                            </div>    
                        </div>
                    }
                    </div>
                </Card.Body>
            </Card>
            
            
        </div>
    )
}
Example #26
Source File: ReportingSummary.js    From SaraAlert with Apache License 2.0 5 votes vote down vote up
render() {
    const COLORS = ['#0088FE', '#00C49F'];
    const data = [...this.props.stats.reporting_summmary];
    const perc = Math.round((this.props.stats.reporting_summmary[0]['value'] / this.props.stats.system_subjects) * 100 * 10) / 10;
    return (
      <React.Fragment>
        <Card className="card-square">
          <Card.Header as="h5">Today&apos;s Reporting Summary</Card.Header>
          <Card.Body>
            <Row className="mx-4 mt-3">
              <Col md="12">
                <Row>
                  <h5>REPORTED TODAY</h5>
                </Row>
                <Row>
                  <h1 className="display-1" style={{ color: '#0088FE' }}>
                    {data[0]['value']}
                  </h1>
                </Row>
                <Row>
                  <h5>NOT YET REPORTED</h5>
                </Row>
                <Row>
                  <h1 className="display-1" style={{ color: '#00C49F' }}>
                    {data[1]['value']}
                  </h1>
                </Row>
              </Col>
              <Col md="12">
                <div style={{ width: '100%', height: '100%' }} className="recharts-wrapper">
                  <ResponsiveContainer>
                    <PieChart onMouseEnter={this.onPieEnter}>
                      <Pie data={data} innerRadius={90} outerRadius={120} fill="#8884d8" paddingAngle={2} dataKey="value">
                        <Label className="display-5" value={perc + '%'} position="center" />
                        {data.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                        ))}
                      </Pie>
                      <Tooltip />
                    </PieChart>
                  </ResponsiveContainer>
                </div>
              </Col>
            </Row>
          </Card.Body>
        </Card>
      </React.Fragment>
    );
  }
Example #27
Source File: Dashboard.jsx    From bull-master with MIT License 4 votes vote down vote up
function Dashboard() {
  const classes = useStyles();
  const [stats, getStats] = useResource(() => ({
    url: '/redis-stats',
    method: 'GET',
  }));
  useInterval(getStats, 4000);
  const [queues, getQueues] = useResource(() => ({
    url: '/queues',
    method: 'GET',
  }));
  useInterval(getQueues, 4000);
  const inQueuePieData = transformStatForPieChart(queues.data?.data || [], [
    'active',
    'paused',
    'delayed',
    'waiting',
  ]);
  const completedPieData = transformStatForPieChart(queues.data?.data || [], [
    'completed',
    'failed',
  ]);
  return (
    <Grid container spacing={3}>
      <Grid item xs={12}>
        <Section>
          <RedisStats stats={stats.data || {}} />
        </Section>
      </Grid>
      <Grid item xs={12} md={6} lg={6}>
        <Section>
          <Title>Currently In Queue</Title>
          <Grid container justify="center">
            <PieChart width={300} height={300}>
              <Pie
                dataKey="value"
                nameKey="name"
                data={inQueuePieData}
                cx={150}
                cy={150}
                paddingAngle={1}
                outerRadius={100}
                fill="#8884d8"
                label
              >
                {inQueuePieData.map((d) => (
                  <Cell key={d.name} fill={COLORS[d.name]} />
                ))}
              </Pie>
              <Tooltip />
            </PieChart>
          </Grid>
          <Grid container justify="center">
            <Title
              variant="body2"
              component="span"
              className={clsx(classes.stat, classes.active)}
            >
              Active - {calculatePercentage(inQueuePieData, 'active')}%
            </Title>
            <Title
              variant="body2"
              component="span"
              className={clsx(classes.stat, classes.delayed)}
            >
              Delayed - {calculatePercentage(inQueuePieData, 'delayed')}%
            </Title>
            <Title
              variant="body2"
              component="span"
              className={clsx(classes.stat, classes.paused)}
            >
              Paused - {calculatePercentage(inQueuePieData, 'paused')}%
            </Title>
          </Grid>
        </Section>
      </Grid>
      <Grid item xs={12} md={6} lg={6}>
        <Section>
          <Title>Finished Jobs</Title>
          <Grid container justify="center">
            <PieChart width={300} height={300}>
              <Pie
                dataKey="value"
                nameKey="name"
                data={completedPieData}
                cx={150}
                cy={150}
                paddingAngle={1}
                outerRadius={100}
                fill="#8884d8"
                label
              >
                {completedPieData.map((d) => (
                  <Cell key={d.name} fill={COLORS[d.name]} />
                ))}
              </Pie>
              <Tooltip />
            </PieChart>
          </Grid>
          <Grid container justify="center">
            <Title
              variant="body2"
              component="span"
              className={clsx(classes.stat, classes.completed)}
            >
              Completed - {calculatePercentage(completedPieData, 'completed')}%
            </Title>
            <Title
              variant="body2"
              component="span"
              className={clsx(classes.stat, classes.failed)}
            >
              Failed - {calculatePercentage(completedPieData, 'failed')}%
            </Title>
          </Grid>
        </Section>
      </Grid>
      <Grid item xs={12}>
        <QueueList queues={queues.data?.data || []} />
      </Grid>
    </Grid>
  );
}
Example #28
Source File: index.js    From ActiveLearningStudio-react-client with GNU Affero General Public License v3.0 4 votes vote down vote up
function DashboardPage(props) {
  const {
    userId,
    firstName,
    metrics,
    getUserMetrics,
    getUserMembership,
  } = props;
  const organization = useSelector((state) => state.organization);
  const { permission } = organization;
  const [showModal, setShowModal] = useState(false);
  const [modalSection, setModalSection] = useState(null);

  const storageData = [
    {
      name: 'Used',
      value: metrics.used_storage,
      color: '#66ddaa',
    },
    {
      name: 'Free',
      value: metrics.total_storage - metrics.used_storage,
      color: '#607a9b',
    },
  ];

  const bandwidthData = [
    {
      name: 'Used',
      value: (metrics.total_bandwidth === 0) ? 0 : metrics.used_bandwidth,
      color: '#66ddaa',
    },
    {
      name: 'Free',
      value: (metrics.total_bandwidth === 0) ? 1 : (metrics.total_bandwidth - metrics.used_bandwidth),
      color: '#607a9b',
    },
  ];

  const usedStoragePercentage = `${Math.round((metrics.used_storage * 100) / metrics.total_storage)}%`;
  const usedBandwidthPercentage = (metrics.total_bandwidth === 0) ? '0%' : `${Math.round((metrics.used_bandwidth * 100) / metrics.total_bandwidth)}%`;

  useEffect(() => {
    if (!userId) return;

    getUserMetrics(userId);
    getUserMembership(userId);
  }, [getUserMembership, getUserMetrics, userId]);

  const handleUpgradeClick = () => {
    Swal.fire({
      icon: 'info',
      title: 'WHAT DO I GET WITH MY FREE ACCOUNT?',
      confirmButtonText: 'Sign Up',
      html: '<ul>'
        + '<li>Free access to CurrikiStudio, designed for the individual user building experiences for their classes</li>'
        + '<li>1GB of Hosting and Services</li>'
        + '<li>Build a portfolio of more than 10 Projects and 100 Playlists</li>'
        + '<li>No loss of work – transfer any or all projects from your demo account</li>'
        + '<li>Publish your projects to Certified LMS Providers, Google Classroom, CMS platforms and websites via CurrikiGo</li>'
        + '<li>Share and access Projects and Playlists with the Curriki Community via CurrikiLibrary</li>'
        + '<ul>',
      preConfirm: () => metricsService.redeemOffer('linodeFREE')
        .catch((error) => { Swal.showValidationMessage(`Request failed: ${error}`); }),
    }).then((result) => {
      if (result.isConfirmed) {
        Swal.fire({
          title: 'Conragtulations!',
          text: 'Account upgrade successful.',
        }).then(() => {
          getUserMetrics(userId);
          getUserMembership(userId);
        });
      }
    });
  };

  const handleCounterClick = (section) => {
    setModalSection(section);
    setShowModal(true);
  };

  const humanFileSize = (bytes, si = false, dp = 1) => {
    const thresh = si ? 1000 : 1024;

    if (Math.abs(bytes) < thresh) {
      return `${bytes} B`;
    }

    const units = si
      ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
      : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
    let u = -1;
    const r = 10 ** dp;

    do {
      // eslint-disable-next-line no-param-reassign
      bytes /= thresh;
      u += 1;
    } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);

    return `${bytes.toFixed(dp)} ${units[u]}`;
  };

  return (
    <>
      <div className="dashboard-page">
        <div className="content-wrapper">
          {permission?.Dashboard?.includes('dashboard:view') ? (
            <div className="content">
              <div className="row">
                <div className="col-md-12">
                  <h1 className="title">
                    {(metrics.membership_type) ? `${metrics.membership_type} Account - ` : ''}
                    Dashboard
                  </h1>
                </div>
              </div>
              <div className="row">
                <div className={(metrics.membership_type_name === 'demo') ? 'col-8 dashboard-panel m-3' : 'col dashboard-panel m-3'}>
                  <div className="row dashboard-panel-header-row">
                    <div className="col">
                      <h1 className="title">
                        {`Hello, ${firstName}`}
                      </h1>
                    </div>
                  </div>
                  <div className="row m-3">
                    <div className="col">
                      Welcome to the CurrikiStudio Dashboard. Here you will find metrics and general information about your account.
                    </div>
                  </div>
                  <div className="row m-3">
                    <div className="col">
                      <div className="row">
                        <div className="col">
                          <PieChart width={200} height={200}>
                            <Pie data={storageData} innerRadius={50} outerRadius={75}>
                              {storageData.map((entry, index) => (
                                <Cell key={`cell-${index}`} fill={entry.color} />
                              ))}
                              <Label value={usedStoragePercentage} position="center" />
                            </Pie>
                          </PieChart>
                        </div>
                        <div className="col">
                          <h1 className="title">Storage</h1>
                          <p>
                            <label>Total Available:</label>
                            {humanFileSize(metrics.total_storage)}
                            <br />
                            <label>Total Used:</label>
                            {humanFileSize(metrics.used_storage)}
                          </p>
                        </div>
                      </div>
                    </div>
                    <div className="col">
                      <div className="row">
                        <div className="col">
                          <PieChart width={200} height={200}>
                            <Pie data={bandwidthData} innerRadius={50} outerRadius={75}>
                              {bandwidthData.map((entry, index) => (
                                <Cell key={`cell-${index}`} fill={entry.color} />
                              ))}
                              <Label value={usedBandwidthPercentage} position="center" />
                            </Pie>
                          </PieChart>
                        </div>
                        <div className="col">
                          <h1 className="title">Bandwidth</h1>
                          <p>
                            <label>Total Available:</label>
                            {humanFileSize(metrics.total_bandwidth)}
                            <br />
                            <label>Total Used:</label>
                            {humanFileSize(metrics.used_bandwidth)}
                          </p>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="row mb-3">
                    <div className="col">
                      <label>Current Plan:</label>
                      {metrics.membership_type}
                    </div>
                    <div className="col text-right">
                      {metrics.membership_type_name === 'demo' && (
                        <a className="btn btn-primary submit mr-5" onClick={handleUpgradeClick}>Upgrade Now</a>
                      )}
                    </div>
                  </div>
                </div>
                {metrics.membership_type_name === 'demo' && (
                  <div className="col">
                    <div className="row">
                      <div className="col dashboard-panel m-3 text-center offer-panel">
                        <div className="row">
                          <div className="col">
                            <h1 className="title">Need more storage, views or publishing options?</h1>
                          </div>
                        </div>
                        <div className="row">
                          <div className="col">
                            We offer you unlimited storage space for all your needs. You can always upgrade to get more space.
                          </div>
                        </div>
                        <div className="row mt-3">
                          <div className="col">
                            <a className="btn btn-primary submit" onClick={handleUpgradeClick}>Upgrade to Basic Account</a>
                          </div>
                        </div>
                        <div className="row mt-1 mb-3">
                          <div className="col">
                            It&apos;s FREE. Courtesy of Linode.com
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </div>
              <div className="row metrics-counters">
                <div className="col dashboard-panel m-3">
                  <div className="row dashboard-panel-header-row">
                    <div className="col">
                      <h1 className="title">Projects</h1>
                    </div>
                  </div>
                  <div className="row text-center">
                    <div className="col">
                      <span className="count" onClick={() => handleCounterClick('project-count')}>{metrics.project_count}</span>
                      <label>COUNT</label>
                    </div>
                    <div className="col">
                      <span>{metrics.project_views}</span>
                      <label>VIEWS</label>
                    </div>
                    <div className="col">
                      <span className="count" onClick={() => handleCounterClick('project-shared-count')}>{metrics.project_shares}</span>
                      <label>SHARED</label>
                    </div>
                  </div>
                </div>
                <div className="col dashboard-panel m-3">
                  <div className="row dashboard-panel-header-row">
                    <div className="col">
                      <h1 className="title">Playlists</h1>
                    </div>
                  </div>
                  <div className="row text-center">
                    <div className="col">
                      <span className="count" onClick={() => handleCounterClick('playlist-count')}>{metrics.playlist_count}</span>
                      <label>COUNT</label>
                    </div>
                    <div className="col">
                      <span>{metrics.playlist_views}</span>
                      <label>VIEWS</label>
                    </div>
                    <div className="col">
                      <span>{metrics.playlist_shares}</span>
                      <label>SHARED</label>
                    </div>
                  </div>
                </div>
                <div className="col dashboard-panel m-3">
                  <div className="row dashboard-panel-header-row">
                    <div className="col">
                      <h1 className="title">Activities</h1>
                    </div>
                  </div>
                  <div className="row text-center">
                    <div className="col">
                      <span className="count" onClick={() => handleCounterClick('activity-count')}>{metrics.activity_count}</span>
                      <label>COUNT</label>
                    </div>
                    <div className="col">
                      <span>{metrics.activity_views}</span>
                      <label>VIEWS</label>
                    </div>
                    <div className="col" onClick={() => handleCounterClick('activity-shared-count')}>
                      <span className="count">{metrics.activity_shares}</span>
                      <label>SHARED</label>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ) : <Alert variant="danger">You are not authorized to access Dashboard.</Alert>}

        </div>
      </div>

      {(showModal) && (
        <SlideModal modalSection={modalSection} closeModal={() => setShowModal(false)} />
      )}

    </>
  );
}
Example #29
Source File: Stats.js    From datapass with GNU Affero General Public License v3.0 4 votes vote down vote up
Stats = () => {
  const [stats, setStats] = useState(null);
  const { targetApi } = useParams();

  const dataProviderKeyList = useMemo(
    () =>
      Object.keys(DATA_PROVIDER_PARAMETERS).filter(
        (dataProviderKey) =>
          !HIDDEN_DATA_PROVIDER_KEYS.includes(dataProviderKey)
      ),
    []
  );

  async function getTargetAPIList(targetApi) {
    let targetApiList;

    switch (targetApi) {
      case 'allApi':
        const ApiTargetConfiguration = pickBy(
          DATA_PROVIDER_PARAMETERS,
          (dataProviderConfig) => dataProviderConfig.type === 'api'
        );
        targetApiList = Object.keys(ApiTargetConfiguration);
        break;
      case 'allServices':
        const serviceTargetConfiguration = pickBy(
          DATA_PROVIDER_PARAMETERS,
          (dataProviderConfig) => dataProviderConfig.type === 'service'
        );
        targetApiList = Object.keys(serviceTargetConfiguration);
        break;
      case undefined:
        targetApiList = [];
        break;
      default:
        targetApiList = [targetApi];
    }
    return getAPIStats(targetApiList);
  }

  useEffect(() => {
    async function fetchStats() {
      const result = await getTargetAPIList(targetApi);

      setStats({
        ...result.data,
        enrollment_by_target_api: stackLowUseAndUnpublishedApi(
          dataProviderKeyList,
          result.data.enrollment_by_target_api,
          10
        ),
      });
    }

    fetchStats();
  }, [targetApi, dataProviderKeyList]);

  if (!stats) {
    return (
      <section className="full-page">
        <Loader />
      </section>
    );
  }

  return (
    <main>
      <ListHeader title="Statistiques d’utilisation">
        <TagContainer>
          <NavLink end to="/stats">
            {({ isActive }) => (
              <Tag type={isActive ? 'info' : ''}>Toutes les habilitations</Tag>
            )}
          </NavLink>
          <NavLink end to={`/stats/allApi`}>
            {({ isActive }) => (
              <Tag type={isActive ? 'info' : ''}>Toutes les API</Tag>
            )}
          </NavLink>
          <NavLink end to={`/stats/allServices`}>
            {({ isActive }) => (
              <Tag type={isActive ? 'info' : ''}>Tous les services</Tag>
            )}
          </NavLink>
          {dataProviderKeyList.map((targetApi) => (
            <NavLink key={targetApi} end to={`/stats/${targetApi}`}>
              {({ isActive }) => (
                <Tag type={isActive ? 'info' : ''}>
                  {DATA_PROVIDER_PARAMETERS[targetApi]?.label}
                </Tag>
              )}
            </NavLink>
          ))}
        </TagContainer>
      </ListHeader>
      <div className="table-container">
        <CardContainer>
          <Card className="stat_card">
            <div className="stat_card_head">
              <h3>Habilitations déposées</h3>
            </div>
            <div className="stat_card_number">{stats.enrollment_count}</div>
          </Card>
          <Card className="stat_card">
            <div className="stat_card_head">
              <h3>Habilitations validées</h3>
              <div className="card__meta">
                <Link
                  inline
                  href={`/public${targetApi ? `/${targetApi}` : ''}`}
                >
                  voir la liste détaillée
                </Link>
              </div>
            </div>
            <div className="stat_card_number">
              <div>{stats.validated_enrollment_count}</div>
            </div>
          </Card>
        </CardContainer>
        <CardContainer>
          <Card className="stat_card">
            <div className="stat_card_head">
              <h3>
                Temps moyen de traitement des demandes d’habilitation
                <Helper title="temps moyen entre la première soumission d’une demande d’habilitation jusqu’à la première réponse d'un instructeur sur les 6 derniers mois" />
              </h3>
              <div className="card__meta">(en jours)</div>
            </div>
            <div className="stat_card_number">
              {stats.average_processing_time_in_days}
            </div>
          </Card>
          <Card className="stat_card">
            <div className="stat_card_head">
              <h3>
                Pourcentage des habilitations nécessitant un aller retour
                <Helper title="sur les 6 derniers mois" />
              </h3>
              <div className="card__meta">(en % des habilitations totales)</div>
            </div>
            <div className="stat_card_number">{stats.go_back_ratio}</div>
          </Card>
        </CardContainer>
        <CardContainer>
          <Card className="stat_card">
            <div className="stat_card_head">
              <h3>Habilitations déposées</h3>
            </div>
            <div className="stat_card_graph">
              <ResponsiveContainer width={'100%'} height={250}>
                <BarChart data={stats.monthly_enrollment_count}>
                  <XAxis
                    dataKey="month"
                    tickFormatter={(value) => moment(value).format('MMM YY')}
                  />
                  <YAxis />
                  <Tooltip
                    formatter={(value, name, props) => [
                      value,
                      USER_STATUS_LABELS[name],
                      props,
                    ]}
                    labelFormatter={(value) => moment(value).format('MMM YYYY')}
                  />
                  <Legend formatter={(value) => USER_STATUS_LABELS[value]} />
                  <CartesianGrid vertical={false} />
                  {Object.keys(EnrollmentStatus).map((status, index, array) => (
                    <Bar
                      key={status}
                      stackId="count"
                      dataKey={status}
                      fill={USER_STATUS_COLORS[status]}
                    >
                      {index === array.length - 1 && (
                        <LabelList dataKey="total" position="top" />
                      )}
                    </Bar>
                  ))}
                </BarChart>
              </ResponsiveContainer>
            </div>
          </Card>
        </CardContainer>
        <CardContainer>
          <Card className="stat_card">
            <div className="stat_card_head">
              <h3>Répartition des habilitations par statut</h3>
            </div>
            <div className="stat_card_graph">
              <ResponsiveContainer width={'100%'} height={250}>
                <PieChart>
                  <Pie data={stats.enrollment_by_status} dataKey="count" label>
                    {stats.enrollment_by_status.map((entry, index) => (
                      <Cell key={index} fill={USER_STATUS_COLORS[entry.name]} />
                    ))}
                  </Pie>
                  <Legend
                    layout={'vertical'}
                    align={'right'}
                    verticalAlign={'middle'}
                    formatter={(value) => USER_STATUS_LABELS[value]}
                  />
                  <Tooltip
                    formatter={(value, name, props) => [
                      value,
                      USER_STATUS_LABELS[name],
                      props,
                    ]}
                  />
                </PieChart>
              </ResponsiveContainer>
            </div>
          </Card>
        </CardContainer>
        <CardContainer>
          <Card className="stat_card">
            <div className="stat_card_head">
              <h3>Répartition des habilitations par API</h3>
            </div>
            <div className="stat_card_graph">
              <ResponsiveContainer width={'100%'} height={450}>
                <PieChart>
                  <Pie
                    data={stats.enrollment_by_target_api}
                    dataKey="count"
                    label
                  >
                    {stats.enrollment_by_target_api.map((entry, index) => (
                      <Cell key={index} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip
                    formatter={(value, name, props) => [
                      value,
                      name === 'others'
                        ? 'Autres'
                        : DATA_PROVIDER_PARAMETERS[name]?.label,
                      props,
                    ]}
                  />
                  <Legend
                    layout={'vertical'}
                    align={'right'}
                    verticalAlign={'middle'}
                    formatter={(value) =>
                      (value === 'others'
                        ? 'Autres'
                        : DATA_PROVIDER_PARAMETERS[value]?.label
                      ).substring(0, 32)
                    }
                  />
                </PieChart>
              </ResponsiveContainer>
            </div>
          </Card>
        </CardContainer>
      </div>
    </main>
  );
}