Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(pci.savings-plan): amount outside plans consumption #15373

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/manager/apps/pci-savings-plan/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"@tanstack/react-query": "5.51.11",
"@tanstack/react-query-devtools": "5.29.2",
"@testing-library/react": "^16.0.0",
"@testing-library/react-hooks": "^8.0.1",
"axios": "^1.1.2",
"class-variance-authority": "^0.7.0",
"clsx": "^1.2.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@

"dashboard_kpis_non_discounted_name": "Montant de facture non remisé",
"dashboard_kpis_non_discounted_tooltip": "Montant de la facture dépassant vos configurations Savings Plans (sur la période sélectionnée pour la ressource sélectionnée)",
"dashboard_kpis_saved_amount_name": "Economies réalisées",
"dashboard_kpis_saved_amount_name_tooltip": "Total des économies réalisées (sur la période sélectionnée pour la ressource sélectionnée)",
"dashboard_kpis_saved_strikethrough": "Au lieu de",
"dashboard_kpis_amount_outiside": "Montant de facture non remisé",
"dashboard_kpis_amount_outiside_tooltip": "Montant de la facture dépassant vos configurations Savings Plans (sur la période sélectionnée pour la ressource sélectionnée)",

"dashboard_kpis_not_available": "Non disponible",

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,34 @@ import {
} from '@ovhcloud/ods-components/react';
import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { getPercentValue } from '@/utils/kpi/utils';
import { isCurrentPeriod } from '@/utils/kpi/utils';
import { SavingsPlanFlavorConsumption } from '@/types/savingsPlanConsumption.type';
import { useKpiData } from '@/hooks/useKpiData';

const Kpi = ({
title,
value,
valueSavedWithoutAmount,
tooltip,
index,
isLoading,
}: {
title: string;
value: number | string;
valueSavedWithoutAmount?: number | string;
tooltip: string;
index: number;
isLoading: boolean;
}) => {
const { t } = useTranslation('dashboard');
if (isLoading)
return (
<div className="h-16 w-[200px] mx-2 flex flex-col justify-center">
<OdsSkeleton />
</div>
);
return (
<div className="flex flex-col gap-2 w-[200px]">
<div className="flex flex-col gap-2 w-auto">
<OdsText preset="heading-5" className="max-w-lg">
{title}
<OdsIcon
Expand All @@ -49,53 +53,67 @@ const Kpi = ({
</OdsTooltip>
</OdsText>
<span className="text-[20px] font-bold mb-0 text-[#0050D7]">{value}</span>
{valueSavedWithoutAmount && (
<div className="flex items-center">
<span className="text-[15px] mb-0 text-[#666ca1] mr-2">
{t('dashboard_kpis_saved_strikethrough')}
</span>
<span className="line-through text-[15px] mb-0 text-[#666ca1]">
{valueSavedWithoutAmount}
</span>
</div>
)}
</div>
);
};

const Kpis = ({
isLoading,
consumption,
period,
}: Readonly<{
isLoading: boolean;
consumption: SavingsPlanFlavorConsumption;
period: string;
}>) => {
const { t } = useTranslation('dashboard');
const defaultMessage = t('dashboard_kpis_not_available');

const computedPercents = useMemo(() => {
if (!consumption?.periods?.length) {
return {
computedUsagePercent: defaultMessage,
computedCoveragePercent: defaultMessage,
};
}
return {
computedUsagePercent:
getPercentValue(consumption, 'utilization') || defaultMessage,
computedCoveragePercent:
getPercentValue(consumption, 'coverage') || defaultMessage,
};
}, [consumption, defaultMessage]);

const { computedUsagePercent, computedCoveragePercent } = computedPercents;
const computedPercents = useKpiData(consumption);
const isCurrentMonth = useMemo(() => isCurrentPeriod(period), [period]);

const kpiData = [
{
title: t('dashboard_kpis_active_plans_name'),
tooltip: t('dashboard_kpis_active_plans_tooltip'),
value: 5,
value: computedPercents.computedActivePlans,
},
{
title: t('dashboard_kpis_usage_percent_name'),
tooltip: t('dashboard_kpis_usage_percent_tooltip'),
value: computedUsagePercent,
value: computedPercents.computedUsagePercent,
},
{
title: t('dashboard_kpis_coverage_percent_name'),
tooltip: t('dashboard_kpis_coverage_percent_tooltip'),
value: computedCoveragePercent,
value: computedPercents.computedCoveragePercent,
},
...(!isCurrentMonth
? [
{
title: t('dashboard_kpis_saved_amount_name'),
tooltip: t('dashboard_kpis_saved_amount_name_tooltip'),
value: computedPercents.computedSavedAmount,
valueSavedWithoutAmount:
computedPercents.computedWithoutSavedAmount,
},
{
title: t('dashboard_kpis_amount_outiside'),
tooltip: t('dashboard_kpis_amount_outiside_tooltip'),
value: computedPercents.computedSavedAmount,
valueSavedWithoutAmount:
computedPercents.computedWithoutSavedAmount,
},
]
: []),
];

return (
Expand All @@ -108,6 +126,7 @@ const Kpis = ({
tooltip={item.tooltip}
index={index}
isLoading={isLoading}
valueSavedWithoutAmount={item.valueSavedWithoutAmount}
/>
{index < kpiData.length - 1 && (
<div className="h-16 w-px bg-gray-300 mx-2"></div>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import Kpis from './Kpis';
import { useKpiData } from '@/hooks/useKpiData';
import { SavingsPlanFlavorConsumption } from '@/types/savingsPlanConsumption.type';

vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string) => key,
}),
}));

vi.mock('@/hooks/useKpiData', () => ({
useKpiData: vi.fn(),
}));

const dummyConsumption = {
fees: { saved_amount: 100, total_price: 200 },
subscriptions: [{}, {}],
periods: [],
} as SavingsPlanFlavorConsumption;

const computedPercentsMock = {
computedActivePlans: '2',
computedUsagePercent: '50%',
computedCoveragePercent: '60%',
computedSavedAmount: '100.00',
computedWithoutSavedAmount: '150.00',
};

describe('Kpis Component', () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2025-01-15T00:00:00Z'));
(useKpiData as any).mockReturnValue(computedPercentsMock);
});

afterEach(() => {
vi.useRealTimers();
vi.resetAllMocks();
});

it('should not render the saved amount KPI if the period is current', () => {
const currentPeriod = 'janvier 2025';
render(
<Kpis
isLoading={false}
consumption={dummyConsumption}
period={currentPeriod}
/>,
);

expect(screen.getByText('dashboard_kpis_active_plans_name')).toBeTruthy();
expect(screen.getByText('dashboard_kpis_usage_percent_name')).toBeTruthy();
expect(
screen.getByText('dashboard_kpis_coverage_percent_name'),
).toBeTruthy();

expect(screen.queryByText('dashboard_kpis_saved_amount_name')).toBeNull();
});

it('should render the saved amount KPI if the period is not current', () => {
const nonCurrentPeriod = 'février 2025';
render(
<Kpis
isLoading={false}
consumption={dummyConsumption}
period={nonCurrentPeriod}
/>,
);

expect(screen.getByText('dashboard_kpis_active_plans_name')).toBeTruthy();
expect(screen.getByText('dashboard_kpis_usage_percent_name')).toBeTruthy();
expect(
screen.getByText('dashboard_kpis_coverage_percent_name'),
).toBeTruthy();
expect(screen.getByText('dashboard_kpis_saved_amount_name')).toBeTruthy();
});

it('should display skeletons when isLoading is true', () => {
const { container } = render(
<Kpis
isLoading={true}
consumption={dummyConsumption}
period="février 2025"
/>,
);
expect(container.querySelector('.h-16')).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { renderHook } from '@testing-library/react-hooks';
import { vi, describe, it, expect, beforeEach } from 'vitest';
import { useKpiData } from './useKpiData';
import { getPercentValue } from '@/utils/kpi/utils';
import { SavingsPlanFlavorConsumption } from '@/types/savingsPlanConsumption.type';

vi.mock('@ovh-ux/manager-pci-common', () => ({
usePricing: () => ({
formatPrice: (
value: number,
{ decimals }: { decimals: number; unit: number },
) => value.toFixed(decimals),
}),
}));

vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string) => key,
}),
}));

