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
@@ -0,0 +1,156 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { message } from 'antd';
import React from 'react';
import { HelmetProvider } from 'react-helmet-async';
import { MemoryRouter } from 'react-router-dom';

import '@testing-library/jest-dom/extend-expect';

import ManualReviewRecentDecisions from '@/webpages/dashboard/mrt/ManualReviewRecentDecisions';

const fakeDecision = {
__typename: 'ManualReviewDecision',
id: 'd1',
jobId: 'j1',
createdAt: '2026-08-23T00:00:00.000Z',
assignedAt: null,
jobCreatedAt: null,
reviewerId: 'u1',
queueId: 'q1',
decisionReason: null,
decisions: [
{
__typename: 'IgnoreDecisionComponent',
type: 'IGNORE',
},
],
};

let lazyCalls = 0;
let rejectDownload = false;
let finishDownload: (() => void) | undefined;
const downloadQuery = vi.fn(async () => {
lazyCalls += 1;
if (lazyCalls === 2) {
if (rejectDownload) {
throw new Error('download query failed');
}
await new Promise<void>((resolve) => {
finishDownload = resolve;
});
}
return { data: { getRecentDecisions: [] } };
});

vi.mock('../../../graphql/generated', async () => {
const actual = await vi.importActual<
typeof import('../../../graphql/generated')
>('../../../graphql/generated');
return {
...actual,
useGQLOrgLookupDataQuery: () => ({
data: {
myOrg: {
id: 'org1',
actions: [],
policies: [],
users: [{ id: 'u1', firstName: 'Ada', lastName: 'Lovelace' }],
mrtQueues: [{ id: 'q1', name: 'Queue 1' }],
},
},
}),
useGQLGetDecidedJobFromJobIdQuery: () => ({ data: undefined }),
useGQLGetRecentDecisionsLazyQuery: () => [
downloadQuery,
{
loading: false,
error: undefined,
data: { getRecentDecisions: [fakeDecision] },
},
],
useGQLGetSkipsForRecentDecisionsLazyQuery: () => [vi.fn()],
useGQLGetDecidedJobLazyQuery: () => [
vi.fn(),
{ loading: false, error: undefined, data: undefined },
],
};
});

vi.mock('./ManualReviewRecentDecisionsFilter', () => ({
default: function FilterStub() {
return <div>filter</div>;
},
}));

describe('Recent Decisions Download spinner', () => {
beforeEach(() => {
lazyCalls = 0;
rejectDownload = false;
finishDownload = undefined;
downloadQuery.mockClear();
});

afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});

it('loads until the CSV download starts', async () => {
const createObjectURL = vi.fn(() => 'blob:decisions');
const revokeObjectURL = vi.fn();
const clickDownload = vi
.spyOn(HTMLAnchorElement.prototype, 'click')
.mockImplementation(() => undefined);
vi.stubGlobal(
'URL',
Object.assign(class extends URL {}, { createObjectURL, revokeObjectURL }),
);

render(
<HelmetProvider>
<MemoryRouter>
<ManualReviewRecentDecisions />
</MemoryRouter>
</HelmetProvider>,
);

const download = await screen.findByRole('button', { name: 'Download' });
fireEvent.click(download);

await waitFor(() => {
expect(download).toHaveClass('ant-btn-loading');
});
expect(finishDownload).toBeDefined();
finishDownload?.();

await waitFor(() => {
expect(createObjectURL).toHaveBeenCalledWith(expect.any(Blob));
expect(clickDownload).toHaveBeenCalledOnce();
expect(revokeObjectURL).toHaveBeenCalledWith('blob:decisions');
expect(download).not.toHaveClass('ant-btn-loading');
});
});

