Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import { useSnackbar } from 'notistack';
import { useTranslation } from 'react-i18next';
import { useMpdGoalAdmin } from '../MpdGoalAdminContext';
import { PrintCohortGoalsButton } from '../PrintCohortGoalsButton/PrintCohortGoalsButton';
import { RunAndSendModal } from '../RunAndSendModal/RunAndSendModal';
import { StaffGoalRow } from '../mpdGoalAdminHelpers';

Expand Down Expand Up @@ -93,11 +94,7 @@ export const GoalsTableToolbar: React.FC = () => {
</>
) : (
<>
{/* Disabled until wired up so assistive tech announces the
inert state instead of a dead control (MPDX-9696). */}
<Button variant="outlined" disabled>
{t('Print All')}
</Button>
<PrintCohortGoalsButton />
<Button
variant="contained"
onClick={() =>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { ThemeProvider } from '@mui/material/styles';
import { act, render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SnackbarProvider } from 'notistack';
import theme from 'src/theme';
import { MpdGoalAdminProvider, useMpdGoalAdmin } from '../MpdGoalAdminContext';
import { TrainingCosts } from '../mpdGoalAdminHelpers';
import { PrintCohortGoalsButton } from './PrintCohortGoalsButton';
import { downloadPdf, generateCohortGoalsPdf } from './printCohortGoalsPdf';

jest.mock('./printCohortGoalsPdf');

const generateMock = generateCohortGoalsPdf as jest.MockedFunction<
typeof generateCohortGoalsPdf
>;
const downloadMock = downloadPdf as jest.MockedFunction<typeof downloadPdf>;

// Test harness exposing context so we can switch cohorts.
let ctx: ReturnType<typeof useMpdGoalAdmin>;
const Capture: React.FC = () => {
ctx = useMpdGoalAdmin();
return <PrintCohortGoalsButton />;
};

const renderButton = () =>
render(
<ThemeProvider theme={theme}>
<SnackbarProvider>
<MpdGoalAdminProvider>
<Capture />
</MpdGoalAdminProvider>
</SnackbarProvider>
</ThemeProvider>,
);

describe('PrintCohortGoalsButton', () => {
beforeEach(() => {
generateMock.mockResolvedValue('blob:mock-pdf');
});

it('is disabled with an explanation until the cohort has training costs', async () => {
const { getByRole, findByText } = renderButton();
// The spring cohort's training costs have not been entered yet.
act(() => ctx.setSelectedCohortId('spring-nso-2027'));

const button = getByRole('button', { name: 'Print All' });
expect(button).toBeDisabled();

userEvent.hover(button.parentElement as HTMLElement);
expect(
await findByText(
'Enter training costs for this cohort to print its goals.',
),
).toBeInTheDocument();
});

it('becomes enabled once training costs are entered', () => {
const { getByRole } = renderButton();
act(() => ctx.setSelectedCohortId('spring-nso-2027'));
expect(getByRole('button', { name: 'Print All' })).toBeDisabled();

const trainingCosts: TrainingCosts = {
nsoIndividual1InRoom: 100,
nsoIndividual2InRoom: 200,
nsoCouple: 300,
nsoFamily: 400,
ibsSingle: 500,
ibsCouple: 600,
refreshRetreatSingle: 700,
refreshRetreatCouple: 800,
faithAndFinanceSingle: 900,
faithAndFinanceCouple: 1000,
cruConferenceSingle: 1100,
cruConferenceCouple: 1200,
cruConferenceFamily: 1300,
};
act(() => ctx.saveTrainingCosts('spring-nso-2027', trainingCosts));
expect(getByRole('button', { name: 'Print All' })).toBeEnabled();
});

it('generates the cohort PDF and downloads it', async () => {
Comment thread
wjames111 marked this conversation as resolved.
const { getByRole } = renderButton();
userEvent.click(getByRole('button', { name: 'Print All' }));

await waitFor(() =>
expect(downloadMock).toHaveBeenCalledWith(
'blob:mock-pdf',
'MPD Goals - Fall NSO 2026.pdf',
),
);
expect(generateMock).toHaveBeenCalledWith(
expect.objectContaining({ id: 'fall-nso-2026' }),
);
expect(getByRole('button', { name: 'Print All' })).toBeEnabled();
});

it('disables the button and shows a spinner while generating', async () => {
let resolvePdf!: (url: string) => void;
generateMock.mockReturnValue(
new Promise((resolve) => (resolvePdf = resolve)),
);
const { getByRole, findByRole } = renderButton();
userEvent.click(getByRole('button', { name: 'Print All' }));

expect(await findByRole('progressbar')).toBeInTheDocument();
expect(getByRole('button', { name: 'Print All' })).toBeDisabled();

resolvePdf('blob:mock-pdf');
await waitFor(() => expect(downloadMock).toHaveBeenCalled());
expect(getByRole('button', { name: 'Print All' })).toBeEnabled();
});

it('shows an error and re-enables the button when generation fails', async () => {
generateMock.mockRejectedValue(new Error('boom'));
const { getByRole, findByText } = renderButton();
userEvent.click(getByRole('button', { name: 'Print All' }));

expect(
await findByText('Unable to export the MPD Goals PDF.'),
).toBeInTheDocument();
expect(downloadMock).not.toHaveBeenCalled();
expect(getByRole('button', { name: 'Print All' })).toBeEnabled();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import React, { useState } from 'react';
import { Button, CircularProgress, Tooltip } from '@mui/material';
import { useSnackbar } from 'notistack';
import { useTranslation } from 'react-i18next';
import { useMpdGoalAdmin } from '../MpdGoalAdminContext';
import { downloadPdf, generateCohortGoalsPdf } from './printCohortGoalsPdf';

/**
* "Print All" — exports every goal in the selected cohort as a single
* printable PDF (used for NSO hard copies). Disabled until the cohort's
* training costs have been entered: without training costs the goal amounts
* aren't final, so printing may not act on them. (Run & Send is expected to
* adopt the same gate when it is wired up — it does not enforce it yet.)
*/
export const PrintCohortGoalsButton: React.FC = () => {
const { t } = useTranslation();
const { enqueueSnackbar } = useSnackbar();
const { selectedCohort } = useMpdGoalAdmin();
const [printing, setPrinting] = useState(false);

const hasTrainingCosts = !!selectedCohort?.trainingCostEntered;

const handlePrint = async () => {
if (!selectedCohort) {
return;
}
setPrinting(true);
try {
const url = await generateCohortGoalsPdf(selectedCohort);
Comment thread
wjames111 marked this conversation as resolved.
downloadPdf(url, `MPD Goals - ${selectedCohort.name}.pdf`);
} catch {
// TODO(MPDX-9691): once generation is a GraphQL mutation, the global
// Apollo error link will already toast failures — remove this snackbar
// (or suppress the generic one) so the user isn't double-toasted.
enqueueSnackbar(t('Unable to export the MPD Goals PDF.'), {
Comment thread
wjames111 marked this conversation as resolved.
variant: 'error',
});
} finally {
setPrinting(false);
}
};

return (
<Tooltip
title={
hasTrainingCosts
? t('Prints every goal in {{cohort}}.', {
cohort: selectedCohort?.name ?? '',
})
: t('Enter training costs for this cohort to print its goals.')
}
>
{/* span so the tooltip still fires while the button is disabled */}
<span>
<Button
variant="outlined"
disabled={!hasTrainingCosts || printing}
onClick={handlePrint}
aria-busy={printing}
>
{t('Print All')}
{printing && (
<CircularProgress size={16} color="inherit" sx={{ ml: 1 }} />
)}
</Button>
</span>
</Tooltip>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { mockCohorts } from '../mockData';
import {
buildPlaceholderPdf,
downloadPdf,
generateCohortGoalsPdf,
} from './printCohortGoalsPdf';

describe('buildPlaceholderPdf', () => {
it('produces a well-formed PDF document', () => {
const pdf = buildPlaceholderPdf(['Hello', 'World']);
expect(pdf).toMatch(/^%PDF-1\.4\n/);
expect(pdf).toMatch(/%%EOF$/);
expect(pdf).toContain('(Hello) Tj');
expect(pdf).toContain('(World) Tj');
// The xref offset in startxref must point at the xref keyword.
const xrefOffset = Number(pdf.match(/startxref\n(\d+)/)?.[1]);
expect(pdf.slice(xrefOffset, xrefOffset + 4)).toBe('xref');
});

it('escapes characters that would terminate a PDF string', () => {
const pdf = buildPlaceholderPdf(['John (Jack) Doe \\ Co']);
expect(pdf).toContain('(John \\(Jack\\) Doe \\\\ Co) Tj');
});

it('throws when the lines exceed the single-page capacity', () => {
expect(() => buildPlaceholderPdf(Array(45).fill('x'))).toThrow();
});
});

describe('generateCohortGoalsPdf', () => {
// jsdom does not implement Blob.text(), so read the blob with a FileReader.
const readBlobText = (blob: Blob) =>
new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = () => reject(reader.error);
reader.readAsText(blob);
});

it('builds a blob URL for a PDF listing every goal in the cohort', async () => {
Comment thread
wjames111 marked this conversation as resolved.
const createObjectURL = jest.fn().mockReturnValue('blob:cohort-pdf');
window.URL.createObjectURL = createObjectURL;

await expect(generateCohortGoalsPdf(mockCohorts[0])).resolves.toBe(
'blob:cohort-pdf',
);
const blob = createObjectURL.mock.calls[0][0] as Blob;
expect(blob.type).toBe('application/pdf');

const pdf = await readBlobText(blob);
expect(pdf).toContain('(MPD Goals - Fall NSO 2026) Tj');
expect(pdf).toContain('(John & Jane Doe: $6,430.25) Tj');
expect(pdf).toContain('(Carlos & Michaela Everts: $5,280.77) Tj');
});
});

describe('downloadPdf', () => {
it('downloads via a temporary anchor and releases the URL', () => {
const revokeObjectURL = jest.fn();
window.URL.revokeObjectURL = revokeObjectURL;
const click = jest
.spyOn(HTMLAnchorElement.prototype, 'click')
.mockImplementation(() => {});
let anchor: HTMLAnchorElement | undefined;
const realCreateElement = document.createElement.bind(document);
const createElement = jest
.spyOn(document, 'createElement')
.mockImplementation((tagName) => {
const element = realCreateElement(tagName);
if (element instanceof HTMLAnchorElement) {
anchor = element;
}
return element;
});

downloadPdf('blob:cohort-pdf', 'MPD Goals - Fall NSO 2026.pdf');

expect(click).toHaveBeenCalled();
expect(anchor?.download).toBe('MPD Goals - Fall NSO 2026.pdf');
expect(anchor?.href).toContain('blob:cohort-pdf');
expect(revokeObjectURL).toHaveBeenCalledWith('blob:cohort-pdf');
click.mockRestore();
createElement.mockRestore();
});
});
Loading
Loading