Skip to content

Commit

Permalink
Using api interface (elastic#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
JordanSh authored and orouz committed Dec 21, 2021
1 parent 94ece0f commit 4e08898
Show file tree
Hide file tree
Showing 14 changed files with 107 additions and 263 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@

import { useQuery } from 'react-query';
import { useKibana } from '../../../common/lib/kibana';
// TODO: find out how to import from the server folder without warnings
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { CloudPostureStats } from '../../../../server/cloud_posture/types';

export const useCloudPostureStatsApi = () => {
const { http } = useKibana().services;
return useQuery(['csp_dashboard_stats'], () => http.get('/api/csp/stats'));
return useQuery(['csp_dashboard_stats'], () => http.get<CloudPostureStats>('/api/csp/stats'));
};

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,39 +5,27 @@
* 2.0.
*/

import React, { useMemo } from 'react';
import {
Axis,
BarSeries,
Chart,
Datum,
Goal,
Partition,
PartitionLayout,
Settings,
} from '@elastic/charts';
import React from 'react';
import { Chart, Datum, Partition, PartitionLayout, Settings } from '@elastic/charts';
import { EuiText, euiPaletteForStatus } from '@elastic/eui';
import { CspData } from './charts_data_types';
import { useNavigateToCSPFindings } from '../../../common/hooks/use_navigate_to_csp_findings';
// TODO: find out how to import from the server folder without warnings
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { BenchmarkStats } from '../../../../../server/cloud_posture/types';

const mock = {
totalPassed: 800,
totalFailed: 300,
};
const [green, , red] = euiPaletteForStatus(3);

export const CloudPostureScoreChart = ({
totalPassed = mock.totalPassed,
totalFailed = mock.totalFailed,
name: benchmarkName = 'benchmark_mock',
}: CspData & { name: string }) => {
totalPassed,
totalFailed,
name: benchmarkName,
}: BenchmarkStats) => {
const { navigate } = useNavigateToCSPFindings();
if (totalPassed === undefined || totalFailed === undefined || name === undefined) return null;

const handleElementClick = (e) => {
const [data] = e;
const [groupsData, chartData] = data;
// const query = `rule.benchmark : ${benchmarkName} and result.evaluation : ${groupsData[0].groupByRollup.toLowerCase()}`;
// console.log(query);
const [groupsData] = data;

navigate(
`(language:kuery,query:'rule.benchmark : "${benchmarkName}" and result.evaluation : ${groupsData[0].groupByRollup.toLowerCase()}')`
Expand All @@ -47,13 +35,10 @@ export const CloudPostureScoreChart = ({
const total = totalPassed + totalFailed;
const percentage = `${((totalPassed / total) * 100).toFixed(1)}%`;

const data = useMemo(
() => [
{ label: 'Passed', value: totalPassed },
{ label: 'Failed', value: totalFailed },
],
[totalFailed, totalPassed]
);
const data = [
{ label: 'Passed', value: totalPassed },
{ label: 'Failed', value: totalFailed },
];

return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
Expand All @@ -75,10 +60,8 @@ export const CloudPostureScoreChart = ({
config={{
partitionLayout: PartitionLayout.sunburst,
linkLabel: { maximumSection: Infinity, maxCount: 0 },
outerSizeRatio: 0.9, // - 0.5 * Math.random(),
outerSizeRatio: 0.9,
emptySizeRatio: 0.8,
// circlePadding: 4,
// fontFamily: 'Arial',
}}
/>
</Chart>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,65 +14,66 @@ import {
EuiIcon,
EuiFlexGrid,
euiPaletteForStatus,
EuiBadge,
} from '@elastic/eui';
import { Chart, Settings, LineSeries } from '@elastic/charts';
import { useCloudPostureStatsApi } from '../../../common/api';

type Trend = Array<[time: number, value: number]>;

const [green, yellow, red] = euiPaletteForStatus(3);
const warningColor = '#F5A700';

const getScoreVariant = (value: number) => {
const getTitleColor = (value: number) => {
if (value <= 65) return 'danger';
if (value <= 86) return '#F5A700';
if (value <= 86) return warningColor;
if (value <= 100) return 'success';
return 'error';
return 'default';
};

const getIsPositiveChange = (value: number) => value > 0;

const getScoreIcon = (value: number) => {
if (value <= 65) return 'alert';
if (value <= 86) return 'alert';
if (value <= 100) return 'check';
return 'error';
};

const getScoreTrendPercentage = (scoreTrend: any) => {
const beforeLast = scoreTrend.at(-2)[1];
const last = scoreTrend.at(-1)[1];
const getScoreTrendPercentage = (scoreTrend: Trend) => {
const beforeLast = scoreTrend[scoreTrend.length - 2][1];
const last = scoreTrend[scoreTrend.length - 1][1];

return (last - beforeLast).toFixed(1);
return Number((last - beforeLast).toFixed(1));
};

const mock = 20;

export const ComplianceStats = () => {
const getStats = useCloudPostureStatsApi();
const postureScore = (getStats.isSuccess && getStats.data.postureScore) || mock;
const postureScore = getStats.isSuccess && getStats.data.postureScore;

const scoreTrend = [
[0, 0],
[1, 10],
[2, 100],
[3, 50],
[4, postureScore],
];
] as Trend;

// TODO: in case we dont have a full length trend we will need to handle the sparkline chart alone. not rendering anything is just a temporary solution
if (!postureScore || scoreTrend.length < 2) return null;

const scoreChange = getScoreTrendPercentage(scoreTrend);
const isPositiveChange = getIsPositiveChange(scoreChange);
const isPositiveChange = scoreChange > 0;

const stats = [
{
title: postureScore,
description: 'Posture Score',
titleColor: getScoreVariant(postureScore),
titleColor: getTitleColor(postureScore),
iconType: getScoreIcon(postureScore),
},
{
title: (
<span>
<EuiIcon size="xl" type={isPositiveChange ? 'sortUp' : 'sortDown'} />
{scoreChange}%
{`${scoreChange}%`}
</span>
),
description: 'Posture Score Trend',
Expand All @@ -92,6 +93,7 @@ export const ComplianceStats = () => {
}}
/>
<LineSeries
id="posture-score-trend-sparkline"
data={scoreTrend}
xAccessor={0}
yAccessors={[1]}
Expand All @@ -104,12 +106,10 @@ export const ComplianceStats = () => {
{
title: '1',
description: 'Active Frameworks',
// titleColor: 'primary',
},
{
title: '1,369',
description: 'Total Resources',
// titleColor: 'accent',
},
];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,13 @@ import {
AreaSeries,
} from '@elastic/charts';
import { dateValueToTuple } from '../index';
// TODO: find out how to import from the server folder without warnings
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { BenchmarkStats } from '../../../../../server/cloud_posture/types';

export const ComplianceTrendChart = ({ postureScore }: BenchmarkStats) => {
if (postureScore === undefined) return null;

export const ComplianceTrendChart = ({ postureScore }) => {
const complianceScoreTrend = [
{ date: Date.now(), value: postureScore },
{ date: Date.now() - 10000, value: 53 },
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React from 'react';
Expand All @@ -17,7 +16,6 @@ import {
} from '@elastic/charts';
import { formatDate, dateFormatAliases } from '@elastic/eui';
import { dateValueToTuple } from '../index';
import { CspData } from './charts_data_types';

const mockData = [
{
Expand Down Expand Up @@ -53,30 +51,30 @@ const mockData = [
},
];

export const FindingsTrendChart = ({ resourcesFindings = mockData }: CspData) => (
<Chart size={{ height: 200 }}>
<Settings
// theme={isDarkTheme ? EUI_CHARTS_THEME_DARK.theme : EUI_CHARTS_THEME_LIGHT.theme}
showLegend={true}
legendPosition="right"
/>
{resourcesFindings.map((resource) => (
<BarSeries
data={resource.data.map(dateValueToTuple)}
id={resource.id}
name={resource.name}
xScaleType="time"
xAccessor={0}
yAccessors={[1]}
stackAccessors={[0]}
export const FindingsTrendChart = () => {
const resourcesFindings = mockData;

return (
<Chart size={{ height: 200 }}>
<Settings showLegend={true} legendPosition="right" />
{resourcesFindings.map((resource) => (
<BarSeries
data={resource.data.map(dateValueToTuple)}
id={resource.id}
name={resource.name}
xScaleType="time"
xAccessor={0}
yAccessors={[1]}
stackAccessors={[0]}
/>
))}
<Axis
title={formatDate(Date.now(), dateFormatAliases.date)}
id="bottom-axis"
position="bottom"
tickFormat={timeFormatter(niceTimeFormatByDay(1))}
/>
))}
<Axis
title={formatDate(Date.now(), dateFormatAliases.date)}
id="bottom-axis"
position="bottom"
tickFormat={timeFormatter(niceTimeFormatByDay(1))}
/>
<Axis id="left-axis" position="left" showGridLines tickFormat={(d) => Number(d).toFixed(2)} />
</Chart>
);
<Axis id="left-axis" position="left" showGridLines tickFormat={(d) => Number(d).toFixed(2)} />
</Chart>
);
};
Loading

0 comments on commit 4e08898

Please sign in to comment.