Skip to content

Commit

Permalink
Merge pull request #5545 from flexion/10472-story
Browse files Browse the repository at this point in the history
10472 story
  • Loading branch information
jimlerza authored Dec 24, 2024
2 parents 9b91f7f + df93ea5 commit 20200b6
Show file tree
Hide file tree
Showing 18 changed files with 149 additions and 296 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ import { unchecksOrdersAndNoticesBoxesInCase } from '../../../support/pages/unch

describe('Petition clerk creates a paper filing', function () {
describe('Create and submit a paper petition', () => {
beforeEach(() => {
cy.window().then(win => {
cy.stub(win, 'open').as('windowOpen');
});
});
it('should create a paper petition', () => {
navigateToDocumentQC('petitionsclerk');

Expand All @@ -43,23 +48,17 @@ describe('Petition clerk creates a paper filing', function () {
it('should display attachment links in the attachment section', () => {
cy.get('[data-testid="petitionFileButton"]').should('be.visible');
cy.get('[data-testid="petitionFileButton"]').click();
cy.get('[data-testid="modal-dialog-header"]').should('be.visible');
cy.get('[data-testid="close-modal-button"]').click();
cy.get('[data-testid="stinFileDisplay"]').should('be.visible');
cy.get('[data-testid="stinFileDisplay"]').should('not.be.enabled');

cy.get('[data-testid="requestForPlaceOfTrialFileButton"]').should(
'be.visible',
);
cy.get('[data-testid="requestForPlaceOfTrialFileButton"]').click();
cy.get('[data-testid="modal-dialog-header"]').should('be.visible');
cy.get('[data-testid="close-modal-button"]').click();
cy.get('[data-testid="attachmentToPetitionFileButton"]').should(
'be.visible',
);
cy.get('[data-testid="attachmentToPetitionFileButton"]').click();
cy.get('[data-testid="modal-dialog-header"]').should('be.visible');
cy.get('[data-testid="close-modal-button"]').click();
});

it('should display Orders/Notices Automatically Created notification', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const loadPDFForPreviewInteractor = async (
docketEntryId,
docketNumber,
}: { docketEntryId?: string; docketNumber?: string },
): Promise<void> => {
): Promise<Blob> => {
try {
return await applicationContext.getPersistenceGateway().getDocument({
applicationContext,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,6 @@ export const respondentRequestsAccessToCase = (cerebralTest, fakeFile) => {
);
expect(cerebralTest.getState('validationErrors')).toEqual({});

await cerebralTest.runSequence('openPdfPreviewModalSequence', {
file: fakeFile,
modalId: 'PDFPreviewModal-Entry of Appearance for Respondent',
});

await cerebralTest.runSequence('updateFormValueSequence', {
key: 'redactionAcknowledgement',
value: true,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,36 +1,44 @@
import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext';
import { loadPdfAction } from './loadPdfAction';
import { loadPdfForTabAction } from '../PDFPreviewTab/loadPdfForTabAction';
import { openUrlInNewTab } from '@web-client/presenter/utilities/openUrlInNewTab';
import { presenter } from '../../presenter-mock';
import { runAction } from '@web-client/presenter/test.cerebral';
import { testPdfDoc } from '../../../../../shared/src/business/test/getFakeFile';

describe('loadPdfAction', () => {
global.Blob = function () {};
jest.mock('@web-client/presenter/utilities/openUrlInNewTab');

describe('loadPdfForTabAction', () => {
let originalWindowOpen;

const fakeFile = testPdfDoc;
const b64File = `data:application/pdf;base64,${Buffer.from(
String.fromCharCode.apply(null, fakeFile),
String.fromCharCode(...fakeFile),
).toString('base64')}`;

const mocks = {
readAsArrayBufferMock: jest.fn().mockImplementation(async function () {
readAsArrayBufferMock: jest.fn().mockImplementation(async function (this: {
result: any;
onload: any;
}) {
this.result = fakeFile;
await this.onload();
}),
readAsDataURLMock: jest.fn().mockImplementation(async function () {
readAsDataURLMock: jest.fn().mockImplementation(async function (this: {
result: any;
onload: any;
}) {
this.result = b64File;
await this.onload();
}),
};

/**
* Mock FileReader Implementation
*/
function MockFileReader() {
this.onload = null;
this.onerror = null;
this.readAsDataURL = mocks.readAsDataURLMock;
this.readAsArrayBuffer = mocks.readAsArrayBufferMock;
class MockFileReader {
public result: unknown = null;
public onload: any;
public onerror: any;

readAsDataURL = mocks.readAsDataURLMock;
readAsArrayBuffer = mocks.readAsArrayBufferMock;
}

beforeAll(() => {
Expand All @@ -44,98 +52,76 @@ describe('loadPdfAction', () => {
);
presenter.providers.applicationContext = applicationContext;
presenter.providers.router = {
createObjectURL: jest.fn(),
createObjectURL: jest.fn().mockReturnValue('some url'),
};
originalWindowOpen = window.open;
(openUrlInNewTab as jest.Mock).mockImplementation(jest.fn());
window.open = jest.fn();
});

it('should detect binary (not base64-encoded) pdf data and read it successfully', async () => {
const result = await runAction(loadPdfAction, {
afterAll(() => {
window.open = originalWindowOpen;
jest.restoreAllMocks();
});

it('should call window.open with correcturl for pdf file', async () => {
await runAction(loadPdfForTabAction, {
modules: {
presenter,
},
props: {
file: fakeFile,
},
state: {
pdfPreviewModal: {},
},
props: { file: fakeFile },
});

expect(mocks.readAsArrayBufferMock).toHaveBeenCalled();
expect(result.state.modal.pdfPreviewModal.error).toBeUndefined();
expect(openUrlInNewTab).toHaveBeenCalledWith({ url: 'some url' });
});

it('should detect base64-encoded pdf data and read it successfully', async () => {
const result = await runAction(loadPdfAction, {
it('should detect binary (not base64-encoded) pdf data and read it successfully', async () => {
await runAction(loadPdfForTabAction, {
modules: {
presenter,
},
props: {
file: b64File,
},
state: {
pdfPreviewModal: {},
file: fakeFile,
},
});

expect(mocks.readAsDataURLMock).toHaveBeenCalled();
expect(result.state.modal.pdfPreviewModal.error).toBeUndefined();
expect(mocks.readAsArrayBufferMock).toHaveBeenCalled();
});

it('should return an error when given an invalid pdf', async () => {
presenter.providers.router.createObjectURL.mockImplementationOnce(() => {
throw new Error('bad pdf data');
});
await expect(
runAction(loadPdfAction, {
runAction(loadPdfForTabAction, {
modules: {
presenter,
},
props: {
file: 'data:binary/pdf,INVALID-BYTES',
},
state: { pdfPreviewModal: {} },
}),
).rejects.toThrow('bad pdf data');
});

it('should error out when the FileReader fails', async () => {
mocks.readAsArrayBufferMock.mockImplementationOnce(function () {
mocks.readAsArrayBufferMock.mockImplementationOnce(function (this: {
result: any;
onerror: any;
}) {
this.result = 'abc';
this.onerror(new Error('An error called via reader.onerror.'));
});

await expect(
runAction(loadPdfAction, {
runAction(loadPdfForTabAction, {
modules: {
presenter,
},
props: {
file: 'this my file',
},
state: {
pdfPreviewModal: {},
},
}),
).rejects.toThrow('An error called via reader.onerror.');
});

it('sets the pdfPreviewUrl on state from the given file', async () => {
presenter.providers.router.createObjectURL.mockReturnValue('fakePdfUri');

const result = await runAction(loadPdfAction, {
modules: {
presenter,
},
props: {
file: b64File,
},
state: {
modal: { pdfPreviewModal: { error: 'Some Error' } },
},
});

expect(result.state.modal.pdfPreviewModal.error).toBeUndefined();
expect(result.state.pdfPreviewUrl).toEqual('fakePdfUri');
});
});
Original file line number Diff line number Diff line change
@@ -1,30 +1,18 @@
import { state } from '@web-client/presenter/app.cerebral';

/**
* loads the pdf for being used in preview modal
*
* @param {object} providers the providers object
* @param {object} providers.store the cerebral store object
* @param {Function} providers.props the cerebral props object
* @returns {Promise} promise which resolves if it successfully loads the pdf
*/
export const loadPdfAction = ({
import { openUrlInNewTab } from '../../utilities/openUrlInNewTab';
export const loadPdfForTabAction = ({
applicationContext,
props,
router,
store,
}: ActionProps) => {
const { file } = props;
const isBase64Encoded = typeof file === 'string' && file.startsWith('data');

store.set(state.modal.pdfPreviewModal, {});

return new Promise((resolve, reject) => {
return new Promise<void>((resolve, reject) => {
const reader = applicationContext.getFileReaderInstance();

reader.onload = () => {
let binaryFile;
if (isBase64Encoded) {
let binaryFile: string | ArrayBuffer | null;
if (isBase64Encoded && reader.result === 'string') {
const base64File = reader.result.replace(/[^,]+,/, '');
binaryFile = atob(base64File);
} else {
Expand All @@ -33,23 +21,22 @@ export const loadPdfAction = ({

try {
const pdfDataUri = router.createObjectURL(
// @ts-ignore
new Blob([binaryFile], { type: 'application/pdf' }),
);
store.set(state.pdfPreviewUrl, pdfDataUri);
store.unset(state.modal.pdfPreviewModal.error);
openUrlInNewTab({ url: pdfDataUri });
resolve();
} catch (err) {
store.set(state.modal.pdfPreviewModal.error, err);
reject(err);
}
};

reader.onerror = function (err) {
store.set(state.modal.pdfPreviewModal.error, err);
reject(err);
};

if (isBase64Encoded) {
// @ts-ignore
reader.readAsDataURL(file);
} else {
reader.readAsArrayBuffer(file);
Expand Down
50 changes: 50 additions & 0 deletions web-client/src/presenter/actions/getPDFForPreviewTabAction.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext';
import { getPDFForPreviewTabAction } from './getPDFForPreviewTabAction';
import { presenter } from '../presenter-mock';
import { runAction } from '@web-client/presenter/test.cerebral';

describe('getPDFForPreviewTabAction', () => {
beforeAll(() => {
presenter.providers.applicationContext = applicationContext;
applicationContext
.getUseCases()
.loadPDFForPreviewInteractor.mockResolvedValue('fake file data');
});

it('returns original props if we already have what appears to be an actual file', async () => {
const props = { file: { name: 'name of a file on a real file object' } };
const result = await runAction(getPDFForPreviewTabAction, {
modules: {
presenter,
},
props,
state: {},
});
expect(result.props).toEqual(props);
expect(
applicationContext.getUseCases().loadPDFForPreviewInteractor,
).not.toHaveBeenCalled();
});

it('returns results from loadPDFForPreviewInteractor if provided a docketNumber and docketEntryId', async () => {
const props = { file: { docketEntryId: '456' } };
await runAction(getPDFForPreviewTabAction, {
modules: {
presenter,
},
props,
state: {
caseDetail: {
docketNumber: '123-20',
},
},
});
expect(
applicationContext.getUseCases().loadPDFForPreviewInteractor.mock
.calls[0][1],
).toMatchObject({
docketEntryId: '456',
docketNumber: '123-20',
});
});
});
21 changes: 21 additions & 0 deletions web-client/src/presenter/actions/getPDFForPreviewTabAction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { state } from '@web-client/presenter/app.cerebral';

export const getPDFForPreviewTabAction = async ({
applicationContext,
get,
props,
}: ActionProps) => {
if (props.file.name) {
return props;
}
const { docketEntryId } = props.file;
const docketNumber = get(state.caseDetail.docketNumber);

const pdfObj = await applicationContext
.getUseCases()
.loadPDFForPreviewInteractor(applicationContext, {
docketEntryId,
docketNumber,
});
return { file: pdfObj };
};
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
import { state } from '@web-client/presenter/app.cerebral';

/**
* opens the document in a new tab
* @param {object} providers the providers object
* @param {object} providers.props the cerebral props object
* @param {object} providers.store the cerebral store object used for clearing alertError, alertSuccess
*/
export const openCaseDocumentDownloadUrlAction = async ({
applicationContext,
props,
Expand Down
1 change: 1 addition & 0 deletions web-client/src/presenter/computeds/fileDocumentHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ export const fileDocumentHelper = (
supportingDocumentTypeList,
...showSecondaryProperties,
...supportingDocumentFlags,
docketNumber: caseDetail.docketNumber,
};

if (form.hasSupportingDocuments) {
Expand Down
Loading

0 comments on commit 20200b6

Please sign in to comment.