diff --git a/public/locales/en/translation.json b/public/locales/en/translation.json index e8e27f9f68..de6614557f 100644 --- a/public/locales/en/translation.json +++ b/public/locales/en/translation.json @@ -175,7 +175,13 @@ "(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.", 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..1cd05ce681 --- /dev/null +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.test.tsx @@ -0,0 +1,282 @@ +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 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[] = months.map((month, index) => + index < 7 + ? { ...month, income: null, expenses: null, net: null } + : { ...month, income: 5000, expenses: 4800, net: 200 }, +); + +const fullYearData: IncomeExpensesMonth[] = months.map((month) => ({ + ...month, + income: 5000, + expenses: 4800, + net: 200, +})); + +const emptyData: IncomeExpensesMonth[] = months.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); + }); + + // 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(); + + const region = await findByRole('region'); + + await waitFor(() => + expect(within(region).getByText('$6,000')).toBeInTheDocument(), + ); + 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(); + + 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..b353f5066b --- /dev/null +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/IncomeExpensesChart/IncomeExpensesChart.tsx @@ -0,0 +1,164 @@ +import { Box, useMediaQuery } from '@mui/material'; +import { DateTime } from 'luxon'; +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, 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. +// `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 } +); + +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?: { index: number }; + data: IncomeExpensesMonth[]; + locale: string; + isPhone: boolean; +} + +// 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 month = payload ? data[payload.index] : undefined; + const date = DateTime.fromISO(month?.isoMonth ?? ''); + return ( + + {dateFormatMonthOnly( + date.isValid ? date : null, + locale, + isPhone ? 'narrow' : 'short', + )} + + ); +}; + +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 ec5a1faea8..84d4a01dce 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.test.tsx @@ -1,6 +1,7 @@ import { ThemeProvider } from '@mui/material/styles'; import userEvent from '@testing-library/user-event'; import { ApolloErgonoMockMap } from 'graphql-ergonomock'; +import { Settings } from 'luxon'; import { GqlMockedProvider } from '__tests__/util/graphqlMocking'; import { render } from '__tests__/util/testingLibraryReactMock'; import { @@ -64,6 +65,7 @@ const columnHeaders = [ 'End Balance', ]; +const defaultLocale = Settings.defaultLocale; describe('StaffTabMonthlySummary', () => { 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 () => { @@ -220,7 +223,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,38 +235,65 @@ describe('StaffTabMonthlySummary', () => { userEvent.click(getByRole('button', { name: 'Table view' })); expect(getByRole('table')).toBeInTheDocument(); + expect(queryByText(/Monthly averages/)).not.toBeInTheDocument(); }); - it('charts labelled empty months without showing a zero amount', async () => { - const { container, findByRole, queryByRole, queryByText } = render( - , + it('draws the contributions and expenses averages of the finished months on the chart', async () => { + const { findByRole, findByTestId, getByText } = render( + , ); userEvent.click(await findByRole('button', { name: 'Chart view' })); - expect(await findByRole('region')).toBeInTheDocument(); - expect(queryByRole('table')).not.toBeInTheDocument(); - expect(queryByText(/^\$/)).not.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', - ]); + expect(await findByTestId('MonthlySummaryAverageKey')).toHaveTextContent( + '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.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' })); + + 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', + ]); + }, + ); }); diff --git a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx index 0b92e8f5fe..33d6678d4c 100644 --- a/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/MonthlySummary.tsx @@ -14,17 +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 { averagesNote, monthlyAverages, toChartData } from './chartData'; export enum MonthlySummaryView { Table = 'table', @@ -70,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], ); @@ -92,18 +82,17 @@ export const StaffTabMonthlySummary: React.FC = ({ const showChart = view === MonthlySummaryView.Chart; const hasData = monthlySummary.length > 0; - - const emptyChartData = useMemo((): MonthlySummaryChartData[] => { + // 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), - income: 0, - expenses: 0, - net: 0, - }; - }); + const months = Array.from({ length: 12 }, (_, index) => ({ + month: thisMonth + .minus({ months: 11 - index }) + .toISODate() + ?.slice(0, 7), + })); + return toChartData(months, locale); }, [locale]); if (loading) { @@ -129,13 +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 new file mode 100644 index 0000000000..6d351fc8f8 --- /dev/null +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.test.ts @@ -0,0 +1,241 @@ +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', () => { + 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', + isoMonth: '2023-01', + income: 4000, + expenses: 3500, + net: 500, + }, + { + month: 'Feb 2023', + isoMonth: '2023-02', + 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', + 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, + }, + ]); + }); + + 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', + isoMonth: '2023-01', + 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 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(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', () => { + // 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('leaves out the last row, even when its date is not this month', () => { + expect( + monthlyAverages([ + { month: '2019-11', contributions: 4000, expenses: 3000 }, + { month: '2019-12', contributions: 5000, expenses: 4000 }, + { month: '2019-12', ...currentMonth }, + ]), + ).toEqual({ income: 4500, expenses: 3500 }); + }); + + 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 }, + currentMonth, + ]), + ).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 }, + currentMonth, + ]), + ).toEqual({ income: undefined, expenses: 300 }); + }); + + 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 }); + }); + + 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 }); + }); + + it('has no averages when no month is finished or active', () => { + const none = { income: undefined, expenses: undefined }; + 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 new file mode 100644 index 0000000000..0a42448c85 --- /dev/null +++ b/src/components/HrTools/MpdSupervisorReport/StaffDetailsTabs/MonthlySummary/chartData.ts @@ -0,0 +1,132 @@ +import { TFunction } from 'i18next'; +import { DateTime } from 'luxon'; +import { monthYearFormat } from 'src/lib/intlFormat'; +import { + IncomeExpensesAverages, + IncomeExpensesMonth, +} from './IncomeExpensesChart/IncomeExpensesChart'; +import { MonthlyPayrollSummaryQuery } from './MonthlyPayrollSummary.generated'; + +type MonthAmounts = Partial< + Pick< + MonthlyPayrollSummaryQuery['monthlyPayrollSummary'][number], + 'month' | 'contributions' | 'expenses' | 'net' + > +>; + +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, +): 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) + : ''; + const isoMonth = summary.month ?? ''; + if (firstActive < 0 || index < firstActive) { + return { month, isoMonth, income: null, expenses: null, net: null }; + } + return { + month, + isoMonth, + 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. +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; +}; + +// The API's last row is the current month, still in progress, so it is left +// 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[], +): IncomeExpensesAverages => { + const pastMonths = averagedMonths(months); + return { + income: average(pastMonths.map((month) => month.contributions)), + expenses: average(pastMonths.map((month) => month.expenses)), + }; +}; + +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 => { + 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.'); + } + + 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/MonthlySummaryChart.tsx b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx index d13a8e98d6..202d8de79b 100644 --- a/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx +++ b/src/components/Reports/MPGAIncomeExpensesReport/Charts/MonthlySummaryChart/MonthlySummaryChart.tsx @@ -1,5 +1,5 @@ import { useMemo } from 'react'; -import { Box, GlobalStyles, Typography } from '@mui/material'; +import { Box, GlobalStyles } from '@mui/material'; import { useTranslation } from 'react-i18next'; import { Bar, @@ -15,6 +15,7 @@ import { currencyFormat } from 'src/lib/intlFormat'; import theme from 'src/theme'; import { ChartFrame } from '../ChartFrame'; import { ChartLegendContent } from '../ChartLegendContent/ChartLegendContent'; +import { MonthlySummaryTooltip } from './MonthlySummaryTooltip'; export interface MonthlySummaryChartData { month: string; @@ -101,49 +102,13 @@ export const MonthlySummaryChart: React.FC = ({ return null; } - const { income, expenses, net } = payload[0] - .payload as MonthlyTotal; - return ( - - - {label} - - - {overrideIncomeText ?? t('Income')}:{' '} - {formatAmount(income)} - - - {t('Expenses')}: {formatAmount(expenses)} - - 0 - ? chartColors[0] - : chartColors[1], - }} - > - {t('Net')}: {formatAmount(net)} - - + ); }} /> 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/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/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()); }; diff --git a/src/theme.ts b/src/theme.ts index fa782bb2ab..5c45add056 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; @@ -265,29 +274,21 @@ 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, + }, + chartExpenses: { + main: chartColors.expenses, + dark: chartColors.expenses, }, chipYellowDark: { main: chipColors.yellowDark,