it('reports an error and stops loading when the query fails', async () => {
rejectDownload = true;
const errorMessage = vi.spyOn(message, 'error');

render(
<HelmetProvider>
<MemoryRouter>
<ManualReviewRecentDecisions />
</MemoryRouter>
</HelmetProvider>,
);

const download = await screen.findByRole('button', { name: 'Download' });
fireEvent.click(download);

await waitFor(() => {
expect(errorMessage).toHaveBeenCalledWith(
'Could not download recent decisions. Please try again.',
);
expect(download).not.toHaveClass('ant-btn-loading');
});
});
});
164 changes: 84 additions & 80 deletions client/src/webpages/dashboard/mrt/ManualReviewRecentDecisions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { HOST_URL } from '@/lib/config';
import { filterNullOrUndefined } from '@/utils/collections';
import { RedoOutlined } from '@ant-design/icons';
import { gql } from '@apollo/client';
import { Button, Checkbox, Input, Tooltip } from 'antd';
import { Button, Checkbox, Input, message, Tooltip } from 'antd';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Helmet } from 'react-helmet-async';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
Expand Down Expand Up @@ -296,6 +296,7 @@ export default function ManualReviewRecentDecisions() {
useGQLGetSkipsForRecentDecisionsLazyQuery();

const [getRecentDecisionsForDownload] = useGQLGetRecentDecisionsLazyQuery();
const [isDownloadingDecisions, setIsDownloadingDecisions] = useState(false);

// Confusingly, getDecidedJob is used to get the job associated with a decision
// whereas getDecidedJobFromJobId is used to get the decision associated with a job
Expand Down Expand Up @@ -695,89 +696,92 @@ export default function ManualReviewRecentDecisions() {
<Button
className="rounded"
onClick={async () => {
const decisions: GQLGetRecentDecisionsQuery[] = [];
for (let i = 0; i < 100; i++) {
const result = await getRecentDecisionsForDownload({
variables: {
input: getRecentDecisionsInput(
unsavedFilterValue ?? {},
page + i,
setIsDownloadingDecisions(true);
try {
const decisions: GQLGetRecentDecisionsQuery[] = [];
for (let i = 0; i < 100; i++) {
const result = await getRecentDecisionsForDownload({
variables: {
input: getRecentDecisionsInput(
unsavedFilterValue ?? {},
page + i,
),
},
});
if (result.data) {
decisions.push(result.data);
}
}
const allDecisions = decisions.flatMap((it) => it.getRecentDecisions);
const allDecisionsCsv = allDecisions.map((decision) => {
const decisions = decision.decisions.flatMap((it) =>
getDecisionColorNamePairs(it, false).map(({ name }) => name),
);
const policies = decision.decisions.flatMap((decision) =>
getPoliciesFromDecision(decision),
);

return {
jobId: decision.jobId,
queue: getQueueName(decision.queueId),
reviewer: getReviewerName(decision.reviewerId),
decisions,
createdAt: parseDatetimeToReadableStringInUTC(
new Date(decision.createdAt),
),
},
assignedAt: decision.assignedAt
? parseDatetimeToReadableStringInUTC(
new Date(decision.assignedAt),
)
: '',
jobCreatedAt: decision.jobCreatedAt
? parseDatetimeToReadableStringInUTC(
new Date(decision.jobCreatedAt),
)
: '',
...getDecisionTimingFields(decision),
policies,
decisionReason: decision.decisionReason ?? '',
};
});
if (result.data) {
decisions.push(result.data);
}
}
const allDecisions = decisions.flatMap((it) => it.getRecentDecisions);
const allDecisionsCsv = allDecisions.map((decision) => {
const decisions = decision.decisions.flatMap((it) =>
getDecisionColorNamePairs(it, false).map(({ name }) => name),
const headers = [...RECENT_DECISIONS_CSV_HEADERS];

const rows = allDecisionsCsv.map((item) => [
JSON.stringify(item.decisions),
JSON.stringify(item.policies),
item.reviewer,
item.queue,
item.jobCreatedAt,
item.assignedAt,
item.createdAt,
item.waitTimeSeconds,
item.handleTimeSeconds,
item.decisionReason,
`${HOST_URL}/dashboard/manual_review/recent?jobId=${item.jobId}`,
]);

const csvContent = [headers, ...rows]
.map((row) => row.map(toCsvField).join(','))
.join('\n');

const blob = new Blob([csvContent], { type: 'text/csv' });
const url = URL.createObjectURL(blob);

const a = document.createElement('a');
a.href = url;
a.download = 'decisions.csv';
a.click();

URL.revokeObjectURL(url);
} catch {
message.error(
'Could not download recent decisions. Please try again.',
);
const policies = decision.decisions.flatMap((decision) =>
getPoliciesFromDecision(decision),
);

return {
jobId: decision.jobId,
queue: getQueueName(decision.queueId),
reviewer: getReviewerName(decision.reviewerId),
decisions,
createdAt: parseDatetimeToReadableStringInUTC(
new Date(decision.createdAt),
),
assignedAt: decision.assignedAt
? parseDatetimeToReadableStringInUTC(
new Date(decision.assignedAt),
)
: '',
jobCreatedAt: decision.jobCreatedAt
? parseDatetimeToReadableStringInUTC(
new Date(decision.jobCreatedAt),
)
: '',
...getDecisionTimingFields(decision),
policies,
decisionReason: decision.decisionReason ?? '',
};
});
// Define the CSV headers
const headers = [...RECENT_DECISIONS_CSV_HEADERS];

// Map the data to CSV rows
const rows = allDecisionsCsv.map((item) => [
JSON.stringify(item.decisions),
JSON.stringify(item.policies), // Convert array/object to JSON string if necessary
item.reviewer,
item.queue,
item.jobCreatedAt,
item.assignedAt,
item.createdAt,
item.waitTimeSeconds,
item.handleTimeSeconds,
item.decisionReason,
`${HOST_URL}/dashboard/manual_review/recent?jobId=${item.jobId}`,
]);

// Combine the headers and rows into a CSV string
const csvContent = [headers, ...rows]
.map((row) => row.map(toCsvField).join(',')) // RFC 4180: quote fields and escape embedded quotes
.join('\n');

// Create a Blob from the CSV content
const blob = new Blob([csvContent], { type: 'text/csv' });
const url = URL.createObjectURL(blob);

// Create a temporary link to download the Blob
const a = document.createElement('a');
a.href = url;
a.download = 'decisions.csv'; // Set the desired file name
a.click();

// Clean up
URL.revokeObjectURL(url);
} finally {
setIsDownloadingDecisions(false);
}
}}
loading={allDecisionsLoading || allDecisionsLoading}
loading={isDownloadingDecisions}
>
Download
</Button>
Expand Down