vi.mock('@/utils/kpi/utils', () => ({
getPercentValue: vi.fn(),
}));

describe('useKpiData', () => {
beforeEach(() => {
vi.clearAllMocks();
});

it('returns default messages when there are no periods', () => {
const consumption = {
fees: { saved_amount: 100, total_price: 200 },
periods: [] as string[],
subscriptions: [] as unknown[],
} as SavingsPlanFlavorConsumption;

const { result } = renderHook(() => useKpiData(consumption));
expect(result.current).toEqual({
computedUsagePercent: 'dashboard_kpis_not_available',
computedCoveragePercent: 'dashboard_kpis_not_available',
computedActivePlans: 'dashboard_kpis_not_available',
computedSavedAmount: 'dashboard_kpis_not_available',
computedWithoutSavedAmount: null,
});
});

it('computes KPI values when valid consumption data is provided', () => {
const consumption = {
fees: { saved_amount: 100, total_price: 200 },
periods: ['2023-01'],
subscriptions: [{}, {}],
} as SavingsPlanFlavorConsumption;

vi.mocked(getPercentValue).mockImplementation((cons, period: string) => {
if (period === 'utilization') return '50%';
if (period === 'coverage') return '60%';
return null;
});

const { result } = renderHook(() => useKpiData(consumption));

expect(result.current).toEqual({
computedUsagePercent: '50%',
computedCoveragePercent: '60%',
computedActivePlans: 2,
computedSavedAmount: '100.00',
computedWithoutSavedAmount: '300.00',
});
});

it('returns default message for negative saved amount', () => {
const consumption = {
fees: { saved_amount: -50, total_price: 200 },
periods: ['2023-01'],
subscriptions: [{}],
} as SavingsPlanFlavorConsumption;

vi.mocked(getPercentValue).mockImplementation((cons, period: string) => {
if (period === 'utilization') return '40%';
return undefined;
});

const { result } = renderHook(() => useKpiData(consumption));

expect(result.current).toEqual({
computedUsagePercent: '40%',
computedCoveragePercent: 'dashboard_kpis_not_available',
computedActivePlans: 1,
computedSavedAmount: 'dashboard_kpis_not_available',
computedWithoutSavedAmount: null,
});
});
});
Loading
Loading