diff --git a/.changeset/cost-insights-sharp-actors-mix.md b/.changeset/cost-insights-sharp-actors-mix.md new file mode 100644 index 0000000000..5ae1035612 --- /dev/null +++ b/.changeset/cost-insights-sharp-actors-mix.md @@ -0,0 +1,10 @@ +--- +'@backstage/plugin-cost-insights': minor +--- + +rename: Tooltip -> BarChartTooltip +rename: TooltipItem -> BarChartTooltipItem +Deprecate BarChartData in favor of BarChartOptions +Export BarChartLegend component +Update BarChart props to accept options prop +Deprecate ProductCost type in favor of Entity. Update CostInsightsApi diff --git a/plugins/cost-insights/src/api/CostInsightsApi.ts b/plugins/cost-insights/src/api/CostInsightsApi.ts index bedbf8319d..9baad5ffab 100644 --- a/plugins/cost-insights/src/api/CostInsightsApi.ts +++ b/plugins/cost-insights/src/api/CostInsightsApi.ts @@ -19,9 +19,9 @@ import { Alert, Cost, Duration, + Entity, Group, Project, - ProductCost, Maybe, MetricData, } from '../types'; @@ -138,7 +138,7 @@ export type CostInsightsApi = { * * @param options Options to use when fetching insights for a particular cloud product and interval timeframe. */ - getProductInsights(options: ProductInsightsOptions): Promise; + getProductInsights(options: ProductInsightsOptions): Promise; /** * Get current cost alerts for a given group. These show up as Action Items for the group on the * Cost Insights page. Alerts may include cost-saving recommendations, such as infrastructure diff --git a/plugins/cost-insights/src/client.ts b/plugins/cost-insights/src/client.ts index 1fa57c624a..740a44fcbd 100644 --- a/plugins/cost-insights/src/client.ts +++ b/plugins/cost-insights/src/client.ts @@ -25,9 +25,9 @@ import { DateAggregation, DEFAULT_DATE_FORMAT, Duration, + Entity, Group, MetricData, - ProductCost, Project, ProjectGrowthData, Trendline, @@ -194,8 +194,9 @@ export class ExampleCostInsightsClient implements CostInsightsApi { async getProductInsights( productInsightsOptions: ProductInsightsOptions, - ): Promise { + ): Promise { const projectProductInsights = await this.request(productInsightsOptions, { + id: productInsightsOptions.product, aggregation: [80_000, 110_000], change: { ratio: 0.375, @@ -205,69 +206,152 @@ export class ExampleCostInsightsClient implements CostInsightsApi { { id: null, // entities with null ids will be appear as "Unlabeled" in product panels aggregation: [45_000, 50_000], + change: { + ratio: 0.111, + amount: 5_000, + }, + entities: [], }, { id: 'entity-a', aggregation: [15_000, 20_000], + change: { + ratio: 0.333, + amount: 5_000, + }, + entities: [], }, { id: 'entity-b', aggregation: [20_000, 30_000], + change: { + ratio: 0.5, + amount: 10_000, + }, + entities: [], + }, + { + id: 'entity-c', + aggregation: [0, 10_000], + change: { + ratio: 10_000, + amount: 10_000, + }, + entities: [], + }, + ], + }); + + const productInsights: Entity = await this.request(productInsightsOptions, { + id: productInsightsOptions.product, + aggregation: [200_000, 250_000], + change: { + ratio: 0.2, + amount: 50_000, + }, + entities: [ + { + id: null, // entities with null ids will be appear as "Unlabeled" in product panels + aggregation: [36_000, 42_000], + change: { + ratio: 0.1666, + amount: 6_000, + }, + entities: [], + }, + { + id: 'entity-a', + aggregation: [15_000, 20_000], + change: { + ratio: -0.33333333, + amount: 5_000, + }, + entities: [], + }, + { + id: 'entity-b', + aggregation: [20_000, 30_000], + change: { + ratio: 0.5, + amount: 10_000, + }, + entities: [], + }, + { + id: 'entity-c', + aggregation: [18_000, 25_000], + change: { + ratio: 0.38, + amount: 7_000, + }, + entities: [], + }, + { + id: 'entity-d', + aggregation: [15_000, 30_000], + change: { + ratio: 1, + amount: 15_000, + }, + entities: [], }, { id: 'entity-e', aggregation: [0, 10_000], + entities: [], + change: { + ratio: 10_000, + amount: 10_000, + }, + }, + { + id: 'entity-f', + aggregation: [17_000, 19_000], + change: { + ratio: 0.118, + amount: 2_000, + }, + entities: [], + }, + { + id: 'entity-g', + aggregation: [80_000, 60_000], + change: { + ratio: -0.25, + amount: -20_000, + }, + entities: [ + { + id: 'vCPU Time Batch Belgium', + aggregation: [15_000, 15_000], + change: { + ratio: 0, + amount: 0, + }, + entities: [], + }, + { + id: 'RAM Time Belgium', + aggregation: [15_000, 30_000], + change: { + ratio: 1, + amount: 15_000, + }, + entities: [], + }, + { + id: 'Local Disk Time PD Standard Belgium', + aggregation: [50_000, 15_000], + change: { + ratio: -0.7, + amount: -35_000, + }, + entities: [], + }, + ], }, ], }); - const productInsights: ProductCost = await this.request( - productInsightsOptions, - { - aggregation: [200_000, 250_000], - change: { - ratio: 0.2, - amount: 50_000, - }, - entities: [ - { - id: null, // entities with null ids will be appear as "Unlabeled" in product panels - aggregation: [15_000, 30_000], - }, - { - id: 'entity-a', - aggregation: [15_000, 20_000], - }, - { - id: 'entity-b', - aggregation: [20_000, 30_000], - }, - { - id: 'entity-c', - aggregation: [18_000, 25_000], - }, - { - id: 'entity-d', - aggregation: [36_000, 42_000], - }, - { - id: 'entity-e', - aggregation: [0, 10_000], - }, - { - id: 'entity-f', - aggregation: [17_000, 19_000], - }, - { - id: 'entity-g', - aggregation: [49_000, 30_000], - }, - { - id: 'entity-h', - aggregation: [0, 34_000], - }, - ], - }, - ); return productInsightsOptions.project ? projectProductInsights diff --git a/plugins/cost-insights/src/components/BarChart/BarChart.test.tsx b/plugins/cost-insights/src/components/BarChart/BarChart.test.tsx index a095324e6e..4e40a5ddda 100644 --- a/plugins/cost-insights/src/components/BarChart/BarChart.test.tsx +++ b/plugins/cost-insights/src/components/BarChart/BarChart.test.tsx @@ -15,56 +15,40 @@ */ import React from 'react'; -import { TooltipPayload } from 'recharts'; import { fireEvent } from '@testing-library/react'; import { BarChart, BarChartProps } from './BarChart'; -import { BarChartData, ResourceData } from '../../types'; +import { ResourceData } from '../../types'; import { createMockEntity } from '../../utils/mockData'; import { resourceSort } from '../../utils/sort'; import { renderInTestApp } from '@backstage/test-utils'; -import { TooltipItemProps } from '../Tooltip'; -import { costInsightsLightTheme } from '../../utils/styles'; + +// Disable responsive container console warnings generated by recharts; doesn't disable React warnings. +jest.spyOn(console, 'warn').mockImplementation(() => {}); const MockEntities = [...Array(10)].map((_, index) => - createMockEntity(() => ({ + createMockEntity(mock => ({ + ...mock, id: `test-id-${index + 1}`, // grow resource costs linearly for testing aggregation: [index * 1000, (index + 1) * 1000], })), ); -const MockBarChartData: BarChartData = { - previousFill: costInsightsLightTheme.palette.yellow, - currentFill: costInsightsLightTheme.palette.darkBlue, - previousName: 'Last Period', - currentName: 'Current Period', -}; - const MockResources: ResourceData[] = MockEntities.map(entity => ({ name: entity.id, previous: entity.aggregation[0], current: entity.aggregation[1], })); -const MockTooltipItem = (payload: TooltipPayload): TooltipItemProps => ({ - label: payload.name, - value: payload.value as string, - fill: payload.fill as string, -}); - const renderWithProps = ({ responsive = false, displayAmount = 6, - barChartData = MockBarChartData, - getTooltipItem = MockTooltipItem, resources = MockResources, }: BarChartProps) => { return renderInTestApp( , ); diff --git a/plugins/cost-insights/src/components/BarChart/BarChart.tsx b/plugins/cost-insights/src/components/BarChart/BarChart.tsx index aa1fd5c601..93f738a38b 100644 --- a/plugins/cost-insights/src/components/BarChart/BarChart.tsx +++ b/plugins/cost-insights/src/components/BarChart/BarChart.tsx @@ -20,22 +20,21 @@ import { BarChart as RechartsBarChart, CartesianGrid, ContentRenderer, - TooltipProps, + TooltipProps as RechartsTooltipProps, + RechartsFunction, ResponsiveContainer, Tooltip as RechartsTooltip, XAxis, YAxis, - TooltipPayload, } from 'recharts'; import { Box, useTheme } from '@material-ui/core'; import { BarChartTick } from './BarChartTick'; import { BarChartStepper } from './BarChartStepper'; -import { Tooltip, TooltipItemProps } from '../Tooltip'; - +import { BarChartTooltip } from './BarChartTooltip'; +import { BarChartTooltipItem } from './BarChartTooltipItem'; import { currencyFormatter } from '../../utils/formatters'; import { BarChartData, - Maybe, ResourceData, DataKey, CostInsightsTheme, @@ -43,28 +42,58 @@ import { import { notEmpty } from '../../utils/assert'; import { useBarChartStyles } from '../../utils/styles'; import { resourceSort } from '../../utils/sort'; +import { isInvalid, titleOf, tooltipItemOf } from '../../utils/graphs'; + +export const defaultTooltip: ContentRenderer = ({ + label, + payload = [], +}) => { + if (isInvalid({ label, payload })) return null; + + const title = titleOf(label); + const items = payload.map(tooltipItemOf).filter(notEmpty); + return ( + + {items.map((item, index) => ( + + ))} + + ); +}; export type BarChartProps = { + resources: ResourceData[]; responsive?: boolean; displayAmount?: number; - barChartData: BarChartData; - getTooltipItem: (payload: TooltipPayload) => Maybe; - resources: ResourceData[]; + options?: Partial; + tooltip?: ContentRenderer; + onClick?: RechartsFunction; + onMouseMove?: RechartsFunction; }; export const BarChart = ({ + resources, responsive = true, displayAmount = 6, - barChartData, - getTooltipItem, - resources, + options = {}, + tooltip = defaultTooltip, + onClick, + onMouseMove, }: BarChartProps) => { const theme = useTheme(); const styles = useBarChartStyles(theme); const [activeChart, setActiveChart] = useState(false); const [stepWindow, setStepWindow] = useState(() => [0, displayAmount]); - const { previousFill, currentFill, previousName, currentName } = barChartData; + const data = Object.assign( + { + previousFill: theme.palette.lightBlue, + currentFill: theme.palette.darkBlue, + previousName: 'Previous', + currentName: 'Current', + }, + options, + ); const [stepStart, stepEnd] = stepWindow; const steps = Math.ceil(resources.length / displayAmount); @@ -95,24 +124,11 @@ export const BarChart = ({ [setStepWindow, resources, displayAmount], ); - const handleChartEnter = () => setActiveChart(true); - - const handleChartLeave = () => setActiveChart(false); - - const renderTooltipContent: ContentRenderer = ({ - label, - payload, - }) => { - if (!(payload && typeof label === 'string')) return [null, null]; - const items = payload.map(getTooltipItem).filter(notEmpty); - return ; - }; - return ( setActiveChart(false)} + onMouseEnter={() => setActiveChart(true)} data-testid="bar-chart-wrapper" > {/* Setting fixed values for height and width generates a console warning in testing but enables ResponsiveContainer to render its children. */} @@ -121,16 +137,22 @@ export const BarChart = ({ width={responsive ? '100%' : styles.container.width} > - + {tooltip && ( + + )} 0, globalResourcesMax]} - tick={{ fill: styles.axis.fill }} + tick={styles.axis} /> diff --git a/plugins/cost-insights/src/components/BarChart/BarChartLabel.tsx b/plugins/cost-insights/src/components/BarChart/BarChartLabel.tsx index 0a21f1ed46..c4402893f3 100644 --- a/plugins/cost-insights/src/components/BarChart/BarChartLabel.tsx +++ b/plugins/cost-insights/src/components/BarChart/BarChartLabel.tsx @@ -15,7 +15,7 @@ */ import React, { PropsWithChildren } from 'react'; -import { Box } from '@material-ui/core'; +import { Box, Typography } from '@material-ui/core'; import { useBarChartLabelStyles } from '../../utils/styles'; type BarChartLabel = { @@ -23,6 +23,7 @@ type BarChartLabel = { y: number; height: number; width: number; + details?: JSX.Element; }; export const BarChartLabel = ({ @@ -30,11 +31,11 @@ export const BarChartLabel = ({ y, height, width, + details, children, }: PropsWithChildren) => { const classes = useBarChartLabelStyles(); const translateX = width * -0.5; - const childArray = React.Children.toArray(children); return ( - {childArray[0]} - {childArray.slice(1)} + + {children} + + {details} ); diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChartLegend.test.tsx b/plugins/cost-insights/src/components/BarChart/BarChartLegend.test.tsx similarity index 56% rename from plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChartLegend.test.tsx rename to plugins/cost-insights/src/components/BarChart/BarChartLegend.test.tsx index ab38ba8d44..3074af716e 100644 --- a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChartLegend.test.tsx +++ b/plugins/cost-insights/src/components/BarChart/BarChartLegend.test.tsx @@ -15,20 +15,15 @@ */ import React from 'react'; -import { UnlabeledDataflowBarChartLegend } from './UnlabeledDataflowBarChartLegend'; import { renderInTestApp } from '@backstage/test-utils'; +import { BarChartLegend } from './BarChartLegend'; -describe('', () => { - it('Displays the correct text', async () => { +describe('', () => { + it(`Should display the correct cost start and end`, async () => { const rendered = await renderInTestApp( - , + , ); - expect(rendered.getByText('Total Unlabeled Cost')).toBeInTheDocument(); - expect(rendered.getByText('Total Labeled Cost')).toBeInTheDocument(); - expect(rendered.getByText('$9,843')).toBeInTheDocument(); - expect(rendered.getByText('$2,309')).toBeInTheDocument(); + expect(rendered.getByText(/\$1,000/)).toBeInTheDocument(); + expect(rendered.queryByText(/\$5,000/)).toBeInTheDocument(); }); }); diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.tsx b/plugins/cost-insights/src/components/BarChart/BarChartLegend.tsx similarity index 55% rename from plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.tsx rename to plugins/cost-insights/src/components/BarChart/BarChartLegend.tsx index 6b5ce17c95..6db0e13572 100644 --- a/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.tsx +++ b/plugins/cost-insights/src/components/BarChart/BarChartLegend.tsx @@ -14,47 +14,58 @@ * limitations under the License. */ -import React from 'react'; +import React, { PropsWithChildren } from 'react'; import { Box, useTheme } from '@material-ui/core'; import { LegendItem } from '../LegendItem'; -import { CostGrowth } from '../CostGrowth'; import { currencyFormatter } from '../../utils/formatters'; -import { ChangeStatistic, CostInsightsTheme, Duration } from '../../types'; +import { CostInsightsTheme } from '../../types'; +import { useBarChartLayoutStyles as useStyles } from '../../utils/styles'; -export type ResourceGrowthBarChartLegendProps = { - change: ChangeStatistic; - duration: Duration; +type BarChartLegendOptions = { previousName: string; + previousFill: string; currentName: string; - costStart: number; - costEnd: number; + currentFill: string; }; -export const ResourceGrowthBarChartLegend = ({ - change, - duration, - previousName, - currentName, +export type BarChartLegendProps = { + costStart: number; + costEnd: number; + options?: Partial; +}; + +export const BarChartLegend = ({ costStart, costEnd, -}: ResourceGrowthBarChartLegendProps) => { + options = {}, + children, +}: PropsWithChildren) => { const theme = useTheme(); + const classes = useStyles(); + + const data = Object.assign( + { + previousName: 'Previous', + previousFill: theme.palette.lightBlue, + currentName: 'Current', + currentFill: theme.palette.darkBlue, + }, + options, + ); return ( - + - + {currencyFormatter.format(costStart)} - + {currencyFormatter.format(costEnd)} - - - + {children} ); }; diff --git a/plugins/cost-insights/src/components/BarChart/BarChartTick.tsx b/plugins/cost-insights/src/components/BarChart/BarChartTick.tsx index 005753fce6..145e5f805b 100644 --- a/plugins/cost-insights/src/components/BarChart/BarChartTick.tsx +++ b/plugins/cost-insights/src/components/BarChart/BarChartTick.tsx @@ -26,6 +26,7 @@ type BarChartTickProps = { value: any; }; visibleTicksCount: number; + details?: JSX.Element; }; export const BarChartTick = ({ @@ -35,11 +36,18 @@ export const BarChartTick = ({ width, payload, visibleTicksCount, + details, }: BarChartTickProps) => { const gutterWidth = 5; const labelWidth = width / visibleTicksCount - gutterWidth * 2; return ( - + {!payload.value ? 'Unlabeled' : payload.value} ); diff --git a/plugins/cost-insights/src/components/Tooltip/Tooltip.test.tsx b/plugins/cost-insights/src/components/BarChart/BarChartTooltip.test.tsx similarity index 74% rename from plugins/cost-insights/src/components/Tooltip/Tooltip.test.tsx rename to plugins/cost-insights/src/components/BarChart/BarChartTooltip.test.tsx index 2f1f8fe7e1..b30714ca58 100644 --- a/plugins/cost-insights/src/components/Tooltip/Tooltip.test.tsx +++ b/plugins/cost-insights/src/components/BarChart/BarChartTooltip.test.tsx @@ -16,10 +16,11 @@ import React from 'react'; import { renderInTestApp } from '@backstage/test-utils'; -import { Tooltip } from './Tooltip'; +import { BarChartTooltip } from './BarChartTooltip'; +import { BarChartTooltipItem } from './BarChartTooltipItem'; import { CostInsightsThemeProvider } from '../CostInsightsPage/CostInsightsThemeProvider'; -const mockTooltipItems = [ +const items = [ { label: 'Cost', value: '$1,000,000', @@ -32,22 +33,14 @@ const mockTooltipItems = [ }, ]; -describe('', () => { - it('renders without exploding', async () => { - const rendered = await renderInTestApp( - - - , - ); - expect( - rendered.container.querySelector('.tooltip-content'), - ).toBeInTheDocument(); - }); +const tooltipItems = () => + items.map(item => ); +describe('', () => { it('formats label and tooltip item text correctly', async () => { const rendered = await renderInTestApp( - + {tooltipItems} , ); expect(rendered.getByText('05/16/2020')).toBeInTheDocument(); diff --git a/plugins/cost-insights/src/components/BarChart/BarChartTooltip.tsx b/plugins/cost-insights/src/components/BarChart/BarChartTooltip.tsx new file mode 100644 index 0000000000..2cb09b724e --- /dev/null +++ b/plugins/cost-insights/src/components/BarChart/BarChartTooltip.tsx @@ -0,0 +1,79 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { ReactNode, PropsWithChildren } from 'react'; +import { Box, Divider, Typography } from '@material-ui/core'; +import { useTooltipStyles as useStyles } from '../../utils/styles'; + +export type BarChartTooltipProps = { + title: string; + content?: ReactNode | string; + subtitle?: ReactNode; + topRight?: ReactNode; + actions?: ReactNode; +}; + +export const BarChartTooltip = ({ + title, + content, + subtitle, + topRight, + actions, + children, +}: PropsWithChildren) => { + const classes = useStyles(); + + return ( + + + + {title} + {subtitle && ( + + {subtitle} + + )} + + {topRight} + + {content && ( + + + {content} + + + )} + + {children} + + {actions && ( + <> + + + {actions} + + + )} + + ); +}; diff --git a/plugins/cost-insights/src/components/Tooltip/TooltipItem.tsx b/plugins/cost-insights/src/components/BarChart/BarChartTooltipItem.tsx similarity index 76% rename from plugins/cost-insights/src/components/Tooltip/TooltipItem.tsx rename to plugins/cost-insights/src/components/BarChart/BarChartTooltipItem.tsx index a084a0fd1d..153182560f 100644 --- a/plugins/cost-insights/src/components/Tooltip/TooltipItem.tsx +++ b/plugins/cost-insights/src/components/BarChart/BarChartTooltipItem.tsx @@ -19,15 +19,18 @@ import { Box, Typography } from '@material-ui/core'; import LensIcon from '@material-ui/icons/Lens'; import { useTooltipStyles as useStyles } from '../../utils/styles'; -export type TooltipItemProps = { - value: string; - label: string; +export type TooltipItem = { fill: string; + label: string; + value: string; }; -export const TooltipItem = ({ fill, label, value }: TooltipItemProps) => { +export type BarChartTooltipItemProps = { + item: TooltipItem; +}; + +export const BarChartTooltipItem = ({ item }: BarChartTooltipItemProps) => { const classes = useStyles(); - const style = { fill: fill }; return ( { > - + - {label} + {item.label} - {value} + {item.value} ); }; diff --git a/plugins/cost-insights/src/components/BarChart/index.ts b/plugins/cost-insights/src/components/BarChart/index.ts index 4525bd24f3..76f859636a 100644 --- a/plugins/cost-insights/src/components/BarChart/index.ts +++ b/plugins/cost-insights/src/components/BarChart/index.ts @@ -16,3 +16,12 @@ export { BarChart } from './BarChart'; export type { BarChartProps } from './BarChart'; +export { BarChartLegend } from './BarChartLegend'; +export type { BarChartLegendProps } from './BarChartLegend'; +export { BarChartTooltip } from './BarChartTooltip'; +export type { BarChartTooltipProps } from './BarChartTooltip'; +export { BarChartTooltipItem } from './BarChartTooltipItem'; +export type { + TooltipItem, + BarChartTooltipItemProps, +} from './BarChartTooltipItem'; diff --git a/plugins/cost-insights/src/components/CostGrowth/CostGrowth.tsx b/plugins/cost-insights/src/components/CostGrowth/CostGrowth.tsx index 89e44ee185..01a0874636 100644 --- a/plugins/cost-insights/src/components/CostGrowth/CostGrowth.tsx +++ b/plugins/cost-insights/src/components/CostGrowth/CostGrowth.tsx @@ -49,7 +49,7 @@ export const CostGrowth = ({ change, duration }: CostGrowthProps) => { const converted = amount / (currency.rate ?? rate); // Determine if growth is significant enough to highlight - const growth = growthOf(engineers, change.ratio); + const growth = growthOf(change.ratio, engineers); const classes = classnames({ [styles.excess]: growth === GrowthType.Excess, [styles.savings]: growth === GrowthType.Savings, diff --git a/plugins/cost-insights/src/components/CostGrowth/CostGrowthIndicator.test.tsx b/plugins/cost-insights/src/components/CostGrowth/CostGrowthIndicator.test.tsx new file mode 100644 index 0000000000..8be5e238cc --- /dev/null +++ b/plugins/cost-insights/src/components/CostGrowth/CostGrowthIndicator.test.tsx @@ -0,0 +1,57 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { renderInTestApp } from '@backstage/test-utils'; +import { CostGrowthIndicator } from './CostGrowthIndicator'; +import { ChangeThreshold, EngineerThreshold } from '../../types'; + +describe.each` + ratio | amount | ariaLabel + ${-0.1} | ${undefined} | ${'savings'} + ${0.01} | ${undefined} | ${'excess'} + ${ChangeThreshold.lower} | ${EngineerThreshold} | ${'savings'} + ${ChangeThreshold.lower - 0.01} | ${EngineerThreshold} | ${'savings'} + ${ChangeThreshold.lower - 0.01} | ${EngineerThreshold + 0.1} | ${'savings'} + ${ChangeThreshold.upper} | ${EngineerThreshold} | ${'excess'} + ${ChangeThreshold.upper + 0.01} | ${EngineerThreshold} | ${'excess'} + ${ChangeThreshold.upper + 0.01} | ${EngineerThreshold + 0.1} | ${'excess'} +`('growthOf', ({ ratio, amount, ariaLabel }) => { + it(`should display the correct indicator for ${ariaLabel}`, async () => { + const { getByLabelText } = await renderInTestApp( + , + ); + expect(getByLabelText(ariaLabel)).toBeInTheDocument(); + }); +}); + +describe.each` + ratio | amount + ${0} | ${undefined} + ${ChangeThreshold.lower} | ${0} + ${ChangeThreshold.lower + 0.01} | ${EngineerThreshold} + ${ChangeThreshold.lower + 0.01} | ${EngineerThreshold + 0.1} + ${ChangeThreshold.lower - 0.01} | ${EngineerThreshold - 0.1} + ${ChangeThreshold.upper + 0.01} | ${EngineerThreshold - 0.1} +`('growthOf', ({ ratio, amount }) => { + it('should display the correct indicator for negligible growth', async () => { + const { queryByLabelText } = await renderInTestApp( + , + ); + expect(queryByLabelText('savings')).not.toBeInTheDocument(); + expect(queryByLabelText('excess')).not.toBeInTheDocument(); + }); +}); diff --git a/plugins/cost-insights/src/components/CostGrowth/CostGrowthIndicator.tsx b/plugins/cost-insights/src/components/CostGrowth/CostGrowthIndicator.tsx new file mode 100644 index 0000000000..e220fdb8e7 --- /dev/null +++ b/plugins/cost-insights/src/components/CostGrowth/CostGrowthIndicator.tsx @@ -0,0 +1,68 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import classnames from 'classnames'; +import { Typography, TypographyProps } from '@material-ui/core'; +import { default as ArrowDropUp } from '@material-ui/icons/ArrowDropUp'; +import { default as ArrowDropDown } from '@material-ui/icons/ArrowDropDown'; +import { growthOf } from '../../utils/change'; +import { GrowthType } from '../../types'; +import { useCostGrowthStyles as useStyles } from '../../utils/styles'; + +export type CostGrowthIndicatorProps = TypographyProps & { + ratio: number; + amount?: number; + formatter?: (amount: number) => string; +}; + +export const CostGrowthIndicator = ({ + ratio, + amount, + formatter, + className, + ...props +}: CostGrowthIndicatorProps) => { + const classes = useStyles(); + const growth = growthOf(ratio, amount); + + const classNames = classnames(classes.indicator, className, { + [classes.savings]: growth === GrowthType.Savings, + [classes.excess]: growth === GrowthType.Excess, + }); + + // Display cost as a factor of engineer cost growth and percentage growth + if (typeof amount === 'number') { + return ( + + {formatter ? formatter(amount) : amount} + {growth === GrowthType.Savings && ( + + )} + {growth === GrowthType.Excess && } + + ); + } + + // Display cost as a factor of percent change + return ( + + {formatter ? formatter(ratio) : ratio} + {ratio < 0 && } + {ratio > 0 && } + + ); +}; diff --git a/plugins/cost-insights/src/components/CostGrowth/index.ts b/plugins/cost-insights/src/components/CostGrowth/index.ts index da17ae8709..569c343380 100644 --- a/plugins/cost-insights/src/components/CostGrowth/index.ts +++ b/plugins/cost-insights/src/components/CostGrowth/index.ts @@ -16,3 +16,5 @@ export { CostGrowth } from './CostGrowth'; export type { CostGrowthProps } from './CostGrowth'; +export { CostGrowthIndicator } from './CostGrowthIndicator'; +export type { CostGrowthIndicatorProps } from './CostGrowthIndicator'; diff --git a/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewCard.tsx b/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewCard.tsx index 7d55026be8..8f52a0070b 100644 --- a/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewCard.tsx +++ b/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewCard.tsx @@ -98,7 +98,7 @@ export const CostOverviewCard = ({ /> - {config.metrics.length > 1 && ( + {config.metrics.length && ( = ({ + label, + payload = [], + }) => { + if (isInvalid({ label, payload })) return null; + + const dataKeys = [data.dailyCost.dataKey, data.metric.dataKey]; + const title = moment(label).format(DEFAULT_DATE_FORMAT); + const items = payload + .filter(p => dataKeys.includes(p.dataKey as string)) + .map(p => ({ + label: + p.dataKey === data.dailyCost.dataKey + ? data.dailyCost.name + : data.metric.name, + value: + p.dataKey === data.dailyCost.dataKey + ? formatGraphValue(p.value as number, data.dailyCost.format) + : formatGraphValue(p.value as number, data.metric.format), + fill: + p.dataKey === data.dailyCost.dataKey + ? theme.palette.blue + : theme.palette.magenta, + })); + + return ( + + {items.map((item, index) => ( + + ))} + + ); + }; return ( )} - - } - animationDuration={100} - /> + ); diff --git a/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewTooltip.tsx b/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewTooltip.tsx deleted file mode 100644 index e0a9b9a9ea..0000000000 --- a/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewTooltip.tsx +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import React from 'react'; -import moment from 'moment'; -import { TooltipPayload, TooltipProps } from 'recharts'; -import { Tooltip, TooltipItemProps } from '../../components/Tooltip'; -import { DEFAULT_DATE_FORMAT } from '../../types'; - -export type CostOverviewTooltipProps = TooltipProps & { - dataKeys: Array; - format: (payload: TooltipPayload) => TooltipItemProps; -}; - -export const CostOverviewTooltip = ({ - label, - payload, - dataKeys, - format, -}: CostOverviewTooltipProps) => { - const tooltipLabel = moment(label).format(DEFAULT_DATE_FORMAT); - const items = payload - ?.filter((p: TooltipPayload) => dataKeys.includes(p.dataKey as string)) - .map(p => format(p)); - return ; -}; diff --git a/plugins/cost-insights/src/components/ProductInsights/ProductInsights.tsx b/plugins/cost-insights/src/components/ProductInsights/ProductInsights.tsx index 16146cb045..c5d39a5139 100644 --- a/plugins/cost-insights/src/components/ProductInsights/ProductInsights.tsx +++ b/plugins/cost-insights/src/components/ProductInsights/ProductInsights.tsx @@ -21,6 +21,7 @@ import { useConfig } from '../../hooks'; export const ProductInsights = ({}) => { const config = useConfig(); + return ( <> diff --git a/plugins/cost-insights/src/components/ProductInsightsCard/ProductEntityDialog.tsx b/plugins/cost-insights/src/components/ProductInsightsCard/ProductEntityDialog.tsx new file mode 100644 index 0000000000..764a18d305 --- /dev/null +++ b/plugins/cost-insights/src/components/ProductInsightsCard/ProductEntityDialog.tsx @@ -0,0 +1,188 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import classnames from 'classnames'; +import { Table, TableColumn } from '@backstage/core'; +import { Dialog, IconButton, Typography } from '@material-ui/core'; +import { default as CloseButton } from '@material-ui/icons/Close'; +import { CostGrowthIndicator } from '../CostGrowth'; +import { currencyFormatter, formatPercent } from '../../utils/formatters'; +import { useEntityDialogStyles as useStyles } from '../../utils/styles'; +import { BarChartOptions, Entity } from '../../types'; + +function createRenderer(col: keyof RowData, classes: Record) { + return function render(rowData: {}): JSX.Element { + const row = rowData as RowData; + const rowStyles = classnames(classes.row, { + [classes.rowTotal]: row.id === 'total', + [classes.colFirst]: col === 'sku', + [classes.colLast]: col === 'ratio', + }); + + switch (col) { + case 'previous': + case 'current': + return ( + + {currencyFormatter.format(row[col])} + + ); + case 'ratio': + return ( + formatPercent(Math.abs(amount))} + /> + ); + default: + return {row.sku}; + } + }; +} + +// material-table does not support fixed rows. Override the sorting algorithm +// to force Total row to bottom by default or when a user sort toggles a column. +function createSorter(field?: keyof Omit) { + return function rowSort(data1: {}, data2: {}): number { + const a = data1 as RowData; + const b = data2 as RowData; + if (a.id === 'total') return 1; + if (b.id === 'total') return 1; + if (field === 'sku') return a.sku.localeCompare(b.sku); + + return field + ? a[field] - b[field] + : b.previous + b.current - (a.previous - a.current); + }; +} + +const defaultEntity: Entity = { + id: null, + aggregation: [0, 0], + change: { ratio: 0, amount: 0 }, + entities: [], +}; + +type RowData = { + id: string; + sku: string; + previous: number; + current: number; + ratio: number; +}; + +type ProductEntityDialogOptions = Partial< + Pick +>; + +type ProductEntityDialogProps = { + open: boolean; + entity?: Entity; + options?: ProductEntityDialogOptions; + onClose: () => void; +}; + +export const ProductEntityDialog = ({ + open, + entity = defaultEntity, + options = {}, + onClose, +}: ProductEntityDialogProps) => { + const classes = useStyles(); + + const data = Object.assign( + { + previousName: 'Previous', + currentName: 'Current', + }, + options, + ); + + const firstColClasses = classnames(classes.column, classes.colFirst); + const lastColClasses = classnames(classes.column, classes.colLast); + + const columns: TableColumn[] = [ + { + field: 'sku', + title: SKU, + render: createRenderer('sku', classes), + customSort: createSorter('sku'), + }, + { + field: 'previous', + title: ( + {data.previousName} + ), + align: 'right', + render: createRenderer('previous', classes), + customSort: createSorter('previous'), + }, + { + field: 'current', + title: ( + {data.currentName} + ), + align: 'right', + render: createRenderer('current', classes), + customSort: createSorter('current'), + }, + { + field: 'ratio', + title: M/M, + align: 'right', + render: createRenderer('ratio', classes), + customSort: createSorter('ratio'), + }, + ]; + + const rowData: RowData[] = entity.entities + .map(e => ({ + id: e.id || 'Unknown', + sku: e.id || 'Unknown', + previous: e.aggregation[0], + current: e.aggregation[1], + ratio: e.change.ratio, + })) + .concat({ + id: 'total', + sku: 'Total', + previous: entity.aggregation[0], + current: entity.aggregation[1], + ratio: entity.change.ratio, + }) + .sort(createSorter()); + + return ( + + + + + + + ); +}; diff --git a/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.test.tsx b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.test.tsx index 9d1610e298..cdbbb79806 100644 --- a/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.test.tsx +++ b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.test.tsx @@ -20,7 +20,6 @@ import { ProductInsightsCard } from './ProductInsightsCard'; import { CostInsightsApi } from '../../api'; import { createMockEntity, - createMockProductCost, mockDefaultLoadingState, MockComputeEngine, MockProductFilters, @@ -35,16 +34,14 @@ import { MockScrollProvider, MockLoadingProvider, } from '../../utils/tests'; -import { Duration, Product, ProductCost, ProductPeriod } from '../../types'; +import { Duration, Entity, Product, ProductPeriod } from '../../types'; -const costInsightsApi = ( - productCost: ProductCost, -): Partial => ({ - getProductInsights: () => - Promise.resolve(productCost) as Promise, +const costInsightsApi = (entity: Entity): Partial => ({ + getProductInsights: () => Promise.resolve(entity), }); -const mockProductCost = createMockProductCost(() => ({ +const mockProductCost = createMockEntity(() => ({ + id: 'test-id', entities: [], aggregation: [3000, 4000], change: { @@ -54,12 +51,12 @@ const mockProductCost = createMockProductCost(() => ({ })); const renderProductInsightsCardInTestApp = async ( - productCost: ProductCost, + entity: Entity, product: Product, duration: Duration, ) => await renderInTestApp( - + @@ -96,27 +93,30 @@ describe('', () => { }); it('Should render the right subheader for products with cost data', async () => { - const productCost = { + const entity = { ...mockProductCost, entities: [...Array(1000)].map(createMockEntity), }; const rendered = await renderProductInsightsCardInTestApp( - productCost, + entity, MockComputeEngine, Duration.P1M, ); const subheader = 'entities, sorted by cost'; - const subheaderRgx = new RegExp( - `${productCost.entities.length} ${subheader}`, - ); + const subheaderRgx = new RegExp(`${entity.entities.length} ${subheader}`); expect(rendered.getByText(subheaderRgx)).toBeInTheDocument(); }); it('Should render the right subheader if there is no cost data or change data', async () => { - const productCost = { entities: [], aggregation: [0, 0] } as ProductCost; + const entity: Entity = { + id: 'test-id', + entities: [], + aggregation: [0, 0], + change: { ratio: 0, amount: 0 }, + }; const subheader = `There are no ${MockComputeEngine.name} costs within this timeframe for your team's projects.`; const rendered = await renderProductInsightsCardInTestApp( - productCost, + entity, MockComputeEngine, Duration.P1M, ); @@ -138,12 +138,12 @@ describe('', () => { 'Should display the correct relative time', ({ duration, periodStartText, periodEndText }) => { it(`Should display the correct relative time for ${duration}`, async () => { - const productCost = { + const entity = { ...mockProductCost, entities: [...Array(3)].map(createMockEntity), }; const rendered = await renderProductInsightsCardInTestApp( - productCost, + entity, MockComputeEngine, duration, ); diff --git a/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.tsx b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.tsx index b78053ab5b..2a1f962000 100644 --- a/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.tsx +++ b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.tsx @@ -16,12 +16,11 @@ import React, { useCallback, useEffect, useState } from 'react'; import { InfoCard, useApi } from '@backstage/core'; -import { Box, Typography } from '@material-ui/core'; import Alert from '@material-ui/lab/Alert'; +import { Typography } from '@material-ui/core'; import { costInsightsApiRef } from '../../api'; +import { ProductInsightsChart } from './ProductInsightsChart'; import { PeriodSelect } from '../PeriodSelect'; -import { ResourceGrowthBarChart } from '../ResourceGrowthBarChart'; -import { ResourceGrowthBarChartLegend } from '../ResourceGrowthBarChartLegend'; import { useFilters, useLastCompleteBillingDate, @@ -30,9 +29,8 @@ import { } from '../../hooks'; import { useProductInsightsCardStyles as useStyles } from '../../utils/styles'; import { mapFiltersToProps, mapLoadingToProps } from './selector'; -import { Duration, Maybe, Product, ProductCost } from '../../types'; +import { Duration, Maybe, Product, Entity } from '../../types'; import { pluralOf } from '../../utils/grammar'; -import { formatPeriod } from '../../utils/formatters'; type ProductInsightsCardProps = { product: Product; @@ -43,7 +41,7 @@ export const ProductInsightsCard = ({ product }: ProductInsightsCardProps) => { const classes = useStyles(); const { ScrollAnchor } = useScroll(product.kind); const lastCompleteBillingDate = useLastCompleteBillingDate(); - const [resource, setResource] = useState>(null); + const [entity, setEntity] = useState>(null); const [error, setError] = useState>(null); const { group, product: productFilter, setProduct, project } = useFilters( @@ -57,39 +55,25 @@ export const ProductInsightsCard = ({ product }: ProductInsightsCardProps) => { // eslint-disable-next-line react-hooks/exhaustive-deps const dispatchLoadingProduct = useCallback(dispatchLoading, [product.kind]); - const amount = resource?.entities?.length || 0; - const hasCostsWithinTimeframe = !!(resource?.change && amount); - - const previousName = formatPeriod( - productFilter.duration, - lastCompleteBillingDate, - false, - ); - const currentName = formatPeriod( - productFilter.duration, - lastCompleteBillingDate, - true, - ); + const amount = entity?.entities?.length || 0; + const hasCostsWithinTimeframe = !!(entity?.change && amount); const subheader = hasCostsWithinTimeframe ? `${amount} ${pluralOf(amount, 'entity', 'entities')}, sorted by cost` : null; - const costStart = resource?.aggregation[0] || 0; - const costEnd = resource?.aggregation[1] || 0; - useEffect(() => { async function load() { if (loadingProduct) { try { - const p: ProductCost = await client.getProductInsights({ + const e: Entity = await client.getProductInsights({ product: product.kind, group: group!, duration: productFilter!.duration, lastCompleteBillingDate, project, }); - setResource(p); + setEntity(e); } catch (e) { setError(e); } finally { @@ -101,7 +85,7 @@ export const ProductInsightsCard = ({ product }: ProductInsightsCardProps) => { }, [ client, product, - setResource, + setEntity, loadingProduct, dispatchLoadingProduct, productFilter, @@ -137,7 +121,7 @@ export const ProductInsightsCard = ({ product }: ProductInsightsCardProps) => { ); } - if (!resource) { + if (!entity) { return null; } @@ -145,23 +129,11 @@ export const ProductInsightsCard = ({ product }: ProductInsightsCardProps) => { {hasCostsWithinTimeframe ? ( - - - - - - + ) : ( There are no {product.name} costs within this timeframe for your diff --git a/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsChart.tsx b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsChart.tsx new file mode 100644 index 0000000000..6050dae9c7 --- /dev/null +++ b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsChart.tsx @@ -0,0 +1,225 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { useEffect, useState } from 'react'; +import { + ContentRenderer, + TooltipProps as RechartsTooltipProps, + RechartsFunction, +} from 'recharts'; +import { Box, Typography } from '@material-ui/core'; +import { default as FullScreenIcon } from '@material-ui/icons/Fullscreen'; +import { LegendItem } from '../LegendItem'; +import { ProductEntityDialog } from './ProductEntityDialog'; +import { CostGrowth, CostGrowthIndicator } from '../CostGrowth'; +import { + BarChart, + BarChartLegend, + BarChartTooltip, + BarChartTooltipItem, +} from '../BarChart'; +import { pluralOf } from '../../utils/grammar'; +import { findAlways, notEmpty } from '../../utils/assert'; +import { formatPeriod, formatPercent } from '../../utils/formatters'; +import { + titleOf, + tooltipItemOf, + resourceOf, + isInvalid, + isActiveLabel, +} from '../../utils/graphs'; +import { + useProductInsightsChartStyles as useStyles, + useBarChartLayoutStyles as useLayoutStyles, +} from '../../utils/styles'; +import { BarChartOptions, Duration, Entity, Maybe } from '../../types'; + +export type ProductInsightsChartProps = { + billingDate: string; + entity: Entity; + duration: Duration; +}; + +export const ProductInsightsChart = ({ + billingDate, + entity, + duration, +}: ProductInsightsChartProps) => { + const classes = useStyles(); + const layoutClasses = useLayoutStyles(); + const [isOpen, setOpen] = useState(false); + const [isClickable, setClickable] = useState(true); + const [selectLabel, setSelected] = useState>(null); + const [activeLabel, setActive] = useState>(null); + + const legendTitle = `Cost ${entity.change.ratio <= 0 ? 'Savings' : 'Growth'}`; + const costStart = entity.aggregation[0]; + const costEnd = entity.aggregation[1]; + const resources = entity.entities.map(resourceOf); + + const options: Partial = { + previousName: formatPeriod(duration, billingDate, false), + currentName: formatPeriod(duration, billingDate, true), + }; + + useEffect(() => { + function toggleModal() { + if (selectLabel) { + setOpen(true); + } else { + setOpen(false); + } + } + + toggleModal(); + }, [selectLabel]); + + useEffect(() => { + // disable click if an entity is unlabeled or if it does not have any skus + function toggleClickableEntity() { + if (activeLabel) { + const hasSkus = entity.entities.find(e => e.id === activeLabel) + ?.entities.length; + if (hasSkus) { + setClickable(true); + } else { + setClickable(false); + } + } else { + setClickable(false); + } + } + + toggleClickableEntity(); + }, [activeLabel, entity]); + + const onMouseMove: RechartsFunction = ( + data: Record<'activeLabel', string | undefined>, + ) => { + if (isActiveLabel(data)) { + setActive(data.activeLabel!); + } else { + setActive(null); + } + }; + + const onClick: RechartsFunction = (data: Record<'activeLabel', string>) => { + if (isActiveLabel(data)) { + setSelected(data.activeLabel); + } else { + setSelected(null); + } + }; + + const renderProductInsightsTooltip: ContentRenderer = ({ + label, + payload = [], + }) => { + /* Labels and payloads may be undefined or empty */ + if (isInvalid({ label, payload })) return null; + + /* + * recharts coerces null values to strings + * entity -> resource -> payload + * { id: null } -> { name: null } -> { label: '' } + */ + const id = label === '' ? null : label; + + const title = titleOf(label); + const items = payload.map(tooltipItemOf).filter(notEmpty); + + const activeEntity = findAlways(entity.entities, e => e.id === id); + const ratio = activeEntity.change.ratio; + const skus = activeEntity.entities; + const subtitle = `${skus.length} ${pluralOf(skus.length, 'SKU')}`; + + if (skus.length) { + return ( + + } + actions={ + + + Click for breakdown + + } + > + {items.map((item, index) => ( + + ))} + + ); + } + + // If an entity doesn't have any skus, there aren't any costs to break down. + return ( + + } + content={ + id + ? null + : "This product has costs that are not labeled and therefore can't be attributed to a specific entity." + } + > + {items.map((item, index) => ( + + ))} + + ); + }; + + const barChartProps = isClickable ? { onClick } : {}; + + return ( + + + + + + + + {selectLabel && entity.entities.length && ( + setSelected(null)} + entity={entity.entities.find(e => e.id === selectLabel)} + options={options} + /> + )} + + ); +}; diff --git a/plugins/cost-insights/src/components/ProductInsightsCard/index.ts b/plugins/cost-insights/src/components/ProductInsightsCard/index.ts index 61222f9466..33a402234c 100644 --- a/plugins/cost-insights/src/components/ProductInsightsCard/index.ts +++ b/plugins/cost-insights/src/components/ProductInsightsCard/index.ts @@ -15,3 +15,4 @@ */ export { ProductInsightsCard } from './ProductInsightsCard'; +export { ProductInsightsChart } from './ProductInsightsChart'; diff --git a/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.tsx b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.tsx index 4311bcc1bf..bcda21e0af 100644 --- a/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.tsx +++ b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.tsx @@ -15,12 +15,9 @@ */ import React from 'react'; -import moment from 'moment'; -import { Box } from '@material-ui/core'; import { InfoCard } from '@backstage/core'; -import { ResourceGrowthBarChart } from '../ResourceGrowthBarChart'; -import { ResourceGrowthBarChartLegend } from '../ResourceGrowthBarChartLegend'; -import { Duration, ProjectGrowthData } from '../../types'; +import { ProjectGrowthAlertChart } from './ProjectGrowthAlertChart'; +import { ProjectGrowthData } from '../../types'; import { pluralOf } from '../../utils/grammar'; type ProjectGrowthAlertProps = { @@ -28,39 +25,17 @@ type ProjectGrowthAlertProps = { }; export const ProjectGrowthAlertCard = ({ alert }: ProjectGrowthAlertProps) => { - const [costStart, costEnd] = alert.aggregation; - const subheader = ` ${alert.products.length} ${pluralOf(alert.products.length, 'product')}${ alert.products.length > 1 ? ', sorted by cost' : '' }`; - const previousName = moment(alert.periodStart, 'YYYY-[Q]Q').format( - '[Q]Q YYYY', - ); - const currentName = moment(alert.periodEnd, 'YYYY-[Q]Q').format('[Q]Q YYYY'); return ( - - - - - - + ); }; diff --git a/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertChart.tsx b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertChart.tsx new file mode 100644 index 0000000000..53e52f18e8 --- /dev/null +++ b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertChart.tsx @@ -0,0 +1,55 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import moment from 'moment'; +import { Box } from '@material-ui/core'; +import { BarChart, BarChartLegend } from '../BarChart'; +import { LegendItem } from '../LegendItem'; +import { CostGrowth } from '../CostGrowth'; +import { BarChartOptions, Duration, ProjectGrowthData } from '../../types'; +import { useBarChartLayoutStyles as useStyles } from '../../utils/styles'; +import { resourceOf } from '../../utils/graphs'; + +type ProjectGrowthAlertChartProps = { + alert: ProjectGrowthData; +}; + +export const ProjectGrowthAlertChart = ({ + alert, +}: ProjectGrowthAlertChartProps) => { + const classes = useStyles(); + + const costStart = alert.aggregation[0]; + const costEnd = alert.aggregation[1]; + const resourceData = alert.products.map(resourceOf); + + const options: Partial = { + previousName: moment(alert.periodStart, 'YYYY-[Q]Q').format('[Q]Q YYYY'), + currentName: moment(alert.periodEnd, 'YYYY-[Q]Q').format('[Q]Q YYYY'), + }; + + return ( + + + + + + + + + ); +}; diff --git a/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/ProjectGrowthInstructionsPage.tsx b/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/ProjectGrowthInstructionsPage.tsx index f2083388ae..41b4ca90f6 100644 --- a/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/ProjectGrowthInstructionsPage.tsx +++ b/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/ProjectGrowthInstructionsPage.tsx @@ -15,19 +15,22 @@ */ import React from 'react'; +import moment from 'moment'; import { Box, Typography } from '@material-ui/core'; import { InfoCard } from '@backstage/core'; import { AlertInstructionsLayout } from '../AlertInstructionsLayout'; +import { ProductInsightsChart } from '../ProductInsightsCard'; import { Alert, + DEFAULT_DATE_FORMAT, Duration, Entity, Product, ProjectGrowthData, } from '../../types'; import { ProjectGrowthAlert } from '../../utils/alerts'; -import { ResourceGrowthBarChartLegend } from '../ResourceGrowthBarChartLegend'; -import { ResourceGrowthBarChart } from '../ResourceGrowthBarChart'; + +const today = moment().format(DEFAULT_DATE_FORMAT); export const ProjectGrowthInstructionsPage = () => { const alertData: ProjectGrowthData = { @@ -54,6 +57,7 @@ export const ProjectGrowthInstructionsPage = () => { }, ], }; + const projectGrowthAlert: Alert = new ProjectGrowthAlert(alertData); const product: Product = { @@ -61,20 +65,34 @@ export const ProjectGrowthInstructionsPage = () => { name: 'Compute Engine', }; - const entities: Entity[] = [ - { - id: 'service-one', - aggregation: [18200, 58500], + const entity: Entity = { + id: 'example-id', + aggregation: [20_000, 60_000], + change: { + ratio: 3, + amount: 40_000, }, - { - id: 'service-two', - aggregation: [1200, 1300], - }, - { - id: 'service-three', - aggregation: [600, 200], - }, - ]; + entities: [ + { + id: 'service-one', + aggregation: [18_200, 58_500], + entities: [], + change: { ratio: 2.21, amount: 40_300 }, + }, + { + id: 'service-two', + aggregation: [1200, 1300], + entities: [], + change: { ratio: 0.083, amount: 100 }, + }, + { + id: 'service-three', + aggregation: [600, 200], + entities: [], + change: { ratio: -0.666, amount: -400 }, + }, + ], + }; return ( @@ -153,27 +171,12 @@ export const ProjectGrowthInstructionsPage = () => { ) that has grown in cost: - {/* ProductInsightsCard without API query / PeriodSelect */} - - - - - - - - + diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.test.tsx b/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.test.tsx deleted file mode 100644 index e3d9d61d1b..0000000000 --- a/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.test.tsx +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import React from 'react'; -import { ResourceGrowthBarChart } from './ResourceGrowthBarChart'; -import { renderInTestApp } from '@backstage/test-utils'; -import { createMockEntity } from '../../utils/mockData'; - -const MockResources = [...Array(10)].map((_, index) => - createMockEntity(() => ({ - id: `test-id-${index + 1}`, - // grow resource costs linearly for testing - aggregation: [index * 1000, (index + 1) * 1000], - })), -); - -describe('', () => { - it('Pre-renders without exploding', async () => { - const rendered = await renderInTestApp( - , - ); - expect(rendered.queryByTestId('bar-chart-wrapper')).toBeInTheDocument(); - }); -}); diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.tsx b/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.tsx deleted file mode 100644 index b4014bf00f..0000000000 --- a/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.tsx +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import React from 'react'; -import { TooltipPayload } from 'recharts'; -import { currencyFormatter } from '../../utils/formatters'; -import { - AlertCost, - BarChartData, - CostInsightsTheme, - DataKey, - Entity, - Maybe, - ResourceData, -} from '../../types'; -import { BarChart } from '../BarChart'; -import { TooltipItemProps } from '../Tooltip'; -import { useTheme } from '@material-ui/core'; - -export type ResourceGrowthBarChartProps = { - resources: Array; - previousName: string; - currentName: string; -}; - -export const ResourceGrowthBarChart = ({ - resources, - previousName, - currentName, -}: ResourceGrowthBarChartProps) => { - const theme = useTheme(); - const getTooltipItem = (payload: TooltipPayload): Maybe => { - const value = - typeof payload.value === 'number' - ? currencyFormatter.format(payload.value) - : (payload.value as string); - const fill = payload.fill as string; - - switch (payload.dataKey) { - case DataKey.Current: - case DataKey.Previous: - return { - label: payload.name, - value: value, - fill: fill, - }; - default: - return null; - } - }; - - const barChartData: BarChartData = { - previousFill: theme.palette.lightBlue, - currentFill: theme.palette.darkBlue, - previousName: previousName, - currentName: currentName, - }; - - const resourceData: ResourceData[] = resources.map(resource => { - return { - name: resource.id, - previous: resource.aggregation[0], - current: resource.aggregation[1], - }; - }); - - return ( - - ); -}; diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChart/index.ts b/plugins/cost-insights/src/components/ResourceGrowthBarChart/index.ts deleted file mode 100644 index ef649a17af..0000000000 --- a/plugins/cost-insights/src/components/ResourceGrowthBarChart/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export { ResourceGrowthBarChart } from './ResourceGrowthBarChart'; diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.test.tsx b/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.test.tsx deleted file mode 100644 index 47285a2363..0000000000 --- a/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.test.tsx +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import React, { PropsWithChildren } from 'react'; -import { renderInTestApp } from '@backstage/test-utils'; -import { ResourceGrowthBarChartLegend } from './ResourceGrowthBarChartLegend'; -import { defaultCurrencies } from '../../utils/currency'; -import { findAlways } from '../../utils/assert'; -import { MockConfigProvider, MockCurrencyProvider } from '../../utils/tests'; -import { Duration } from '../../types'; - -const engineers = findAlways(defaultCurrencies, c => c.kind === null); - -const MockContext = ({ children }: PropsWithChildren<{}>) => ( - - {children} - -); - -describe('', () => { - describe.each` - ratio | amount | costText | engineerTest - ${2.5} | ${300_000} | ${'Cost Growth'} | ${/\~6 engineers/} - ${-2.5} | ${-120_000} | ${'Cost Savings'} | ${/\~2 engineers/} - `( - 'Should display the cost text', - ({ ratio, amount, costText, engineerTest }) => { - it(`Should display the correct cost and engineer text for ${ratio} percent change`, async () => { - const rendered = await renderInTestApp( - - - , - ); - expect(rendered.getByText(costText)).toBeInTheDocument(); - expect(rendered.queryByText(engineerTest)).toBeInTheDocument(); - }); - }, - ); -}); diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/index.ts b/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/index.ts deleted file mode 100644 index ee77a483e6..0000000000 --- a/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export { ResourceGrowthBarChartLegend } from './ResourceGrowthBarChartLegend'; diff --git a/plugins/cost-insights/src/components/Tooltip/Tooltip.tsx b/plugins/cost-insights/src/components/Tooltip/Tooltip.tsx deleted file mode 100644 index e0ee93c669..0000000000 --- a/plugins/cost-insights/src/components/Tooltip/Tooltip.tsx +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import React from 'react'; -import { Box, Typography } from '@material-ui/core'; -import { TooltipItem, TooltipItemProps } from './TooltipItem'; -import { useTooltipStyles } from '../../utils/styles'; - -export type TooltipProps = { - label?: string; - items?: Array; -}; - -export const Tooltip = ({ label, items }: TooltipProps) => { - const classes = useTooltipStyles(); - return ( - - {label && ( - - {label} - - )} - {items && - items.map((item, index) => ( - - ))} - - ); -}; diff --git a/plugins/cost-insights/src/components/Tooltip/index.ts b/plugins/cost-insights/src/components/Tooltip/index.ts deleted file mode 100644 index b26409480e..0000000000 --- a/plugins/cost-insights/src/components/Tooltip/index.ts +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export { Tooltip } from './Tooltip'; -export type { TooltipProps } from './Tooltip'; -export { TooltipItem } from './TooltipItem'; -export type { TooltipItemProps } from './TooltipItem'; diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.tsx b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.tsx index 8bc5ebfb6e..e56b3b044e 100644 --- a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.tsx +++ b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.tsx @@ -15,12 +15,12 @@ */ import React from 'react'; -import { Box } from '@material-ui/core'; import { InfoCard } from '@backstage/core'; -import { UnlabeledDataflowBarChart } from './UnlabeledDataflowBarChart'; -import { UnlabeledDataflowBarChartLegend } from './UnlabeledDataflowBarChartLegend'; -import { UnlabeledDataflowData } from '../../types'; +import { Box } from '@material-ui/core'; +import { BarChart, BarChartLegend } from '../BarChart'; +import { UnlabeledDataflowData, ResourceData } from '../../types'; import { pluralOf } from '../../utils/grammar'; +import { useBarChartLayoutStyles as useStyles } from '../../utils/styles'; type UnlabeledDataflowAlertProps = { alert: UnlabeledDataflowData; @@ -29,22 +29,31 @@ type UnlabeledDataflowAlertProps = { export const UnlabeledDataflowAlertCard = ({ alert, }: UnlabeledDataflowAlertProps) => { + const classes = useStyles(); const projects = pluralOf(alert.projects.length, 'project'); const subheader = ` Showing costs from ${alert.projects.length} ${projects} with unlabeled Dataflow jobs in the last 30 days. `; + const options = { + previousName: 'Unlabeled Cost', + currentName: 'Labeled Cost', + }; + + const resources: ResourceData[] = alert.projects.map(project => ({ + name: project.id, + previous: project.unlabeledCost, + current: project.labeledCost, + })); + return ( - - - - - - - + + + ); diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChart.tsx b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChart.tsx deleted file mode 100644 index faf27ba04f..0000000000 --- a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChart.tsx +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import React from 'react'; -import { TooltipPayload } from 'recharts'; -import { BarChart } from '../BarChart'; -import { TooltipItemProps } from '../Tooltip'; -import { - BarChartData, - CostInsightsTheme, - ResourceData, - UnlabeledDataflowAlertProject, -} from '../../types'; -import { currencyFormatter } from '../../utils/formatters'; -import { useTheme } from '@material-ui/core'; - -type UnlabeledDataflowBarChartProps = { - projects: Array; -}; - -export const UnlabeledDataflowBarChart = ({ - projects, -}: UnlabeledDataflowBarChartProps) => { - const theme = useTheme(); - const barChartData: BarChartData = { - previousFill: theme.palette.lightBlue, - currentFill: theme.palette.darkBlue, - previousName: 'Unlabeled Cost', - currentName: 'Labeled Cost', - }; - - const getTooltipItem = (payload: TooltipPayload): TooltipItemProps => { - return { - label: payload.name, - value: - typeof payload.value === 'number' - ? currencyFormatter.format(payload.value) - : (payload.value as string), - fill: payload.fill as string, - }; - }; - - const resources: ResourceData[] = projects.map(project => { - return { - name: project.id, - previous: project.unlabeledCost || 0, - current: project.labeledCost || 0, - }; - }); - - return ( - - ); -}; diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChartLegend.tsx b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChartLegend.tsx deleted file mode 100644 index aac37c799d..0000000000 --- a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChartLegend.tsx +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import React from 'react'; -import { Box, useTheme } from '@material-ui/core'; -import { LegendItem } from '../LegendItem'; -import { currencyFormatter } from '../../utils/formatters'; -import { CostInsightsTheme } from '../../types'; - -type UnlabeledDataflowBarChartLegendProps = { - labeledCost: number; - unlabeledCost: number; -}; - -export const UnlabeledDataflowBarChartLegend = ({ - unlabeledCost, - labeledCost, -}: UnlabeledDataflowBarChartLegendProps) => { - const theme = useTheme(); - return ( - - - - {currencyFormatter.format(unlabeledCost)} - - - - - {currencyFormatter.format(labeledCost)} - - - - ); -}; diff --git a/plugins/cost-insights/src/components/index.ts b/plugins/cost-insights/src/components/index.ts index 5b918144d9..c390666419 100644 --- a/plugins/cost-insights/src/components/index.ts +++ b/plugins/cost-insights/src/components/index.ts @@ -17,4 +17,3 @@ export * from './BarChart'; export * from './CostGrowth'; export * from './LegendItem'; -export * from './Tooltip'; diff --git a/plugins/cost-insights/src/types/Alert.ts b/plugins/cost-insights/src/types/Alert.ts index d6046e3241..c5c0463d99 100644 --- a/plugins/cost-insights/src/types/Alert.ts +++ b/plugins/cost-insights/src/types/Alert.ts @@ -41,13 +41,16 @@ export interface ResourceData { name: Maybe; } -export interface BarChartData { +export interface BarChartOptions { previousFill: string; currentFill: string; previousName: string; currentName: string; } +/** deprecated use BarChartOptions instead */ +export interface BarChartData extends BarChartOptions {} + export enum DataKey { Previous = 'previous', Current = 'current', diff --git a/plugins/cost-insights/src/types/Entity.ts b/plugins/cost-insights/src/types/Entity.ts index f5ac620289..83347f05c3 100644 --- a/plugins/cost-insights/src/types/Entity.ts +++ b/plugins/cost-insights/src/types/Entity.ts @@ -20,5 +20,68 @@ import { Maybe } from './Maybe'; export interface Entity { id: Maybe; aggregation: [number, number]; - change?: Maybe; + entities: Entity[]; + change: ChangeStatistic; } + +/* + An entity is a tree-like structure that represents any unique + product or service that generates cost over a fixed period of time. + An entity could be atomic or composite. An atomic entity is indivisible + and cannot be broken into sub-entities. + + A composite entity can be broken down recursively into sub-entities + that generate cost **over the same time period**. All costs must sum to the root cost. + + Entities with null ids are considered "unlabeled" - costs without attribution. + If an entity is a composite, it may only have one (1) null child but may have any number of + null grandchildren. + + { + id: 'product', + aggregation: [0, 200], + change: { + ratio: 2000, + amount: 200 + }, + entities: [ + { + id: 'service-a', + aggregation: [0, 100], + change: { + ratio: 100, + amount: 100 + }, + entities: [] + }, + { + id: 'service-b', + aggregation: [0, 100], + change: { + ratio: 100, + amount: 100 + }, + entities: [ + { + id: 'service-b-sku-a', + aggregation: [0, 25], + change: { + ratio: 25, + amount: 25 + }, + entities: [] + }, + { + id: null, // Unlabeled cost for service-b + aggregation: [0, 75], + change: { + ratio: 75, + amount: 75 + }, + entities: [] + }, + ] + }, + ] + } +*/ diff --git a/plugins/cost-insights/src/types/Product.ts b/plugins/cost-insights/src/types/Product.ts index d2087644cb..77df579a11 100644 --- a/plugins/cost-insights/src/types/Product.ts +++ b/plugins/cost-insights/src/types/Product.ts @@ -14,17 +14,7 @@ * limitations under the License. */ -import { Entity } from './Entity'; -import { ChangeStatistic } from './ChangeStatistic'; -import { Maybe } from './Maybe'; - export interface Product { kind: string; name: string; } - -export interface ProductCost { - entities?: Array; - aggregation: [number, number]; - change?: Maybe; -} diff --git a/plugins/cost-insights/src/utils/change.test.ts b/plugins/cost-insights/src/utils/change.test.ts new file mode 100644 index 0000000000..daf4538f2c --- /dev/null +++ b/plugins/cost-insights/src/utils/change.test.ts @@ -0,0 +1,62 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { growthOf } from './change'; +import { GrowthType, ChangeThreshold, EngineerThreshold } from '../types'; + +const GrowthMap = { + [GrowthType.Negligible]: 'negligible growth', + [GrowthType.Savings]: 'cost savings', + [GrowthType.Excess]: 'cost excess', +}; + +describe.each` + ratio | amount | expected + ${0.0} | ${undefined} | ${GrowthType.Negligible} + ${0.0} | ${EngineerThreshold} | ${GrowthType.Negligible} + ${ChangeThreshold.lower} | ${0} | ${GrowthType.Negligible} + ${ChangeThreshold.lower + 0.01} | ${undefined} | ${GrowthType.Negligible} + ${ChangeThreshold.lower + 0.01} | ${EngineerThreshold} | ${GrowthType.Negligible} + ${ChangeThreshold.lower + 0.01} | ${EngineerThreshold + 0.1} | ${GrowthType.Negligible} + ${ChangeThreshold.lower - 0.01} | ${EngineerThreshold - 0.1} | ${GrowthType.Negligible} + ${ChangeThreshold.upper - 0.01} | ${undefined} | ${GrowthType.Negligible} + ${ChangeThreshold.upper + 0.01} | ${EngineerThreshold - 0.1} | ${GrowthType.Negligible} + ${ChangeThreshold.lower} | ${undefined} | ${GrowthType.Savings} + ${ChangeThreshold.lower} | ${EngineerThreshold} | ${GrowthType.Savings} + ${ChangeThreshold.lower - 0.01} | ${undefined} | ${GrowthType.Savings} + ${ChangeThreshold.lower - 0.01} | ${EngineerThreshold} | ${GrowthType.Savings} + ${ChangeThreshold.lower - 0.01} | ${EngineerThreshold + 0.1} | ${GrowthType.Savings} + ${ChangeThreshold.upper} | ${undefined} | ${GrowthType.Excess} + ${ChangeThreshold.upper} | ${EngineerThreshold} | ${GrowthType.Excess} + ${ChangeThreshold.upper + 0.01} | ${undefined} | ${GrowthType.Excess} + ${ChangeThreshold.upper + 0.01} | ${EngineerThreshold} | ${GrowthType.Excess} + ${ChangeThreshold.upper + 0.01} | ${EngineerThreshold + 0.1} | ${GrowthType.Excess} +`( + 'growthOf', + ({ + ratio, + amount, + expected, + }: { + ratio: number; + amount: number; + expected: GrowthType; + }) => { + it(`should display ${GrowthMap[expected]}`, () => { + expect(growthOf(ratio, amount)).toBe(expected); + }); + }, +); diff --git a/plugins/cost-insights/src/utils/change.ts b/plugins/cost-insights/src/utils/change.ts index 1fe3662537..cc797bb3b0 100644 --- a/plugins/cost-insights/src/utils/change.ts +++ b/plugins/cost-insights/src/utils/change.ts @@ -24,14 +24,18 @@ import { } from '../types'; import { aggregationSort } from '../utils/sort'; -// Used by for displaying status colors -export function growthOf(amount: number, ratio: number) { - if (amount >= EngineerThreshold && ratio >= ChangeThreshold.upper) { - return GrowthType.Excess; - } - - if (amount >= EngineerThreshold && ratio <= ChangeThreshold.lower) { - return GrowthType.Savings; +// Used for displaying status colors +export function growthOf(ratio: number, amount?: number) { + if (typeof amount === 'number') { + if (amount >= EngineerThreshold && ratio >= ChangeThreshold.upper) { + return GrowthType.Excess; + } + if (amount >= EngineerThreshold && ratio <= ChangeThreshold.lower) { + return GrowthType.Savings; + } + } else { + if (ratio >= ChangeThreshold.upper) return GrowthType.Excess; + if (ratio <= ChangeThreshold.lower) return GrowthType.Savings; } return GrowthType.Negligible; diff --git a/plugins/cost-insights/src/utils/graphs.ts b/plugins/cost-insights/src/utils/graphs.ts new file mode 100644 index 0000000000..ac06e20587 --- /dev/null +++ b/plugins/cost-insights/src/utils/graphs.ts @@ -0,0 +1,79 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { TooltipPayload, TooltipProps } from 'recharts'; +import { AlertCost, DataKey, Entity, ResourceData } from '../types'; +import { + currencyFormatter, + dateFormatter, + lengthyCurrencyFormatter, +} from './formatters'; + +export function formatGraphValue(value: number, format?: string) { + if (format === 'number') { + return value.toLocaleString(); + } + + if (value < 1) { + return lengthyCurrencyFormatter.format(value); + } + + return currencyFormatter.format(value); +} + +export const overviewGraphTickFormatter = (millis: string | number) => + typeof millis === 'number' ? dateFormatter.format(millis) : millis; + +export const tooltipItemOf = (payload: TooltipPayload) => { + const value = + typeof payload.value === 'number' + ? currencyFormatter.format(payload.value) + : (payload.value as string); + const fill = payload.fill as string; + + switch (payload.dataKey) { + case DataKey.Current: + case DataKey.Previous: + return { + label: payload.name, + value: value, + fill: fill, + }; + default: + return null; + } +}; + +export const resourceOf = (entity: Entity | AlertCost): ResourceData => ({ + name: entity.id, + previous: entity.aggregation[0], + current: entity.aggregation[1], +}); + +export const titleOf = (label?: string | number) => { + return label ? String(label) : 'Unlabeled'; +}; + +export const isInvalid = ({ label, payload }: TooltipProps) => { + // null labels are empty strings, which are valid + return label === undefined || !payload || !payload.length; +}; + +export const isActiveLabel = ( + data?: Record<'activeLabel', string | undefined>, +) => { + return data?.activeLabel && data.activeLabel !== ''; +}; diff --git a/plugins/cost-insights/src/utils/graphs.tsx b/plugins/cost-insights/src/utils/graphs.tsx deleted file mode 100644 index 167132cb36..0000000000 --- a/plugins/cost-insights/src/utils/graphs.tsx +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { - currencyFormatter, - dateFormatter, - lengthyCurrencyFormatter, -} from './formatters'; - -export function formatGraphValue(value: number, format?: string) { - if (format === 'number') { - return value.toLocaleString(); - } - - if (value < 1) { - return lengthyCurrencyFormatter.format(value); - } - - return currencyFormatter.format(value); -} - -export const overviewGraphTickFormatter = (millis: string | number) => - typeof millis === 'number' ? dateFormatter.format(millis) : millis; diff --git a/plugins/cost-insights/src/utils/mockData.ts b/plugins/cost-insights/src/utils/mockData.ts index 58ba4a4251..ddeb4636b9 100644 --- a/plugins/cost-insights/src/utils/mockData.ts +++ b/plugins/cost-insights/src/utils/mockData.ts @@ -20,7 +20,6 @@ import { Duration, Entity, Product, - ProductCost, ProductFilters, ProjectGrowthData, UnlabeledDataflowAlertProject, @@ -41,6 +40,11 @@ export const createMockEntity = ( const defaultEntity: Entity = { id: 'test-entity', aggregation: [100, 200], + entities: [], + change: { + ratio: 0, + amount: 0, + }, }; if (typeof callback === 'function') { @@ -62,19 +66,6 @@ export const createMockProduct = ( return { ...defaultProduct }; }; -export const createMockProductCost = ( - callback?: mockEntityRenderer, -): ProductCost => { - const defaultProduct: ProductCost = { - entities: [], - aggregation: [0, 0], - }; - if (typeof callback === 'function') { - return callback({ ...defaultProduct }); - } - return { ...defaultProduct }; -}; - export const createMockProjectGrowthData = ( callback?: mockAlertRenderer, ): ProjectGrowthData => { diff --git a/plugins/cost-insights/src/utils/sort.ts b/plugins/cost-insights/src/utils/sort.ts index 944f5fc806..f4fc1987d1 100644 --- a/plugins/cost-insights/src/utils/sort.ts +++ b/plugins/cost-insights/src/utils/sort.ts @@ -19,5 +19,6 @@ export const aggregationSort = ( a: DateAggregation, b: DateAggregation, ): number => a.date.localeCompare(b.date); + export const resourceSort = (a: ResourceData, b: ResourceData) => b.previous + b.current - (a.previous + a.current); diff --git a/plugins/cost-insights/src/utils/styles.ts b/plugins/cost-insights/src/utils/styles.ts index b20c601276..de743d8459 100644 --- a/plugins/cost-insights/src/utils/styles.ts +++ b/plugins/cost-insights/src/utils/styles.ts @@ -15,6 +15,7 @@ */ import { createStyles, + emphasize, darken, getLuminance, lighten, @@ -116,6 +117,18 @@ export const useBarChartStyles = (theme: CostInsightsTheme) => ({ }, }); +export const useBarChartLayoutStyles = makeStyles(theme => + createStyles({ + wrapper: { + display: 'flex', + flexDirection: 'column', + }, + legend: { + paddingBottom: theme.spacing(2), + }, + }), +); + export const useBarChartStepperButtonStyles = makeStyles( (theme: CostInsightsTheme) => createStyles({ @@ -146,12 +159,13 @@ export const useBarChartStepperButtonStyles = makeStyles( }), ); -export const useBarChartLabelStyles = makeStyles(() => +export const useBarChartLabelStyles = makeStyles(theme => createStyles({ foreignObject: { textAlign: 'center', }, label: { + fontWeight: theme.typography.fontWeightBold, display: 'block', textDecoration: 'none', overflow: 'hidden', @@ -162,6 +176,11 @@ export const useBarChartLabelStyles = makeStyles(() => marginLeft: 2, fontSize: '1.25em', }, + button: { + textTransform: 'none', + fontWeight: theme.typography.fontWeightBold, + fontSize: theme.typography.fontSize, + }, }), ); @@ -244,6 +263,12 @@ export const useCostGrowthStyles = makeStyles( savings: { color: theme.palette.status.ok, }, + indicator: { + display: 'flex', + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'flex-end', + }, }), ); @@ -356,16 +381,31 @@ export const useTooltipStyles = makeStyles( (theme: CostInsightsTheme) => createStyles({ tooltip: { - padding: theme.spacing(1.5), backgroundColor: theme.palette.tooltip.background, borderRadius: theme.shape.borderRadius, boxShadow: theme.shadows[1], color: theme.palette.tooltip.color, fontSize: theme.typography.fontSize, + width: 250, + }, + actions: { + padding: theme.spacing(2), + }, + header: { + padding: theme.spacing(2), + }, + content: { + padding: theme.spacing(2), }, lensIcon: { fontSize: `.75rem`, }, + divider: { + backgroundColor: emphasize(theme.palette.divider, 1), + }, + subtitle: { + fontStyle: 'italic', + }, }), ); @@ -446,6 +486,21 @@ export const useProductInsightsCardStyles = makeStyles( }), ); +export const useProductInsightsChartStyles = makeStyles( + (theme: BackstageTheme) => + createStyles({ + indicator: { + fontWeight: theme.typography.fontWeightBold, + fontSize: '1.25rem', + }, + actions: { + display: 'flex', + justifyContent: 'space-between', + alignItems: 'center', + }, + }), +); + export const useBackdropStyles = makeStyles( (theme: BackstageTheme) => createStyles({ @@ -463,3 +518,42 @@ export const useSubtleTypographyStyles = makeStyles( }, }), ); + +export const useEntityDialogStyles = makeStyles(theme => + createStyles({ + dialogContent: { + padding: 0, + }, + dialogTitle: { + padding: 0, + }, + closeButton: { + position: 'absolute', + right: theme.spacing(1), + top: theme.spacing(1), + color: theme.palette.grey[500], + zIndex: 100, + }, + row: { + fontSize: theme.typography.fontSize * 1.25, + }, + rowTotal: { + fontWeight: theme.typography.fontWeightBold, + }, + colFirst: { + paddingLeft: theme.spacing(2), + }, + colLast: { + paddingRight: theme.spacing(2), + }, + column: { + fontWeight: theme.typography.fontWeightBold, + }, + growth: { + display: 'flex', + flexDirection: 'row', + alignContent: 'center', + justifyContent: 'flex-end', + }, + }), +);