From 0758e69c10e780ce7e609c78b284077a81ea0608 Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:06:18 -0800 Subject: [PATCH 01/16] MPDX-10389 Show 12-month averages on the Supervisor Report chart Co-Authored-By: Claude Opus 5.5 --- public/locales/en/translation.json | 1 + .../MonthlySummary/MonthlySummary.test.tsx | 13 ++++ .../MonthlySummary/MonthlySummary.tsx | 7 +++ .../MonthlySummary/monthlyAverages.test.ts | 32 ++++++++++ .../MonthlySummary/monthlyAverages.ts | 25 ++++++++ .../MonthlySummaryChart.test.tsx | 62 +++++++++++++++++++ .../MonthlySummaryChart.tsx | 61 +++++++++++++++--- 7 files changed, 193 insertions(+), 8 deletions(-) create mode 100644 src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/monthlyAverages.test.ts create mode 100644 src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/monthlyAverages.ts diff --git a/public/locales/en/translation.json b/public/locales/en/translation.json index 9cb4279ad5..4ffb56c8f3 100644 --- a/public/locales/en/translation.json +++ b/public/locales/en/translation.json @@ -277,6 +277,7 @@ "{{mode}} Minister's Housing Allowance Calculation Tool": "{{mode}} Minister's Housing Allowance Calculation Tool", "{{month}} ending balance": "{{month}} ending balance", "{{months}} months ago": "{{months}} months ago", + "{{name}} 12-month avg: {{amount}}": "{{name}} 12-month avg: {{amount}}", "{{name}} has one or multiple invalid numbers. Please fix.": "{{name}} has one or multiple invalid numbers. Please fix.", "{{name}} may request up to their Board Approved {{sectionKind}} Amount of {{approvedAmount}}.": "{{name}} may request up to their Board Approved {{sectionKind}} Amount of {{approvedAmount}}.", "{{name}} won't get MHA once this request takes effect.": "{{name}} won't get MHA once this request takes effect.", diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx index ec5a1faea8..0b0861e295 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx @@ -234,6 +234,19 @@ describe('StaffTabMonthlySummary', () => { expect(getByRole('table')).toBeInTheDocument(); }); + it('draws the 12-month contributions and expenses averages on the chart', async () => { + const { findByRole, findByText, getByText } = render( + , + ); + + userEvent.click(await findByRole('button', { name: 'Chart view' })); + + expect( + await findByText('Contributions 12-month avg: $3,733.33'), + ).toBeInTheDocument(); + expect(getByText('Expenses 12-month avg: $3,733.33')).toBeInTheDocument(); + }); + it('charts labelled empty months without showing a zero amount', async () => { const { container, findByRole, queryByRole, queryByText } = render( , diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx index 0b92e8f5fe..b7bb2d0ae7 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx @@ -25,6 +25,7 @@ import { pendingField } from '../../helpers'; import { useMonthlyPayrollSummaryQuery } from './MonthlyPayrollSummary.generated'; import { SupportVsGoalCells } from './SupportVsGoalCells'; import { ToggleSummaryView } from './ToggleSummaryView/ToggleSummaryView'; +import { monthlyAverages } from './monthlyAverages'; export enum MonthlySummaryView { Table = 'table', @@ -85,6 +86,11 @@ export const StaffTabMonthlySummary: React.FC = ({ [monthlySummary, locale], ); + const averages = useMemo( + () => monthlyAverages(monthlySummary), + [monthlySummary], + ); + const tableRows = useMemo( () => [...monthlySummary].reverse(), [monthlySummary], @@ -136,6 +142,7 @@ export const StaffTabMonthlySummary: React.FC = ({ width={100} overrideIncomeText={t('Contributions')} noDataLabel={hasData ? undefined : t('N/A')} + averages={averages} /> ) : ( diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/monthlyAverages.test.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/monthlyAverages.test.ts new file mode 100644 index 0000000000..d359ac5400 --- /dev/null +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/monthlyAverages.test.ts @@ -0,0 +1,32 @@ +import { monthlyAverages } from './monthlyAverages'; + +describe('monthlyAverages', () => { + it('averages contributions and expenses across the months', () => { + expect( + monthlyAverages([ + { contributions: 4000, expenses: 3500 }, + { contributions: 4200, expenses: 4500 }, + { contributions: 3200, expenses: 3100 }, + ]), + ).toEqual({ income: 3800, expenses: 3700 }); + }); + + it('skips months with no amount but counts months reported as zero', () => { + expect( + monthlyAverages([ + { contributions: null, expenses: null }, + { contributions: 0, expenses: 1000 }, + { contributions: 3000, expenses: null }, + ]), + ).toEqual({ income: 1500, expenses: 1000 }); + }); + + it('has no average for a field with no amounts', () => { + expect( + monthlyAverages([ + { contributions: null, expenses: 200 }, + { contributions: undefined, expenses: 400 }, + ]), + ).toEqual({ income: undefined, expenses: 300 }); + }); +}); diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/monthlyAverages.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/monthlyAverages.ts new file mode 100644 index 0000000000..207c6658bf --- /dev/null +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/monthlyAverages.ts @@ -0,0 +1,25 @@ +import { MonthlySummaryAverages } from 'src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart'; + +interface MonthAmounts { + contributions?: number | null; + expenses?: number | null; +} + +// Months with no amount yet (the current month, months before they joined) +// are left out so they don't drag the average down. A reported $0 counts. +const average = (values: Array) => { + const amounts = values.filter( + (value): value is number => value !== null && value !== undefined, + ); + if (amounts.length === 0) { + return undefined; + } + return amounts.reduce((sum, value) => sum + value, 0) / amounts.length; +}; + +export const monthlyAverages = ( + months: MonthAmounts[], +): MonthlySummaryAverages => ({ + income: average(months.map((month) => month.contributions)), + expenses: average(months.map((month) => month.expenses)), +}); diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx index 1bf17de202..b75faf2af3 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx @@ -45,6 +45,27 @@ const ChartWithNoDataLabel: React.FC = () => ( ); +const averagesData = [ + { month: 'Jan 2023', income: 4000, expenses: 3500, net: 500 }, + { month: 'Feb 2023', income: 3600, expenses: 3900, net: -300 }, +]; + +const ChartWithAverages: React.FC<{ noDataLabel?: string }> = ({ + noDataLabel, +}) => ( + + + +); + describe('MonthlySummaryChart', () => { it('renders the bar chart', async () => { const { findByRole } = render(); @@ -110,6 +131,47 @@ describe('MonthlySummaryChart', () => { expect(within(region).queryByText(/^\$/)).not.toBeInTheDocument(); }); + it('draws a dashed line with its amount for each average when given averages', async () => { + const { findByRole } = render(); + + const region = await findByRole('region'); + + expect( + await within(region).findByText('Contributions 12-month avg: $3,800.00'), + ).toBeInTheDocument(); + expect( + within(region).getByText('Expenses 12-month avg: $3,700.00'), + ).toBeInTheDocument(); + const lines = region.querySelectorAll('.recharts-reference-line line'); + expect(lines).toHaveLength(2); + lines.forEach((line) => + expect(line).toHaveAttribute('stroke-dasharray', '6 4'), + ); + }); + + it('draws no average lines without averages', async () => { + const { findByRole } = render(); + + const region = await findByRole('region'); + + await waitFor(() => + expect(region.querySelector('svg.recharts-surface')).toBeTruthy(), + ); + expect(region.querySelectorAll('.recharts-reference-line')).toHaveLength(0); + }); + + it('draws no average lines when amounts are masked', async () => { + const { findByRole } = render(); + + const region = await findByRole('region'); + + await waitFor(() => + expect(region.querySelector('svg.recharts-surface')).toBeTruthy(), + ); + expect(region.querySelectorAll('.recharts-reference-line')).toHaveLength(0); + expect(within(region).queryByText(/12-month avg/)).not.toBeInTheDocument(); + }); + it('renders legend with correct labels', async () => { const { findByRole } = render(); diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx index d13a8e98d6..f01c2a7b14 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx @@ -6,6 +6,7 @@ import { BarChart, LabelList, Legend, + ReferenceLine, Tooltip, XAxis, YAxis, @@ -23,6 +24,11 @@ export interface MonthlySummaryChartData { net: number; } +export interface MonthlySummaryAverages { + income?: number; + expenses?: number; +} + interface MonthlySummaryChartProps { data: MonthlySummaryChartData[]; currency: string; @@ -31,6 +37,8 @@ interface MonthlySummaryChartProps { width: number; overrideIncomeText?: string; noDataLabel?: string; + // Draws a dashed line at each average, labelled with its amount + averages?: MonthlySummaryAverages; } interface MonthlyTotal extends MonthlySummaryChartData { @@ -47,6 +55,7 @@ export const MonthlySummaryChart: React.FC = ({ width, overrideIncomeText, noDataLabel, + averages, }) => { const { t } = useTranslation(); const locale = useLocale(); @@ -58,6 +67,27 @@ export const MonthlySummaryChart: React.FC = ({ ? noDataLabel : currencyFormat(value, currency, locale, { showTrailingZeros: true }); + const incomeName = overrideIncomeText ?? t('Income'); + + const averageLines = maskAmounts + ? [] + : [ + { + key: 'income', + value: averages?.income, + name: incomeName, + color: chartColors[0], + labelPosition: 'insideTopLeft' as const, + }, + { + key: 'expenses', + value: averages?.expenses, + name: t('Expenses'), + color: chartColors[1], + labelPosition: 'insideBottomLeft' as const, + }, + ]; + const monthlyTotals = useMemo( (): MonthlyTotal[] => data.map((month) => ({ @@ -123,8 +153,7 @@ export const MonthlySummaryChart: React.FC = ({ {label} - {overrideIncomeText ?? t('Income')}:{' '} - {formatAmount(income)} + {incomeName}: {formatAmount(income)} {t('Expenses')}: {formatAmount(expenses)} @@ -147,11 +176,7 @@ export const MonthlySummaryChart: React.FC = ({ ); }} /> - + = ({ /> )} + {averageLines.map(({ key, value, name, color, labelPosition }) => + value === undefined ? null : ( + + ), + )} = ({ )} payload={[ { - value: overrideIncomeText ?? t('Income'), + value: incomeName, type: 'square', color: chartColors[0], }, From 341c83dba7e7e9ce8b0cb0fe43ac2cba6a780ae0 Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:07:59 -0800 Subject: [PATCH 02/16] MPDX-10389 Move chart averages and data into helpers Co-Authored-By: Claude Opus 5.5 --- .../MonthlySummary/MonthlySummary.tsx | 15 +---- ...thlyAverages.test.ts => chartData.test.ts} | 19 +++++- .../{monthlyAverages.ts => chartData.ts} | 21 ++++++- .../MonthlySummaryChart.tsx | 52 +++------------- .../averageReferenceLines.tsx | 59 +++++++++++++++++++ 5 files changed, 106 insertions(+), 60 deletions(-) rename src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/{monthlyAverages.test.ts => chartData.test.ts} (62%) rename src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/{monthlyAverages.ts => chartData.ts} (52%) create mode 100644 src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx index b7bb2d0ae7..f6fe0b91d5 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx @@ -25,7 +25,7 @@ import { pendingField } from '../../helpers'; import { useMonthlyPayrollSummaryQuery } from './MonthlyPayrollSummary.generated'; import { SupportVsGoalCells } from './SupportVsGoalCells'; import { ToggleSummaryView } from './ToggleSummaryView/ToggleSummaryView'; -import { monthlyAverages } from './monthlyAverages'; +import { monthlyAverages, toChartData } from './chartData'; export enum MonthlySummaryView { Table = 'table', @@ -71,18 +71,7 @@ export const StaffTabMonthlySummary: React.FC = ({ ) => (value === null || value === undefined ? pendingField : format(value)); const chartData = useMemo( - (): MonthlySummaryChartData[] => - monthlySummary.map((summary) => { - const date = DateTime.fromISO(summary.month ?? ''); - return { - month: date.isValid - ? monthYearFormat(date.month, date.year, locale) - : '', - income: summary.contributions ?? 0, - expenses: summary.expenses ?? 0, - net: summary.net ?? 0, - }; - }), + () => toChartData(monthlySummary, locale), [monthlySummary, locale], ); diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/monthlyAverages.test.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts similarity index 62% rename from src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/monthlyAverages.test.ts rename to src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts index d359ac5400..d0c6c89a94 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/monthlyAverages.test.ts +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts @@ -1,4 +1,21 @@ -import { monthlyAverages } from './monthlyAverages'; +import { monthlyAverages, toChartData } from './chartData'; + +describe('toChartData', () => { + it('labels each month and charts missing amounts as zero', () => { + expect( + toChartData( + [ + { month: '2023-01', contributions: 4000, expenses: 3500, net: 500 }, + { month: '2023-02', contributions: null, expenses: null, net: null }, + ], + 'en-US', + ), + ).toEqual([ + { month: 'Jan 2023', income: 4000, expenses: 3500, net: 500 }, + { month: 'Feb 2023', income: 0, expenses: 0, net: 0 }, + ]); + }); +}); describe('monthlyAverages', () => { it('averages contributions and expenses across the months', () => { diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/monthlyAverages.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts similarity index 52% rename from src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/monthlyAverages.ts rename to src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts index 207c6658bf..cb8d180ccd 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/monthlyAverages.ts +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts @@ -1,10 +1,29 @@ -import { MonthlySummaryAverages } from 'src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart'; +import { DateTime } from 'luxon'; +import { MonthlySummaryChartData } from 'src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart'; +import { MonthlySummaryAverages } from 'src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines'; +import { monthYearFormat } from 'src/lib/intlFormat'; interface MonthAmounts { + month?: string | null; contributions?: number | null; expenses?: number | null; + net?: number | null; } +export const toChartData = ( + months: MonthAmounts[], + locale: string, +): MonthlySummaryChartData[] => + months.map((summary) => { + const date = DateTime.fromISO(summary.month ?? ''); + return { + month: date.isValid ? monthYearFormat(date.month, date.year, locale) : '', + income: summary.contributions ?? 0, + expenses: summary.expenses ?? 0, + net: summary.net ?? 0, + }; + }); + // Months with no amount yet (the current month, months before they joined) // are left out so they don't drag the average down. A reported $0 counts. const average = (values: Array) => { diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx index f01c2a7b14..b2697514be 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx @@ -6,7 +6,6 @@ import { BarChart, LabelList, Legend, - ReferenceLine, Tooltip, XAxis, YAxis, @@ -16,6 +15,10 @@ import { currencyFormat } from 'src/lib/intlFormat'; import theme from 'src/theme'; import { ChartFrame } from '../ChartFrame'; import { ChartLegendContent } from '../ChartLegendContent/ChartLegendContent'; +import { + MonthlySummaryAverages, + averageReferenceLines, +} from './averageReferenceLines'; export interface MonthlySummaryChartData { month: string; @@ -24,11 +27,6 @@ export interface MonthlySummaryChartData { net: number; } -export interface MonthlySummaryAverages { - income?: number; - expenses?: number; -} - interface MonthlySummaryChartProps { data: MonthlySummaryChartData[]; currency: string; @@ -69,25 +67,6 @@ export const MonthlySummaryChart: React.FC = ({ const incomeName = overrideIncomeText ?? t('Income'); - const averageLines = maskAmounts - ? [] - : [ - { - key: 'income', - value: averages?.income, - name: incomeName, - color: chartColors[0], - labelPosition: 'insideTopLeft' as const, - }, - { - key: 'expenses', - value: averages?.expenses, - name: t('Expenses'), - color: chartColors[1], - labelPosition: 'insideBottomLeft' as const, - }, - ]; - const monthlyTotals = useMemo( (): MonthlyTotal[] => data.map((month) => ({ @@ -204,26 +183,9 @@ export const MonthlySummaryChart: React.FC = ({ /> )} - {averageLines.map(({ key, value, name, color, labelPosition }) => - value === undefined ? null : ( - - ), - )} + {averages && + !maskAmounts && + averageReferenceLines({ t, averages, incomeName, formatAmount })} string | undefined; +} + +// Recharts only finds its own elements among the chart's direct children, so +// this returns ReferenceLine elements instead of being a component. +export const averageReferenceLines = ({ + t, + averages, + incomeName, + formatAmount, +}: AverageReferenceLinesOptions) => + [ + { + key: 'income', + value: averages.income, + name: incomeName, + color: theme.palette.success.main, + labelPosition: 'insideTopLeft' as const, + }, + { + key: 'expenses', + value: averages.expenses, + name: t('Expenses'), + color: theme.palette.error.main, + labelPosition: 'insideBottomLeft' as const, + }, + ].map(({ key, value, name, color, labelPosition }) => + value === undefined ? null : ( + + ), + ); From 93473fe52315df26fae95e69a59dc3f27ab5a178 Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:11:11 -0800 Subject: [PATCH 03/16] MPDX-10389 Keep average labels apart and readable Co-Authored-By: Claude Opus 5.5 --- public/locales/en/translation.json | 2 +- .../MonthlySummary/MonthlySummary.test.tsx | 11 ++++++--- .../MonthlySummary/chartData.ts | 17 +++++++------- .../MonthlySummaryChart.test.tsx | 6 ++--- .../averageReferenceLines.tsx | 23 +++++++++++++------ 5 files changed, 37 insertions(+), 22 deletions(-) diff --git a/public/locales/en/translation.json b/public/locales/en/translation.json index 4ffb56c8f3..33f2404d58 100644 --- a/public/locales/en/translation.json +++ b/public/locales/en/translation.json @@ -277,7 +277,7 @@ "{{mode}} Minister's Housing Allowance Calculation Tool": "{{mode}} Minister's Housing Allowance Calculation Tool", "{{month}} ending balance": "{{month}} ending balance", "{{months}} months ago": "{{months}} months ago", - "{{name}} 12-month avg: {{amount}}": "{{name}} 12-month avg: {{amount}}", + "{{name}} average: {{amount}}": "{{name}} average: {{amount}}", "{{name}} has one or multiple invalid numbers. Please fix.": "{{name}} has one or multiple invalid numbers. Please fix.", "{{name}} may request up to their Board Approved {{sectionKind}} Amount of {{approvedAmount}}.": "{{name}} may request up to their Board Approved {{sectionKind}} Amount of {{approvedAmount}}.", "{{name}} won't get MHA once this request takes effect.": "{{name}} won't get MHA once this request takes effect.", diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx index 0b0861e295..b45ab98e2f 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx @@ -236,15 +236,20 @@ describe('StaffTabMonthlySummary', () => { it('draws the 12-month contributions and expenses averages on the chart', async () => { const { findByRole, findByText, getByText } = render( - , + , ); userEvent.click(await findByRole('button', { name: 'Chart view' })); expect( - await findByText('Contributions 12-month avg: $3,733.33'), + await findByText('Contributions average: $4,500.00'), ).toBeInTheDocument(); - expect(getByText('Expenses 12-month avg: $3,733.33')).toBeInTheDocument(); + expect(getByText('Expenses average: $3,300.00')).toBeInTheDocument(); }); it('charts labelled empty months without showing a zero amount', async () => { diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts index cb8d180ccd..0794c15f91 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts @@ -2,13 +2,14 @@ import { DateTime } from 'luxon'; import { MonthlySummaryChartData } from 'src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart'; import { MonthlySummaryAverages } from 'src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines'; import { monthYearFormat } from 'src/lib/intlFormat'; +import { MonthlyPayrollSummaryQuery } from './MonthlyPayrollSummary.generated'; -interface MonthAmounts { - month?: string | null; - contributions?: number | null; - expenses?: number | null; - net?: number | null; -} +type MonthAmounts = Partial< + Pick< + MonthlyPayrollSummaryQuery['monthlyPayrollSummary'][number], + 'month' | 'contributions' | 'expenses' | 'net' + > +>; export const toChartData = ( months: MonthAmounts[], @@ -24,8 +25,8 @@ export const toChartData = ( }; }); -// Months with no amount yet (the current month, months before they joined) -// are left out so they don't drag the average down. A reported $0 counts. +// Months with no amount (before they joined, or not synced) are left out so +// they don't drag the average down. A reported $0 counts. const average = (values: Array) => { const amounts = values.filter( (value): value is number => value !== null && value !== undefined, diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx index b75faf2af3..bb5cbce64a 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx @@ -137,10 +137,10 @@ describe('MonthlySummaryChart', () => { const region = await findByRole('region'); expect( - await within(region).findByText('Contributions 12-month avg: $3,800.00'), + await within(region).findByText('Contributions average: $3,800.00'), ).toBeInTheDocument(); expect( - within(region).getByText('Expenses 12-month avg: $3,700.00'), + within(region).getByText('Expenses average: $3,700.00'), ).toBeInTheDocument(); const lines = region.querySelectorAll('.recharts-reference-line line'); expect(lines).toHaveLength(2); @@ -169,7 +169,7 @@ describe('MonthlySummaryChart', () => { expect(region.querySelector('svg.recharts-surface')).toBeTruthy(), ); expect(region.querySelectorAll('.recharts-reference-line')).toHaveLength(0); - expect(within(region).queryByText(/12-month avg/)).not.toBeInTheDocument(); + expect(within(region).queryByText(/average/)).not.toBeInTheDocument(); }); it('renders legend with correct labels', async () => { diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx index 8bab68be90..3e262a9bd4 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx @@ -21,23 +21,27 @@ export const averageReferenceLines = ({ averages, incomeName, formatAmount, -}: AverageReferenceLinesOptions) => - [ +}: AverageReferenceLinesOptions) => { + // The higher line's label sits above it and the lower one's below, so the + // two labels never share the gap between close lines. + const incomeOnTop = (averages.income ?? 0) >= (averages.expenses ?? 0); + + return [ { key: 'income', value: averages.income, name: incomeName, color: theme.palette.success.main, - labelPosition: 'insideTopLeft' as const, + above: incomeOnTop, }, { key: 'expenses', value: averages.expenses, name: t('Expenses'), color: theme.palette.error.main, - labelPosition: 'insideBottomLeft' as const, + above: !incomeOnTop, }, - ].map(({ key, value, name, color, labelPosition }) => + ].map(({ key, value, name, color, above }) => value === undefined ? null : ( ), ); +}; From b48664775b5a8b9fe42b68481e7e6afcdb7bef6b Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:12:48 -0800 Subject: [PATCH 04/16] MPDX-10389 Put each average label on the right side Co-Authored-By: Claude Opus 5.5 --- .../MonthlySummaryChart.test.tsx | 16 ++++++++++++++++ .../averageReferenceLines.tsx | 3 ++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx index bb5cbce64a..067968a7bb 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx @@ -149,6 +149,22 @@ describe('MonthlySummaryChart', () => { ); }); + it('puts the higher average label above its line and the lower one below', async () => { + const { findByRole } = render(); + + const region = await findByRole('region'); + await within(region).findByText('Contributions average: $3,800.00'); + + const [income, expenses] = Array.from( + region.querySelectorAll('.recharts-reference-line'), + ).map((line) => ({ + lineY: Number(line.querySelector('line')?.getAttribute('y1')), + labelY: Number(line.querySelector('text')?.getAttribute('y')), + })); + expect(income.labelY).toBeLessThan(income.lineY); + expect(expenses.labelY).toBeGreaterThan(expenses.lineY); + }); + it('draws no average lines without averages', async () => { const { findByRole } = render(); diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx index 3e262a9bd4..cbdc5d3722 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx @@ -54,7 +54,8 @@ export const averageReferenceLines = ({ name, amount: formatAmount(value), }), - position: above ? 'insideTopRight' : 'insideBottomRight', + // On a flat line, "insideBottom" sits above it and "insideTop" below + position: above ? 'insideBottomRight' : 'insideTopRight', fill: color, fontSize: theme.typography.body2.fontSize, // A white outline keeps the label readable where it crosses a bar From 6284827190dabbe09ad72003af594d15dd890f9b Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:17:22 -0800 Subject: [PATCH 05/16] MPDX-10389 Leave the current month out of the averages Co-Authored-By: Claude Opus 5.5 --- .../MonthlySummary/chartData.test.ts | 11 +++++++ .../MonthlySummary/chartData.ts | 20 +++++++---- .../MonthlySummaryChart.test.tsx | 28 +++++++++++++--- .../MonthlySummaryChart.tsx | 33 ++++++++++--------- .../averageReferenceLines.tsx | 29 ++++++++-------- 5 files changed, 82 insertions(+), 39 deletions(-) diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts index d0c6c89a94..f199e933eb 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts @@ -38,6 +38,17 @@ describe('monthlyAverages', () => { ).toEqual({ income: 1500, expenses: 1000 }); }); + // Tests run pinned to 2020-01-01, so 2020-01 is the current month. + it('leaves out the current month, which is still in progress', () => { + expect( + monthlyAverages([ + { month: '2019-11', contributions: 4000, expenses: 3000 }, + { month: '2019-12', contributions: 5000, expenses: 4000 }, + { month: '2020-01', contributions: 900, expenses: 500 }, + ]), + ).toEqual({ income: 4500, expenses: 3500 }); + }); + it('has no average for a field with no amounts', () => { expect( monthlyAverages([ diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts index 0794c15f91..18d9734737 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts @@ -1,6 +1,8 @@ import { DateTime } from 'luxon'; -import { MonthlySummaryChartData } from 'src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart'; -import { MonthlySummaryAverages } from 'src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines'; +import { + MonthlySummaryAverages, + MonthlySummaryChartData, +} from 'src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart'; import { monthYearFormat } from 'src/lib/intlFormat'; import { MonthlyPayrollSummaryQuery } from './MonthlyPayrollSummary.generated'; @@ -37,9 +39,15 @@ const average = (values: Array) => { return amounts.reduce((sum, value) => sum + value, 0) / amounts.length; }; +// The current month is still in progress, so it is left out too, the same as +// the Dashboard's donation average. export const monthlyAverages = ( months: MonthAmounts[], -): MonthlySummaryAverages => ({ - income: average(months.map((month) => month.contributions)), - expenses: average(months.map((month) => month.expenses)), -}); +): MonthlySummaryAverages => { + const currentMonth = DateTime.local().toFormat('yyyy-MM'); + const pastMonths = months.filter((month) => month.month !== currentMonth); + return { + income: average(pastMonths.map((month) => month.contributions)), + expenses: average(pastMonths.map((month) => month.expenses)), + }; +}; diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx index 067968a7bb..9b7e1f1dfb 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx @@ -3,7 +3,10 @@ import React from 'react'; import { render, waitFor, within } from '@testing-library/react'; import { useMPGAIncomeExpenses } from '../../MPGAIncomeExpensesContext/MPGAIncomeExpensesContext'; import { MPGAIncomeExpensesReportTestWrapper } from '../../MPGAIncomeExpensesReportTestWrapper'; -import { MonthlySummaryChart } from './MonthlySummaryChart'; +import { + MonthlySummaryAverages, + MonthlySummaryChart, +} from './MonthlySummaryChart'; import { useMonthlySummaryChartData } from './useMonthlySummaryChartData'; const mutationSpy = jest.fn(); @@ -50,9 +53,10 @@ const averagesData = [ { month: 'Feb 2023', income: 3600, expenses: 3900, net: -300 }, ]; -const ChartWithAverages: React.FC<{ noDataLabel?: string }> = ({ - noDataLabel, -}) => ( +const ChartWithAverages: React.FC<{ + noDataLabel?: string; + averages?: MonthlySummaryAverages; +}> = ({ noDataLabel, averages = { income: 3800, expenses: 3700 } }) => ( = ({ aspect={1.35} width={100} overrideIncomeText="Contributions" - averages={{ income: 3800, expenses: 3700 }} + averages={averages} noDataLabel={noDataLabel} /> @@ -165,6 +169,20 @@ describe('MonthlySummaryChart', () => { expect(expenses.labelY).toBeGreaterThan(expenses.lineY); }); + it('puts a lone $0 average label above its line, clear of the axis', async () => { + const { findByRole } = render( + , + ); + + const region = await findByRole('region'); + await within(region).findByText('Expenses average: $0.00'); + + const line = region.querySelector('.recharts-reference-line'); + expect(Number(line?.querySelector('text')?.getAttribute('y'))).toBeLessThan( + Number(line?.querySelector('line')?.getAttribute('y1')), + ); + }); + it('draws no average lines without averages', async () => { const { findByRole } = render(); diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx index b2697514be..955fc9a082 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx @@ -15,10 +15,7 @@ import { currencyFormat } from 'src/lib/intlFormat'; import theme from 'src/theme'; import { ChartFrame } from '../ChartFrame'; import { ChartLegendContent } from '../ChartLegendContent/ChartLegendContent'; -import { - MonthlySummaryAverages, - averageReferenceLines, -} from './averageReferenceLines'; +import { averageReferenceLines } from './averageReferenceLines'; export interface MonthlySummaryChartData { month: string; @@ -27,6 +24,11 @@ export interface MonthlySummaryChartData { net: number; } +export interface MonthlySummaryAverages { + income?: number; + expenses?: number; +} + interface MonthlySummaryChartProps { data: MonthlySummaryChartData[]; currency: string; @@ -60,10 +62,11 @@ export const MonthlySummaryChart: React.FC = ({ const maskAmounts = noDataLabel !== undefined; + const formatCurrency = (value: number) => + currencyFormat(value, currency, locale, { showTrailingZeros: true }); + const formatAmount = (value: number) => - maskAmounts - ? noDataLabel - : currencyFormat(value, currency, locale, { showTrailingZeros: true }); + maskAmounts ? noDataLabel : formatCurrency(value); const incomeName = overrideIncomeText ?? t('Income'); @@ -175,17 +178,17 @@ export const MonthlySummaryChart: React.FC = ({ fill: theme.palette.chartBlack.main, fontSize: theme.typography.body2.fontSize, }} - formatter={(value: number) => - currencyFormat(value, currency, locale, { - showTrailingZeros: true, - }) - } + formatter={formatCurrency} /> )} - {averages && - !maskAmounts && - averageReferenceLines({ t, averages, incomeName, formatAmount })} + {!maskAmounts && + averageReferenceLines({ + t, + averages, + incomeName, + formatCurrency, + })} string | undefined; + formatCurrency: (value: number) => string; } // Recharts only finds its own elements among the chart's direct children, so @@ -20,25 +16,32 @@ export const averageReferenceLines = ({ t, averages, incomeName, - formatAmount, + formatCurrency, }: AverageReferenceLinesOptions) => { + if (!averages) { + return []; + } + // The higher line's label sits above it and the lower one's below, so the - // two labels never share the gap between close lines. - const incomeOnTop = (averages.income ?? 0) >= (averages.expenses ?? 0); + // two labels never share the gap between close lines. A lone line's label + // sits above it. + const incomeOnTop = + (averages.income ?? -Infinity) >= (averages.expenses ?? -Infinity); return [ { key: 'income', value: averages.income, name: incomeName, - color: theme.palette.success.main, + // Darker than the bars so the line shows where it crosses its own bars + color: theme.palette.success.dark, above: incomeOnTop, }, { key: 'expenses', value: averages.expenses, name: t('Expenses'), - color: theme.palette.error.main, + color: theme.palette.error.dark, above: !incomeOnTop, }, ].map(({ key, value, name, color, above }) => @@ -52,7 +55,7 @@ export const averageReferenceLines = ({ label={{ value: t('{{name}} average: {{amount}}', { name, - amount: formatAmount(value), + amount: formatCurrency(value), }), // On a flat line, "insideBottom" sits above it and "insideTop" below position: above ? 'insideBottomRight' : 'insideTopRight', From 83da79161f8bb4a20d1e0766b2f97b4ed81cf75f Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:25:26 -0800 Subject: [PATCH 06/16] MPDX-10389 Drop the API's last row, not the clock month Co-Authored-By: Claude Opus 5.5 --- .../MonthlySummary/MonthlySummary.test.tsx | 4 ++- .../MonthlySummary/chartData.test.ts | 29 +++++++++++-------- .../MonthlySummary/chartData.ts | 7 ++--- 3 files changed, 23 insertions(+), 17 deletions(-) diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx index b45ab98e2f..b445acda31 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx @@ -234,12 +234,14 @@ describe('StaffTabMonthlySummary', () => { expect(getByRole('table')).toBeInTheDocument(); }); - it('draws the 12-month contributions and expenses averages on the chart', async () => { + it('draws the contributions and expenses averages of the finished months on the chart', async () => { const { findByRole, findByText, getByText } = render( , ); diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts index f199e933eb..e11cda9118 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts @@ -18,35 +18,39 @@ describe('toChartData', () => { }); describe('monthlyAverages', () => { - it('averages contributions and expenses across the months', () => { + // The API's last row is always the current month, still in progress. + const currentMonth = { contributions: 900, expenses: 500 }; + + it('averages contributions and expenses across the finished months', () => { expect( monthlyAverages([ { contributions: 4000, expenses: 3500 }, { contributions: 4200, expenses: 4500 }, { contributions: 3200, expenses: 3100 }, + currentMonth, ]), ).toEqual({ income: 3800, expenses: 3700 }); }); - it('skips months with no amount but counts months reported as zero', () => { + it('leaves out the last row, even when its date is not this month', () => { expect( monthlyAverages([ - { contributions: null, expenses: null }, - { contributions: 0, expenses: 1000 }, - { contributions: 3000, expenses: null }, + { month: '2019-11', contributions: 4000, expenses: 3000 }, + { month: '2019-12', contributions: 5000, expenses: 4000 }, + { month: '2019-12', ...currentMonth }, ]), - ).toEqual({ income: 1500, expenses: 1000 }); + ).toEqual({ income: 4500, expenses: 3500 }); }); - // Tests run pinned to 2020-01-01, so 2020-01 is the current month. - it('leaves out the current month, which is still in progress', () => { + it('skips months with no amount but counts months reported as zero', () => { expect( monthlyAverages([ - { month: '2019-11', contributions: 4000, expenses: 3000 }, - { month: '2019-12', contributions: 5000, expenses: 4000 }, - { month: '2020-01', contributions: 900, expenses: 500 }, + { contributions: null, expenses: null }, + { contributions: 0, expenses: 1000 }, + { contributions: 3000, expenses: null }, + currentMonth, ]), - ).toEqual({ income: 4500, expenses: 3500 }); + ).toEqual({ income: 1500, expenses: 1000 }); }); it('has no average for a field with no amounts', () => { @@ -54,6 +58,7 @@ describe('monthlyAverages', () => { monthlyAverages([ { contributions: null, expenses: 200 }, { contributions: undefined, expenses: 400 }, + currentMonth, ]), ).toEqual({ income: undefined, expenses: 300 }); }); diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts index 18d9734737..28dbdbea25 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts @@ -39,13 +39,12 @@ const average = (values: Array) => { return amounts.reduce((sum, value) => sum + value, 0) / amounts.length; }; -// The current month is still in progress, so it is left out too, the same as -// the Dashboard's donation average. +// The API's last row is the current month, still in progress, so it is left +// out too, the same as the Dashboard's donation average. export const monthlyAverages = ( months: MonthAmounts[], ): MonthlySummaryAverages => { - const currentMonth = DateTime.local().toFormat('yyyy-MM'); - const pastMonths = months.filter((month) => month.month !== currentMonth); + const pastMonths = months.slice(0, -1); return { income: average(pastMonths.map((month) => month.contributions)), expenses: average(pastMonths.map((month) => month.expenses)), From 38f9cc2fbb175e15ed1ce19a041ef5e4d802ca58 Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:01:32 -0800 Subject: [PATCH 07/16] MPDX-10389 Say the averages cover the last 11 full months Co-Authored-By: Claude Opus 5.5 --- public/locales/en/translation.json | 3 ++- .../MonthlySummary/MonthlySummary.test.tsx | 8 ++++++-- .../MonthlySummary/MonthlySummary.tsx | 7 +++++-- .../MonthlySummary/chartData.ts | 2 +- .../MonthlySummaryChart.test.tsx | 19 +++++++++++++------ .../MonthlySummaryChart.tsx | 2 ++ .../averageReferenceLines.tsx | 3 ++- 7 files changed, 31 insertions(+), 13 deletions(-) diff --git a/public/locales/en/translation.json b/public/locales/en/translation.json index 33f2404d58..e8a8f2cee1 100644 --- a/public/locales/en/translation.json +++ b/public/locales/en/translation.json @@ -277,7 +277,7 @@ "{{mode}} Minister's Housing Allowance Calculation Tool": "{{mode}} Minister's Housing Allowance Calculation Tool", "{{month}} ending balance": "{{month}} ending balance", "{{months}} months ago": "{{months}} months ago", - "{{name}} average: {{amount}}": "{{name}} average: {{amount}}", + "{{name}} average ({{period}}): {{amount}}": "{{name}} average ({{period}}): {{amount}}", "{{name}} has one or multiple invalid numbers. Please fix.": "{{name}} has one or multiple invalid numbers. Please fix.", "{{name}} may request up to their Board Approved {{sectionKind}} Amount of {{approvedAmount}}.": "{{name}} may request up to their Board Approved {{sectionKind}} Amount of {{approvedAmount}}.", "{{name}} won't get MHA once this request takes effect.": "{{name}} won't get MHA once this request takes effect.", @@ -1867,6 +1867,7 @@ "Language": "Language", "last": "last", "Last": "Last", + "last 11 full months": "last 11 full months", "Last 12 Months": "Last 12 Months", "Last Full 12 Months": "Last Full 12 Months", "Last Full Month": "Last Full Month", diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx index b445acda31..e699cd57b3 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx @@ -249,9 +249,13 @@ describe('StaffTabMonthlySummary', () => { userEvent.click(await findByRole('button', { name: 'Chart view' })); expect( - await findByText('Contributions average: $4,500.00'), + await findByText( + 'Contributions average (last 11 full months): $4,500.00', + ), + ).toBeInTheDocument(); + expect( + getByText('Expenses average (last 11 full months): $3,300.00'), ).toBeInTheDocument(); - expect(getByText('Expenses average: $3,300.00')).toBeInTheDocument(); }); it('charts labelled empty months without showing a zero amount', async () => { diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx index f6fe0b91d5..be3d26ae1d 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx @@ -76,8 +76,11 @@ export const StaffTabMonthlySummary: React.FC = ({ ); const averages = useMemo( - () => monthlyAverages(monthlySummary), - [monthlySummary], + () => ({ + ...monthlyAverages(monthlySummary), + period: t('last 11 full months'), + }), + [monthlySummary, t], ); const tableRows = useMemo( diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts index 28dbdbea25..ba9c180ec5 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts @@ -43,7 +43,7 @@ const average = (values: Array) => { // out too, the same as the Dashboard's donation average. export const monthlyAverages = ( months: MonthAmounts[], -): MonthlySummaryAverages => { +): Omit => { const pastMonths = months.slice(0, -1); return { income: average(pastMonths.map((month) => month.contributions)), diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx index 9b7e1f1dfb..49c41b9ff8 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx @@ -56,7 +56,10 @@ const averagesData = [ const ChartWithAverages: React.FC<{ noDataLabel?: string; averages?: MonthlySummaryAverages; -}> = ({ noDataLabel, averages = { income: 3800, expenses: 3700 } }) => ( +}> = ({ + noDataLabel, + averages = { income: 3800, expenses: 3700, period: 'last 2 months' }, +}) => ( { const region = await findByRole('region'); expect( - await within(region).findByText('Contributions average: $3,800.00'), + await within(region).findByText( + 'Contributions average (last 2 months): $3,800.00', + ), ).toBeInTheDocument(); expect( - within(region).getByText('Expenses average: $3,700.00'), + within(region).getByText('Expenses average (last 2 months): $3,700.00'), ).toBeInTheDocument(); const lines = region.querySelectorAll('.recharts-reference-line line'); expect(lines).toHaveLength(2); @@ -157,7 +162,9 @@ describe('MonthlySummaryChart', () => { const { findByRole } = render(); const region = await findByRole('region'); - await within(region).findByText('Contributions average: $3,800.00'); + await within(region).findByText( + 'Contributions average (last 2 months): $3,800.00', + ); const [income, expenses] = Array.from( region.querySelectorAll('.recharts-reference-line'), @@ -171,11 +178,11 @@ describe('MonthlySummaryChart', () => { it('puts a lone $0 average label above its line, clear of the axis', async () => { const { findByRole } = render( - , + , ); const region = await findByRole('region'); - await within(region).findByText('Expenses average: $0.00'); + await within(region).findByText('Expenses average (last 2 months): $0.00'); const line = region.querySelector('.recharts-reference-line'); expect(Number(line?.querySelector('text')?.getAttribute('y'))).toBeLessThan( diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx index 955fc9a082..effb6da615 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx @@ -27,6 +27,8 @@ export interface MonthlySummaryChartData { export interface MonthlySummaryAverages { income?: number; expenses?: number; + // Which months the averages cover, e.g. "last 11 full months" + period: string; } interface MonthlySummaryChartProps { diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx index c1bd3402b8..711edd9a40 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx @@ -53,8 +53,9 @@ export const averageReferenceLines = ({ strokeWidth={2} strokeDasharray="6 4" label={{ - value: t('{{name}} average: {{amount}}', { + value: t('{{name}} average ({{period}}): {{amount}}', { name, + period: averages.period, amount: formatCurrency(value), }), // On a flat line, "insideBottom" sits above it and "insideTop" below From 8902d3c4510520da1de899f298fa8086e11f2f22 Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:26:50 -0800 Subject: [PATCH 08/16] MPDX-10389 Short line labels plus one averages note above chart Co-Authored-By: Claude Opus 5.5 --- public/locales/en/translation.json | 4 +-- .../MonthlySummary/MonthlySummary.test.tsx | 15 +++++---- .../MonthlySummary/MonthlySummary.tsx | 33 +++++++++---------- .../MonthlySummary/chartData.ts | 2 +- .../MonthlySummaryChart.test.tsx | 19 ++++------- .../MonthlySummaryChart.tsx | 2 -- .../averageReferenceLines.tsx | 3 +- 7 files changed, 34 insertions(+), 44 deletions(-) diff --git a/public/locales/en/translation.json b/public/locales/en/translation.json index e8a8f2cee1..cbaf001ce6 100644 --- a/public/locales/en/translation.json +++ b/public/locales/en/translation.json @@ -277,7 +277,7 @@ "{{mode}} Minister's Housing Allowance Calculation Tool": "{{mode}} Minister's Housing Allowance Calculation Tool", "{{month}} ending balance": "{{month}} ending balance", "{{months}} months ago": "{{months}} months ago", - "{{name}} average ({{period}}): {{amount}}": "{{name}} average ({{period}}): {{amount}}", + "{{name}} average: {{amount}}": "{{name}} average: {{amount}}", "{{name}} has one or multiple invalid numbers. Please fix.": "{{name}} has one or multiple invalid numbers. Please fix.", "{{name}} may request up to their Board Approved {{sectionKind}} Amount of {{approvedAmount}}.": "{{name}} may request up to their Board Approved {{sectionKind}} Amount of {{approvedAmount}}.", "{{name}} won't get MHA once this request takes effect.": "{{name}} won't get MHA once this request takes effect.", @@ -714,6 +714,7 @@ "Average monthly payroll per fiscal quarter · last 8 quarters": "Average monthly payroll per fiscal quarter · last 8 quarters", "Average monthly utility costs.": "Average monthly utility costs.", "Average: {{average}}": "Average: {{average}}", + "Averages: last 11 full months": "Averages: last 11 full months", "Avery 5160": "Avery 5160", "Avery 7160": "Avery 7160", "avg": "avg", @@ -1867,7 +1868,6 @@ "Language": "Language", "last": "last", "Last": "Last", - "last 11 full months": "last 11 full months", "Last 12 Months": "Last 12 Months", "Last Full 12 Months": "Last Full 12 Months", "Last Full Month": "Last Full Month", diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx index e699cd57b3..e9d6fe1a70 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx @@ -220,7 +220,7 @@ describe('StaffTabMonthlySummary', () => { }); it('switches to the chart view and back when the toggle is clicked', async () => { - const { findByRole, getByRole, queryByRole } = render( + const { findByRole, getByRole, queryByRole, queryByText } = render( , ); @@ -232,6 +232,9 @@ describe('StaffTabMonthlySummary', () => { userEvent.click(getByRole('button', { name: 'Table view' })); expect(getByRole('table')).toBeInTheDocument(); + expect( + queryByText('Averages: last 11 full months'), + ).not.toBeInTheDocument(); }); it('draws the contributions and expenses averages of the finished months on the chart', async () => { @@ -249,13 +252,10 @@ describe('StaffTabMonthlySummary', () => { userEvent.click(await findByRole('button', { name: 'Chart view' })); expect( - await findByText( - 'Contributions average (last 11 full months): $4,500.00', - ), - ).toBeInTheDocument(); - expect( - getByText('Expenses average (last 11 full months): $3,300.00'), + await findByText('Contributions average: $4,500.00'), ).toBeInTheDocument(); + expect(getByText('Expenses average: $3,300.00')).toBeInTheDocument(); + expect(getByText('Averages: last 11 full months')).toBeInTheDocument(); }); it('charts labelled empty months without showing a zero amount', async () => { @@ -268,6 +268,7 @@ describe('StaffTabMonthlySummary', () => { expect(await findByRole('region')).toBeInTheDocument(); expect(queryByRole('table')).not.toBeInTheDocument(); expect(queryByText(/^\$/)).not.toBeInTheDocument(); + expect(queryByText(/^Averages:/)).not.toBeInTheDocument(); // Tests run pinned to 2020-01-01, so the window ends on the current month. const ticks = Array.from( diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx index be3d26ae1d..192dd13c22 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx @@ -75,14 +75,6 @@ export const StaffTabMonthlySummary: React.FC = ({ [monthlySummary, locale], ); - const averages = useMemo( - () => ({ - ...monthlyAverages(monthlySummary), - period: t('last 11 full months'), - }), - [monthlySummary, t], - ); - const tableRows = useMemo( () => [...monthlySummary].reverse(), [monthlySummary], @@ -127,15 +119,22 @@ export const StaffTabMonthlySummary: React.FC = ({ /> {showChart ? ( - + <> + {hasData && ( + + {t('Averages: last 11 full months')} + + )} + + ) : ( diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts index ba9c180ec5..28dbdbea25 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts @@ -43,7 +43,7 @@ const average = (values: Array) => { // out too, the same as the Dashboard's donation average. export const monthlyAverages = ( months: MonthAmounts[], -): Omit => { +): MonthlySummaryAverages => { const pastMonths = months.slice(0, -1); return { income: average(pastMonths.map((month) => month.contributions)), diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx index 49c41b9ff8..9b7e1f1dfb 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx @@ -56,10 +56,7 @@ const averagesData = [ const ChartWithAverages: React.FC<{ noDataLabel?: string; averages?: MonthlySummaryAverages; -}> = ({ - noDataLabel, - averages = { income: 3800, expenses: 3700, period: 'last 2 months' }, -}) => ( +}> = ({ noDataLabel, averages = { income: 3800, expenses: 3700 } }) => ( { const region = await findByRole('region'); expect( - await within(region).findByText( - 'Contributions average (last 2 months): $3,800.00', - ), + await within(region).findByText('Contributions average: $3,800.00'), ).toBeInTheDocument(); expect( - within(region).getByText('Expenses average (last 2 months): $3,700.00'), + within(region).getByText('Expenses average: $3,700.00'), ).toBeInTheDocument(); const lines = region.querySelectorAll('.recharts-reference-line line'); expect(lines).toHaveLength(2); @@ -162,9 +157,7 @@ describe('MonthlySummaryChart', () => { const { findByRole } = render(); const region = await findByRole('region'); - await within(region).findByText( - 'Contributions average (last 2 months): $3,800.00', - ); + await within(region).findByText('Contributions average: $3,800.00'); const [income, expenses] = Array.from( region.querySelectorAll('.recharts-reference-line'), @@ -178,11 +171,11 @@ describe('MonthlySummaryChart', () => { it('puts a lone $0 average label above its line, clear of the axis', async () => { const { findByRole } = render( - , + , ); const region = await findByRole('region'); - await within(region).findByText('Expenses average (last 2 months): $0.00'); + await within(region).findByText('Expenses average: $0.00'); const line = region.querySelector('.recharts-reference-line'); expect(Number(line?.querySelector('text')?.getAttribute('y'))).toBeLessThan( diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx index effb6da615..955fc9a082 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx @@ -27,8 +27,6 @@ export interface MonthlySummaryChartData { export interface MonthlySummaryAverages { income?: number; expenses?: number; - // Which months the averages cover, e.g. "last 11 full months" - period: string; } interface MonthlySummaryChartProps { diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx index 711edd9a40..c1bd3402b8 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx @@ -53,9 +53,8 @@ export const averageReferenceLines = ({ strokeWidth={2} strokeDasharray="6 4" label={{ - value: t('{{name}} average ({{period}}): {{amount}}', { + value: t('{{name}} average: {{amount}}', { name, - period: averages.period, amount: formatCurrency(value), }), // On a flat line, "insideBottom" sits above it and "insideTop" below From ae6de5c4cfe951c40b0289ef7cc332671376b7b0 Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:33:45 -0800 Subject: [PATCH 09/16] MPDX-10389 Move average amounts into a legend above the chart Co-Authored-By: Claude Opus 5.5 --- .../ChartLegendContent.test.tsx | 19 ++++ .../ChartLegendContent/ChartLegendContent.tsx | 36 +++++--- .../MonthlySummaryChart.test.tsx | 76 +++++++++------- .../MonthlySummaryChart.tsx | 70 +++++++++------ .../averageReferenceLines.tsx | 90 +++++++++---------- 5 files changed, 172 insertions(+), 119 deletions(-) diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.test.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.test.tsx index 10954419f8..434b36c87f 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.test.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.test.tsx @@ -32,6 +32,25 @@ describe('ChartLegendContent', () => { }); }); + it('draws a dashed line swatch for a dashed line entry', () => { + const { getByRole } = render( + , + ); + + const line = getByRole('listitem').querySelector('line'); + expect(line).toHaveAttribute('stroke', theme.palette.error.dark); + expect(line).toHaveAttribute('stroke-dasharray', '6 4'); + }); + it('renders no items when recharts supplies no payload', () => { const { queryAllByRole } = render(); diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.tsx index 9c1455290b..cf15eb98f3 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.tsx @@ -26,17 +26,31 @@ export const ChartLegendContent: React.FC = ({ key={`item-${index}`} style={{ display: 'flex', alignItems: 'center' }} > - + {entry.type === 'plainline' ? ( + + + + ) : ( + + )} {entry.value} diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx index 9b7e1f1dfb..cf4273e684 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx @@ -135,52 +135,67 @@ describe('MonthlySummaryChart', () => { expect(within(region).queryByText(/^\$/)).not.toBeInTheDocument(); }); - it('draws a dashed line with its amount for each average when given averages', async () => { + it('lists each average with its amount in the legend', async () => { const { findByRole } = render(); - const region = await findByRole('region'); + const list = await findByRole('list'); expect( - await within(region).findByText('Contributions average: $3,800.00'), - ).toBeInTheDocument(); - expect( - within(region).getByText('Expenses average: $3,700.00'), - ).toBeInTheDocument(); - const lines = region.querySelectorAll('.recharts-reference-line line'); - expect(lines).toHaveLength(2); - lines.forEach((line) => - expect(line).toHaveAttribute('stroke-dasharray', '6 4'), - ); + within(list) + .getAllByRole('listitem') + .map((item) => item.textContent), + ).toEqual([ + 'Contributions', + 'Expenses', + 'Contributions average: $3,800.00', + 'Expenses average: $3,700.00', + ]); + }); + + it('puts the legend above the chart when it lists averages', async () => { + const { findByRole } = render(); + + const list = await findByRole('list'); + + expect(list.closest('.recharts-wrapper')).toBeNull(); }); - it('puts the higher average label above its line and the lower one below', async () => { + it('draws an unlabelled dashed line for each average', async () => { const { findByRole } = render(); const region = await findByRole('region'); - await within(region).findByText('Contributions average: $3,800.00'); - - const [income, expenses] = Array.from( - region.querySelectorAll('.recharts-reference-line'), - ).map((line) => ({ - lineY: Number(line.querySelector('line')?.getAttribute('y1')), - labelY: Number(line.querySelector('text')?.getAttribute('y')), - })); - expect(income.labelY).toBeLessThan(income.lineY); - expect(expenses.labelY).toBeGreaterThan(expenses.lineY); + + await waitFor(() => + expect( + region.querySelectorAll('.recharts-reference-line line'), + ).toHaveLength(2), + ); + region + .querySelectorAll('.recharts-reference-line line') + .forEach((line) => + expect(line).toHaveAttribute('stroke-dasharray', '6 4'), + ); + expect( + region.querySelectorAll('.recharts-reference-line text'), + ).toHaveLength(0); }); - it('puts a lone $0 average label above its line, clear of the axis', async () => { + it('shows a lone $0 average in the legend and as a line', async () => { const { findByRole } = render( , ); - const region = await findByRole('region'); - await within(region).findByText('Expenses average: $0.00'); + const list = await findByRole('list'); - const line = region.querySelector('.recharts-reference-line'); - expect(Number(line?.querySelector('text')?.getAttribute('y'))).toBeLessThan( - Number(line?.querySelector('line')?.getAttribute('y1')), - ); + expect( + within(list).getByText('Expenses average: $0.00'), + ).toBeInTheDocument(); + expect( + within(list).queryByText(/Contributions average/), + ).not.toBeInTheDocument(); + expect( + (await findByRole('region')).querySelectorAll('.recharts-reference-line'), + ).toHaveLength(1); }); it('draws no average lines without averages', async () => { @@ -212,6 +227,7 @@ describe('MonthlySummaryChart', () => { const list = await findByRole('list'); const items = within(list).getAllByRole('listitem'); expect(items).toHaveLength(2); + expect(list.closest('.recharts-legend-wrapper')).toBeInTheDocument(); expect(within(list).getByText('Income')).toBeInTheDocument(); expect(within(list).getByText('Expenses')).toBeInTheDocument(); diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx index 955fc9a082..648c5eca87 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx @@ -6,6 +6,7 @@ import { BarChart, LabelList, Legend, + LegendProps, Tooltip, XAxis, YAxis, @@ -15,7 +16,10 @@ import { currencyFormat } from 'src/lib/intlFormat'; import theme from 'src/theme'; import { ChartFrame } from '../ChartFrame'; import { ChartLegendContent } from '../ChartLegendContent/ChartLegendContent'; -import { averageReferenceLines } from './averageReferenceLines'; +import { + averageLegendItems, + averageReferenceLines, +} from './averageReferenceLines'; export interface MonthlySummaryChartData { month: string; @@ -37,7 +41,7 @@ interface MonthlySummaryChartProps { width: number; overrideIncomeText?: string; noDataLabel?: string; - // Draws a dashed line at each average, labelled with its amount + // Draws a dashed line at each average and lists its amount in the legend averages?: MonthlySummaryAverages; } @@ -70,6 +74,28 @@ export const MonthlySummaryChart: React.FC = ({ const incomeName = overrideIncomeText ?? t('Income'); + // Masked amounts hide the averages too + const averageOptions = { + t, + averages: maskAmounts ? undefined : averages, + incomeName, + }; + + const averageItems = averageLegendItems({ + ...averageOptions, + formatCurrency, + }); + + // Averages make the legend wrap to several lines on a phone, so then it sits + // above the chart instead of taking height from the plot + const legendAbove = averageItems.length > 0; + + const legendPayload: LegendProps['payload'] = [ + { value: incomeName, type: 'square', color: chartColors[0] }, + { value: t('Expenses'), type: 'square', color: chartColors[1] }, + ...averageItems, + ]; + const monthlyTotals = useMemo( (): MonthlyTotal[] => data.map((month) => ({ @@ -90,6 +116,7 @@ export const MonthlySummaryChart: React.FC = ({ }} /> + {legendAbove && } = ({ /> )} - {!maskAmounts && - averageReferenceLines({ - t, - averages, - incomeName, - formatCurrency, - })} - ( - - )} - payload={[ - { - value: incomeName, - type: 'square', - color: chartColors[0], - }, - { - value: t('Expenses'), - type: 'square', - color: chartColors[1], - }, - ]} - /> + {averageReferenceLines(averageOptions)} + {!legendAbove && ( + ( + + )} + payload={legendPayload} + /> + )} diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx index c1bd3402b8..02de05a3e2 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx @@ -3,70 +3,62 @@ import { ReferenceLine } from 'recharts'; import theme from 'src/theme'; import { MonthlySummaryAverages } from './MonthlySummaryChart'; -interface AverageReferenceLinesOptions { +interface AverageSeriesOptions { t: TFunction; averages?: MonthlySummaryAverages; incomeName: string; - formatCurrency: (value: number) => string; } -// Recharts only finds its own elements among the chart's direct children, so -// this returns ReferenceLine elements instead of being a component. -export const averageReferenceLines = ({ - t, - averages, - incomeName, - formatCurrency, -}: AverageReferenceLinesOptions) => { - if (!averages) { - return []; - } +interface AverageLegendOptions extends AverageSeriesOptions { + formatCurrency: (value: number) => string; +} - // The higher line's label sits above it and the lower one's below, so the - // two labels never share the gap between close lines. A lone line's label - // sits above it. - const incomeOnTop = - (averages.income ?? -Infinity) >= (averages.expenses ?? -Infinity); +const averageDash = '6 4'; - return [ +// The averages that have a value, each in a darker shade of its bars' color so +// the line shows where it crosses its own bars +const averageSeries = ({ t, averages, incomeName }: AverageSeriesOptions) => + [ { key: 'income', - value: averages.income, + value: averages?.income, name: incomeName, - // Darker than the bars so the line shows where it crosses its own bars color: theme.palette.success.dark, - above: incomeOnTop, }, { key: 'expenses', - value: averages.expenses, + value: averages?.expenses, name: t('Expenses'), color: theme.palette.error.dark, - above: !incomeOnTop, }, - ].map(({ key, value, name, color, above }) => - value === undefined ? null : ( - - ), + ].flatMap(({ value, ...series }) => + value === undefined ? [] : [{ ...series, value }], ); -}; + +// Recharts only finds its own elements among the chart's direct children, so +// this returns ReferenceLine elements instead of being a component. The lines +// have no text; their amounts are in the legend. +export const averageReferenceLines = (options: AverageSeriesOptions) => + averageSeries(options).map(({ key, value, color }) => ( + + )); + +export const averageLegendItems = ({ + formatCurrency, + ...options +}: AverageLegendOptions) => + averageSeries(options).map(({ value, name, color }) => ({ + value: options.t('{{name}} average: {{amount}}', { + name, + amount: formatCurrency(value), + }), + type: 'plainline' as const, + color, + payload: { strokeDasharray: averageDash }, + })); From 75470f303f3e1785d8a79e0d0d2b2cd451d72230 Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:38:04 -0800 Subject: [PATCH 10/16] MPDX-10389 Move chart legend setup into a helper Co-Authored-By: Claude Opus 5.5 --- .../MonthlySummaryChart.tsx | 24 ++++++------------ .../averageReferenceLines.tsx | 25 +++++++++++++++++-- 2 files changed, 30 insertions(+), 19 deletions(-) diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx index 648c5eca87..c56396de8f 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx @@ -6,7 +6,6 @@ import { BarChart, LabelList, Legend, - LegendProps, Tooltip, XAxis, YAxis, @@ -16,10 +15,7 @@ import { currencyFormat } from 'src/lib/intlFormat'; import theme from 'src/theme'; import { ChartFrame } from '../ChartFrame'; import { ChartLegendContent } from '../ChartLegendContent/ChartLegendContent'; -import { - averageLegendItems, - averageReferenceLines, -} from './averageReferenceLines'; +import { averageReferenceLines, chartLegend } from './averageReferenceLines'; export interface MonthlySummaryChartData { month: string; @@ -49,7 +45,10 @@ interface MonthlyTotal extends MonthlySummaryChartData { tallest: number; } -const chartColors = [theme.palette.success.main, theme.palette.error.main]; +const chartColors: [string, string] = [ + theme.palette.success.main, + theme.palette.error.main, +]; export const MonthlySummaryChart: React.FC = ({ data, @@ -81,21 +80,12 @@ export const MonthlySummaryChart: React.FC = ({ incomeName, }; - const averageItems = averageLegendItems({ + const { legendPayload, legendAbove } = chartLegend({ ...averageOptions, formatCurrency, + barColors: chartColors, }); - // Averages make the legend wrap to several lines on a phone, so then it sits - // above the chart instead of taking height from the plot - const legendAbove = averageItems.length > 0; - - const legendPayload: LegendProps['payload'] = [ - { value: incomeName, type: 'square', color: chartColors[0] }, - { value: t('Expenses'), type: 'square', color: chartColors[1] }, - ...averageItems, - ]; - const monthlyTotals = useMemo( (): MonthlyTotal[] => data.map((month) => ({ diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx index 02de05a3e2..291a2ca7f0 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx @@ -1,5 +1,5 @@ import { TFunction } from 'i18next'; -import { ReferenceLine } from 'recharts'; +import { LegendProps, ReferenceLine } from 'recharts'; import theme from 'src/theme'; import { MonthlySummaryAverages } from './MonthlySummaryChart'; @@ -49,7 +49,7 @@ export const averageReferenceLines = (options: AverageSeriesOptions) => /> )); -export const averageLegendItems = ({ +const averageLegendItems = ({ formatCurrency, ...options }: AverageLegendOptions) => @@ -62,3 +62,24 @@ export const averageLegendItems = ({ color, payload: { strokeDasharray: averageDash }, })); + +interface ChartLegendOptions extends AverageLegendOptions { + barColors: [string, string]; +} + +// The bars' legend entries plus one per average +export const chartLegend = ({ barColors, ...options }: ChartLegendOptions) => { + const averageItems = averageLegendItems(options); + const legendPayload: LegendProps['payload'] = [ + { value: options.incomeName, type: 'square', color: barColors[0] }, + { value: options.t('Expenses'), type: 'square', color: barColors[1] }, + ...averageItems, + ]; + + return { + legendPayload, + // Averages make the legend wrap to several lines on a phone, so then it + // sits above the chart instead of taking height from the plot + legendAbove: averageItems.length > 0, + }; +}; From b01019da81cfe8c87282511affd367cb78fe8c19 Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:29:13 -0800 Subject: [PATCH 11/16] MPDX-10389 Show averages in a key row above the chart Co-Authored-By: Claude Opus 5.5 --- public/locales/en/translation.json | 4 +- .../MonthlySummary/MonthlySummary.test.tsx | 16 ++-- .../MonthlySummary/MonthlySummary.tsx | 28 +++---- .../ChartLegendContent.test.tsx | 19 ----- .../ChartLegendContent/ChartLegendContent.tsx | 36 +++------ .../Charts/MonthlySummaryChart/AverageKey.tsx | 71 +++++++++++++++++ .../MonthlySummaryChart.test.tsx | 78 +++++++++++++------ .../MonthlySummaryChart.tsx | 43 ++++++---- .../averageReferenceLines.tsx | 58 ++++---------- 9 files changed, 199 insertions(+), 154 deletions(-) create mode 100644 src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/AverageKey.tsx diff --git a/public/locales/en/translation.json b/public/locales/en/translation.json index 2fe33e8038..be40754046 100644 --- a/public/locales/en/translation.json +++ b/public/locales/en/translation.json @@ -171,6 +171,7 @@ "(GMT+13:00) Tokelau Is.": "(GMT+13:00) Tokelau Is.", "(If applicable) Line 10 × {{seca}}": "(If applicable) Line 10 × {{seca}}", "(If applicable) Line 5 × {{seca}}": "(If applicable) Line 5 × {{seca}}", + "(last 11 full months)": "(last 11 full months)", "(N/A)": "(N/A)", "(Quarter)": "(Quarter)", "(Sent by {{firstName}} {{lastName}})": "(Sent by {{firstName}} {{lastName}})", @@ -277,7 +278,7 @@ "{{mode}} Minister's Housing Allowance Calculation Tool": "{{mode}} Minister's Housing Allowance Calculation Tool", "{{month}} ending balance": "{{month}} ending balance", "{{months}} months ago": "{{months}} months ago", - "{{name}} average: {{amount}}": "{{name}} average: {{amount}}", + "{{name}} average": "{{name}} average", "{{name}} has one or multiple invalid numbers. Please fix.": "{{name}} has one or multiple invalid numbers. Please fix.", "{{name}} may request up to their Board Approved {{sectionKind}} Amount of {{approvedAmount}}.": "{{name}} may request up to their Board Approved {{sectionKind}} Amount of {{approvedAmount}}.", "{{name}} won't get MHA once this request takes effect.": "{{name}} won't get MHA once this request takes effect.", @@ -714,7 +715,6 @@ "Average monthly payroll per fiscal quarter · last 8 quarters": "Average monthly payroll per fiscal quarter · last 8 quarters", "Average monthly utility costs.": "Average monthly utility costs.", "Average: {{average}}": "Average: {{average}}", - "Averages: last 11 full months": "Averages: last 11 full months", "Avery 5160": "Avery 5160", "Avery 7160": "Avery 7160", "avg": "avg", diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx index e9d6fe1a70..d149193ec2 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx @@ -232,13 +232,11 @@ describe('StaffTabMonthlySummary', () => { userEvent.click(getByRole('button', { name: 'Table view' })); expect(getByRole('table')).toBeInTheDocument(); - expect( - queryByText('Averages: last 11 full months'), - ).not.toBeInTheDocument(); + expect(queryByText('(last 11 full months)')).not.toBeInTheDocument(); }); it('draws the contributions and expenses averages of the finished months on the chart', async () => { - const { findByRole, findByText, getByText } = render( + const { findByRole, findByTestId } = render( { userEvent.click(await findByRole('button', { name: 'Chart view' })); - expect( - await findByText('Contributions average: $4,500.00'), - ).toBeInTheDocument(); - expect(getByText('Expenses average: $3,300.00')).toBeInTheDocument(); - expect(getByText('Averages: last 11 full months')).toBeInTheDocument(); + expect(await findByTestId('MonthlySummaryAverageKey')).toHaveTextContent( + 'Contributions average $4,500.00Expenses average $3,300.00(last 11 full months)', + ); }); it('charts labelled empty months without showing a zero amount', async () => { @@ -268,7 +264,7 @@ describe('StaffTabMonthlySummary', () => { expect(await findByRole('region')).toBeInTheDocument(); expect(queryByRole('table')).not.toBeInTheDocument(); expect(queryByText(/^\$/)).not.toBeInTheDocument(); - expect(queryByText(/^Averages:/)).not.toBeInTheDocument(); + expect(queryByText(/full months/)).not.toBeInTheDocument(); // Tests run pinned to 2020-01-01, so the window ends on the current month. const ticks = Array.from( diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx index 192dd13c22..1787783e44 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx @@ -119,22 +119,18 @@ export const StaffTabMonthlySummary: React.FC = ({ /> {showChart ? ( - <> - {hasData && ( - - {t('Averages: last 11 full months')} - - )} - - + ) : (
diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.test.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.test.tsx index 434b36c87f..10954419f8 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.test.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.test.tsx @@ -32,25 +32,6 @@ describe('ChartLegendContent', () => { }); }); - it('draws a dashed line swatch for a dashed line entry', () => { - const { getByRole } = render( - , - ); - - const line = getByRole('listitem').querySelector('line'); - expect(line).toHaveAttribute('stroke', theme.palette.error.dark); - expect(line).toHaveAttribute('stroke-dasharray', '6 4'); - }); - it('renders no items when recharts supplies no payload', () => { const { queryAllByRole } = render(); diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.tsx index cf15eb98f3..9c1455290b 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/ChartLegendContent/ChartLegendContent.tsx @@ -26,31 +26,17 @@ export const ChartLegendContent: React.FC = ({ key={`item-${index}`} style={{ display: 'flex', alignItems: 'center' }} > - {entry.type === 'plainline' ? ( - - - - ) : ( - - )} + {entry.value} diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/AverageKey.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/AverageKey.tsx new file mode 100644 index 0000000000..6e7beae1d4 --- /dev/null +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/AverageKey.tsx @@ -0,0 +1,71 @@ +import { Grid, Typography } from '@mui/material'; +import { useTranslation } from 'react-i18next'; +import { LegendProps } from 'recharts'; +import { ChartLegendContent } from '../ChartLegendContent/ChartLegendContent'; +import { AverageSeries, averageDash } from './averageReferenceLines'; + +interface AverageKeyProps { + series: AverageSeries[]; + formatCurrency: (value: number) => string; + note?: string; + // The bars' legend, shown under the key outside the chart so it can't + // overlap the plot on a phone + legend: LegendProps['payload']; +} + +// A key row above the chart, like the Dashboard's Monthly Giving chart: a +// dashed swatch matching each average line, its name in bold, then the amount +export const AverageKey: React.FC = ({ + series, + formatCurrency, + note, + legend, +}) => { + const { t } = useTranslation(); + + return ( + <> + + {series.map(({ key, name, color, value }) => ( + + + + {t('{{name}} average', { name })}{' '} + {formatCurrency(value)} + + + ))} + {note && ( + + + {note} + + + )} + + + + ); +}; diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx index cf4273e684..ac1149f3e3 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx @@ -1,6 +1,7 @@ import '../sharedRechartMock'; import React from 'react'; import { render, waitFor, within } from '@testing-library/react'; +import theme from 'src/theme'; import { useMPGAIncomeExpenses } from '../../MPGAIncomeExpensesContext/MPGAIncomeExpensesContext'; import { MPGAIncomeExpensesReportTestWrapper } from '../../MPGAIncomeExpensesReportTestWrapper'; import { @@ -135,29 +136,58 @@ describe('MonthlySummaryChart', () => { expect(within(region).queryByText(/^\$/)).not.toBeInTheDocument(); }); - it('lists each average with its amount in the legend', async () => { - const { findByRole } = render(); + it('lists only the bars in the legend, between the key and the chart, when averages show', async () => { + const { findByRole, getByTestId } = render(); const list = await findByRole('list'); + const region = await findByRole('region'); expect( within(list) .getAllByRole('listitem') .map((item) => item.textContent), - ).toEqual([ - 'Contributions', - 'Expenses', - 'Contributions average: $3,800.00', - 'Expenses average: $3,700.00', - ]); + ).toEqual(['Contributions', 'Expenses']); + // Outside the chart so it can't overlap the plot on a phone + expect( + getByTestId('MonthlySummaryAverageKey').compareDocumentPosition(list) & + Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + expect(region).not.toContainElement(list); }); - it('puts the legend above the chart when it lists averages', async () => { - const { findByRole } = render(); + it('shows a key above the chart with each average and the note', async () => { + const { findByRole, getByTestId } = render( + , + ); - const list = await findByRole('list'); + const region = await findByRole('region'); + const key = getByTestId('MonthlySummaryAverageKey'); - expect(list.closest('.recharts-wrapper')).toBeNull(); + expect( + key.compareDocumentPosition(region) & Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + const contributions = within(key).getByText('Contributions average'); + expect(contributions.tagName).toBe('STRONG'); + expect(contributions.parentElement).toHaveTextContent( + 'Contributions average $3,800.00', + ); + expect( + within(key).getByText('Expenses average').parentElement, + ).toHaveTextContent('Expenses average $3,700.00'); + expect(within(key).getByText('(last 3 months)')).toBeInTheDocument(); + + const swatches = key.querySelectorAll('svg[aria-hidden="true"] line'); + expect( + Array.from(swatches).map((line) => [ + line.getAttribute('stroke'), + line.getAttribute('stroke-dasharray'), + ]), + ).toEqual([ + [theme.palette.success.dark, '6 4'], + [theme.palette.error.dark, '6 4'], + ]); }); it('draws an unlabelled dashed line for each average', async () => { @@ -180,26 +210,21 @@ describe('MonthlySummaryChart', () => { ).toHaveLength(0); }); - it('shows a lone $0 average in the legend and as a line', async () => { - const { findByRole } = render( + it('shows a lone $0 average in the key and as a line', async () => { + const { findByTestId, findByRole } = render( , ); - const list = await findByRole('list'); + const key = await findByTestId('MonthlySummaryAverageKey'); - expect( - within(list).getByText('Expenses average: $0.00'), - ).toBeInTheDocument(); - expect( - within(list).queryByText(/Contributions average/), - ).not.toBeInTheDocument(); + expect(key).toHaveTextContent(/^Expenses average \$0\.00$/); expect( (await findByRole('region')).querySelectorAll('.recharts-reference-line'), ).toHaveLength(1); }); - it('draws no average lines without averages', async () => { - const { findByRole } = render(); + it('draws no average lines or key without averages', async () => { + const { findByRole, queryByTestId } = render(); const region = await findByRole('region'); @@ -207,10 +232,13 @@ describe('MonthlySummaryChart', () => { expect(region.querySelector('svg.recharts-surface')).toBeTruthy(), ); expect(region.querySelectorAll('.recharts-reference-line')).toHaveLength(0); + expect(queryByTestId('MonthlySummaryAverageKey')).not.toBeInTheDocument(); }); it('draws no average lines when amounts are masked', async () => { - const { findByRole } = render(); + const { findByRole, queryByTestId } = render( + , + ); const region = await findByRole('region'); @@ -218,7 +246,7 @@ describe('MonthlySummaryChart', () => { expect(region.querySelector('svg.recharts-surface')).toBeTruthy(), ); expect(region.querySelectorAll('.recharts-reference-line')).toHaveLength(0); - expect(within(region).queryByText(/average/)).not.toBeInTheDocument(); + expect(queryByTestId('MonthlySummaryAverageKey')).not.toBeInTheDocument(); }); it('renders legend with correct labels', async () => { diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx index c56396de8f..a3d3998618 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx @@ -6,6 +6,7 @@ import { BarChart, LabelList, Legend, + LegendProps, Tooltip, XAxis, YAxis, @@ -15,7 +16,8 @@ import { currencyFormat } from 'src/lib/intlFormat'; import theme from 'src/theme'; import { ChartFrame } from '../ChartFrame'; import { ChartLegendContent } from '../ChartLegendContent/ChartLegendContent'; -import { averageReferenceLines, chartLegend } from './averageReferenceLines'; +import { AverageKey } from './AverageKey'; +import { averageReferenceLines, averageSeries } from './averageReferenceLines'; export interface MonthlySummaryChartData { month: string; @@ -27,6 +29,8 @@ export interface MonthlySummaryChartData { export interface MonthlySummaryAverages { income?: number; expenses?: number; + // Shown at the end of the key row, e.g. which months the averages cover + note?: string; } interface MonthlySummaryChartProps { @@ -37,7 +41,7 @@ interface MonthlySummaryChartProps { width: number; overrideIncomeText?: string; noDataLabel?: string; - // Draws a dashed line at each average and lists its amount in the legend + // Draws a dashed line at each average and lists its amount in a key above averages?: MonthlySummaryAverages; } @@ -45,9 +49,14 @@ interface MonthlyTotal extends MonthlySummaryChartData { tallest: number; } -const chartColors: [string, string] = [ - theme.palette.success.main, - theme.palette.error.main, +const chartColors = [theme.palette.success.main, theme.palette.error.main]; + +const barLegend = ( + incomeName: string, + expensesName: string, +): LegendProps['payload'] => [ + { value: incomeName, type: 'square', color: chartColors[0] }, + { value: expensesName, type: 'square', color: chartColors[1] }, ]; export const MonthlySummaryChart: React.FC = ({ @@ -74,17 +83,16 @@ export const MonthlySummaryChart: React.FC = ({ const incomeName = overrideIncomeText ?? t('Income'); // Masked amounts hide the averages too - const averageOptions = { + const averageLines = averageSeries({ t, averages: maskAmounts ? undefined : averages, incomeName, - }; - - const { legendPayload, legendAbove } = chartLegend({ - ...averageOptions, - formatCurrency, - barColors: chartColors, }); + // With the key row, the legend sits above the chart too, so it can't + // overlap the plot on a phone + const legendAbove = averageLines.length > 0; + + const legendPayload = barLegend(incomeName, t('Expenses')); const monthlyTotals = useMemo( (): MonthlyTotal[] => @@ -106,7 +114,14 @@ export const MonthlySummaryChart: React.FC = ({ }} /> - {legendAbove && } + {legendAbove && ( + + )} = ({ /> )} - {averageReferenceLines(averageOptions)} + {averageReferenceLines(averageLines)} {!legendAbove && ( string; +export interface AverageSeries { + key: string; + value: number; + name: string; + color: string; } -const averageDash = '6 4'; +export const averageDash = '6 4'; // The averages that have a value, each in a darker shade of its bars' color so // the line shows where it crosses its own bars -const averageSeries = ({ t, averages, incomeName }: AverageSeriesOptions) => +export const averageSeries = ({ + t, + averages, + incomeName, +}: AverageSeriesOptions): AverageSeries[] => [ { key: 'income', @@ -37,9 +44,9 @@ const averageSeries = ({ t, averages, incomeName }: AverageSeriesOptions) => // Recharts only finds its own elements among the chart's direct children, so // this returns ReferenceLine elements instead of being a component. The lines -// have no text; their amounts are in the legend. -export const averageReferenceLines = (options: AverageSeriesOptions) => - averageSeries(options).map(({ key, value, color }) => ( +// have no text; their amounts are in the key above the chart. +export const averageReferenceLines = (series: AverageSeries[]) => + series.map(({ key, value, color }) => ( strokeDasharray={averageDash} /> )); - -const averageLegendItems = ({ - formatCurrency, - ...options -}: AverageLegendOptions) => - averageSeries(options).map(({ value, name, color }) => ({ - value: options.t('{{name}} average: {{amount}}', { - name, - amount: formatCurrency(value), - }), - type: 'plainline' as const, - color, - payload: { strokeDasharray: averageDash }, - })); - -interface ChartLegendOptions extends AverageLegendOptions { - barColors: [string, string]; -} - -// The bars' legend entries plus one per average -export const chartLegend = ({ barColors, ...options }: ChartLegendOptions) => { - const averageItems = averageLegendItems(options); - const legendPayload: LegendProps['payload'] = [ - { value: options.incomeName, type: 'square', color: barColors[0] }, - { value: options.t('Expenses'), type: 'square', color: barColors[1] }, - ...averageItems, - ]; - - return { - legendPayload, - // Averages make the legend wrap to several lines on a phone, so then it - // sits above the chart instead of taking height from the plot - legendAbove: averageItems.length > 0, - }; -}; From 44ee033ea4dd0bf3588b08b5b8eeff3a174dbb32 Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:56:34 -0800 Subject: [PATCH 12/16] MPDX-10389 Leave pre-join empty months out of the averages Co-Authored-By: Claude Opus 5.5 --- public/locales/en/translation.json | 3 +- .../MonthlySummary/MonthlySummary.test.tsx | 6 +-- .../MonthlySummary/MonthlySummary.tsx | 6 ++- .../MonthlySummary/chartData.test.ts | 42 +++++++++++++++++-- .../MonthlySummary/chartData.ts | 18 +++++--- 5 files changed, 60 insertions(+), 15 deletions(-) diff --git a/public/locales/en/translation.json b/public/locales/en/translation.json index be40754046..aa52955d6c 100644 --- a/public/locales/en/translation.json +++ b/public/locales/en/translation.json @@ -171,7 +171,8 @@ "(GMT+13:00) Tokelau Is.": "(GMT+13:00) Tokelau Is.", "(If applicable) Line 10 × {{seca}}": "(If applicable) Line 10 × {{seca}}", "(If applicable) Line 5 × {{seca}}": "(If applicable) Line 5 × {{seca}}", - "(last 11 full months)": "(last 11 full months)", + "(last {{count}} full months)_one": "(last full month)", + "(last {{count}} full months)_other": "(last {{count}} full months)", "(N/A)": "(N/A)", "(Quarter)": "(Quarter)", "(Sent by {{firstName}} {{lastName}})": "(Sent by {{firstName}} {{lastName}})", diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx index d149193ec2..702086628a 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx @@ -232,7 +232,7 @@ describe('StaffTabMonthlySummary', () => { userEvent.click(getByRole('button', { name: 'Table view' })); expect(getByRole('table')).toBeInTheDocument(); - expect(queryByText('(last 11 full months)')).not.toBeInTheDocument(); + expect(queryByText(/full month/)).not.toBeInTheDocument(); }); it('draws the contributions and expenses averages of the finished months on the chart', async () => { @@ -250,7 +250,7 @@ describe('StaffTabMonthlySummary', () => { userEvent.click(await findByRole('button', { name: 'Chart view' })); expect(await findByTestId('MonthlySummaryAverageKey')).toHaveTextContent( - 'Contributions average $4,500.00Expenses average $3,300.00(last 11 full months)', + 'Contributions average $4,500.00Expenses average $3,300.00(last 2 full months)', ); }); @@ -264,7 +264,7 @@ describe('StaffTabMonthlySummary', () => { expect(await findByRole('region')).toBeInTheDocument(); expect(queryByRole('table')).not.toBeInTheDocument(); expect(queryByText(/^\$/)).not.toBeInTheDocument(); - expect(queryByText(/full months/)).not.toBeInTheDocument(); + expect(queryByText(/full month/)).not.toBeInTheDocument(); // Tests run pinned to 2020-01-01, so the window ends on the current month. const ticks = Array.from( diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx index 1787783e44..7c5173e510 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx @@ -82,6 +82,8 @@ export const StaffTabMonthlySummary: React.FC = ({ const showChart = view === MonthlySummaryView.Chart; const hasData = monthlySummary.length > 0; + const { months: averagedMonths, ...averages } = + monthlyAverages(monthlySummary); const emptyChartData = useMemo((): MonthlySummaryChartData[] => { const thisMonth = DateTime.local().startOf('month'); @@ -127,8 +129,8 @@ export const StaffTabMonthlySummary: React.FC = ({ overrideIncomeText={t('Contributions')} noDataLabel={hasData ? undefined : t('N/A')} averages={{ - ...monthlyAverages(monthlySummary), - note: t('(last 11 full months)'), + ...averages, + note: t('(last {{count}} full months)', { count: averagedMonths }), }} /> ) : ( diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts index e11cda9118..3080541b4f 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts @@ -29,7 +29,7 @@ describe('monthlyAverages', () => { { contributions: 3200, expenses: 3100 }, currentMonth, ]), - ).toEqual({ income: 3800, expenses: 3700 }); + ).toEqual({ income: 3800, expenses: 3700, months: 3 }); }); it('leaves out the last row, even when its date is not this month', () => { @@ -39,7 +39,7 @@ describe('monthlyAverages', () => { { month: '2019-12', contributions: 5000, expenses: 4000 }, { month: '2019-12', ...currentMonth }, ]), - ).toEqual({ income: 4500, expenses: 3500 }); + ).toEqual({ income: 4500, expenses: 3500, months: 2 }); }); it('skips months with no amount but counts months reported as zero', () => { @@ -50,7 +50,7 @@ describe('monthlyAverages', () => { { contributions: 3000, expenses: null }, currentMonth, ]), - ).toEqual({ income: 1500, expenses: 1000 }); + ).toEqual({ income: 1500, expenses: 1000, months: 2 }); }); it('has no average for a field with no amounts', () => { @@ -60,6 +60,40 @@ describe('monthlyAverages', () => { { contributions: undefined, expenses: 400 }, currentMonth, ]), - ).toEqual({ income: undefined, expenses: 300 }); + ).toEqual({ income: undefined, expenses: 300, months: 2 }); + }); + + it('leaves out the empty months before the staff member started', () => { + // The API sends months before someone joined as $0, not null + expect( + monthlyAverages([ + { contributions: 0, expenses: 0 }, + { contributions: 0, expenses: 0 }, + { contributions: 4000, expenses: 3000 }, + { contributions: 5000, expenses: 3600 }, + currentMonth, + ]), + ).toEqual({ income: 4500, expenses: 3300, months: 2 }); + }); + + it('counts an empty month once activity has started', () => { + expect( + monthlyAverages([ + { contributions: 0, expenses: 0 }, + { contributions: 4000, expenses: 3000 }, + { contributions: 0, expenses: 0 }, + { contributions: 5000, expenses: 3600 }, + currentMonth, + ]), + ).toEqual({ income: 3000, expenses: 2200, months: 3 }); + }); + + it('has no averages when no month is finished or active', () => { + const none = { income: undefined, expenses: undefined, months: 0 }; + expect(monthlyAverages([])).toEqual(none); + expect(monthlyAverages([currentMonth])).toEqual(none); + expect( + monthlyAverages([{ contributions: 0, expenses: 0 }, currentMonth]), + ).toEqual(none); }); }); diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts index 28dbdbea25..855720b636 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts @@ -27,8 +27,8 @@ export const toChartData = ( }; }); -// Months with no amount (before they joined, or not synced) are left out so -// they don't drag the average down. A reported $0 counts. +// Months with no amount (not synced) are left out so they don't drag the +// average down. A reported $0 counts. const average = (values: Array) => { const amounts = values.filter( (value): value is number => value !== null && value !== undefined, @@ -39,14 +39,22 @@ const average = (values: Array) => { return amounts.reduce((sum, value) => sum + value, 0) / amounts.length; }; +const isEmpty = (month: MonthAmounts) => + !month.contributions && !month.expenses; + // The API's last row is the current month, still in progress, so it is left -// out too, the same as the Dashboard's donation average. +// out too, the same as the Dashboard's donation average. The API sends the +// months before someone joined as $0, so empty months before their first +// activity are left out as well. `months` is how many months are averaged. export const monthlyAverages = ( months: MonthAmounts[], -): MonthlySummaryAverages => { - const pastMonths = months.slice(0, -1); +): MonthlySummaryAverages & { months: number } => { + const finishedMonths = months.slice(0, -1); + const firstActive = finishedMonths.findIndex((month) => !isEmpty(month)); + const pastMonths = firstActive < 0 ? [] : finishedMonths.slice(firstActive); return { income: average(pastMonths.map((month) => month.contributions)), expenses: average(pastMonths.map((month) => month.expenses)), + months: pastMonths.length, }; }; From 74c9caf8ad6cad65821b535d1c6a14ae158f928d Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:03:00 -0800 Subject: [PATCH 13/16] MPDX-10389 Apply Joanna's chart design changes Co-Authored-By: Claude Opus 5.5 --- public/locales/en/translation.json | 9 +- .../IncomeExpensesChart/AverageKey.test.tsx | 115 ++++++++ .../IncomeExpensesChart/AverageKey.tsx | 109 ++++++++ .../IncomeExpensesChart.test.tsx | 261 ++++++++++++++++++ .../IncomeExpensesChart.tsx | 145 ++++++++++ .../IncomeExpensesChart/averageLines.tsx | 104 +++++++ .../MonthlySummary/MonthlySummary.test.tsx | 20 +- .../MonthlySummary/MonthlySummary.tsx | 34 +-- .../MonthlySummary/chartData.test.ts | 111 +++++++- .../MonthlySummary/chartData.ts | 103 +++++-- .../Charts/MonthlySummaryChart/AverageKey.tsx | 71 ----- .../MonthlySummaryChart.test.tsx | 142 +--------- .../MonthlySummaryChart.tsx | 144 +++------- .../MonthlySummaryTooltip.tsx | 62 +++++ .../averageReferenceLines.tsx | 57 ---- src/theme.ts | 17 ++ 16 files changed, 1073 insertions(+), 431 deletions(-) create mode 100644 src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/AverageKey.test.tsx create mode 100644 src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/AverageKey.tsx create mode 100644 src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.test.tsx create mode 100644 src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.tsx create mode 100644 src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/averageLines.tsx delete mode 100644 src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/AverageKey.tsx create mode 100644 src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryTooltip.tsx delete mode 100644 src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx diff --git a/public/locales/en/translation.json b/public/locales/en/translation.json index aa52955d6c..de6614557f 100644 --- a/public/locales/en/translation.json +++ b/public/locales/en/translation.json @@ -171,13 +171,17 @@ "(GMT+13:00) Tokelau Is.": "(GMT+13:00) Tokelau Is.", "(If applicable) Line 10 × {{seca}}": "(If applicable) Line 10 × {{seca}}", "(If applicable) Line 5 × {{seca}}": "(If applicable) Line 5 × {{seca}}", - "(last {{count}} full months)_one": "(last full month)", - "(last {{count}} full months)_other": "(last {{count}} full months)", "(N/A)": "(N/A)", "(Quarter)": "(Quarter)", "(Sent by {{firstName}} {{lastName}})": "(Sent by {{firstName}} {{lastName}})", "(Year)": "(Year)", + "Averages will show after your first full month.": "Averages will show after your first full month.", + "Avg. difference": "Avg. difference", "Dismiss": "Dismiss", + "Monthly averages for the last {{count}} full months ({{range}}). {{month}} is still in progress._one": "Monthly average for the last full month ({{range}}). {{month}} is still in progress.", + "Monthly averages for the last {{count}} full months ({{range}}). {{month}} is still in progress._other": "Monthly averages for the last {{count}} full months ({{range}}). {{month}} is still in progress.", + "Monthly averages for the {{count}} full months on record ({{range}}). {{month}} is still in progress._one": "Monthly average for the {{count}} full month on record ({{range}}). {{month}} is still in progress.", + "Monthly averages for the {{count}} full months on record ({{range}}). {{month}} is still in progress._other": "Monthly averages for the {{count}} full months on record ({{range}}). {{month}} is still in progress.", "Review your goal, see how to present it to partners, and read your next steps. We also emailed you the full worksheet as a PDF.": "Review your goal, see how to present it to partners, and read your next steps. We also emailed you the full worksheet as a PDF.", "View my MPD goal": "View my MPD goal", "Your goal changed since you last looked. Review the updated worksheet, which was also emailed to you as a PDF.": "Your goal changed since you last looked. Review the updated worksheet, which was also emailed to you as a PDF.", @@ -279,7 +283,6 @@ "{{mode}} Minister's Housing Allowance Calculation Tool": "{{mode}} Minister's Housing Allowance Calculation Tool", "{{month}} ending balance": "{{month}} ending balance", "{{months}} months ago": "{{months}} months ago", - "{{name}} average": "{{name}} average", "{{name}} has one or multiple invalid numbers. Please fix.": "{{name}} has one or multiple invalid numbers. Please fix.", "{{name}} may request up to their Board Approved {{sectionKind}} Amount of {{approvedAmount}}.": "{{name}} may request up to their Board Approved {{sectionKind}} Amount of {{approvedAmount}}.", "{{name}} won't get MHA once this request takes effect.": "{{name}} won't get MHA once this request takes effect.", diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/AverageKey.test.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/AverageKey.test.tsx new file mode 100644 index 0000000000..4e901d643c --- /dev/null +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/AverageKey.test.tsx @@ -0,0 +1,115 @@ +import { ThemeProvider } from '@mui/material/styles'; +import { render } from '__tests__/util/testingLibraryReactMock'; +import theme from 'src/theme'; +import { AverageKey } from './AverageKey'; +import { IncomeExpensesAverages } from './IncomeExpensesChart'; + +interface TestComponentProps { + averages?: IncomeExpensesAverages; + note?: string; +} + +const TestComponent: React.FC = ({ + averages = { income: 56150 / 11, expenses: 53450 / 11 }, + note = 'Monthly averages for the last 11 full months.', +}) => ( + + + +); + +describe('AverageKey', () => { + it('lists each series with its average, then the difference', () => { + const { getByTestId } = render(); + + const key = getByTestId('MonthlySummaryAverageKey'); + + expect(Array.from(key.children).map((item) => item.textContent)).toEqual([ + 'Contributionsavg $5,104.55', + 'Expensesavg $4,859.09', + 'Avg. difference+$245.46', + ]); + }); + + it('shows the amounts at 14px, weight 600', () => { + const { getByText } = render(); + + ['$5,104.55', '$4,859.09', '+$245.46'].forEach((amount) => + expect(getByText(amount)).toHaveStyle({ + fontSize: '14px', + fontWeight: 600, + }), + ); + }); + + it('signs a negative difference', () => { + const { getByText } = render( + , + ); + + expect(getByText('-$100.00')).toBeInTheDocument(); + }); + + it('shows no sign on a zero difference', () => { + const { getByText } = render( + , + ); + + expect(getByText('$0.00').previousSibling).toHaveTextContent( + 'Avg. difference', + ); + }); + + it('draws a bar swatch and a line swatch in the same pattern as its line', () => { + const { getByTestId } = render(); + + const key = getByTestId('MonthlySummaryAverageKey'); + + expect( + Array.from(key.querySelectorAll('svg[aria-hidden="true"] rect')).map( + (rect) => rect.getAttribute('fill'), + ), + ).toEqual(['#43A047', '#B71C1C']); + expect( + Array.from( + key.querySelectorAll('svg[aria-hidden="true"] line[stroke-width="3"]'), + ).map((line) => [ + line.getAttribute('stroke'), + line.getAttribute('stroke-dasharray'), + ]), + ).toEqual([ + ['#1B5E20', '12 6'], + ['#B71C1C', '3 4'], + ]); + }); + + it('shows the note under the key in small gray text', () => { + const { getByText, getByTestId } = render(); + + const note = getByText('Monthly averages for the last 11 full months.'); + + expect( + getByTestId('MonthlySummaryAverageKey').compareDocumentPosition(note) & + Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + expect(note).toHaveStyle({ fontSize: '13px', color: '#757575' }); + }); + + it('lists the series without averages or a difference when there are no averages', () => { + const { getByTestId, getByText } = render( + , + ); + + expect( + Array.from(getByTestId('MonthlySummaryAverageKey').children).map( + (item) => item.textContent, + ), + ).toEqual(['Contributions', 'Expenses']); + expect( + getByText('Averages will show after your first full month.'), + ).toBeInTheDocument(); + }); +}); diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/AverageKey.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/AverageKey.tsx new file mode 100644 index 0000000000..22004a51ee --- /dev/null +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/AverageKey.tsx @@ -0,0 +1,109 @@ +import { Box, Typography } from '@mui/material'; +import { useTranslation } from 'react-i18next'; +import { useFormatters } from 'src/components/HrTools/Shared/useFormatters'; +import theme from 'src/theme'; +import { IncomeExpensesAverages } from './IncomeExpensesChart'; +import { AverageLine, AverageSeries, averageSeries } from './averageLines'; + +const Amount: React.FC<{ children: string }> = ({ children }) => ( + + {children} + +); + +interface SeriesKeyProps { + series: AverageSeries; +} + +// The bars' swatch and name, then the line's swatch and the average +const SeriesKey: React.FC = ({ series }) => { + const { t } = useTranslation(); + const { formatCurrency } = useFormatters(); + + return ( + + + + {series.name} + + {series.value !== undefined && ( + + + + {t('avg')} {formatCurrency(series.value)} + + + )} + + ); +}; + +// Each average is rounded to cents first, so the difference matches the two +// amounts shown +const averageDifference = ({ income, expenses }: IncomeExpensesAverages) => + income === undefined || expenses === undefined + ? undefined + : (Math.round(income * 100) - Math.round(expenses * 100)) / 100; + +interface AverageKeyProps { + averages: IncomeExpensesAverages; + // Says which months the averages cover + note: string; +} + +// One row on wider screens. On a phone each series gets its own row, name on +// the left and average on the right. +export const AverageKey: React.FC = ({ averages, note }) => { + const { t } = useTranslation(); + const { formatCurrency } = useFormatters(); + const difference = averageDifference(averages); + + return ( + + + {averageSeries(t, averages).map((series) => ( + + ))} + {difference !== undefined && ( + + {t('Avg. difference')} + {`${difference > 0 ? '+' : ''}${formatCurrency(difference)}`} + + )} + + + {note} + + + ); +}; diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.test.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.test.tsx new file mode 100644 index 0000000000..b172c6af8a --- /dev/null +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.test.tsx @@ -0,0 +1,261 @@ +import 'src/components/Reports/MPGAIncomeExpensesReport/Charts/sharedRechartMock'; +import { ThemeProvider } from '@mui/material/styles'; +import { waitFor, within } from '@testing-library/react'; +import matchMediaMock from '__tests__/util/matchMediaMock'; +import { render } from '__tests__/util/testingLibraryReactMock'; +import theme from 'src/theme'; +import { + IncomeExpensesAverages, + IncomeExpensesChart, + IncomeExpensesMonth, +} from './IncomeExpensesChart'; + +const monthNames = [ + 'Dec 2025', + 'Jan 2026', + 'Feb 2026', + 'Mar 2026', + 'Apr 2026', + 'May 2026', + 'Jun 2026', + 'Jul 2026', + 'Aug 2026', + 'Sep 2026', + 'Oct 2026', + 'Nov 2026', +]; + +// A staff member who started in July: no amounts before then +const newStaffData: IncomeExpensesMonth[] = monthNames.map((month, index) => + index < 7 + ? { month, income: null, expenses: null, net: null } + : { month, income: 5000, expenses: 4800, net: 200 }, +); + +const fullYearData: IncomeExpensesMonth[] = monthNames.map((month) => ({ + month, + income: 5000, + expenses: 4800, + net: 200, +})); + +const emptyData: IncomeExpensesMonth[] = monthNames.map((month) => ({ + month, + income: null, + expenses: null, + net: null, +})); + +interface TestComponentProps { + data?: IncomeExpensesMonth[]; + averages?: IncomeExpensesAverages; + note?: string; +} + +const TestComponent: React.FC = ({ + data = fullYearData, + averages = { income: 56150 / 11, expenses: 53450 / 11 }, + note = 'Monthly averages for the last 11 full months.', +}) => ( + + + +); + +const tickLabels = (container: HTMLElement) => + Array.from( + container.querySelectorAll('.xAxis .recharts-cartesian-axis-tick text'), + ) as SVGTextElement[]; + +describe('IncomeExpensesChart', () => { + afterEach(() => { + matchMediaMock({ width: window.innerWidth }); + }); + + describe('chart', () => { + it('colors the bars with the chart colors', async () => { + const { findByRole } = render(); + + const region = await findByRole('region'); + + await waitFor(() => + expect( + region.querySelectorAll('.recharts-bar-rectangle path'), + ).toHaveLength(24), + ); + const fills = new Set( + Array.from(region.querySelectorAll('.recharts-bar-rectangle path')).map( + (bar) => bar.getAttribute('fill'), + ), + ); + expect(fills).toEqual( + new Set([ + theme.palette.chartContributions.main, + theme.palette.chartExpenses.main, + ]), + ); + }); + + it('draws each average as a 3px patterned line on a white edge', async () => { + const { findByRole } = render(); + + const region = await findByRole('region'); + + await waitFor(() => + expect( + region.querySelectorAll('.recharts-reference-line line'), + ).toHaveLength(4), + ); + expect( + Array.from( + region.querySelectorAll('.recharts-reference-line line'), + ).map((line) => [ + line.getAttribute('stroke'), + line.getAttribute('stroke-width'), + line.getAttribute('stroke-dasharray'), + line.getAttribute('stroke-dashoffset'), + ]), + ).toEqual([ + ['#fff', '5', '14 4', '1'], + ['#1B5E20', '3', '12 6', null], + ['#fff', '5', '5 2', '1'], + ['#B71C1C', '3', '3 4', null], + ]); + }); + + it('draws no bars for the months before the first recorded month and grays their names', async () => { + const { container, findByRole } = render( + , + ); + + const region = await findByRole('region'); + + await waitFor(() => + expect( + region.querySelectorAll('.recharts-bar-rectangle path'), + ).toHaveLength(10), + ); + expect( + tickLabels(container).map((tick) => [ + tick.textContent, + tick.getAttribute('fill'), + ]), + ).toEqual([ + ['Dec', '#9e9e9e'], + ['Jan', '#9e9e9e'], + ['Feb', '#9e9e9e'], + ['Mar', '#9e9e9e'], + ['Apr', '#9e9e9e'], + ['May', '#9e9e9e'], + ['Jun', '#9e9e9e'], + ['Jul', '#666'], + ['Aug', '#666'], + ['Sep', '#666'], + ['Oct', '#666'], + ['Nov', '#666'], + ]); + }); + + it('starts the average lines at the first recorded month', async () => { + const { container, findByRole } = render( + , + ); + + const region = await findByRole('region'); + + await waitFor(() => + expect( + region.querySelectorAll('.recharts-reference-line line'), + ).toHaveLength(4), + ); + // Ticks sit in the middle of each month's band + const [jun, jul] = tickLabels(container) + .slice(6, 8) + .map((tick) => Number(tick.getAttribute('x'))); + const julyStart = jul - (jul - jun) / 2; + region + .querySelectorAll('.recharts-reference-line line') + .forEach((line) => + expect(Number(line.getAttribute('x1'))).toBeCloseTo(julyStart), + ); + }); + + it('starts the average lines at the left edge with a full year', async () => { + const { container, findByRole } = render(); + + const region = await findByRole('region'); + + await waitFor(() => + expect( + region.querySelectorAll('.recharts-reference-line line'), + ).toHaveLength(4), + ); + const [dec, jan] = tickLabels(container) + .slice(0, 2) + .map((tick) => Number(tick.getAttribute('x'))); + expect( + Number( + region + .querySelector('.recharts-reference-line line') + ?.getAttribute('x1'), + ), + ).toBeCloseTo(dec - (jan - dec) / 2); + }); + + it('labels the y-axis in dollars and the months by short name on wider screens', async () => { + const { container, findByRole } = render(); + + const region = await findByRole('region'); + + await waitFor(() => + expect(within(region).getByText('$6,000')).toBeInTheDocument(), + ); + expect(tickLabels(container)[0]).toHaveTextContent(/^Dec$/); + }); + + it('labels the y-axis in thousands and the months by first letter on a phone', async () => { + matchMediaMock({ width: 390 }); + const { container, findByRole } = render(); + + const region = await findByRole('region'); + + await waitFor(() => + expect(within(region).getByText('$6K')).toBeInTheDocument(), + ); + expect(within(region).getByText('$1.5K')).toBeInTheDocument(); + expect(tickLabels(container).map((tick) => tick.textContent)).toEqual([ + 'D', + 'J', + 'F', + 'M', + 'A', + 'M', + 'J', + 'J', + 'A', + 'S', + 'O', + 'N', + ]); + }); + + it('draws no bars, lines or amounts when no month has data', async () => { + const { findByRole } = render( + , + ); + + const region = await findByRole('region'); + + await waitFor(() => + expect(region.querySelector('svg.recharts-surface')).toBeTruthy(), + ); + expect( + region.querySelectorAll('.recharts-bar-rectangle path'), + ).toHaveLength(0); + expect(region.querySelectorAll('.recharts-reference-line')).toHaveLength( + 0, + ); + expect(within(region).queryByText(/\$/)).not.toBeInTheDocument(); + }); + }); +}); diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.tsx new file mode 100644 index 0000000000..8dcd2d7b1f --- /dev/null +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.tsx @@ -0,0 +1,145 @@ +import { Box, useMediaQuery } from '@mui/material'; +import { useTranslation } from 'react-i18next'; +import { + Bar, + BarChart, + ResponsiveContainer, + Text, + TextProps, + Tooltip, + TooltipProps, + XAxis, + YAxis, +} from 'recharts'; +import { useFormatters } from 'src/components/HrTools/Shared/useFormatters'; +import { MonthlySummaryChartData } from 'src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart'; +import { MonthlySummaryTooltip } from 'src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryTooltip'; +import { useLocale } from 'src/hooks/useLocale'; +import { currencyFormat } from 'src/lib/intlFormat'; +import theme from 'src/theme'; +import { AverageKey } from './AverageKey'; +import { averageReferenceLines, averageSeries } from './averageLines'; + +// A month before the staff member started has no amounts, so it has no bars +export type IncomeExpensesMonth = + | MonthlySummaryChartData + | { month: string; income: null; expenses: null; net: null }; + +export interface IncomeExpensesAverages { + income?: number; + expenses?: number; +} + +interface IncomeExpensesChartProps { + data: IncomeExpensesMonth[]; + averages: IncomeExpensesAverages; + // Says which months the averages cover + note: string; +} + +interface MonthTickProps extends Omit { + payload?: { value: string; index: number }; + data: IncomeExpensesMonth[]; + isPhone: boolean; +} + +// The month's short name, or its first letter on a phone. Months with no +// amounts are grayed out. +const MonthTick: React.FC = ({ + payload, + data, + isPhone, + ...props +}) => { + const name = payload?.value.split(' ')[0] ?? ''; + const empty = data[payload?.index ?? 0]?.income === null; + return ( + + {isPhone ? name.charAt(0) : name} + + ); +}; + +interface ChartTooltipProps extends TooltipProps { + incomeName: string; +} + +const ChartTooltip: React.FC = ({ + active, + payload, + label, + incomeName, +}) => { + const { formatCurrency } = useFormatters(); + if (!active) { + return null; + } + // Months before the staff member started have nothing to show + const month = payload?.[0]?.payload as IncomeExpensesMonth | undefined; + if (month === undefined || month.income === null) { + return null; + } + + return ( + + ); +}; + +export const IncomeExpensesChart: React.FC = ({ + data, + averages, + note, +}) => { + const { t } = useTranslation(); + const locale = useLocale(); + const isPhone = useMediaQuery(theme.breakpoints.down('sm')); + + const series = averageSeries(t, averages); + const firstMonth = data.findIndex((month) => month.income !== null); + + const formatAxisAmount = (value: number) => + isPhone + ? new Intl.NumberFormat(locale, { + style: 'currency', + currency: 'USD', + notation: 'compact', + }).format(value) + : currencyFormat(value, 'USD', locale); + + return ( + <> + + {/* The plot gets at least 200px on a phone however the key wraps; the + 45px is the x-axis and margins */} + + + + ( + + )} + /> + + } /> + {series.map(({ key, name, barColor }) => ( + + ))} + {firstMonth >= 0 && + averageReferenceLines(series, firstMonth / data.length)} + + + + + ); +}; diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/averageLines.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/averageLines.tsx new file mode 100644 index 0000000000..f19c1ed6ba --- /dev/null +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/averageLines.tsx @@ -0,0 +1,104 @@ +import { TFunction } from 'i18next'; +import { ReferenceLine } from 'recharts'; +import theme from 'src/theme'; +import { IncomeExpensesAverages } from './IncomeExpensesChart'; + +export interface AverageSeries { + key: string; + name: string; + barColor: string; + lineColor: string; + // Dash and gap lengths + pattern: [number, number]; + value?: number; +} + +// Long dashes for contributions and dots for expenses, so the two lines differ +// by more than color +export const averageSeries = ( + t: TFunction, + averages: IncomeExpensesAverages, +): AverageSeries[] => [ + { + key: 'income', + name: t('Contributions'), + barColor: theme.palette.chartContributions.main, + lineColor: theme.palette.chartContributions.dark, + pattern: [12, 6], + value: averages.income, + }, + { + key: 'expenses', + name: t('Expenses'), + barColor: theme.palette.chartExpenses.main, + lineColor: theme.palette.chartExpenses.dark, + pattern: [3, 4], + value: averages.expenses, + }, +]; + +interface AverageLineProps { + x1?: number; + x2?: number; + y1?: number; + series: AverageSeries; + // Where the line starts, as a share of its length + start: number; +} + +// A 3px patterned line on a 1px white edge. The edge's dashes are 2px longer +// and start 1px sooner, so the edge wraps the ends of each dash too. +export const AverageLine: React.FC = ({ + x1 = 0, + x2 = 0, + y1 = 0, + series: { lineColor, pattern }, + start, +}) => { + const left = Math.min(x1, x2); + const right = Math.max(x1, x2); + const from = left + (right - left) * start; + const [dash, gap] = pattern; + + return ( + + + + + ); +}; + +// Recharts only finds its own elements among the chart's direct children, so +// this returns ReferenceLine elements instead of being a component. `start` +// is the first recorded month's share of the months shown. +export const averageReferenceLines = (series: AverageSeries[], start: number) => + series.flatMap((average) => + average.value === undefined + ? [] + : [ + ( + + )} + />, + ], + ); diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx index 702086628a..2be0986486 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx @@ -232,11 +232,11 @@ describe('StaffTabMonthlySummary', () => { userEvent.click(getByRole('button', { name: 'Table view' })); expect(getByRole('table')).toBeInTheDocument(); - expect(queryByText(/full month/)).not.toBeInTheDocument(); + expect(queryByText(/Monthly averages/)).not.toBeInTheDocument(); }); it('draws the contributions and expenses averages of the finished months on the chart', async () => { - const { findByRole, findByTestId } = render( + const { findByRole, findByTestId, getByText } = render( { userEvent.click(await findByRole('button', { name: 'Chart view' })); expect(await findByTestId('MonthlySummaryAverageKey')).toHaveTextContent( - 'Contributions average $4,500.00Expenses average $3,300.00(last 2 full months)', + 'Contributionsavg $4,500.00Expensesavg $3,300.00Avg. difference+$1,200.00', ); + expect( + getByText(/^Monthly averages for the last 2 full months/), + ).toHaveTextContent(/\(Jan.+Feb 2023\)\. March is still in progress\.$/); }); it('charts labelled empty months without showing a zero amount', async () => { - const { container, findByRole, queryByRole, queryByText } = render( - , - ); + const { container, findByRole, getByText, queryByRole, queryByText } = + render(); userEvent.click(await findByRole('button', { name: 'Chart view' })); expect(await findByRole('region')).toBeInTheDocument(); expect(queryByRole('table')).not.toBeInTheDocument(); - expect(queryByText(/^\$/)).not.toBeInTheDocument(); - expect(queryByText(/full month/)).not.toBeInTheDocument(); + expect(queryByText(/\$/)).not.toBeInTheDocument(); + expect( + getByText('Averages will show after your first full month.'), + ).toBeInTheDocument(); // Tests run pinned to 2020-01-01, so the window ends on the current month. const ticks = Array.from( diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx index 7c5173e510..f352a6cde7 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx @@ -14,18 +14,18 @@ import { DateTime } from 'luxon'; import { useTranslation } from 'react-i18next'; import { DynamicComponentPlaceholder } from 'src/components/DynamicPlaceholders/DynamicComponentPlaceholder'; import { useFormatters } from 'src/components/HrTools/Shared/useFormatters'; -import { - MonthlySummaryChart, - MonthlySummaryChartData, -} from 'src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart'; import { useLocale } from 'src/hooks/useLocale'; import { monthYearFormat } from 'src/lib/intlFormat'; import theme from 'src/theme'; import { pendingField } from '../../helpers'; +import { + IncomeExpensesChart, + IncomeExpensesMonth, +} from './IncomeExpensesChart/IncomeExpensesChart'; import { useMonthlyPayrollSummaryQuery } from './MonthlyPayrollSummary.generated'; import { SupportVsGoalCells } from './SupportVsGoalCells'; import { ToggleSummaryView } from './ToggleSummaryView/ToggleSummaryView'; -import { monthlyAverages, toChartData } from './chartData'; +import { averagesNote, monthlyAverages, toChartData } from './chartData'; export enum MonthlySummaryView { Table = 'table', @@ -82,18 +82,15 @@ export const StaffTabMonthlySummary: React.FC = ({ const showChart = view === MonthlySummaryView.Chart; const hasData = monthlySummary.length > 0; - const { months: averagedMonths, ...averages } = - monthlyAverages(monthlySummary); - - const emptyChartData = useMemo((): MonthlySummaryChartData[] => { + const emptyChartData = useMemo((): IncomeExpensesMonth[] => { const thisMonth = DateTime.local().startOf('month'); return Array.from({ length: 12 }, (_, index) => { const date = thisMonth.minus({ months: 11 - index }); return { month: monthYearFormat(date.month, date.year, locale), - income: 0, - expenses: 0, - net: 0, + income: null, + expenses: null, + net: null, }; }); }, [locale]); @@ -121,17 +118,10 @@ export const StaffTabMonthlySummary: React.FC = ({ /> {showChart ? ( - ) : ( diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts index 3080541b4f..92a17f73a5 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts @@ -1,4 +1,8 @@ -import { monthlyAverages, toChartData } from './chartData'; +import i18n from 'src/lib/i18n'; +import translation from '../../../../../../public/locales/en/translation.json'; +import { averagesNote, monthlyAverages, toChartData } from './chartData'; + +i18n.addResourceBundle('en', 'translation', translation); describe('toChartData', () => { it('labels each month and charts missing amounts as zero', () => { @@ -15,6 +19,97 @@ describe('toChartData', () => { { month: 'Feb 2023', income: 0, expenses: 0, net: 0 }, ]); }); + + it('charts no amounts for the empty months before the staff member started', () => { + expect( + toChartData( + [ + { month: '2023-01', contributions: 0, expenses: 0, net: 0 }, + { month: '2023-02', contributions: null, expenses: null, net: null }, + { month: '2023-03', contributions: 4000, expenses: 3500, net: 500 }, + { month: '2023-04', contributions: 0, expenses: 0, net: 0 }, + ], + 'en-US', + ), + ).toEqual([ + { month: 'Jan 2023', income: null, expenses: null, net: null }, + { month: 'Feb 2023', income: null, expenses: null, net: null }, + { month: 'Mar 2023', income: 4000, expenses: 3500, net: 500 }, + { month: 'Apr 2023', income: 0, expenses: 0, net: 0 }, + ]); + }); + + it('charts no amounts when no month has activity', () => { + expect( + toChartData( + [{ month: '2023-01', contributions: 0, expenses: 0, net: 0 }], + 'en-US', + ), + ).toEqual([{ month: 'Jan 2023', income: null, expenses: null, net: null }]); + }); +}); + +describe('averagesNote', () => { + // Intl puts thin spaces around the dash in a month range + const note = (months: Parameters[1]) => + averagesNote(i18n.t, months, 'en-US').replace(/\s/g, ' '); + const month = (iso: string, amount = 1000) => ({ + month: iso, + contributions: amount, + expenses: amount, + }); + const year = [ + '2025-12', + '2026-01', + '2026-02', + '2026-03', + '2026-04', + '2026-05', + '2026-06', + '2026-07', + '2026-08', + '2026-09', + '2026-10', + '2026-11', + ]; + + it('names the last full months and the month in progress', () => { + expect(note(year.map((iso) => month(iso)))).toBe( + 'Monthly averages for the last 11 full months (Dec 2025 – Oct 2026). November is still in progress.', + ); + }); + + it('names the months on record for someone who started this year', () => { + expect( + note(year.map((iso) => month(iso, iso < '2026-07' ? 0 : 1000))), + ).toBe( + 'Monthly averages for the 4 full months on record (Jul – Oct 2026). November is still in progress.', + ); + }); + + it('names a single month on record', () => { + expect( + note(year.map((iso) => month(iso, iso < '2026-10' ? 0 : 1000))), + ).toBe( + 'Monthly average for the 1 full month on record (Oct 2026). November is still in progress.', + ); + }); + + it('says averages will show after the first full month', () => { + expect(note([])).toBe('Averages will show after your first full month.'); + expect( + note(year.map((iso) => month(iso, iso < '2026-11' ? 0 : 1000))), + ).toBe('Averages will show after your first full month.'); + }); + + it('leaves the dates out when the API leaves a month unnamed', () => { + expect( + note([ + { contributions: 1000, expenses: 1000 }, + { contributions: 1000, expenses: 1000 }, + ]), + ).toMatch(/^Monthly average for the last full month \(\)\./); + }); }); describe('monthlyAverages', () => { @@ -29,7 +124,7 @@ describe('monthlyAverages', () => { { contributions: 3200, expenses: 3100 }, currentMonth, ]), - ).toEqual({ income: 3800, expenses: 3700, months: 3 }); + ).toEqual({ income: 3800, expenses: 3700 }); }); it('leaves out the last row, even when its date is not this month', () => { @@ -39,7 +134,7 @@ describe('monthlyAverages', () => { { month: '2019-12', contributions: 5000, expenses: 4000 }, { month: '2019-12', ...currentMonth }, ]), - ).toEqual({ income: 4500, expenses: 3500, months: 2 }); + ).toEqual({ income: 4500, expenses: 3500 }); }); it('skips months with no amount but counts months reported as zero', () => { @@ -50,7 +145,7 @@ describe('monthlyAverages', () => { { contributions: 3000, expenses: null }, currentMonth, ]), - ).toEqual({ income: 1500, expenses: 1000, months: 2 }); + ).toEqual({ income: 1500, expenses: 1000 }); }); it('has no average for a field with no amounts', () => { @@ -60,7 +155,7 @@ describe('monthlyAverages', () => { { contributions: undefined, expenses: 400 }, currentMonth, ]), - ).toEqual({ income: undefined, expenses: 300, months: 2 }); + ).toEqual({ income: undefined, expenses: 300 }); }); it('leaves out the empty months before the staff member started', () => { @@ -73,7 +168,7 @@ describe('monthlyAverages', () => { { contributions: 5000, expenses: 3600 }, currentMonth, ]), - ).toEqual({ income: 4500, expenses: 3300, months: 2 }); + ).toEqual({ income: 4500, expenses: 3300 }); }); it('counts an empty month once activity has started', () => { @@ -85,11 +180,11 @@ describe('monthlyAverages', () => { { contributions: 5000, expenses: 3600 }, currentMonth, ]), - ).toEqual({ income: 3000, expenses: 2200, months: 3 }); + ).toEqual({ income: 3000, expenses: 2200 }); }); it('has no averages when no month is finished or active', () => { - const none = { income: undefined, expenses: undefined, months: 0 }; + const none = { income: undefined, expenses: undefined }; expect(monthlyAverages([])).toEqual(none); expect(monthlyAverages([currentMonth])).toEqual(none); expect( diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts index 855720b636..0409177146 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts @@ -1,9 +1,10 @@ +import { TFunction } from 'i18next'; import { DateTime } from 'luxon'; -import { - MonthlySummaryAverages, - MonthlySummaryChartData, -} from 'src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart'; import { monthYearFormat } from 'src/lib/intlFormat'; +import { + IncomeExpensesAverages, + IncomeExpensesMonth, +} from './IncomeExpensesChart/IncomeExpensesChart'; import { MonthlyPayrollSummaryQuery } from './MonthlyPayrollSummary.generated'; type MonthAmounts = Partial< @@ -13,19 +14,35 @@ type MonthAmounts = Partial< > >; +const isEmpty = (month: MonthAmounts) => + !month.contributions && !month.expenses; + +// The API sends the months before someone joined as $0, so the empty months +// before their first activity are left out of the chart and the averages. +const firstActiveIndex = (months: MonthAmounts[]) => + months.findIndex((month) => !isEmpty(month)); + export const toChartData = ( months: MonthAmounts[], locale: string, -): MonthlySummaryChartData[] => - months.map((summary) => { +): IncomeExpensesMonth[] => { + const firstActive = firstActiveIndex(months); + return months.map((summary, index) => { const date = DateTime.fromISO(summary.month ?? ''); + const month = date.isValid + ? monthYearFormat(date.month, date.year, locale) + : ''; + if (firstActive < 0 || index < firstActive) { + return { month, income: null, expenses: null, net: null }; + } return { - month: date.isValid ? monthYearFormat(date.month, date.year, locale) : '', + month, income: summary.contributions ?? 0, expenses: summary.expenses ?? 0, net: summary.net ?? 0, }; }); +}; // Months with no amount (not synced) are left out so they don't drag the // average down. A reported $0 counts. @@ -39,22 +56,72 @@ const average = (values: Array) => { return amounts.reduce((sum, value) => sum + value, 0) / amounts.length; }; -const isEmpty = (month: MonthAmounts) => - !month.contributions && !month.expenses; - // The API's last row is the current month, still in progress, so it is left -// out too, the same as the Dashboard's donation average. The API sends the -// months before someone joined as $0, so empty months before their first -// activity are left out as well. `months` is how many months are averaged. +// out, the same as the Dashboard's donation average. So are the empty months +// before the staff member's first activity. +const averagedMonths = (months: MonthAmounts[]) => { + const finishedMonths = months.slice(0, -1); + const firstActive = firstActiveIndex(finishedMonths); + return firstActive < 0 ? [] : finishedMonths.slice(firstActive); +}; + export const monthlyAverages = ( months: MonthAmounts[], -): MonthlySummaryAverages & { months: number } => { - const finishedMonths = months.slice(0, -1); - const firstActive = finishedMonths.findIndex((month) => !isEmpty(month)); - const pastMonths = firstActive < 0 ? [] : finishedMonths.slice(firstActive); +): IncomeExpensesAverages => { + const pastMonths = averagedMonths(months); return { income: average(pastMonths.map((month) => month.contributions)), expenses: average(pastMonths.map((month) => month.expenses)), - months: pastMonths.length, }; }; + +const toDate = (month: MonthAmounts | undefined) => + DateTime.fromISO(month?.month ?? ''); + +// Blank when the API leaves a month unnamed +const formatMonths = ( + locale: string, + options: Intl.DateTimeFormatOptions, + start: DateTime, + end = start, +) => + start.isValid && end.isValid + ? new Intl.DateTimeFormat(locale, options).formatRange( + start.toJSDate(), + end.toJSDate(), + ) + : ''; + +// Says which months the averages cover, e.g. "Monthly averages for the last +// 11 full months (Dec 2025 – Oct 2026). November is still in progress." +export const averagesNote = ( + t: TFunction, + months: MonthAmounts[], + locale: string, +): string => { + const pastMonths = averagedMonths(months); + if (pastMonths.length === 0) { + return t('Averages will show after your first full month.'); + } + + const options = { + count: pastMonths.length, + range: formatMonths( + locale, + { month: 'short', year: 'numeric' }, + toDate(pastMonths[0]), + toDate(pastMonths.at(-1)), + ), + month: formatMonths(locale, { month: 'long' }, toDate(months.at(-1))), + }; + // No empty months were left out before the first one averaged + return pastMonths.length === months.length - 1 + ? t( + 'Monthly averages for the last {{count}} full months ({{range}}). {{month}} is still in progress.', + options, + ) + : t( + 'Monthly averages for the {{count}} full months on record ({{range}}). {{month}} is still in progress.', + options, + ); +}; diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/AverageKey.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/AverageKey.tsx deleted file mode 100644 index 6e7beae1d4..0000000000 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/AverageKey.tsx +++ /dev/null @@ -1,71 +0,0 @@ -import { Grid, Typography } from '@mui/material'; -import { useTranslation } from 'react-i18next'; -import { LegendProps } from 'recharts'; -import { ChartLegendContent } from '../ChartLegendContent/ChartLegendContent'; -import { AverageSeries, averageDash } from './averageReferenceLines'; - -interface AverageKeyProps { - series: AverageSeries[]; - formatCurrency: (value: number) => string; - note?: string; - // The bars' legend, shown under the key outside the chart so it can't - // overlap the plot on a phone - legend: LegendProps['payload']; -} - -// A key row above the chart, like the Dashboard's Monthly Giving chart: a -// dashed swatch matching each average line, its name in bold, then the amount -export const AverageKey: React.FC = ({ - series, - formatCurrency, - note, - legend, -}) => { - const { t } = useTranslation(); - - return ( - <> - - {series.map(({ key, name, color, value }) => ( - - - - {t('{{name}} average', { name })}{' '} - {formatCurrency(value)} - - - ))} - {note && ( - - - {note} - - - )} - - - - ); -}; diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx index ac1149f3e3..1bf17de202 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.test.tsx @@ -1,13 +1,9 @@ import '../sharedRechartMock'; import React from 'react'; import { render, waitFor, within } from '@testing-library/react'; -import theme from 'src/theme'; import { useMPGAIncomeExpenses } from '../../MPGAIncomeExpensesContext/MPGAIncomeExpensesContext'; import { MPGAIncomeExpensesReportTestWrapper } from '../../MPGAIncomeExpensesReportTestWrapper'; -import { - MonthlySummaryAverages, - MonthlySummaryChart, -} from './MonthlySummaryChart'; +import { MonthlySummaryChart } from './MonthlySummaryChart'; import { useMonthlySummaryChartData } from './useMonthlySummaryChartData'; const mutationSpy = jest.fn(); @@ -49,28 +45,6 @@ const ChartWithNoDataLabel: React.FC = () => ( ); -const averagesData = [ - { month: 'Jan 2023', income: 4000, expenses: 3500, net: 500 }, - { month: 'Feb 2023', income: 3600, expenses: 3900, net: -300 }, -]; - -const ChartWithAverages: React.FC<{ - noDataLabel?: string; - averages?: MonthlySummaryAverages; -}> = ({ noDataLabel, averages = { income: 3800, expenses: 3700 } }) => ( - - - -); - describe('MonthlySummaryChart', () => { it('renders the bar chart', async () => { const { findByRole } = render(); @@ -136,126 +110,12 @@ describe('MonthlySummaryChart', () => { expect(within(region).queryByText(/^\$/)).not.toBeInTheDocument(); }); - it('lists only the bars in the legend, between the key and the chart, when averages show', async () => { - const { findByRole, getByTestId } = render(); - - const list = await findByRole('list'); - const region = await findByRole('region'); - - expect( - within(list) - .getAllByRole('listitem') - .map((item) => item.textContent), - ).toEqual(['Contributions', 'Expenses']); - // Outside the chart so it can't overlap the plot on a phone - expect( - getByTestId('MonthlySummaryAverageKey').compareDocumentPosition(list) & - Node.DOCUMENT_POSITION_FOLLOWING, - ).toBeTruthy(); - expect(region).not.toContainElement(list); - }); - - it('shows a key above the chart with each average and the note', async () => { - const { findByRole, getByTestId } = render( - , - ); - - const region = await findByRole('region'); - const key = getByTestId('MonthlySummaryAverageKey'); - - expect( - key.compareDocumentPosition(region) & Node.DOCUMENT_POSITION_FOLLOWING, - ).toBeTruthy(); - const contributions = within(key).getByText('Contributions average'); - expect(contributions.tagName).toBe('STRONG'); - expect(contributions.parentElement).toHaveTextContent( - 'Contributions average $3,800.00', - ); - expect( - within(key).getByText('Expenses average').parentElement, - ).toHaveTextContent('Expenses average $3,700.00'); - expect(within(key).getByText('(last 3 months)')).toBeInTheDocument(); - - const swatches = key.querySelectorAll('svg[aria-hidden="true"] line'); - expect( - Array.from(swatches).map((line) => [ - line.getAttribute('stroke'), - line.getAttribute('stroke-dasharray'), - ]), - ).toEqual([ - [theme.palette.success.dark, '6 4'], - [theme.palette.error.dark, '6 4'], - ]); - }); - - it('draws an unlabelled dashed line for each average', async () => { - const { findByRole } = render(); - - const region = await findByRole('region'); - - await waitFor(() => - expect( - region.querySelectorAll('.recharts-reference-line line'), - ).toHaveLength(2), - ); - region - .querySelectorAll('.recharts-reference-line line') - .forEach((line) => - expect(line).toHaveAttribute('stroke-dasharray', '6 4'), - ); - expect( - region.querySelectorAll('.recharts-reference-line text'), - ).toHaveLength(0); - }); - - it('shows a lone $0 average in the key and as a line', async () => { - const { findByTestId, findByRole } = render( - , - ); - - const key = await findByTestId('MonthlySummaryAverageKey'); - - expect(key).toHaveTextContent(/^Expenses average \$0\.00$/); - expect( - (await findByRole('region')).querySelectorAll('.recharts-reference-line'), - ).toHaveLength(1); - }); - - it('draws no average lines or key without averages', async () => { - const { findByRole, queryByTestId } = render(); - - const region = await findByRole('region'); - - await waitFor(() => - expect(region.querySelector('svg.recharts-surface')).toBeTruthy(), - ); - expect(region.querySelectorAll('.recharts-reference-line')).toHaveLength(0); - expect(queryByTestId('MonthlySummaryAverageKey')).not.toBeInTheDocument(); - }); - - it('draws no average lines when amounts are masked', async () => { - const { findByRole, queryByTestId } = render( - , - ); - - const region = await findByRole('region'); - - await waitFor(() => - expect(region.querySelector('svg.recharts-surface')).toBeTruthy(), - ); - expect(region.querySelectorAll('.recharts-reference-line')).toHaveLength(0); - expect(queryByTestId('MonthlySummaryAverageKey')).not.toBeInTheDocument(); - }); - it('renders legend with correct labels', async () => { const { findByRole } = render(); const list = await findByRole('list'); const items = within(list).getAllByRole('listitem'); expect(items).toHaveLength(2); - expect(list.closest('.recharts-legend-wrapper')).toBeInTheDocument(); expect(within(list).getByText('Income')).toBeInTheDocument(); expect(within(list).getByText('Expenses')).toBeInTheDocument(); diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx index a3d3998618..202d8de79b 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx @@ -1,12 +1,11 @@ import { useMemo } from 'react'; -import { Box, GlobalStyles, Typography } from '@mui/material'; +import { Box, GlobalStyles } from '@mui/material'; import { useTranslation } from 'react-i18next'; import { Bar, BarChart, LabelList, Legend, - LegendProps, Tooltip, XAxis, YAxis, @@ -16,8 +15,7 @@ import { currencyFormat } from 'src/lib/intlFormat'; import theme from 'src/theme'; import { ChartFrame } from '../ChartFrame'; import { ChartLegendContent } from '../ChartLegendContent/ChartLegendContent'; -import { AverageKey } from './AverageKey'; -import { averageReferenceLines, averageSeries } from './averageReferenceLines'; +import { MonthlySummaryTooltip } from './MonthlySummaryTooltip'; export interface MonthlySummaryChartData { month: string; @@ -26,13 +24,6 @@ export interface MonthlySummaryChartData { net: number; } -export interface MonthlySummaryAverages { - income?: number; - expenses?: number; - // Shown at the end of the key row, e.g. which months the averages cover - note?: string; -} - interface MonthlySummaryChartProps { data: MonthlySummaryChartData[]; currency: string; @@ -41,8 +32,6 @@ interface MonthlySummaryChartProps { width: number; overrideIncomeText?: string; noDataLabel?: string; - // Draws a dashed line at each average and lists its amount in a key above - averages?: MonthlySummaryAverages; } interface MonthlyTotal extends MonthlySummaryChartData { @@ -51,14 +40,6 @@ interface MonthlyTotal extends MonthlySummaryChartData { const chartColors = [theme.palette.success.main, theme.palette.error.main]; -const barLegend = ( - incomeName: string, - expensesName: string, -): LegendProps['payload'] => [ - { value: incomeName, type: 'square', color: chartColors[0] }, - { value: expensesName, type: 'square', color: chartColors[1] }, -]; - export const MonthlySummaryChart: React.FC = ({ data, currency, @@ -67,32 +48,16 @@ export const MonthlySummaryChart: React.FC = ({ width, overrideIncomeText, noDataLabel, - averages, }) => { const { t } = useTranslation(); const locale = useLocale(); const maskAmounts = noDataLabel !== undefined; - const formatCurrency = (value: number) => - currencyFormat(value, currency, locale, { showTrailingZeros: true }); - const formatAmount = (value: number) => - maskAmounts ? noDataLabel : formatCurrency(value); - - const incomeName = overrideIncomeText ?? t('Income'); - - // Masked amounts hide the averages too - const averageLines = averageSeries({ - t, - averages: maskAmounts ? undefined : averages, - incomeName, - }); - // With the key row, the legend sits above the chart too, so it can't - // overlap the plot on a phone - const legendAbove = averageLines.length > 0; - - const legendPayload = barLegend(incomeName, t('Expenses')); + maskAmounts + ? noDataLabel + : currencyFormat(value, currency, locale, { showTrailingZeros: true }); const monthlyTotals = useMemo( (): MonthlyTotal[] => @@ -114,14 +79,6 @@ export const MonthlySummaryChart: React.FC = ({ }} /> - {legendAbove && ( - - )} = ({ return null; } - const { income, expenses, net } = payload[0] - .payload as MonthlyTotal; - return ( - - - {label} - - - {incomeName}: {formatAmount(income)} - - - {t('Expenses')}: {formatAmount(expenses)} - - 0 - ? chartColors[0] - : chartColors[1], - }} - > - {t('Net')}: {formatAmount(net)} - - + ); }} /> - + = ({ fill: theme.palette.chartBlack.main, fontSize: theme.typography.body2.fontSize, }} - formatter={formatCurrency} + formatter={(value: number) => + currencyFormat(value, currency, locale, { + showTrailingZeros: true, + }) + } /> )} - {averageReferenceLines(averageLines)} - {!legendAbove && ( - ( - - )} - payload={legendPayload} - /> - )} + ( + + )} + payload={[ + { + value: overrideIncomeText ?? t('Income'), + type: 'square', + color: chartColors[0], + }, + { + value: t('Expenses'), + type: 'square', + color: chartColors[1], + }, + ]} + /> diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryTooltip.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryTooltip.tsx new file mode 100644 index 0000000000..5d967e46d0 --- /dev/null +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryTooltip.tsx @@ -0,0 +1,62 @@ +import { Box, Typography } from '@mui/material'; +import { useTranslation } from 'react-i18next'; +import theme from 'src/theme'; + +interface MonthlySummaryTooltipProps { + label: string; + month: { income: number; expenses: number; net: number }; + incomeName: string; + formatAmount: (value: number) => string | undefined; +} + +// A month's income, expenses and net, shared by the MPGA report's and the +// Supervisor Report's income and expenses charts +export const MonthlySummaryTooltip: React.FC = ({ + label, + month: { income, expenses, net }, + incomeName, + formatAmount, +}) => { + const { t } = useTranslation(); + + return ( + + + {label} + + + {incomeName}: {formatAmount(income)} + + + {t('Expenses')}: {formatAmount(expenses)} + + 0 + ? theme.palette.success.main + : theme.palette.error.main, + }} + > + {t('Net')}: {formatAmount(net)} + + + ); +}; diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx deleted file mode 100644 index 530bab8691..0000000000 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/averageReferenceLines.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import { TFunction } from 'i18next'; -import { ReferenceLine } from 'recharts'; -import theme from 'src/theme'; -import { MonthlySummaryAverages } from './MonthlySummaryChart'; - -interface AverageSeriesOptions { - t: TFunction; - averages?: MonthlySummaryAverages; - incomeName: string; -} - -export interface AverageSeries { - key: string; - value: number; - name: string; - color: string; -} - -export const averageDash = '6 4'; - -// The averages that have a value, each in a darker shade of its bars' color so -// the line shows where it crosses its own bars -export const averageSeries = ({ - t, - averages, - incomeName, -}: AverageSeriesOptions): AverageSeries[] => - [ - { - key: 'income', - value: averages?.income, - name: incomeName, - color: theme.palette.success.dark, - }, - { - key: 'expenses', - value: averages?.expenses, - name: t('Expenses'), - color: theme.palette.error.dark, - }, - ].flatMap(({ value, ...series }) => - value === undefined ? [] : [{ ...series, value }], - ); - -// Recharts only finds its own elements among the chart's direct children, so -// this returns ReferenceLine elements instead of being a component. The lines -// have no text; their amounts are in the key above the chart. -export const averageReferenceLines = (series: AverageSeries[]) => - series.map(({ key, value, color }) => ( - - )); diff --git a/src/theme.ts b/src/theme.ts index fa782bb2ab..9de06ed5d2 100644 --- a/src/theme.ts +++ b/src/theme.ts @@ -56,6 +56,11 @@ const chartColors = { blueLight: '#BBDEFB', black: '#000000', blueDark: '#007890', + // Income vs expenses bars, with a darker average line for contributions. + // Far apart in lightness so color-blind users can tell the bars apart. + contributions: '#43A047', + contributionsDark: '#1B5E20', + expenses: '#B71C1C', }; const chipColors = { @@ -121,6 +126,8 @@ declare module '@mui/material/styles' { chartBlueLight: PaletteColor; chartBlack: PaletteColor; chartBlueDark: PaletteColor; + chartContributions: PaletteColor; + chartExpenses: PaletteColor; chipYellowDark: PaletteColor; chipYellowLight: PaletteColor; chipBlueDark: PaletteColor; @@ -174,6 +181,8 @@ declare module '@mui/material/styles' { chartBlueLight: PaletteColorOptions; chartBlack: PaletteColorOptions; chartBlueDark: PaletteColorOptions; + chartContributions: PaletteColorOptions; + chartExpenses: PaletteColorOptions; chipYellowDark: PaletteColorOptions; chipYellowLight: PaletteColorOptions; chipBlueDark: PaletteColorOptions; @@ -289,6 +298,14 @@ const theme = createTheme({ chartBlueDark: { main: chartColors.blueDark, }, + chartContributions: { + main: chartColors.contributions, + dark: chartColors.contributionsDark, + }, + chartExpenses: { + main: chartColors.expenses, + dark: chartColors.expenses, + }, chipYellowDark: { main: chipColors.yellowDark, }, From 0365fbe189f9afc441300e91585d69038ff674e7 Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:20:24 -0800 Subject: [PATCH 14/16] MPDX-10389 Keep the theme setup from growing Co-Authored-By: Claude Opus 5.5 --- src/theme.ts | 32 ++++++++------------------------ 1 file changed, 8 insertions(+), 24 deletions(-) diff --git a/src/theme.ts b/src/theme.ts index 9de06ed5d2..5c45add056 100644 --- a/src/theme.ts +++ b/src/theme.ts @@ -274,30 +274,14 @@ const theme = createTheme({ statusDanger: { main: statusColors.danger, }, - chartBlue: { - main: chartColors.blue, - }, - chartGreen: { - main: chartColors.green, - }, - chartPink: { - main: chartColors.pink, - }, - chartOrange: { - main: chartColors.orange, - }, - chartGray: { - main: chartColors.gray, - }, - chartBlueLight: { - main: chartColors.blueLight, - }, - chartBlack: { - main: chartColors.black, - }, - chartBlueDark: { - main: chartColors.blueDark, - }, + chartBlue: { main: chartColors.blue }, + chartGreen: { main: chartColors.green }, + chartPink: { main: chartColors.pink }, + chartOrange: { main: chartColors.orange }, + chartGray: { main: chartColors.gray }, + chartBlueLight: { main: chartColors.blueLight }, + chartBlack: { main: chartColors.black }, + chartBlueDark: { main: chartColors.blueDark }, chartContributions: { main: chartColors.contributions, dark: chartColors.contributionsDark, From 317ad0110597dace1118586aeb635f0de74a59da Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:36:08 -0800 Subject: [PATCH 15/16] MPDX-10389 Locale-safe month ticks and a no-data note Co-Authored-By: Claude Opus 5.5 --- .../IncomeExpensesChart.test.tsx | 44 ++++++------- .../IncomeExpensesChart.tsx | 42 +++++++++---- .../MonthlySummary/MonthlySummary.test.tsx | 4 +- .../MonthlySummary/MonthlySummary.tsx | 1 + .../MonthlySummary/chartData.test.ts | 63 ++++++++++++++++--- .../MonthlySummary/chartData.ts | 7 ++- .../MonthlySummaryTooltip.test.tsx | 37 +++++++++++ src/lib/intlFormat.ts | 3 +- 8 files changed, 155 insertions(+), 46 deletions(-) create mode 100644 src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryTooltip.test.tsx diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.test.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.test.tsx index b172c6af8a..10ed0ca89d 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.test.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.test.tsx @@ -10,37 +10,37 @@ import { IncomeExpensesMonth, } from './IncomeExpensesChart'; -const monthNames = [ - 'Dec 2025', - 'Jan 2026', - 'Feb 2026', - 'Mar 2026', - 'Apr 2026', - 'May 2026', - 'Jun 2026', - 'Jul 2026', - 'Aug 2026', - 'Sep 2026', - 'Oct 2026', - 'Nov 2026', -]; +const months = [ + '2025-12', + '2026-01', + '2026-02', + '2026-03', + '2026-04', + '2026-05', + '2026-06', + '2026-07', + '2026-08', + '2026-09', + '2026-10', + '2026-11', +].map((isoMonth) => ({ isoMonth, month: `Label ${isoMonth}` })); // A staff member who started in July: no amounts before then -const newStaffData: IncomeExpensesMonth[] = monthNames.map((month, index) => +const newStaffData: IncomeExpensesMonth[] = months.map((month, index) => index < 7 - ? { month, income: null, expenses: null, net: null } - : { month, income: 5000, expenses: 4800, net: 200 }, + ? { ...month, income: null, expenses: null, net: null } + : { ...month, income: 5000, expenses: 4800, net: 200 }, ); -const fullYearData: IncomeExpensesMonth[] = monthNames.map((month) => ({ - month, +const fullYearData: IncomeExpensesMonth[] = months.map((month) => ({ + ...month, income: 5000, expenses: 4800, net: 200, })); -const emptyData: IncomeExpensesMonth[] = monthNames.map((month) => ({ - month, +const emptyData: IncomeExpensesMonth[] = months.map((month) => ({ + ...month, income: null, expenses: null, net: null, @@ -202,6 +202,8 @@ describe('IncomeExpensesChart', () => { ).toBeCloseTo(dec - (jan - dec) / 2); }); + // Labels like "2026年7月" don't start with the month, so the ticks come + // from the month itself, not its label it('labels the y-axis in dollars and the months by short name on wider screens', async () => { const { container, findByRole } = render(); diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.tsx index 8dcd2d7b1f..9655e538c4 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.tsx @@ -1,4 +1,5 @@ import { Box, useMediaQuery } from '@mui/material'; +import { DateTime } from 'luxon'; import { useTranslation } from 'react-i18next'; import { Bar, @@ -15,15 +16,17 @@ import { useFormatters } from 'src/components/HrTools/Shared/useFormatters'; import { MonthlySummaryChartData } from 'src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart'; import { MonthlySummaryTooltip } from 'src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryTooltip'; import { useLocale } from 'src/hooks/useLocale'; -import { currencyFormat } from 'src/lib/intlFormat'; +import { currencyFormat, dateFormatMonthOnly } from 'src/lib/intlFormat'; import theme from 'src/theme'; import { AverageKey } from './AverageKey'; import { averageReferenceLines, averageSeries } from './averageLines'; -// A month before the staff member started has no amounts, so it has no bars -export type IncomeExpensesMonth = +// A month before the staff member started has no amounts, so it has no bars. +// `isoMonth` is the API's YYYY-MM month, for the axis labels. +export type IncomeExpensesMonth = { isoMonth: string } & ( | MonthlySummaryChartData - | { month: string; income: null; expenses: null; net: null }; + | { month: string; income: null; expenses: null; net: null } +); export interface IncomeExpensesAverages { income?: number; @@ -38,24 +41,34 @@ interface IncomeExpensesChartProps { } interface MonthTickProps extends Omit { - payload?: { value: string; index: number }; + payload?: { index: number }; data: IncomeExpensesMonth[]; + locale: string; isPhone: boolean; } -// The month's short name, or its first letter on a phone. Months with no -// amounts are grayed out. +// The month's short name, or its one-letter name on a phone, formatted from +// the month itself so it works in every locale. Months with no amounts are +// grayed out. const MonthTick: React.FC = ({ payload, data, + locale, isPhone, ...props }) => { - const name = payload?.value.split(' ')[0] ?? ''; - const empty = data[payload?.index ?? 0]?.income === null; + const month = data[payload?.index ?? 0]; + const date = DateTime.fromISO(month?.isoMonth ?? ''); return ( - - {isPhone ? name.charAt(0) : name} + + {dateFormatMonthOnly( + date.isValid ? date : null, + locale, + isPhone ? 'narrow' : 'short', + )} ); }; @@ -127,7 +140,12 @@ export const IncomeExpensesChart: React.FC = ({ dataKey="month" interval={0} tick={(props) => ( - + )} /> diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx index 2be0986486..ba51a9a183 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx @@ -266,9 +266,7 @@ describe('StaffTabMonthlySummary', () => { expect(await findByRole('region')).toBeInTheDocument(); expect(queryByRole('table')).not.toBeInTheDocument(); expect(queryByText(/\$/)).not.toBeInTheDocument(); - expect( - getByText('Averages will show after your first full month.'), - ).toBeInTheDocument(); + expect(getByText('No data available.')).toBeInTheDocument(); // Tests run pinned to 2020-01-01, so the window ends on the current month. const ticks = Array.from( diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx index f352a6cde7..b4a9e9f4fd 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx @@ -88,6 +88,7 @@ export const StaffTabMonthlySummary: React.FC = ({ const date = thisMonth.minus({ months: 11 - index }); return { month: monthYearFormat(date.month, date.year, locale), + isoMonth: date.toFormat('yyyy-MM'), income: null, expenses: null, net: null, diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts index 92a17f73a5..6d351fc8f8 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts @@ -15,8 +15,20 @@ describe('toChartData', () => { 'en-US', ), ).toEqual([ - { month: 'Jan 2023', income: 4000, expenses: 3500, net: 500 }, - { month: 'Feb 2023', income: 0, expenses: 0, net: 0 }, + { + month: 'Jan 2023', + isoMonth: '2023-01', + income: 4000, + expenses: 3500, + net: 500, + }, + { + month: 'Feb 2023', + isoMonth: '2023-02', + income: 0, + expenses: 0, + net: 0, + }, ]); }); @@ -32,10 +44,34 @@ describe('toChartData', () => { 'en-US', ), ).toEqual([ - { month: 'Jan 2023', income: null, expenses: null, net: null }, - { month: 'Feb 2023', income: null, expenses: null, net: null }, - { month: 'Mar 2023', income: 4000, expenses: 3500, net: 500 }, - { month: 'Apr 2023', income: 0, expenses: 0, net: 0 }, + { + month: 'Jan 2023', + isoMonth: '2023-01', + income: null, + expenses: null, + net: null, + }, + { + month: 'Feb 2023', + isoMonth: '2023-02', + income: null, + expenses: null, + net: null, + }, + { + month: 'Mar 2023', + isoMonth: '2023-03', + income: 4000, + expenses: 3500, + net: 500, + }, + { + month: 'Apr 2023', + isoMonth: '2023-04', + income: 0, + expenses: 0, + net: 0, + }, ]); }); @@ -45,7 +81,15 @@ describe('toChartData', () => { [{ month: '2023-01', contributions: 0, expenses: 0, net: 0 }], 'en-US', ), - ).toEqual([{ month: 'Jan 2023', income: null, expenses: null, net: null }]); + ).toEqual([ + { + month: 'Jan 2023', + isoMonth: '2023-01', + income: null, + expenses: null, + net: null, + }, + ]); }); }); @@ -95,8 +139,11 @@ describe('averagesNote', () => { ); }); + it('says there is no data when the API returns no months', () => { + expect(note([])).toBe('No data available.'); + }); + it('says averages will show after the first full month', () => { - expect(note([])).toBe('Averages will show after your first full month.'); expect( note(year.map((iso) => month(iso, iso < '2026-11' ? 0 : 1000))), ).toBe('Averages will show after your first full month.'); diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts index 0409177146..0a42448c85 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts @@ -32,11 +32,13 @@ export const toChartData = ( const month = date.isValid ? monthYearFormat(date.month, date.year, locale) : ''; + const isoMonth = summary.month ?? ''; if (firstActive < 0 || index < firstActive) { - return { month, income: null, expenses: null, net: null }; + return { month, isoMonth, income: null, expenses: null, net: null }; } return { month, + isoMonth, income: summary.contributions ?? 0, expenses: summary.expenses ?? 0, net: summary.net ?? 0, @@ -99,6 +101,9 @@ export const averagesNote = ( months: MonthAmounts[], locale: string, ): string => { + if (months.length === 0) { + return t('No data available.'); + } const pastMonths = averagedMonths(months); if (pastMonths.length === 0) { return t('Averages will show after your first full month.'); diff --git a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryTooltip.test.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryTooltip.test.tsx new file mode 100644 index 0000000000..0835924873 --- /dev/null +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryTooltip.test.tsx @@ -0,0 +1,37 @@ +import { ThemeProvider } from '@mui/material/styles'; +import { render } from '__tests__/util/testingLibraryReactMock'; +import theme from 'src/theme'; +import { MonthlySummaryTooltip } from './MonthlySummaryTooltip'; + +const renderTooltip = (net: number) => + render( + + `$${value}`} + /> + , + ); + +describe('MonthlySummaryTooltip', () => { + it('shows the month, income, expenses and net', () => { + const { getByText } = renderTooltip(200); + + expect(getByText('Jul 2026')).toBeInTheDocument(); + expect(getByText('Contributions: $5000')).toBeInTheDocument(); + expect(getByText('Expenses: $4800')).toBeInTheDocument(); + expect(getByText('Net: $200')).toBeInTheDocument(); + }); + + it.each([ + [200, theme.palette.success.main], + [-200, theme.palette.error.main], + [0, 'inherit'], + ])('colors a net of %s', (net, color) => { + const { getByText } = renderTooltip(net); + + expect(getByText(`Net: $${net}`)).toHaveStyle({ color }); + }); +}); diff --git a/src/lib/intlFormat.ts b/src/lib/intlFormat.ts index e7e236ad28..5772610dcc 100644 --- a/src/lib/intlFormat.ts +++ b/src/lib/intlFormat.ts @@ -199,12 +199,13 @@ export const dateFormatWithoutYear = ( export const dateFormatMonthOnly = ( date: DateTime | null, locale: string, + month: 'short' | 'narrow' = 'short', ): string => { if (date === null) { return ''; } return new Intl.DateTimeFormat(locale, { - month: 'short', + month, }).format(date.toJSDate()); }; From 53731552a0a441ab9891fc82c5839fd534a7e010 Mon Sep 17 00:00:00 2001 From: Jeff Clay <91073628+jeff-clay@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:52:09 -0800 Subject: [PATCH 16/16] MPDX-10389 Keep empty-chart months in Latin digits Co-Authored-By: Claude Opus 5.5 --- .../IncomeExpensesChart.test.tsx | 19 ++++++ .../IncomeExpensesChart.tsx | 5 +- .../MonthlySummary/MonthlySummary.test.tsx | 65 ++++++++++--------- .../MonthlySummary/MonthlySummary.tsx | 19 +++--- 4 files changed, 67 insertions(+), 41 deletions(-) diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.test.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.test.tsx index 10ed0ca89d..1cd05ce681 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.test.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.test.tsx @@ -215,6 +215,25 @@ describe('IncomeExpensesChart', () => { expect(tickLabels(container)[0]).toHaveTextContent(/^Dec$/); }); + it('leaves the label blank for a month the API left unnamed', async () => { + const { container, findByRole } = render( + + index === 0 ? { ...month, isoMonth: '' } : month, + )} + />, + ); + + await findByRole('region'); + + await waitFor(() => + expect(tickLabels(container).map((tick) => tick.textContent)).toContain( + 'Jan', + ), + ); + expect(container).not.toHaveTextContent('Dec'); + }); + it('labels the y-axis in thousands and the months by first letter on a phone', async () => { matchMediaMock({ width: 390 }); const { container, findByRole } = render(); diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.tsx index 9655e538c4..b353f5066b 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.tsx @@ -22,7 +22,8 @@ import { AverageKey } from './AverageKey'; import { averageReferenceLines, averageSeries } from './averageLines'; // A month before the staff member started has no amounts, so it has no bars. -// `isoMonth` is the API's YYYY-MM month, for the axis labels. +// `isoMonth` is the YYYY-MM month for the axis labels, or empty when the API +// leaves the month unnamed. export type IncomeExpensesMonth = { isoMonth: string } & ( | MonthlySummaryChartData | { month: string; income: null; expenses: null; net: null } @@ -57,7 +58,7 @@ const MonthTick: React.FC = ({ isPhone, ...props }) => { - const month = data[payload?.index ?? 0]; + const month = payload ? data[payload.index] : undefined; const date = DateTime.fromISO(month?.isoMonth ?? ''); return ( { beforeEach(() => { beforeTestResizeObserver(); @@ -71,6 +73,7 @@ describe('StaffTabMonthlySummary', () => { afterEach(() => { afterTestResizeObserver(); + Settings.defaultLocale = defaultLocale; }); it('renders the headers and a row per month newest first, showing negative net and end balance in parentheses without a minus sign', async () => { @@ -257,36 +260,40 @@ describe('StaffTabMonthlySummary', () => { ).toHaveTextContent(/\(Jan.+Feb 2023\)\. March is still in progress\.$/); }); - it('charts labelled empty months without showing a zero amount', async () => { - const { container, findByRole, getByText, queryByRole, queryByText } = - render(); + it.each(['en-US', 'ar-EG'])( + 'charts labelled empty months without a zero amount in a %s browser (ar-EG has Arabic digits)', + async (browserLocale) => { + Settings.defaultLocale = browserLocale; + const { container, findByRole, getByText, queryByRole, queryByText } = + render(); - userEvent.click(await findByRole('button', { name: 'Chart view' })); + userEvent.click(await findByRole('button', { name: 'Chart view' })); - expect(await findByRole('region')).toBeInTheDocument(); - expect(queryByRole('table')).not.toBeInTheDocument(); - expect(queryByText(/\$/)).not.toBeInTheDocument(); - expect(getByText('No data available.')).toBeInTheDocument(); + expect(await findByRole('region')).toBeInTheDocument(); + expect(queryByRole('table')).not.toBeInTheDocument(); + expect(queryByText(/\$/)).not.toBeInTheDocument(); + expect(getByText('No data available.')).toBeInTheDocument(); - // Tests run pinned to 2020-01-01, so the window ends on the current month. - const ticks = Array.from( - container.querySelectorAll( - '.recharts-cartesian-axis .recharts-cartesian-axis-tick tspan', - ), - ).map((tick) => tick.textContent); - expect(ticks).toEqual([ - 'Feb', - 'Mar', - 'Apr', - 'May', - 'Jun', - 'Jul', - 'Aug', - 'Sep', - 'Oct', - 'Nov', - 'Dec', - 'Jan', - ]); - }); + // Tests run pinned to 2020-01-01, so the window ends on the current month. + const ticks = Array.from( + container.querySelectorAll( + '.recharts-cartesian-axis .recharts-cartesian-axis-tick tspan', + ), + ).map((tick) => tick.textContent); + expect(ticks).toEqual([ + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec', + 'Jan', + ]); + }, + ); }); diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx index b4a9e9f4fd..33d6678d4c 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx @@ -82,18 +82,17 @@ export const StaffTabMonthlySummary: React.FC = ({ const showChart = view === MonthlySummaryView.Chart; const hasData = monthlySummary.length > 0; + // The last 12 months with no amounts. toISODate keeps the month in Latin + // digits whatever the browser's locale. const emptyChartData = useMemo((): IncomeExpensesMonth[] => { const thisMonth = DateTime.local().startOf('month'); - return Array.from({ length: 12 }, (_, index) => { - const date = thisMonth.minus({ months: 11 - index }); - return { - month: monthYearFormat(date.month, date.year, locale), - isoMonth: date.toFormat('yyyy-MM'), - income: null, - expenses: null, - net: null, - }; - }); + const months = Array.from({ length: 12 }, (_, index) => ({ + month: thisMonth + .minus({ months: 11 - index }) + .toISODate() + ?.slice(0, 7), + })); + return toChartData(months, locale); }, [locale]); if (loading) {