diff --git a/.circleci/config.yml b/.circleci/config.yml index 19e2315225c..4126234dc47 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -2,7 +2,7 @@ version: 2.1 orbs: git-shallow-clone: guitarrapc/git-shallow-clone@2.8.0 -efcms-docker-image: &efcms-docker-image $AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/ef-cms-us-east-1:4.3.7 +efcms-docker-image: &efcms-docker-image $AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/ef-cms-us-east-1:4.3.8 parameters: run_build_and_deploy: diff --git a/Dockerfile b/Dockerfile index 91343bb61fa..dec65e5cd61 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ # Note: node-20.14.0-chrome-125.0.* is debian 12.5 (bookworm) -FROM cypress/browsers:node-20.16.0-chrome-127.0.6533.88-1-ff-128.0.3-edge-127.0.2651.74-1 +FROM cypress/browsers:node-20.16.0-chrome-127.0.6533.119-1-ff-129.0.1-edge-127.0.2651.98-1 WORKDIR /home/app @@ -37,12 +37,12 @@ RUN apt-get install -y build-essential RUN apt-get install -y libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev ENV JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64 -RUN curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64-2.17.30.zip" -o "awscliv2.zip" && \ +RUN curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64-2.17.36.zip" -o "awscliv2.zip" && \ unzip awscliv2.zip && \ ./aws/install && \ rm -rf awscliv2.zip -RUN wget -q -O terraform.zip https://releases.hashicorp.com/terraform/1.9.4/terraform_1.9.4_linux_amd64.zip && \ +RUN wget -q -O terraform.zip https://releases.hashicorp.com/terraform/1.9.5/terraform_1.9.5_linux_amd64.zip && \ unzip -o terraform.zip terraform && \ rm terraform.zip && \ cp terraform /usr/local/bin/ diff --git a/cypress-smoketests.config.ts b/cypress-smoketests.config.ts index d79d850112c..fa94c93204f 100644 --- a/cypress-smoketests.config.ts +++ b/cypress-smoketests.config.ts @@ -4,6 +4,7 @@ import { deleteAllCypressTestAccounts, deleteAllIrsCypressTestAccounts, getIrsBearerToken, + getUserByEmail, } from './cypress/helpers/cypressTasks/cognito/cognito-helpers'; import { defineConfig } from 'cypress'; import { @@ -33,20 +34,26 @@ export default defineConfig({ return confirmUser({ email }); }, createAccount({ - irsEnv, + isIrsEnv, + name, password, role, + userId, userName, }: { - irsEnv: boolean; + userName: string; password: string; role: string; - userName: string; + isIrsEnv: boolean; + name: string; + userId: string; }) { return createAccount({ - isIrsEnv: irsEnv, + isIrsEnv, + name, password, role, + userId, userName, }); }, @@ -83,6 +90,9 @@ export default defineConfig({ getNewAccountVerificationCode({ email }) { return getNewAccountVerificationCode({ email }); }, + getUserByEmail(email: string) { + return getUserByEmail(email); + }, readAllItemsInBucket({ bucketName, retries, diff --git a/cypress.config.ts b/cypress.config.ts index d8b11899dd1..0f8ee3fc286 100644 --- a/cypress.config.ts +++ b/cypress.config.ts @@ -1,6 +1,7 @@ import { confirmUser, deleteAllCypressTestAccounts, + getUserByEmail, } from './cypress/helpers/cypressTasks/cognito/cognito-helpers'; import { defineConfig } from 'cypress'; import { @@ -56,6 +57,9 @@ export default defineConfig({ getNewAccountVerificationCode({ email }) { return getNewAccountVerificationCode({ email }); }, + getUserByEmail(email: string) { + return getUserByEmail(email); + }, table(message) { console.table(message); return null; diff --git a/cypress/deployed-and-local/integration/advancedSearch/search.cy.ts b/cypress/deployed-and-local/integration/advancedSearch/search.cy.ts index 816cd85a671..e75979b072c 100644 --- a/cypress/deployed-and-local/integration/advancedSearch/search.cy.ts +++ b/cypress/deployed-and-local/integration/advancedSearch/search.cy.ts @@ -10,9 +10,12 @@ import { } from '../../../helpers/authentication/login-as-helpers'; describe('Advanced Search', () => { + beforeEach(() => { + Cypress.session.clearCurrentSessionData(); + }); + it('should find a served paper case when the user searches by party name or docket number', () => { /** Arrange */ - loginAsPetitionsClerk1(); createAndServePaperPetition().then(({ docketNumber, name }) => { /** Act */ cy.get('[data-testid="search-link"]').click(); diff --git a/cypress/deployed-and-local/integration/authentication/petitioner-account-creation.cy.ts b/cypress/deployed-and-local/integration/authentication/petitioner-account-creation.cy.ts index 23ebe8ce469..b94df3a7e23 100644 --- a/cypress/deployed-and-local/integration/authentication/petitioner-account-creation.cy.ts +++ b/cypress/deployed-and-local/integration/authentication/petitioner-account-creation.cy.ts @@ -87,11 +87,37 @@ describe('Petitioner Account Creation', () => { }); describe('Create Petitioner Account and login', () => { - const TEST_EMAIL = `cypress_test_account+success_${GUID}@example.com`; const TEST_NAME = 'Cypress Test'; const TEST_PASSWORD = generatePassword(VALID_PASSWORD_CONFIG); - it('should create an account and verify it using the verification link, then login and create an eletronic case', () => { + it('should prevent multiple submissions', () => { + const TEST_EMAIL = `cypress_test_account+no_multiple_submissions_${GUID}@example.com`; + cy.visit('/create-account/petitioner'); + cy.get('[data-testid="petitioner-account-creation-email"]').type( + TEST_EMAIL, + ); + cy.get('[data-testid="petitioner-account-creation-name"]').type( + TEST_NAME, + ); + cy.get('[data-testid="petitioner-account-creation-password"]').type( + TEST_PASSWORD, + ); + cy.get( + '[data-testid="petitioner-account-creation-confirm-password"]', + ).type(TEST_PASSWORD); + cy.intercept('POST', '/auth/account/create').as('accountCreationRequest'); + + // eslint-disable-next-line cypress/unsafe-to-chain-command + cy.get('[data-testid="petitioner-account-creation-submit-button"]') + .click({ force: true }) + .click({ force: true }); + + cy.wait('@accountCreationRequest'); + cy.get('@accountCreationRequest.all').should('have.length', 1); + }); + + it('should create an account and verify it using the verification link, then login and create an electronic case', () => { + const TEST_EMAIL = `cypress_test_account+success_${GUID}@example.com`; createAPetitioner({ email: TEST_EMAIL, name: TEST_NAME, diff --git a/cypress/deployed-and-local/integration/documentQC/complete-docket-qc.cy.ts b/cypress/deployed-and-local/integration/documentQC/complete-docket-qc.cy.ts index 2119d786ee5..5001c0e3df0 100644 --- a/cypress/deployed-and-local/integration/documentQC/complete-docket-qc.cy.ts +++ b/cypress/deployed-and-local/integration/documentQC/complete-docket-qc.cy.ts @@ -1,4 +1,4 @@ -import { ROLES } from '../../../../shared/src/business/entities/EntityConstants'; +/* eslint-disable promise/no-nesting */ import { assertExists, retry } from '../../../helpers/retry'; import { goToCase } from '../../../helpers/caseDetail/go-to-case'; import { @@ -10,29 +10,10 @@ import { petitionsClerkServesPetition } from '../../../helpers/documentQC/petiti import { uploadFile } from '../../../helpers/file/upload-file'; describe('Document QC Complete', () => { - let CASE_SERVICE_SUPERVISOR_INFO: { userId: string; name: string } = - undefined as unknown as { userId: string; name: string }; - let DOCKET_CLERK_INFO: { userId: string; name: string } = - undefined as unknown as { userId: string; name: string }; - const docketSectionMessage = 'To CSS under Docket Section'; const petitionsSectionMessage = 'To CSS under Petitions Section'; before(() => { - cy.intercept('GET', '**/users', req => { - req.on('before:response', res => { - if (res.body.role === ROLES.caseServicesSupervisor) { - CASE_SERVICE_SUPERVISOR_INFO = res.body; - } - if (res.body.role === ROLES.docketClerk) { - DOCKET_CLERK_INFO = res.body; - } - }); - }); - - cy.login('caseServicesSupervisor1'); - cy.login('docketclerk1'); - loginAsPetitioner(); petitionerCreatesElectronicCase().then(docketNumber => { cy.wrap(docketNumber).as('DOCKET_NUMBER'); @@ -54,18 +35,22 @@ describe('Document QC Complete', () => { cy.get('@DOCKET_NUMBER').then(docketNumber => { loginAsAdmissionsClerk(); goToCase(docketNumber); + cy.task<{ userId: string; name: string; email: string; role: string }>( + 'getUserByEmail', + 'caseServicesSupervisor1@example.com', + ).then(caseServiceSupervisorInfo => { + sendMessages( + caseServiceSupervisorInfo.userId, + docketSectionMessage, + 'docket', + ); - sendMessages( - CASE_SERVICE_SUPERVISOR_INFO.userId, - docketSectionMessage, - 'docket', - ); - - sendMessages( - CASE_SERVICE_SUPERVISOR_INFO.userId, - petitionsSectionMessage, - 'petitions', - ); + sendMessages( + caseServiceSupervisorInfo.userId, + petitionsSectionMessage, + 'petitions', + ); + }); retry(() => { cy.login('caseServicesSupervisor1', '/messages/my/inbox'); @@ -125,42 +110,49 @@ describe('Document QC Complete', () => { cy.get(`[data-testid="work-item-${docketNumber}"]`) .find('[data-testid="checkbox-assign-work-item"]') .click(); - - cy.get('[data-testid="dropdown-select-assignee"]').select( - DOCKET_CLERK_INFO.name, - ); - - retry(() => { - cy.login( - 'caseServicesSupervisor1', - '/document-qc/section/inbox/selectedSection?section=docket', + cy.task<{ userId: string; name: string; email: string; role: string }>( + 'getUserByEmail', + 'docketclerk1@example.com', + ).then(docketClerkInfo => { + cy.get('[data-testid="dropdown-select-assignee"]').select( + docketClerkInfo.name, ); - cy.get('table.usa-table'); - return cy.get('body').then(body => { - const workItem = body.find( - `[data-testid="work-item-${docketNumber}"]`, - ); - const assigneeName = workItem.find( - '[data-testid="table-column-work-item-assigned-to"]', + + retry(() => { + cy.login( + 'caseServicesSupervisor1', + '/document-qc/section/inbox/selectedSection?section=docket', ); - const text = assigneeName.text(); - return cy.wrap(text.includes(DOCKET_CLERK_INFO.name)); + cy.get('table.usa-table'); + return cy.get('body').then(body => { + const workItem = body.find( + `[data-testid="work-item-${docketNumber}"]`, + ); + const assigneeName = workItem.find( + '[data-testid="table-column-work-item-assigned-to"]', + ); + const text = assigneeName.text(); + return cy.wrap(text.includes(docketClerkInfo.name)); + }); }); - }); - cy.get(`[data-testid="work-item-${docketNumber}"]`) - .find('.message-document-title') - .find('a') - .click(); + cy.get(`[data-testid="work-item-${docketNumber}"]`) + .find('.message-document-title') + .find('a') + .click(); - cy.get('#save-and-finish').click(); + cy.get('#save-and-finish').click(); - cy.get('[data-testid="success-alert"]').should('contain', 'QC Completed'); + cy.get('[data-testid="success-alert"]').should( + 'contain', + 'QC Completed', + ); - cy.visit('/document-qc/my/outbox'); - cy.get(`[data-testid="section-work-item-outbox-${docketNumber}"]`).should( - 'exist', - ); + cy.visit('/document-qc/my/outbox'); + cy.get( + `[data-testid="section-work-item-outbox-${docketNumber}"]`, + ).should('exist'); + }); }); }); @@ -181,9 +173,14 @@ describe('Document QC Complete', () => { .find('[data-testid="checkbox-assign-work-item"]') .click(); - cy.get('[data-testid="dropdown-select-assignee"]').select( - CASE_SERVICE_SUPERVISOR_INFO.name, - ); + cy.task<{ userId: string; name: string; email: string; role: string }>( + 'getUserByEmail', + 'caseServicesSupervisor1@example.com', + ).then(caseServiceSupervisorInfo => { + cy.get('[data-testid="dropdown-select-assignee"]').select( + caseServiceSupervisorInfo.name, + ); + }); cy.visit('/document-qc/my/inbox'); cy.get( diff --git a/cypress/deployed-and-local/integration/irsSuperUser/irs-super-user-can-download-stin.cy.ts b/cypress/deployed-and-local/integration/irsSuperUser/irs-super-user-can-download-stin.cy.ts index ea84c9f723e..25d97f6ae1c 100644 --- a/cypress/deployed-and-local/integration/irsSuperUser/irs-super-user-can-download-stin.cy.ts +++ b/cypress/deployed-and-local/integration/irsSuperUser/irs-super-user-can-download-stin.cy.ts @@ -3,6 +3,7 @@ import { getCypressEnv } from '../../../helpers/env/cypressEnvironment'; import { loginAsPetitioner } from '../../../helpers/authentication/login-as-helpers'; import { petitionerCreatesElectronicCase } from '../../../helpers/fileAPetition/petitioner-creates-electronic-case'; import { petitionsClerkQcsAndServesElectronicCase } from '../../../helpers/documentQC/petitions-clerk-qcs-and-serves-electronic-case'; +import { v4 } from 'uuid'; if (!Cypress.env('SMOKETESTS_LOCAL')) { describe('irs superuser integration', () => { @@ -20,9 +21,11 @@ if (!Cypress.env('SMOKETESTS_LOCAL')) { it('should let an irs superuser view the reconciliation report and download a STIN', () => { cy.task('createAccount', { - irsEnv: true, + isIrsEnv: true, + name: 'irsSuperUser CI/CD', password, role: ROLES.irsSuperuser, + userId: v4(), userName, }); diff --git a/cypress/helpers/authentication/login-as-helpers.ts b/cypress/helpers/authentication/login-as-helpers.ts index e0175319390..7db3a4c8848 100644 --- a/cypress/helpers/authentication/login-as-helpers.ts +++ b/cypress/helpers/authentication/login-as-helpers.ts @@ -1,3 +1,5 @@ +import { getCypressEnv } from '../env/cypressEnvironment'; + export function loginAsTestAdmissionsClerk() { cy.login('testAdmissionsClerk'); cy.get('#inbox-tab-content').should('exist'); @@ -35,8 +37,6 @@ export function loginAsPrivatePractitioner( cy.login(practitionerUser); cy.get('[data-testid="file-a-petition"]').should('exist'); cy.get('[data-testid="search-for-a-case-card"]').should('exist'); - cy.get('[data-testid="open-cases-count"]').contains('Open Cases'); - cy.get('[data-testid="closed-cases-count"]').contains('Closed Cases'); } export function loginAsIrsPractitioner( @@ -59,7 +59,11 @@ export function loginAsIrsPractitioner1() { } export function loginAsPetitioner( - petitionerUser: 'petitioner' | 'petitioner1' | 'petitioner7' = 'petitioner1', + petitionerUser: + | 'petitioner' + | 'petitioner1' + | 'petitioner2' + | 'petitioner7' = 'petitioner1', ) { cy.login(petitionerUser); cy.get('[data-testid="file-a-petition"]').should('exist'); @@ -76,7 +80,7 @@ export function loginAsPetitionsClerk() { } export function loginAsPetitionsClerk1() { - cy.login('petitionsclerk1'); + login({ email: 'petitionsclerk1@example.com' }); cy.get('[data-testid="inbox-tab-content"]').should('exist'); } @@ -119,3 +123,25 @@ export function loginAsIrsSuperUser() { cy.login('irssuperuser'); cy.get('[data-testid="advanced-search-link"]').should('exist'); } + +// We created this new login function because our current login function was too generically +// waiting for the account menu button, resulting in visiting a route before the page was fully loaded. +// We need to deprecate usage of cy.login and have all tests login through helper functions so we properly await +function login({ email }: { email: string }) { + cy.clearAllCookies(); + cy.visit('/login'); + cy.get('[data-testid="email-input"]').type(email); + cy.get('[data-testid="password-input"]').type( + getCypressEnv().defaultAccountPass, + ); + cy.get('[data-testid="login-button"]').click(); + cy.window().then(win => + win.localStorage.setItem('__cypressOrderInSameTab', 'true'), + ); + cy.intercept('GET', 'https://**/dynamsoft.webtwain.initiate.js', { + body: `window.Dynamsoft = {DWT: { + GetWebTwain() {} + }}`, + statusCode: 200, + }); +} diff --git a/cypress/helpers/cypressTasks/cognito/cognito-helpers.ts b/cypress/helpers/cypressTasks/cognito/cognito-helpers.ts index 257a317ee36..215726dc546 100644 --- a/cypress/helpers/cypressTasks/cognito/cognito-helpers.ts +++ b/cypress/helpers/cypressTasks/cognito/cognito-helpers.ts @@ -52,9 +52,9 @@ const getClientId = async (userPoolId: string): Promise => { return clientId; }; -export const getCognitoUserIdByEmail = async ( +export const getUserByEmail = async ( email: string, -): Promise => { +): Promise<{ role: string; name: string; userId: string; email: string }> => { const userPoolId = await getUserPoolId(); const foundUser = await getCognito().adminGetUser({ UserPoolId: userPoolId, @@ -65,7 +65,24 @@ export const getCognitoUserIdByEmail = async ( element => element.Name === 'custom:userId', )?.Value!; - return userId; + const name = foundUser.UserAttributes?.find( + element => element.Name === 'name' || element.Name === 'custom:name', // custom:name is only used locally for cognito-local + )?.Value!; + + const userEmail = foundUser.UserAttributes?.find( + element => element.Name === 'email', + )?.Value!; + + const role = foundUser.UserAttributes?.find( + element => element.Name === 'custom:role', + )?.Value!; + + return { + email: userEmail, + name, + role, + userId, + }; }; const getUserPoolId = async (isIrsEnv = false): Promise => { @@ -88,19 +105,31 @@ const getUserPoolId = async (isIrsEnv = false): Promise => { export const createAccount = async ({ isIrsEnv, + name, password, role, + userId, userName, }: { userName: string; password: string; role: string; isIrsEnv: boolean; + name: string; + userId: string; }): Promise => { const userPoolId = await getUserPoolId(isIrsEnv); await getCognito().adminCreateUser({ TemporaryPassword: password, UserAttributes: [ + { + Name: 'name', + Value: name, + }, + { + Name: 'custom:userId', + Value: userId, + }, { Name: 'custom:role', Value: role, diff --git a/cypress/helpers/cypressTasks/dynamo/dynamo-helpers.ts b/cypress/helpers/cypressTasks/dynamo/dynamo-helpers.ts index c8176092544..b887201e996 100644 --- a/cypress/helpers/cypressTasks/dynamo/dynamo-helpers.ts +++ b/cypress/helpers/cypressTasks/dynamo/dynamo-helpers.ts @@ -1,6 +1,6 @@ -import { getCognitoUserIdByEmail } from '../cognito/cognito-helpers'; import { getCypressEnv } from '../../env/cypressEnvironment'; import { getDocumentClient } from './getDynamoCypress'; +import { getUserByEmail } from '../cognito/cognito-helpers'; export const getUserConfirmationCodeFromDynamo = async ( userId: string, @@ -21,7 +21,7 @@ export const getNewAccountVerificationCode = async ({ userId: string | undefined; confirmationCode: string | undefined; }> => { - const userId = await getCognitoUserIdByEmail(email); + const { userId } = await getUserByEmail(email); if (!userId) return { confirmationCode: undefined, @@ -39,7 +39,7 @@ export const getNewAccountVerificationCode = async ({ export const expireUserConfirmationCode = async ( email: string, ): Promise => { - const userId = await getCognitoUserIdByEmail(email); + const { userId } = await getUserByEmail(email); if (!userId) return null; await getDocumentClient() @@ -99,7 +99,7 @@ export const getEmailVerificationToken = async ({ }: { email: string; }): Promise => { - const userId = await getCognitoUserIdByEmail(email); + const { userId } = await getUserByEmail(email); const result = await getDocumentClient().get({ Key: { pk: `user|${userId}`, diff --git a/cypress/helpers/cypressTasks/wait-for-practitioner-email-update.ts b/cypress/helpers/cypressTasks/wait-for-practitioner-email-update.ts index 2c7c50bef4b..add62bd31c6 100644 --- a/cypress/helpers/cypressTasks/wait-for-practitioner-email-update.ts +++ b/cypress/helpers/cypressTasks/wait-for-practitioner-email-update.ts @@ -1,6 +1,6 @@ -import { getCognitoUserIdByEmail } from './cognito/cognito-helpers'; import { getCypressEnv } from '../env/cypressEnvironment'; import { getDocumentClient } from './dynamo/getDynamoCypress'; +import { getUserByEmail } from './cognito/cognito-helpers'; export async function waitForPractitionerEmailUpdate({ attempts = 0, @@ -12,11 +12,11 @@ export async function waitForPractitionerEmailUpdate({ attempts?: number; }): Promise { const maxAttempts = 10; - const practitionerUserId = await getCognitoUserIdByEmail(practitionerEmail); + const { userId } = await getUserByEmail(practitionerEmail); const result = await getDocumentClient().get({ Key: { pk: `case|${docketNumber}`, - sk: `privatePractitioner|${practitionerUserId}`, + sk: `privatePractitioner|${userId}`, }, TableName: getCypressEnv().dynamoDbTableName, }); diff --git a/cypress/helpers/fileAPetition/create-and-serve-paper-petition.ts b/cypress/helpers/fileAPetition/create-and-serve-paper-petition.ts index 1f71df09beb..9780a655748 100644 --- a/cypress/helpers/fileAPetition/create-and-serve-paper-petition.ts +++ b/cypress/helpers/fileAPetition/create-and-serve-paper-petition.ts @@ -1,8 +1,10 @@ +import { loginAsPetitionsClerk1 } from '../authentication/login-as-helpers'; + export function createAndServePaperPetition( options = { yearReceived: '2020' }, ) { const name = 'rick james ' + Date.now(); - cy.login('petitionsclerk1'); + loginAsPetitionsClerk1(); cy.get('[data-testid="inbox-tab-content"]').should('exist'); cy.get('[data-testid="document-qc-nav-item"]').click(); cy.get('[data-testid="start-a-petition"]').click(); diff --git a/cypress/local-only/tests/accessibility/customCaseReport/docket-clerk.cy.ts b/cypress/local-only/tests/accessibility/customCaseReport/docket-clerk.cy.ts index 800ef6d1722..1a092b5a739 100644 --- a/cypress/local-only/tests/accessibility/customCaseReport/docket-clerk.cy.ts +++ b/cypress/local-only/tests/accessibility/customCaseReport/docket-clerk.cy.ts @@ -24,7 +24,6 @@ describe('Custom Case Report - Docket Clerk Accessibility', () => { { includedImpacts: impactLevel, retries: 3, - rules: { listitem: { enabled: false } }, // https://github.com/flexion/ef-cms/issues/10397 }, terminalLog, ); diff --git a/cypress/local-only/tests/integration/caseDetail/docketRecord/electronicFiling/logged-in-user-can-see-un-served-petition-document.cy.ts b/cypress/local-only/tests/integration/caseDetail/docketRecord/electronicFiling/logged-in-user-can-see-un-served-petition-document.cy.ts index 6fd23258bc2..82f7e668dcb 100644 --- a/cypress/local-only/tests/integration/caseDetail/docketRecord/electronicFiling/logged-in-user-can-see-un-served-petition-document.cy.ts +++ b/cypress/local-only/tests/integration/caseDetail/docketRecord/electronicFiling/logged-in-user-can-see-un-served-petition-document.cy.ts @@ -1,5 +1,6 @@ import { externalUserSearchesDocketNumber } from '../../../../../../helpers/advancedSearch/external-user-searches-docket-number'; import { + loginAsDocketClerk1, loginAsPetitioner, loginAsPrivatePractitioner, } from '../../../../../../helpers/authentication/login-as-helpers'; @@ -13,7 +14,7 @@ describe('Logged In User Can See Un-Served Petition Document', () => { loginAsPetitioner(); petitionerCreatesElectronicCaseForBusiness().as('DOCKET_NUMBER'); - cy.login('petitioner1'); + loginAsPetitioner('petitioner1'); cy.get('@DOCKET_NUMBER').then(docketNumber => { externalUserSearchesDocketNumber(docketNumber); }); @@ -23,7 +24,7 @@ describe('Logged In User Can See Un-Served Petition Document', () => { cy.get('[data-testid="document-download-link-DISC"]').should('exist'); cy.get('[data-testid="document-download-link-ATP"]').should('exist'); - cy.login('petitioner2'); + loginAsPetitioner('petitioner2'); cy.get('@DOCKET_NUMBER').then(docketNumber => { externalUserSearchesDocketNumber(docketNumber); }); @@ -33,7 +34,7 @@ describe('Logged In User Can See Un-Served Petition Document', () => { cy.get('[data-testid="document-download-link-DISC"]').should('not.exist'); cy.get('[data-testid="document-download-link-ATP"]').should('not.exist'); - cy.login('docketClerk1'); + loginAsDocketClerk1(); cy.get('@DOCKET_NUMBER').then(docketNumber => { cy.get('[data-testid="docket-number-search-input"]').type(docketNumber); cy.get('[data-testid="search-docket-number"]').click(); @@ -49,7 +50,7 @@ describe('Logged In User Can See Un-Served Petition Document', () => { loginAsPrivatePractitioner(); privatePractitionerCreatesElectronicCaseForBusiness().as('DOCKET_NUMBER'); - cy.login('privatePractitioner1'); + loginAsPrivatePractitioner('privatePractitioner1'); cy.get('@DOCKET_NUMBER').then(docketNumber => { externalUserSearchesDocketNumber(docketNumber); }); @@ -59,7 +60,7 @@ describe('Logged In User Can See Un-Served Petition Document', () => { cy.get('[data-testid="document-download-link-DISC"]').should('exist'); cy.get('[data-testid="document-download-link-ATP"]').should('exist'); - cy.login('privatePractitioner2'); + loginAsPrivatePractitioner('privatePractitioner2'); cy.get('@DOCKET_NUMBER').then(docketNumber => { externalUserSearchesDocketNumber(docketNumber); }); @@ -69,7 +70,7 @@ describe('Logged In User Can See Un-Served Petition Document', () => { cy.get('[data-testid="document-download-link-DISC"]').should('not.exist'); cy.get('[data-testid="document-download-link-ATP"]').should('not.exist'); - cy.login('docketClerk1'); + loginAsDocketClerk1(); cy.get('@DOCKET_NUMBER').then(docketNumber => { cy.get('[data-testid="docket-number-search-input"]').type(docketNumber); cy.get('[data-testid="search-docket-number"]').click(); diff --git a/docs/entity-locking.md b/docs/entity-locking.md index 2d52f8eff08..2e0a1db0d83 100644 --- a/docs/entity-locking.md +++ b/docs/entity-locking.md @@ -135,18 +135,19 @@ You may wish for a function to be called if you fail to acquire a lock. One use const handleLockError = async ( applicationContext: IApplicationContext, originalRequest: any, + authorizedUser: UnknownAuthUser ) => { - const user = applicationContext.getCurrentUser(); - - await applicationContext.getNotificationGateway().sendNotificationToUser({ - applicationContext, - message: { - action: 'retry_async_request', - originalRequest, - requestToRetry: 'update_something', - }, - userId: user.userId, - }); + if(authorizedUser?.userId) { + await applicationContext.getNotificationGateway().sendNotificationToUser({ + applicationContext, + message: { + action: 'retry_async_request', + originalRequest, + requestToRetry: 'update_something', + }, + userId: user.userId, + }); + } }; ``` diff --git a/package-lock.json b/package-lock.json index 8fa06925868..d56e78d775c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,35 +12,35 @@ "dependencies": { "@18f/us-federal-holidays": "4.0.0", "@aws-crypto/sha256-browser": "5.2.0", - "@aws-sdk/client-api-gateway": "3.632.0", - "@aws-sdk/client-apigatewaymanagementapi": "3.632.0", - "@aws-sdk/client-apigatewayv2": "3.632.0", - "@aws-sdk/client-cloudfront": "3.632.0", - "@aws-sdk/client-cloudwatch": "3.632.0", - "@aws-sdk/client-cloudwatch-logs": "3.632.0", - "@aws-sdk/client-cognito-identity-provider": "3.632.0", - "@aws-sdk/client-dynamodb": "3.632.0", - "@aws-sdk/client-dynamodb-streams": "3.632.0", - "@aws-sdk/client-glue": "3.632.0", - "@aws-sdk/client-lambda": "3.632.0", - "@aws-sdk/client-opensearch": "3.632.0", - "@aws-sdk/client-route-53": "3.632.0", - "@aws-sdk/client-s3": "3.633.0", - "@aws-sdk/client-ses": "3.632.0", - "@aws-sdk/client-sns": "3.632.0", - "@aws-sdk/client-sqs": "3.632.0", - "@aws-sdk/client-ssm": "3.632.0", + "@aws-sdk/client-api-gateway": "3.637.0", + "@aws-sdk/client-apigatewaymanagementapi": "3.637.0", + "@aws-sdk/client-apigatewayv2": "3.637.0", + "@aws-sdk/client-cloudfront": "3.637.0", + "@aws-sdk/client-cloudwatch": "3.637.0", + "@aws-sdk/client-cloudwatch-logs": "3.637.0", + "@aws-sdk/client-cognito-identity-provider": "3.637.0", + "@aws-sdk/client-dynamodb": "3.637.0", + "@aws-sdk/client-dynamodb-streams": "3.637.0", + "@aws-sdk/client-glue": "3.637.0", + "@aws-sdk/client-lambda": "3.637.0", + "@aws-sdk/client-opensearch": "3.637.0", + "@aws-sdk/client-route-53": "3.637.0", + "@aws-sdk/client-s3": "3.637.0", + "@aws-sdk/client-ses": "3.637.0", + "@aws-sdk/client-sns": "3.637.0", + "@aws-sdk/client-sqs": "3.637.0", + "@aws-sdk/client-ssm": "3.637.0", "@aws-sdk/cloudfront-signer": "3.621.0", - "@aws-sdk/credential-provider-node": "3.632.0", - "@aws-sdk/lib-dynamodb": "3.632.0", - "@aws-sdk/lib-storage": "3.633.0", + "@aws-sdk/credential-provider-node": "3.637.0", + "@aws-sdk/lib-dynamodb": "3.637.0", + "@aws-sdk/lib-storage": "3.637.0", "@aws-sdk/node-http-handler": "3.374.0", "@aws-sdk/protocol-http": "3.374.0", "@aws-sdk/rds-signer": "^3.637.0", - "@aws-sdk/s3-presigned-post": "3.633.0", - "@aws-sdk/s3-request-presigner": "3.633.0", + "@aws-sdk/s3-presigned-post": "3.637.0", + "@aws-sdk/s3-request-presigner": "3.637.0", "@aws-sdk/signature-v4": "3.374.0", - "@aws-sdk/util-dynamodb": "3.632.0", + "@aws-sdk/util-dynamodb": "3.637.0", "@cerebral/react": "4.2.1", "@fortawesome/fontawesome-svg-core": "1.2.36", "@fortawesome/free-regular-svg-icons": "5.15.4", @@ -52,13 +52,13 @@ "@uswds/uswds": "3.7.1", "aws-lambda": "1.0.7", "aws-xray-sdk": "3.9.0", - "axios": "1.7.4", + "axios": "1.7.5", "broadcast-channel": "7.0.0", "canvas": "2.11.2", "cerebral": "5.2.1", "classnames": "2.5.1", "cookie": "0.6.0", - "core-js": "3.38.0", + "core-js": "3.38.1", "cors": "2.8.5", "csv-stringify": "6.5.1", "deep-freeze": "0.0.1", @@ -90,7 +90,6 @@ "react-dom": "18.3.1", "react-idle-timer": "5.7.2", "react-number-format": "5.4.0", - "react-paginate": "8.2.0", "react-quill": "2.0.0", "react-responsive": "10.0.0", "react-select": "5.8.0", @@ -106,12 +105,12 @@ "winston": "3.14.2" }, "devDependencies": { - "@aws-sdk/client-iam": "3.632.0", - "@aws-sdk/client-secrets-manager": "3.632.0", + "@aws-sdk/client-iam": "3.637.0", + "@aws-sdk/client-secrets-manager": "3.637.0", "@babel/cli": "7.24.8", "@babel/core": "7.25.2", "@babel/eslint-parser": "7.25.1", - "@babel/preset-env": "7.25.3", + "@babel/preset-env": "7.25.4", "@babel/preset-react": "7.24.7", "@babel/preset-typescript": "7.24.7", "@babel/register": "7.24.6", @@ -122,19 +121,18 @@ "@types/jest": "29.5.12", "@types/lodash": "4.17.7", "@types/luxon": "3.4.2", - "@types/node": "22.4.0", + "@types/node": "22.5.0", "@types/promise-retry": "1.1.6", - "@types/react": "18.3.3", + "@types/react": "18.3.4", "@types/react-dom": "18.3.0", - "@types/react-paginate": "7.1.4", "@types/uuid": "10.0.0", "@types/websocket": "1.0.10", - "@typescript-eslint/eslint-plugin": "8.1.0", - "@typescript-eslint/parser": "8.1.0", + "@typescript-eslint/eslint-plugin": "8.2.0", + "@typescript-eslint/parser": "8.2.0", "@vendia/serverless-express": "4.12.6", "ajv": "8.17.1", - "artillery": "2.0.19", - "artillery-plugin-metrics-by-endpoint": "1.13.0", + "artillery": "2.0.20", + "artillery-plugin-metrics-by-endpoint": "1.14.0", "autoprefixer": "10.4.20", "aws-sdk-client-mock": "4.0.1", "axe-core": "4.10.0", @@ -154,7 +152,7 @@ "decimal.js": "10.4.3", "dynamodb-admin": "4.6.1", "dynamodb-streams-readable": "3.0.0", - "esbuild": "0.23.0", + "esbuild": "0.23.1", "esbuild-css-modules-plugin": "3.1.2", "esbuild-plugin-babel-cached": "0.2.3", "esbuild-plugin-clean": "1.0.1", @@ -181,7 +179,7 @@ "eslint-plugin-spellcheck": "0.0.20", "esm": "3.2.25", "file-loader": "6.2.0", - "husky": "9.1.4", + "husky": "9.1.5", "jest": "29.7.0", "jest-environment-jsdom": "29.7.0", "jest-environment-node": "29.7.0", @@ -207,7 +205,7 @@ "readline": "1.3.0", "s3rver": "github:20minutes/s3rver", "sass": "1.77.8", - "sass-loader": "16.0.0", + "sass-loader": "16.0.1", "shuffle-seed": "1.1.6", "stream-browserify": "3.0.0", "style-loader": "4.0.0", @@ -449,9 +447,9 @@ } }, "node_modules/@artilleryio/int-commons": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/@artilleryio/int-commons/-/int-commons-2.10.0.tgz", - "integrity": "sha512-CukRix3yxcsbjPTPhIyXN7qZ6f/3W+LQtF96RxuZ7L3P0F7y7t4NswPSll2+zDkAMvvBgFojgPL+bFf2EDIiOA==", + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/@artilleryio/int-commons/-/int-commons-2.11.0.tgz", + "integrity": "sha512-De713S8MG7qV3Qp1TWPLt+ivA9NHvetzdbNoNNWszLeljCP6Frp+jmXlZG3u7dISFzq/ONH0ROO17n8CEytY/g==", "dev": true, "dependencies": { "async": "^2.6.4", @@ -465,12 +463,12 @@ } }, "node_modules/@artilleryio/int-core": { - "version": "2.14.0", - "resolved": "https://registry.npmjs.org/@artilleryio/int-core/-/int-core-2.14.0.tgz", - "integrity": "sha512-u0q5p5aWE7DRNRnfmj8JzXqNFitoBKQ4/N/Uur4PXcZCPzB7yQWppRPRJqFUh14zmC/UybDMui1EnbDhBqGGIg==", + "version": "2.15.0", + "resolved": "https://registry.npmjs.org/@artilleryio/int-core/-/int-core-2.15.0.tgz", + "integrity": "sha512-C2EP+6PrU/PoBDDgr0hyIFlC1OGmvjgs5HMuUEJyyIVfm1eN1BeSRlQ5q3SG/baxz7IySO1WaGZ9FX/KefBofQ==", "dev": true, "dependencies": { - "@artilleryio/int-commons": "2.10.0", + "@artilleryio/int-commons": "2.11.0", "@artilleryio/sketches-js": "^2.1.1", "agentkeepalive": "^4.1.0", "arrivals": "^2.1.2", @@ -811,47 +809,47 @@ } }, "node_modules/@aws-sdk/client-api-gateway": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-api-gateway/-/client-api-gateway-3.632.0.tgz", - "integrity": "sha512-bO9JQHLXWYiAZ32kwzCcxjtslegucEnb9Oi3B5NpknrbqTkAmUFDnD9vFyAnEovorfnZAOOO9Xlr+pyNDP+iNQ==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-api-gateway/-/client-api-gateway-3.637.0.tgz", + "integrity": "sha512-jAdpZj8siCmut2P7rVLZASUmBOQbY2AB7hIlVmlpoZ9TC2mGYMaXbK/swegWS7nf5LyO6xrgcl/463TtR3IbrA==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", "@aws-sdk/middleware-sdk-api-gateway": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -876,46 +874,46 @@ } }, "node_modules/@aws-sdk/client-apigatewaymanagementapi": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-apigatewaymanagementapi/-/client-apigatewaymanagementapi-3.632.0.tgz", - "integrity": "sha512-1R/17iZBBlc7QqfBUyNWWYANDJz0K5wNVHYnqmjZKYyo7eGr9/GV4Qo9uFtjcmGdlTi3B2zmti/7rSyVIjxymw==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-apigatewaymanagementapi/-/client-apigatewaymanagementapi-3.637.0.tgz", + "integrity": "sha512-MN3b4T4icjfCxNi9iPh3ERsKBzEu4ua3Hoj65MX7hVrnsaPebjZXGw7YAJPe/ugV4SKPyrGAyuno0LLaoFw55g==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -939,46 +937,46 @@ } }, "node_modules/@aws-sdk/client-apigatewayv2": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-apigatewayv2/-/client-apigatewayv2-3.632.0.tgz", - "integrity": "sha512-yl/BjrYV2b4gnwbCL+moYVTRLWYja2VCESyWOnW98rNK95wwjb/t/CNWfidi40Lhg37IdIyMmY7g18mkKk/8/w==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-apigatewayv2/-/client-apigatewayv2-3.637.0.tgz", + "integrity": "sha512-mnqulbdo5t8W9ScFzfsLL5RPE96iSHWB+eAoIllztu+oW1HrRY4w/HcKqEz+5hK4FS+CPaH08ZwCAxVkRJ9biA==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -1003,219 +1001,9 @@ } }, "node_modules/@aws-sdk/client-cloudfront": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-cloudfront/-/client-cloudfront-3.632.0.tgz", - "integrity": "sha512-xCjfX83ySDomnT0Lr5dNo1kwM6SrtNuTWFd7BJb7FeqMeUyjwI/9/zbrXY6eNZAzwSSxNVrJSYHkCioe+Rfwxw==", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", - "@aws-sdk/middleware-host-header": "3.620.0", - "@aws-sdk/middleware-logger": "3.609.0", - "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", - "@aws-sdk/region-config-resolver": "3.614.0", - "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", - "@aws-sdk/util-user-agent-browser": "3.609.0", - "@aws-sdk/util-user-agent-node": "3.614.0", - "@aws-sdk/xml-builder": "3.609.0", - "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", - "@smithy/fetch-http-handler": "^3.2.4", - "@smithy/hash-node": "^3.0.3", - "@smithy/invalid-dependency": "^3.0.3", - "@smithy/middleware-content-length": "^3.0.5", - "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", - "@smithy/middleware-serde": "^3.0.3", - "@smithy/middleware-stack": "^3.0.3", - "@smithy/node-config-provider": "^3.1.4", - "@smithy/node-http-handler": "^3.1.4", - "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", - "@smithy/types": "^3.3.0", - "@smithy/url-parser": "^3.0.3", - "@smithy/util-base64": "^3.0.0", - "@smithy/util-body-length-browser": "^3.0.0", - "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", - "@smithy/util-endpoints": "^2.0.5", - "@smithy/util-middleware": "^3.0.3", - "@smithy/util-retry": "^3.0.3", - "@smithy/util-stream": "^3.1.3", - "@smithy/util-utf8": "^3.0.0", - "@smithy/util-waiter": "^3.1.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-sdk/client-cloudfront/node_modules/@smithy/util-utf8": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-3.0.0.tgz", - "integrity": "sha512-rUeT12bxFnplYDe815GXbq/oixEGHfRFFtcTF3YdDi/JaENIM6aSYYLJydG83UNzLXeRI5K8abYd/8Sp/QM0kA==", - "dependencies": { - "@smithy/util-buffer-from": "^3.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-sdk/client-cloudwatch": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-cloudwatch/-/client-cloudwatch-3.632.0.tgz", - "integrity": "sha512-RIItCf874T8aiE17yikJ6VcARvRv/sn86WMpyJCN0+aUMSOB8X86OHe7KCUN72EkvFKeWXim808RPpS8fZLXKw==", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", - "@aws-sdk/middleware-host-header": "3.620.0", - "@aws-sdk/middleware-logger": "3.609.0", - "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", - "@aws-sdk/region-config-resolver": "3.614.0", - "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", - "@aws-sdk/util-user-agent-browser": "3.609.0", - "@aws-sdk/util-user-agent-node": "3.614.0", - "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", - "@smithy/fetch-http-handler": "^3.2.4", - "@smithy/hash-node": "^3.0.3", - "@smithy/invalid-dependency": "^3.0.3", - "@smithy/middleware-compression": "^3.0.7", - "@smithy/middleware-content-length": "^3.0.5", - "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", - "@smithy/middleware-serde": "^3.0.3", - "@smithy/middleware-stack": "^3.0.3", - "@smithy/node-config-provider": "^3.1.4", - "@smithy/node-http-handler": "^3.1.4", - "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", - "@smithy/types": "^3.3.0", - "@smithy/url-parser": "^3.0.3", - "@smithy/util-base64": "^3.0.0", - "@smithy/util-body-length-browser": "^3.0.0", - "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", - "@smithy/util-endpoints": "^2.0.5", - "@smithy/util-middleware": "^3.0.3", - "@smithy/util-retry": "^3.0.3", - "@smithy/util-utf8": "^3.0.0", - "@smithy/util-waiter": "^3.1.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-sdk/client-cloudwatch-logs": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-cloudwatch-logs/-/client-cloudwatch-logs-3.632.0.tgz", - "integrity": "sha512-QrG04Ss2/KDsvGmoBH9QHjaC/wx7Gf9U2F5o8gYbHVU5ZGDW+zMX2Sj/6jjSyZ4qLD4sxK7sRHwK+fYA21OQQA==", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", - "@aws-sdk/middleware-host-header": "3.620.0", - "@aws-sdk/middleware-logger": "3.609.0", - "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", - "@aws-sdk/region-config-resolver": "3.614.0", - "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", - "@aws-sdk/util-user-agent-browser": "3.609.0", - "@aws-sdk/util-user-agent-node": "3.614.0", - "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", - "@smithy/eventstream-serde-browser": "^3.0.6", - "@smithy/eventstream-serde-config-resolver": "^3.0.3", - "@smithy/eventstream-serde-node": "^3.0.5", - "@smithy/fetch-http-handler": "^3.2.4", - "@smithy/hash-node": "^3.0.3", - "@smithy/invalid-dependency": "^3.0.3", - "@smithy/middleware-content-length": "^3.0.5", - "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", - "@smithy/middleware-serde": "^3.0.3", - "@smithy/middleware-stack": "^3.0.3", - "@smithy/node-config-provider": "^3.1.4", - "@smithy/node-http-handler": "^3.1.4", - "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", - "@smithy/types": "^3.3.0", - "@smithy/url-parser": "^3.0.3", - "@smithy/util-base64": "^3.0.0", - "@smithy/util-body-length-browser": "^3.0.0", - "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", - "@smithy/util-endpoints": "^2.0.5", - "@smithy/util-middleware": "^3.0.3", - "@smithy/util-retry": "^3.0.3", - "@smithy/util-utf8": "^3.0.0", - "tslib": "^2.6.2", - "uuid": "^9.0.1" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-sdk/client-cloudwatch-logs/node_modules/@smithy/util-utf8": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-3.0.0.tgz", - "integrity": "sha512-rUeT12bxFnplYDe815GXbq/oixEGHfRFFtcTF3YdDi/JaENIM6aSYYLJydG83UNzLXeRI5K8abYd/8Sp/QM0kA==", - "dependencies": { - "@smithy/util-buffer-from": "^3.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-sdk/client-cloudwatch-logs/node_modules/uuid": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", - "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", - "funding": [ - "https://github.com/sponsors/broofa", - "https://github.com/sponsors/ctavan" - ], - "bin": { - "uuid": "dist/bin/uuid" - } - }, - "node_modules/@aws-sdk/client-cloudwatch/node_modules/@smithy/util-utf8": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-3.0.0.tgz", - "integrity": "sha512-rUeT12bxFnplYDe815GXbq/oixEGHfRFFtcTF3YdDi/JaENIM6aSYYLJydG83UNzLXeRI5K8abYd/8Sp/QM0kA==", - "dependencies": { - "@smithy/util-buffer-from": "^3.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-sdk/client-cognito-identity": { "version": "3.637.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-cognito-identity/-/client-cognito-identity-3.637.0.tgz", - "integrity": "sha512-391mca6yEfXVcSOTLGcxzlT0QCFfvoymLlVHfb//bzl806UUTq12cR2k+AnaCKLj+QSejmA7n6lwZWADm00Fvg==", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-cloudfront/-/client-cloudfront-3.637.0.tgz", + "integrity": "sha512-yuKqFTRlRHAA5mVds/ufO8n6ENcCFAW0D6nXldQcMOCXIuz1UQRE5qyEwajIdDGtFnyeZVf5fWRMx3ylWC7h0Q==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", @@ -1232,6 +1020,7 @@ "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", + "@aws-sdk/xml-builder": "3.609.0", "@smithy/config-resolver": "^3.0.5", "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", @@ -1256,65 +1045,16 @@ "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", + "@smithy/util-stream": "^3.1.3", "@smithy/util-utf8": "^3.0.0", + "@smithy/util-waiter": "^3.1.2", "tslib": "^2.6.2" }, "engines": { "node": ">=16.0.0" } }, - "node_modules/@aws-sdk/client-cognito-identity-provider": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-cognito-identity-provider/-/client-cognito-identity-provider-3.632.0.tgz", - "integrity": "sha512-RP9L/LKu3qwXT6z+eq8tjOb4kpT2JiQYi483pVg85jf1PiIB+aoPA0Dbre7f+b7Wpo3FyPIlFqKuHzqhPWZvfQ==", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", - "@aws-sdk/middleware-host-header": "3.620.0", - "@aws-sdk/middleware-logger": "3.609.0", - "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", - "@aws-sdk/region-config-resolver": "3.614.0", - "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", - "@aws-sdk/util-user-agent-browser": "3.609.0", - "@aws-sdk/util-user-agent-node": "3.614.0", - "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", - "@smithy/fetch-http-handler": "^3.2.4", - "@smithy/hash-node": "^3.0.3", - "@smithy/invalid-dependency": "^3.0.3", - "@smithy/middleware-content-length": "^3.0.5", - "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", - "@smithy/middleware-serde": "^3.0.3", - "@smithy/middleware-stack": "^3.0.3", - "@smithy/node-config-provider": "^3.1.4", - "@smithy/node-http-handler": "^3.1.4", - "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", - "@smithy/types": "^3.3.0", - "@smithy/url-parser": "^3.0.3", - "@smithy/util-base64": "^3.0.0", - "@smithy/util-body-length-browser": "^3.0.0", - "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", - "@smithy/util-endpoints": "^2.0.5", - "@smithy/util-middleware": "^3.0.3", - "@smithy/util-retry": "^3.0.3", - "@smithy/util-utf8": "^3.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-sdk/client-cognito-identity-provider/node_modules/@smithy/util-utf8": { + "node_modules/@aws-sdk/client-cloudfront/node_modules/@smithy/util-utf8": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-3.0.0.tgz", "integrity": "sha512-rUeT12bxFnplYDe815GXbq/oixEGHfRFFtcTF3YdDi/JaENIM6aSYYLJydG83UNzLXeRI5K8abYd/8Sp/QM0kA==", @@ -1326,14 +1066,17 @@ "node": ">=16.0.0" } }, - "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/client-sso": { + "node_modules/@aws-sdk/client-cloudwatch": { "version": "3.637.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.637.0.tgz", - "integrity": "sha512-+KjLvgX5yJYROWo3TQuwBJlHCY0zz9PsLuEolmXQn0BVK1L/m9GteZHtd+rEdAoDGBpE0Xqjy1oz5+SmtsaRUw==", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-cloudwatch/-/client-cloudwatch-3.637.0.tgz", + "integrity": "sha512-S6UcU3vCKOAUVLCXTabyUMWAr1e1kHn7Hcy6VZ4sxxu5hQqbSGiety3vrjmPTALlV5rmhu3N+hlRZt2TRXwDRg==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", @@ -1348,6 +1091,7 @@ "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", + "@smithy/middleware-compression": "^3.0.7", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", "@smithy/middleware-retry": "^3.0.15", @@ -1368,19 +1112,22 @@ "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", "@smithy/util-utf8": "^3.0.0", + "@smithy/util-waiter": "^3.1.2", "tslib": "^2.6.2" }, "engines": { "node": ">=16.0.0" } }, - "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/client-sso-oidc": { + "node_modules/@aws-sdk/client-cloudwatch-logs": { "version": "3.637.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso-oidc/-/client-sso-oidc-3.637.0.tgz", - "integrity": "sha512-27bHALN6Qb6m6KZmPvRieJ/QRlj1lyac/GT2Rn5kJpre8Mpp+yxrtvp3h9PjNBty4lCeFEENfY4dGNSozBuBcw==", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-cloudwatch-logs/-/client-cloudwatch-logs-3.637.0.tgz", + "integrity": "sha512-JK9BgR3zHo/3VHSMO5ovDgk95TGEiY1DnlJ1AIPl/t6i87gZojurQFlbVuwzLDMZGoFfH0FuAJTW2+sH6nzh8A==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", "@aws-sdk/core": "3.635.0", "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", @@ -1394,6 +1141,9 @@ "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", "@smithy/core": "^2.4.0", + "@smithy/eventstream-serde-browser": "^3.0.6", + "@smithy/eventstream-serde-config-resolver": "^3.0.3", + "@smithy/eventstream-serde-node": "^3.0.5", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", @@ -1417,23 +1167,58 @@ "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2", + "uuid": "^9.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/client-cloudwatch-logs/node_modules/@smithy/util-utf8": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-3.0.0.tgz", + "integrity": "sha512-rUeT12bxFnplYDe815GXbq/oixEGHfRFFtcTF3YdDi/JaENIM6aSYYLJydG83UNzLXeRI5K8abYd/8Sp/QM0kA==", + "dependencies": { + "@smithy/util-buffer-from": "^3.0.0", "tslib": "^2.6.2" }, "engines": { "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/client-cloudwatch-logs/node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/@aws-sdk/client-cloudwatch/node_modules/@smithy/util-utf8": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-3.0.0.tgz", + "integrity": "sha512-rUeT12bxFnplYDe815GXbq/oixEGHfRFFtcTF3YdDi/JaENIM6aSYYLJydG83UNzLXeRI5K8abYd/8Sp/QM0kA==", + "dependencies": { + "@smithy/util-buffer-from": "^3.0.0", + "tslib": "^2.6.2" }, - "peerDependencies": { - "@aws-sdk/client-sts": "^3.637.0" + "engines": { + "node": ">=16.0.0" } }, - "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/client-sts": { + "node_modules/@aws-sdk/client-cognito-identity": { "version": "3.637.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.637.0.tgz", - "integrity": "sha512-xUi7x4qDubtA8QREtlblPuAcn91GS/09YVEY/RwU7xCY0aqGuFwgszAANlha4OUIqva8oVj2WO4gJuG+iaSnhw==", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-cognito-identity/-/client-cognito-identity-3.637.0.tgz", + "integrity": "sha512-391mca6yEfXVcSOTLGcxzlT0QCFfvoymLlVHfb//bzl806UUTq12cR2k+AnaCKLj+QSejmA7n6lwZWADm00Fvg==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", "@aws-sdk/core": "3.635.0", "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", @@ -1476,131 +1261,63 @@ "node": ">=16.0.0" } }, - "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core": { - "version": "3.635.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.635.0.tgz", - "integrity": "sha512-i1x/E/sgA+liUE1XJ7rj1dhyXpAKO1UKFUcTTHXok2ARjWTvszHnSXMOsB77aPbmn0fUp1JTx2kHUAZ1LVt5Bg==", - "dependencies": { - "@smithy/core": "^2.4.0", - "@smithy/node-config-provider": "^3.1.4", - "@smithy/property-provider": "^3.1.3", - "@smithy/protocol-http": "^4.1.0", - "@smithy/signature-v4": "^4.1.0", - "@smithy/smithy-client": "^3.2.0", - "@smithy/types": "^3.3.0", - "@smithy/util-middleware": "^3.0.3", - "fast-xml-parser": "4.4.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-http": { - "version": "3.635.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.635.0.tgz", - "integrity": "sha512-iJyRgEjOCQlBMXqtwPLIKYc7Bsc6nqjrZybdMDenPDa+kmLg7xh8LxHsu9088e+2/wtLicE34FsJJIfzu3L82g==", + "node_modules/@aws-sdk/client-cognito-identity-provider": { + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-cognito-identity-provider/-/client-cognito-identity-provider-3.637.0.tgz", + "integrity": "sha512-udgyXL5ZQPTcXbzCq4plPxCEnYWGnC5+nWpCQAOcCACpA0rtQQ9OKabq/SiNO+6PVUMQFKRrZq6LS2p76mjl1w==", "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", + "@aws-sdk/middleware-host-header": "3.620.0", + "@aws-sdk/middleware-logger": "3.609.0", + "@aws-sdk/middleware-recursion-detection": "3.620.0", + "@aws-sdk/middleware-user-agent": "3.637.0", + "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", + "@aws-sdk/util-endpoints": "3.637.0", + "@aws-sdk/util-user-agent-browser": "3.609.0", + "@aws-sdk/util-user-agent-node": "3.614.0", + "@smithy/config-resolver": "^3.0.5", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", + "@smithy/hash-node": "^3.0.3", + "@smithy/invalid-dependency": "^3.0.3", + "@smithy/middleware-content-length": "^3.0.5", + "@smithy/middleware-endpoint": "^3.1.0", + "@smithy/middleware-retry": "^3.0.15", + "@smithy/middleware-serde": "^3.0.3", + "@smithy/middleware-stack": "^3.0.3", + "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", - "@smithy/property-provider": "^3.1.3", "@smithy/protocol-http": "^4.1.0", "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", - "@smithy/util-stream": "^3.1.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-ini": { - "version": "3.637.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.637.0.tgz", - "integrity": "sha512-h+PFCWfZ0Q3Dx84SppET/TFpcQHmxFW8/oV9ArEvMilw4EBN+IlxgbL0CnHwjHW64szcmrM0mbebjEfHf4FXmw==", - "dependencies": { - "@aws-sdk/credential-provider-env": "3.620.1", - "@aws-sdk/credential-provider-http": "3.635.0", - "@aws-sdk/credential-provider-process": "3.620.1", - "@aws-sdk/credential-provider-sso": "3.637.0", - "@aws-sdk/credential-provider-web-identity": "3.621.0", - "@aws-sdk/types": "3.609.0", - "@smithy/credential-provider-imds": "^3.2.0", - "@smithy/property-provider": "^3.1.3", - "@smithy/shared-ini-file-loader": "^3.1.4", - "@smithy/types": "^3.3.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - }, - "peerDependencies": { - "@aws-sdk/client-sts": "^3.637.0" - } - }, - "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-node": { - "version": "3.637.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.637.0.tgz", - "integrity": "sha512-yoEhoxJJfs7sPVQ6Is939BDQJZpZCoUgKr/ySse4YKOZ24t4VqgHA6+wV7rYh+7IW24Rd91UTvEzSuHYTlxlNA==", - "dependencies": { - "@aws-sdk/credential-provider-env": "3.620.1", - "@aws-sdk/credential-provider-http": "3.635.0", - "@aws-sdk/credential-provider-ini": "3.637.0", - "@aws-sdk/credential-provider-process": "3.620.1", - "@aws-sdk/credential-provider-sso": "3.637.0", - "@aws-sdk/credential-provider-web-identity": "3.621.0", - "@aws-sdk/types": "3.609.0", - "@smithy/credential-provider-imds": "^3.2.0", - "@smithy/property-provider": "^3.1.3", - "@smithy/shared-ini-file-loader": "^3.1.4", - "@smithy/types": "^3.3.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-sso": { - "version": "3.637.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.637.0.tgz", - "integrity": "sha512-Mvz+h+e62/tl+dVikLafhv+qkZJ9RUb8l2YN/LeKMWkxQylPT83CPk9aimVhCV89zth1zpREArl97+3xsfgQvA==", - "dependencies": { - "@aws-sdk/client-sso": "3.637.0", - "@aws-sdk/token-providers": "3.614.0", - "@aws-sdk/types": "3.609.0", - "@smithy/property-provider": "^3.1.3", - "@smithy/shared-ini-file-loader": "^3.1.4", - "@smithy/types": "^3.3.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-user-agent": { - "version": "3.637.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.637.0.tgz", - "integrity": "sha512-EYo0NE9/da/OY8STDsK2LvM4kNa79DBsf4YVtaG4P5pZ615IeFsD8xOHZeuJmUrSMlVQ8ywPRX7WMucUybsKug==", - "dependencies": { - "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.637.0", - "@smithy/protocol-http": "^4.1.0", - "@smithy/types": "^3.3.0", + "@smithy/url-parser": "^3.0.3", + "@smithy/util-base64": "^3.0.0", + "@smithy/util-body-length-browser": "^3.0.0", + "@smithy/util-body-length-node": "^3.0.0", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", + "@smithy/util-endpoints": "^2.0.5", + "@smithy/util-middleware": "^3.0.3", + "@smithy/util-retry": "^3.0.3", + "@smithy/util-utf8": "^3.0.0", "tslib": "^2.6.2" }, "engines": { "node": ">=16.0.0" } }, - "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints": { - "version": "3.637.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.637.0.tgz", - "integrity": "sha512-pAqOKUHeVWHEXXDIp/qoMk/6jyxIb6GGjnK1/f8dKHtKIEs4tKsnnL563gceEvdad53OPXIt86uoevCcCzmBnw==", + "node_modules/@aws-sdk/client-cognito-identity-provider/node_modules/@smithy/util-utf8": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-3.0.0.tgz", + "integrity": "sha512-rUeT12bxFnplYDe815GXbq/oixEGHfRFFtcTF3YdDi/JaENIM6aSYYLJydG83UNzLXeRI5K8abYd/8Sp/QM0kA==", "dependencies": { - "@aws-sdk/types": "3.609.0", - "@smithy/types": "^3.3.0", - "@smithy/util-endpoints": "^2.0.5", + "@smithy/util-buffer-from": "^3.0.0", "tslib": "^2.6.2" }, "engines": { @@ -1620,47 +1337,47 @@ } }, "node_modules/@aws-sdk/client-dynamodb": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-dynamodb/-/client-dynamodb-3.632.0.tgz", - "integrity": "sha512-Y7u/B/lyLdLZBrBSXjYZviyck0e3dZLL/Va6HIShNlDG8FyWuArefWr57/bu9Q8smdqpEduldprSRSWI7MPykg==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-dynamodb/-/client-dynamodb-3.637.0.tgz", + "integrity": "sha512-zUneT0yLgJjC69yry2fgYVWkv68OeV3amWaDXHirA8yJgygyc7tBLo+sQmtHczmKt8dBD9bU3OWpbAbtpF9Esw==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-endpoint-discovery": "3.620.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -1674,46 +1391,46 @@ } }, "node_modules/@aws-sdk/client-dynamodb-streams": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-dynamodb-streams/-/client-dynamodb-streams-3.632.0.tgz", - "integrity": "sha512-vy44vep7i1ZzVC/3cv11Jh3hDOxQnqz3ftXDEAJEC9t+Ltz74Z9drPdxR3DyA8//hZI3SfIMdURAaTUXBb6e1A==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-dynamodb-streams/-/client-dynamodb-streams-3.637.0.tgz", + "integrity": "sha512-WBh9Dn2Fm37SAFvWaa2or7NSuxNLJ62cFEVHX+SrKzJxhXSWYs24BoHW4XxMb6jiT0ka3GMctu//7Y1//MBU3A==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -1761,46 +1478,46 @@ } }, "node_modules/@aws-sdk/client-glue": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-glue/-/client-glue-3.632.0.tgz", - "integrity": "sha512-2UyPVHGNT/LKDmFUYxghW95fP6rCrMMhk4FgUUGnTFBOqsfAhfR9VPw8iACvH0I5RdP0qqumh1ZBEXwcokpngA==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-glue/-/client-glue-3.637.0.tgz", + "integrity": "sha512-QhkixUI3eTittXRBv43qfh9hEjIPc1IoBmqKAzn8dSA2choX3XxpLvDLKbyv26yCq5QnZIiZ5SzOtr5pTJG/BA==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -1824,47 +1541,47 @@ } }, "node_modules/@aws-sdk/client-iam": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-iam/-/client-iam-3.632.0.tgz", - "integrity": "sha512-iwivASUliVxCEbT/mu5s03SCyqQKNXbJUpG17ywT4taA2xvLisGRI5iNV3OYT1qDmK9DOLMSJYpeX2GWCijPxw==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-iam/-/client-iam-3.637.0.tgz", + "integrity": "sha512-mo1gCm3yayuiFPCQkY5i5wbL6jjgCprpAfeMP5zFOcDsr7BqX9ijTrRzK+dx0SwiTdRKOW6zJaDiWA1UZgb60A==", "dev": true, "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -1890,27 +1607,27 @@ } }, "node_modules/@aws-sdk/client-lambda": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-lambda/-/client-lambda-3.632.0.tgz", - "integrity": "sha512-vF4KRuHGr6EfW+dssm56S6b+jAa8dKqdWduHNms1TQFah0iOkjc9Dpo4p4j6bobZcuricGko/OZy9ynb1Dwldg==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-lambda/-/client-lambda-3.637.0.tgz", + "integrity": "sha512-XVQn4p/9XNMEImxCY97WlA83Q63HRrDhks4kby5YGG2fZckaNJxXE+/FFYsznse8hXKLUJ1/aI3hZSnXTthq5g==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/eventstream-serde-browser": "^3.0.6", "@smithy/eventstream-serde-config-resolver": "^3.0.3", "@smithy/eventstream-serde-node": "^3.0.5", @@ -1919,20 +1636,20 @@ "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -1958,46 +1675,46 @@ } }, "node_modules/@aws-sdk/client-opensearch": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-opensearch/-/client-opensearch-3.632.0.tgz", - "integrity": "sha512-ZeWedGeWBj6rh+tEX0olvyLUH6iMpNt5cO5pw49Mjpnt4dE3W4JgieCd5ZyfFtJoHroYvG41ZA4p+b2aUjxgwQ==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-opensearch/-/client-opensearch-3.637.0.tgz", + "integrity": "sha512-SLmKOVBxImEziHS60hRB1d/pNSJVr+FRSlRSSV5KIEXvWrtrmNAZGly3KnXjPuDUpCflWrpuKX7sm2c9//CANQ==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -2021,48 +1738,48 @@ } }, "node_modules/@aws-sdk/client-route-53": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-route-53/-/client-route-53-3.632.0.tgz", - "integrity": "sha512-BEMRHWxmXBzWlnCuW1rTaqYHUSGPDMpQbZdsC7dCuVcYdIBwKfJrPe1HtvT0+6W/KkDQqxoEgKrl47+Jzl06qw==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-route-53/-/client-route-53-3.637.0.tgz", + "integrity": "sha512-lF73WvWrCmfvmESx397G/GS8ecLIiB7PRy3Cpn1yl8V6LR3Hmuthgd7DbpN1YHtkEnwr0mVQUMy5c2IUD9D3kg==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", "@aws-sdk/middleware-sdk-route53": "3.609.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@aws-sdk/xml-builder": "3.609.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -2087,17 +1804,17 @@ } }, "node_modules/@aws-sdk/client-s3": { - "version": "3.633.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-s3/-/client-s3-3.633.0.tgz", - "integrity": "sha512-KPwNGlZlCRUADNTvwPJmvDvlh8N/jxjcv5e71M/mWxLXwSPdlHlRjVSBL1/CPSXUr86XRAsPL+BCRkdiytUhbg==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-s3/-/client-s3-3.637.0.tgz", + "integrity": "sha512-y6UC94fsMvhKbf0dzfnjVP1HePeGjplfcYfilZU1COIJLyTkMcUv4XcT4I407CGIrvgEafONHkiC09ygqUauNA==", "dependencies": { "@aws-crypto/sha1-browser": "5.2.0", "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-bucket-endpoint": "3.620.0", "@aws-sdk/middleware-expect-continue": "3.620.0", "@aws-sdk/middleware-flexible-checksums": "3.620.0", @@ -2105,18 +1822,18 @@ "@aws-sdk/middleware-location-constraint": "3.609.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-sdk-s3": "3.633.0", + "@aws-sdk/middleware-sdk-s3": "3.635.0", "@aws-sdk/middleware-ssec": "3.609.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", - "@aws-sdk/signature-v4-multi-region": "3.633.0", + "@aws-sdk/signature-v4-multi-region": "3.635.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@aws-sdk/xml-builder": "3.609.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/eventstream-serde-browser": "^3.0.6", "@smithy/eventstream-serde-config-resolver": "^3.0.3", "@smithy/eventstream-serde-node": "^3.0.5", @@ -2128,20 +1845,20 @@ "@smithy/md5-js": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -2167,47 +1884,47 @@ } }, "node_modules/@aws-sdk/client-secrets-manager": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-secrets-manager/-/client-secrets-manager-3.632.0.tgz", - "integrity": "sha512-WsQhPHHK1yPfALcP1B7nBSGDzky6vFTUEXnUdfzb5Xy2cT+JTBTS6ChtQGqqOuGHDP/3t/9soqZ+L6rUCYBb/Q==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-secrets-manager/-/client-secrets-manager-3.637.0.tgz", + "integrity": "sha512-4AEV+4yhaFYlnD90MbtOouqTyrPVmD8OeGotsjtWxgnVHk55Vd0/dIWVGjic0YCxH3SNdWqJJ9G8Vd93fWymVA==", "dev": true, "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -2246,46 +1963,46 @@ } }, "node_modules/@aws-sdk/client-ses": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-ses/-/client-ses-3.632.0.tgz", - "integrity": "sha512-hi01MPJF55LEK7NB1LZrqUV7b5GyjH08EToYuekFvQf9aNoR5mqWuMEDQ/dFAowYhUa2KqCdn67HnPn0ySQxHg==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-ses/-/client-ses-3.637.0.tgz", + "integrity": "sha512-pHkI8iMxbdtNeaa0a+c0T29bRZMFu8HQtGtwPlSwvD1elDVFrlWXw74MrlaW0aRPGryF4sHxVHk3YkxhxAS5iw==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -2310,46 +2027,46 @@ } }, "node_modules/@aws-sdk/client-sns": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sns/-/client-sns-3.632.0.tgz", - "integrity": "sha512-I8S0tFx26LL59/PiL4Reqna+LW7oIbRB+jygl4vrf4XIvpX5o4tmZmOmR0caYA+Cks3AomCi4cp+7WuwUpuATQ==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sns/-/client-sns-3.637.0.tgz", + "integrity": "sha512-6FDeWqTCeIPgImMyabqoFd9/EFS3XIaMYrqmHUTSPNlrhRkuJWh+3zS/S5a7tPxqkadOIqajf9UCzMCvjJru8g==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -2373,48 +2090,48 @@ } }, "node_modules/@aws-sdk/client-sqs": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sqs/-/client-sqs-3.632.0.tgz", - "integrity": "sha512-UK4JQ6nF6qDtc2rLdrYTgyZWTdUgfVHbVHQdHkrni2TNac3kEksgiDFxsm6zQjy1NoOg4YdPDeMOeHRvWImlPQ==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sqs/-/client-sqs-3.637.0.tgz", + "integrity": "sha512-0slT2OCa8uOottHFjIBD9EuTotu3Qdzp7Z7PqtkSqQdbXxC8CFsDLNfZVqpU8o/+mf79I2fJK21pEPhBnm654g==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-sdk-sqs": "3.622.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-sdk-sqs": "3.635.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/md5-js": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -2438,46 +2155,46 @@ } }, "node_modules/@aws-sdk/client-ssm": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-ssm/-/client-ssm-3.632.0.tgz", - "integrity": "sha512-p9QZguhC6NB6CQTFgLcYhU1yhGF7SN9kDMtFwtFBxTPO/SQJ/PJcEyL40yXPbuPUXFtT/YRhT9mIwQagfkXzAA==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-ssm/-/client-ssm-3.637.0.tgz", + "integrity": "sha512-cr0/c95KpFIwoCCofXu1Em/Sw8SjIFCZ3X1ji2rW81QdLpw7icP01SMcRTbgtiKeN12fKZDXmrupkI6zhnG0MA==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/client-sts": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/client-sts": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -2514,93 +2231,45 @@ "uuid": "dist/bin/uuid" } }, - "node_modules/@aws-sdk/client-sso": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.632.0.tgz", - "integrity": "sha512-iYWHiKBz44m3chCFvtvHnvCpL2rALzyr1e6tOZV3dLlOKtQtDUlPy6OtnXDu4y+wyJCniy8ivG3+LAe4klzn1Q==", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/middleware-host-header": "3.620.0", - "@aws-sdk/middleware-logger": "3.609.0", - "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", - "@aws-sdk/region-config-resolver": "3.614.0", - "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", - "@aws-sdk/util-user-agent-browser": "3.609.0", - "@aws-sdk/util-user-agent-node": "3.614.0", - "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", - "@smithy/fetch-http-handler": "^3.2.4", - "@smithy/hash-node": "^3.0.3", - "@smithy/invalid-dependency": "^3.0.3", - "@smithy/middleware-content-length": "^3.0.5", - "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", - "@smithy/middleware-serde": "^3.0.3", - "@smithy/middleware-stack": "^3.0.3", - "@smithy/node-config-provider": "^3.1.4", - "@smithy/node-http-handler": "^3.1.4", - "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", - "@smithy/types": "^3.3.0", - "@smithy/url-parser": "^3.0.3", - "@smithy/util-base64": "^3.0.0", - "@smithy/util-body-length-browser": "^3.0.0", - "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", - "@smithy/util-endpoints": "^2.0.5", - "@smithy/util-middleware": "^3.0.3", - "@smithy/util-retry": "^3.0.3", - "@smithy/util-utf8": "^3.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, "node_modules/@aws-sdk/client-sso-oidc": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso-oidc/-/client-sso-oidc-3.632.0.tgz", - "integrity": "sha512-Oh1fIWaoZluihOCb/zDEpRTi+6an82fgJz7fyRBugyLhEtDjmvpCQ3oKjzaOhoN+4EvXAm1ZS/ZgpvXBlIRTgw==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso-oidc/-/client-sso-oidc-3.637.0.tgz", + "integrity": "sha512-27bHALN6Qb6m6KZmPvRieJ/QRlj1lyac/GT2Rn5kJpre8Mpp+yxrtvp3h9PjNBty4lCeFEENfY4dGNSozBuBcw==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -2611,7 +2280,7 @@ "node": ">=16.0.0" }, "peerDependencies": { - "@aws-sdk/client-sts": "^3.632.0" + "@aws-sdk/client-sts": "^3.637.0" } }, "node_modules/@aws-sdk/client-sso-oidc/node_modules/@smithy/util-utf8": { @@ -2626,58 +2295,46 @@ "node": ">=16.0.0" } }, - "node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-utf8": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-3.0.0.tgz", - "integrity": "sha512-rUeT12bxFnplYDe815GXbq/oixEGHfRFFtcTF3YdDi/JaENIM6aSYYLJydG83UNzLXeRI5K8abYd/8Sp/QM0kA==", - "dependencies": { - "@smithy/util-buffer-from": "^3.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, "node_modules/@aws-sdk/client-sts": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.632.0.tgz", - "integrity": "sha512-Ss5cBH09icpTvT+jtGGuQlRdwtO7RyE9BF4ZV/CEPATdd9whtJt4Qxdya8BUnkWR7h5HHTrQHqai3YVYjku41A==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.637.0.tgz", + "integrity": "sha512-xUi7x4qDubtA8QREtlblPuAcn91GS/09YVEY/RwU7xCY0aqGuFwgszAANlha4OUIqva8oVj2WO4gJuG+iaSnhw==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.632.0", - "@aws-sdk/core": "3.629.0", - "@aws-sdk/credential-provider-node": "3.632.0", + "@aws-sdk/client-sso-oidc": "3.637.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/credential-provider-node": "3.637.0", "@aws-sdk/middleware-host-header": "3.620.0", "@aws-sdk/middleware-logger": "3.609.0", "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.632.0", + "@aws-sdk/middleware-user-agent": "3.637.0", "@aws-sdk/region-config-resolver": "3.614.0", "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@aws-sdk/util-user-agent-browser": "3.609.0", "@aws-sdk/util-user-agent-node": "3.614.0", "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/hash-node": "^3.0.3", "@smithy/invalid-dependency": "^3.0.3", "@smithy/middleware-content-length": "^3.0.5", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.14", + "@smithy/middleware-retry": "^3.0.15", "@smithy/middleware-serde": "^3.0.3", "@smithy/middleware-stack": "^3.0.3", "@smithy/node-config-provider": "^3.1.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/url-parser": "^3.0.3", "@smithy/util-base64": "^3.0.0", "@smithy/util-body-length-browser": "^3.0.0", "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.14", - "@smithy/util-defaults-mode-node": "^3.0.14", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", "@smithy/util-endpoints": "^2.0.5", "@smithy/util-middleware": "^3.0.3", "@smithy/util-retry": "^3.0.3", @@ -2713,16 +2370,16 @@ } }, "node_modules/@aws-sdk/core": { - "version": "3.629.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.629.0.tgz", - "integrity": "sha512-+/ShPU/tyIBM3oY1cnjgNA/tFyHtlWq+wXF9xEKRv19NOpYbWQ+xzNwVjGq8vR07cCRqy/sDQLWPhxjtuV/FiQ==", + "version": "3.635.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.635.0.tgz", + "integrity": "sha512-i1x/E/sgA+liUE1XJ7rj1dhyXpAKO1UKFUcTTHXok2ARjWTvszHnSXMOsB77aPbmn0fUp1JTx2kHUAZ1LVt5Bg==", "dependencies": { - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/node-config-provider": "^3.1.4", "@smithy/property-provider": "^3.1.3", "@smithy/protocol-http": "^4.1.0", "@smithy/signature-v4": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/util-middleware": "^3.0.3", "fast-xml-parser": "4.4.1", @@ -2761,17 +2418,87 @@ "node": ">=16.0.0" } }, - "node_modules/@aws-sdk/credential-provider-http": { - "version": "3.622.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.622.0.tgz", - "integrity": "sha512-VUHbr24Oll1RK3WR8XLUugLpgK9ZuxEm/NVeVqyFts1Ck9gsKpRg1x4eH7L7tW3SJ4TDEQNMbD7/7J+eoL2svg==", + "node_modules/@aws-sdk/credential-provider-node": { + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.637.0.tgz", + "integrity": "sha512-yoEhoxJJfs7sPVQ6Is939BDQJZpZCoUgKr/ySse4YKOZ24t4VqgHA6+wV7rYh+7IW24Rd91UTvEzSuHYTlxlNA==", + "dependencies": { + "@aws-sdk/credential-provider-env": "3.620.1", + "@aws-sdk/credential-provider-http": "3.635.0", + "@aws-sdk/credential-provider-ini": "3.637.0", + "@aws-sdk/credential-provider-process": "3.620.1", + "@aws-sdk/credential-provider-sso": "3.637.0", + "@aws-sdk/credential-provider-web-identity": "3.621.0", + "@aws-sdk/types": "3.609.0", + "@smithy/credential-provider-imds": "^3.2.0", + "@smithy/property-provider": "^3.1.3", + "@smithy/shared-ini-file-loader": "^3.1.4", + "@smithy/types": "^3.3.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-node/node_modules/@aws-sdk/client-sso": { + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.637.0.tgz", + "integrity": "sha512-+KjLvgX5yJYROWo3TQuwBJlHCY0zz9PsLuEolmXQn0BVK1L/m9GteZHtd+rEdAoDGBpE0Xqjy1oz5+SmtsaRUw==", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.635.0", + "@aws-sdk/middleware-host-header": "3.620.0", + "@aws-sdk/middleware-logger": "3.609.0", + "@aws-sdk/middleware-recursion-detection": "3.620.0", + "@aws-sdk/middleware-user-agent": "3.637.0", + "@aws-sdk/region-config-resolver": "3.614.0", + "@aws-sdk/types": "3.609.0", + "@aws-sdk/util-endpoints": "3.637.0", + "@aws-sdk/util-user-agent-browser": "3.609.0", + "@aws-sdk/util-user-agent-node": "3.614.0", + "@smithy/config-resolver": "^3.0.5", + "@smithy/core": "^2.4.0", + "@smithy/fetch-http-handler": "^3.2.4", + "@smithy/hash-node": "^3.0.3", + "@smithy/invalid-dependency": "^3.0.3", + "@smithy/middleware-content-length": "^3.0.5", + "@smithy/middleware-endpoint": "^3.1.0", + "@smithy/middleware-retry": "^3.0.15", + "@smithy/middleware-serde": "^3.0.3", + "@smithy/middleware-stack": "^3.0.3", + "@smithy/node-config-provider": "^3.1.4", + "@smithy/node-http-handler": "^3.1.4", + "@smithy/protocol-http": "^4.1.0", + "@smithy/smithy-client": "^3.2.0", + "@smithy/types": "^3.3.0", + "@smithy/url-parser": "^3.0.3", + "@smithy/util-base64": "^3.0.0", + "@smithy/util-body-length-browser": "^3.0.0", + "@smithy/util-body-length-node": "^3.0.0", + "@smithy/util-defaults-mode-browser": "^3.0.15", + "@smithy/util-defaults-mode-node": "^3.0.15", + "@smithy/util-endpoints": "^2.0.5", + "@smithy/util-middleware": "^3.0.3", + "@smithy/util-retry": "^3.0.3", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-node/node_modules/@aws-sdk/credential-provider-http": { + "version": "3.635.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.635.0.tgz", + "integrity": "sha512-iJyRgEjOCQlBMXqtwPLIKYc7Bsc6nqjrZybdMDenPDa+kmLg7xh8LxHsu9088e+2/wtLicE34FsJJIfzu3L82g==", "dependencies": { "@aws-sdk/types": "3.609.0", "@smithy/fetch-http-handler": "^3.2.4", "@smithy/node-http-handler": "^3.1.4", "@smithy/property-provider": "^3.1.3", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/util-stream": "^3.1.3", "tslib": "^2.6.2" @@ -2780,15 +2507,15 @@ "node": ">=16.0.0" } }, - "node_modules/@aws-sdk/credential-provider-ini": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.632.0.tgz", - "integrity": "sha512-m6epoW41xa1ajU5OiHcmQHoGVtrbXBaRBOUhlCLZmcaqMLYsboM4iD/WZP8aatKEON5tTnVXh/4StV8D/+wemw==", + "node_modules/@aws-sdk/credential-provider-node/node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.637.0.tgz", + "integrity": "sha512-h+PFCWfZ0Q3Dx84SppET/TFpcQHmxFW8/oV9ArEvMilw4EBN+IlxgbL0CnHwjHW64szcmrM0mbebjEfHf4FXmw==", "dependencies": { "@aws-sdk/credential-provider-env": "3.620.1", - "@aws-sdk/credential-provider-http": "3.622.0", + "@aws-sdk/credential-provider-http": "3.635.0", "@aws-sdk/credential-provider-process": "3.620.1", - "@aws-sdk/credential-provider-sso": "3.632.0", + "@aws-sdk/credential-provider-sso": "3.637.0", "@aws-sdk/credential-provider-web-identity": "3.621.0", "@aws-sdk/types": "3.609.0", "@smithy/credential-provider-imds": "^3.2.0", @@ -2801,22 +2528,17 @@ "node": ">=16.0.0" }, "peerDependencies": { - "@aws-sdk/client-sts": "^3.632.0" + "@aws-sdk/client-sts": "^3.637.0" } }, - "node_modules/@aws-sdk/credential-provider-node": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.632.0.tgz", - "integrity": "sha512-cL8fuJWm/xQBO4XJPkeuZzl3XinIn9EExWgzpG48NRMKR5us1RI/ucv7xFbBBaG+r/sDR2HpYBIA3lVIpm1H3Q==", + "node_modules/@aws-sdk/credential-provider-node/node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.637.0.tgz", + "integrity": "sha512-Mvz+h+e62/tl+dVikLafhv+qkZJ9RUb8l2YN/LeKMWkxQylPT83CPk9aimVhCV89zth1zpREArl97+3xsfgQvA==", "dependencies": { - "@aws-sdk/credential-provider-env": "3.620.1", - "@aws-sdk/credential-provider-http": "3.622.0", - "@aws-sdk/credential-provider-ini": "3.632.0", - "@aws-sdk/credential-provider-process": "3.620.1", - "@aws-sdk/credential-provider-sso": "3.632.0", - "@aws-sdk/credential-provider-web-identity": "3.621.0", + "@aws-sdk/client-sso": "3.637.0", + "@aws-sdk/token-providers": "3.614.0", "@aws-sdk/types": "3.609.0", - "@smithy/credential-provider-imds": "^3.2.0", "@smithy/property-provider": "^3.1.3", "@smithy/shared-ini-file-loader": "^3.1.4", "@smithy/types": "^3.3.0", @@ -2826,28 +2548,23 @@ "node": ">=16.0.0" } }, - "node_modules/@aws-sdk/credential-provider-process": { - "version": "3.620.1", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.620.1.tgz", - "integrity": "sha512-hWqFMidqLAkaV9G460+1at6qa9vySbjQKKc04p59OT7lZ5cO5VH5S4aI05e+m4j364MBROjjk2ugNvfNf/8ILg==", + "node_modules/@aws-sdk/credential-provider-node/node_modules/@smithy/util-utf8": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-3.0.0.tgz", + "integrity": "sha512-rUeT12bxFnplYDe815GXbq/oixEGHfRFFtcTF3YdDi/JaENIM6aSYYLJydG83UNzLXeRI5K8abYd/8Sp/QM0kA==", "dependencies": { - "@aws-sdk/types": "3.609.0", - "@smithy/property-provider": "^3.1.3", - "@smithy/shared-ini-file-loader": "^3.1.4", - "@smithy/types": "^3.3.0", + "@smithy/util-buffer-from": "^3.0.0", "tslib": "^2.6.2" }, "engines": { "node": ">=16.0.0" } }, - "node_modules/@aws-sdk/credential-provider-sso": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.632.0.tgz", - "integrity": "sha512-P/4wB6j7ym5QCPTL2xlMfvf2NcXSh+z0jmsZP4WW/tVwab4hvgabPPbLeEZDSWZ0BpgtxKGvRq0GSHuGeirQbA==", + "node_modules/@aws-sdk/credential-provider-process": { + "version": "3.620.1", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.620.1.tgz", + "integrity": "sha512-hWqFMidqLAkaV9G460+1at6qa9vySbjQKKc04p59OT7lZ5cO5VH5S4aI05e+m4j364MBROjjk2ugNvfNf/8ILg==", "dependencies": { - "@aws-sdk/client-sso": "3.632.0", - "@aws-sdk/token-providers": "3.614.0", "@aws-sdk/types": "3.609.0", "@smithy/property-provider": "^3.1.3", "@smithy/shared-ini-file-loader": "^3.1.4", @@ -2949,128 +2666,6 @@ "node": ">=16.0.0" } }, - "node_modules/@aws-sdk/credential-providers/node_modules/@aws-sdk/client-sso-oidc": { - "version": "3.637.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso-oidc/-/client-sso-oidc-3.637.0.tgz", - "integrity": "sha512-27bHALN6Qb6m6KZmPvRieJ/QRlj1lyac/GT2Rn5kJpre8Mpp+yxrtvp3h9PjNBty4lCeFEENfY4dGNSozBuBcw==", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.635.0", - "@aws-sdk/credential-provider-node": "3.637.0", - "@aws-sdk/middleware-host-header": "3.620.0", - "@aws-sdk/middleware-logger": "3.609.0", - "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.637.0", - "@aws-sdk/region-config-resolver": "3.614.0", - "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.637.0", - "@aws-sdk/util-user-agent-browser": "3.609.0", - "@aws-sdk/util-user-agent-node": "3.614.0", - "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.4.0", - "@smithy/fetch-http-handler": "^3.2.4", - "@smithy/hash-node": "^3.0.3", - "@smithy/invalid-dependency": "^3.0.3", - "@smithy/middleware-content-length": "^3.0.5", - "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.15", - "@smithy/middleware-serde": "^3.0.3", - "@smithy/middleware-stack": "^3.0.3", - "@smithy/node-config-provider": "^3.1.4", - "@smithy/node-http-handler": "^3.1.4", - "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.2.0", - "@smithy/types": "^3.3.0", - "@smithy/url-parser": "^3.0.3", - "@smithy/util-base64": "^3.0.0", - "@smithy/util-body-length-browser": "^3.0.0", - "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.15", - "@smithy/util-defaults-mode-node": "^3.0.15", - "@smithy/util-endpoints": "^2.0.5", - "@smithy/util-middleware": "^3.0.3", - "@smithy/util-retry": "^3.0.3", - "@smithy/util-utf8": "^3.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - }, - "peerDependencies": { - "@aws-sdk/client-sts": "^3.637.0" - } - }, - "node_modules/@aws-sdk/credential-providers/node_modules/@aws-sdk/client-sts": { - "version": "3.637.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.637.0.tgz", - "integrity": "sha512-xUi7x4qDubtA8QREtlblPuAcn91GS/09YVEY/RwU7xCY0aqGuFwgszAANlha4OUIqva8oVj2WO4gJuG+iaSnhw==", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.637.0", - "@aws-sdk/core": "3.635.0", - "@aws-sdk/credential-provider-node": "3.637.0", - "@aws-sdk/middleware-host-header": "3.620.0", - "@aws-sdk/middleware-logger": "3.609.0", - "@aws-sdk/middleware-recursion-detection": "3.620.0", - "@aws-sdk/middleware-user-agent": "3.637.0", - "@aws-sdk/region-config-resolver": "3.614.0", - "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.637.0", - "@aws-sdk/util-user-agent-browser": "3.609.0", - "@aws-sdk/util-user-agent-node": "3.614.0", - "@smithy/config-resolver": "^3.0.5", - "@smithy/core": "^2.4.0", - "@smithy/fetch-http-handler": "^3.2.4", - "@smithy/hash-node": "^3.0.3", - "@smithy/invalid-dependency": "^3.0.3", - "@smithy/middleware-content-length": "^3.0.5", - "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/middleware-retry": "^3.0.15", - "@smithy/middleware-serde": "^3.0.3", - "@smithy/middleware-stack": "^3.0.3", - "@smithy/node-config-provider": "^3.1.4", - "@smithy/node-http-handler": "^3.1.4", - "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.2.0", - "@smithy/types": "^3.3.0", - "@smithy/url-parser": "^3.0.3", - "@smithy/util-base64": "^3.0.0", - "@smithy/util-body-length-browser": "^3.0.0", - "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.15", - "@smithy/util-defaults-mode-node": "^3.0.15", - "@smithy/util-endpoints": "^2.0.5", - "@smithy/util-middleware": "^3.0.3", - "@smithy/util-retry": "^3.0.3", - "@smithy/util-utf8": "^3.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-sdk/credential-providers/node_modules/@aws-sdk/core": { - "version": "3.635.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.635.0.tgz", - "integrity": "sha512-i1x/E/sgA+liUE1XJ7rj1dhyXpAKO1UKFUcTTHXok2ARjWTvszHnSXMOsB77aPbmn0fUp1JTx2kHUAZ1LVt5Bg==", - "dependencies": { - "@smithy/core": "^2.4.0", - "@smithy/node-config-provider": "^3.1.4", - "@smithy/property-provider": "^3.1.3", - "@smithy/protocol-http": "^4.1.0", - "@smithy/signature-v4": "^4.1.0", - "@smithy/smithy-client": "^3.2.0", - "@smithy/types": "^3.3.0", - "@smithy/util-middleware": "^3.0.3", - "fast-xml-parser": "4.4.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, "node_modules/@aws-sdk/credential-providers/node_modules/@aws-sdk/credential-provider-http": { "version": "3.635.0", "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.635.0.tgz", @@ -3114,28 +2709,6 @@ "@aws-sdk/client-sts": "^3.637.0" } }, - "node_modules/@aws-sdk/credential-providers/node_modules/@aws-sdk/credential-provider-node": { - "version": "3.637.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.637.0.tgz", - "integrity": "sha512-yoEhoxJJfs7sPVQ6Is939BDQJZpZCoUgKr/ySse4YKOZ24t4VqgHA6+wV7rYh+7IW24Rd91UTvEzSuHYTlxlNA==", - "dependencies": { - "@aws-sdk/credential-provider-env": "3.620.1", - "@aws-sdk/credential-provider-http": "3.635.0", - "@aws-sdk/credential-provider-ini": "3.637.0", - "@aws-sdk/credential-provider-process": "3.620.1", - "@aws-sdk/credential-provider-sso": "3.637.0", - "@aws-sdk/credential-provider-web-identity": "3.621.0", - "@aws-sdk/types": "3.609.0", - "@smithy/credential-provider-imds": "^3.2.0", - "@smithy/property-provider": "^3.1.3", - "@smithy/shared-ini-file-loader": "^3.1.4", - "@smithy/types": "^3.3.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, "node_modules/@aws-sdk/credential-providers/node_modules/@aws-sdk/credential-provider-sso": { "version": "3.637.0", "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.637.0.tgz", @@ -3153,35 +2726,6 @@ "node": ">=16.0.0" } }, - "node_modules/@aws-sdk/credential-providers/node_modules/@aws-sdk/middleware-user-agent": { - "version": "3.637.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.637.0.tgz", - "integrity": "sha512-EYo0NE9/da/OY8STDsK2LvM4kNa79DBsf4YVtaG4P5pZ615IeFsD8xOHZeuJmUrSMlVQ8ywPRX7WMucUybsKug==", - "dependencies": { - "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.637.0", - "@smithy/protocol-http": "^4.1.0", - "@smithy/types": "^3.3.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-sdk/credential-providers/node_modules/@aws-sdk/util-endpoints": { - "version": "3.637.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.637.0.tgz", - "integrity": "sha512-pAqOKUHeVWHEXXDIp/qoMk/6jyxIb6GGjnK1/f8dKHtKIEs4tKsnnL563gceEvdad53OPXIt86uoevCcCzmBnw==", - "dependencies": { - "@aws-sdk/types": "3.609.0", - "@smithy/types": "^3.3.0", - "@smithy/util-endpoints": "^2.0.5", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, "node_modules/@aws-sdk/credential-providers/node_modules/@smithy/util-utf8": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-3.0.0.tgz", @@ -3207,13 +2751,13 @@ } }, "node_modules/@aws-sdk/lib-dynamodb": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/lib-dynamodb/-/lib-dynamodb-3.632.0.tgz", - "integrity": "sha512-8QBjfCEKPOpU2stxCJ/DGDL7Gb1tzgwPwC1XLMzLW3rR94EcrlmJatEBXIHbGQypVvHVdwu3xILDrp4qn6P+Sg==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/lib-dynamodb/-/lib-dynamodb-3.637.0.tgz", + "integrity": "sha512-jyIZBagxcwrzWdgDZdlqXKWz1uKPNGxFuUODwhRj3337EZz+yVo1qSfs6s9TKO7+nta+kPLg2mo064KXP5XHJw==", "dependencies": { - "@aws-sdk/util-dynamodb": "3.632.0", - "@smithy/core": "^2.3.2", - "@smithy/smithy-client": "^3.1.12", + "@aws-sdk/util-dynamodb": "3.637.0", + "@smithy/core": "^2.4.0", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "tslib": "^2.6.2" }, @@ -3221,17 +2765,17 @@ "node": ">=16.0.0" }, "peerDependencies": { - "@aws-sdk/client-dynamodb": "^3.632.0" + "@aws-sdk/client-dynamodb": "^3.637.0" } }, "node_modules/@aws-sdk/lib-storage": { - "version": "3.633.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/lib-storage/-/lib-storage-3.633.0.tgz", - "integrity": "sha512-bc+o95CWgyY9BwY6BmmvM+SfmOTNzkvszE8jSNtw4RO8rhhy+cDkwMOpyHe2mBWMUEq2LMXW3TvIrPZT1bvTyA==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/lib-storage/-/lib-storage-3.637.0.tgz", + "integrity": "sha512-HiNGOP4a1QrCWwO1joKw4mCp19nLXoF9K52PislBaYDI35IlHC3DP6MeOg5zmElwtL1GtEHFBy5olfPWPsLyLg==", "dependencies": { "@smithy/abort-controller": "^3.1.1", "@smithy/middleware-endpoint": "^3.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "buffer": "5.6.0", "events": "3.3.0", "stream-browserify": "3.0.0", @@ -3241,7 +2785,7 @@ "node": ">=16.0.0" }, "peerDependencies": { - "@aws-sdk/client-s3": "^3.633.0" + "@aws-sdk/client-s3": "^3.637.0" } }, "node_modules/@aws-sdk/middleware-bucket-endpoint": { @@ -3403,18 +2947,18 @@ } }, "node_modules/@aws-sdk/middleware-sdk-s3": { - "version": "3.633.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.633.0.tgz", - "integrity": "sha512-7jjmWVw28wIHOdrHyTCvwKr1EYGrZI13DviwAOwRC0y9dB8gGCdRiA4fNczripUBxolCCE9mpqLrqy5pXtTzvA==", + "version": "3.635.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.635.0.tgz", + "integrity": "sha512-RLdYJPEV4JL/7NBoFUs7VlP90X++5FlJdxHz0DzCjmiD3qCviKy+Cym3qg1gBgHwucs5XisuClxDrGokhAdTQw==", "dependencies": { - "@aws-sdk/core": "3.629.0", + "@aws-sdk/core": "3.635.0", "@aws-sdk/types": "3.609.0", "@aws-sdk/util-arn-parser": "3.568.0", - "@smithy/core": "^2.3.2", + "@smithy/core": "^2.4.0", "@smithy/node-config-provider": "^3.1.4", "@smithy/protocol-http": "^4.1.0", "@smithy/signature-v4": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/util-config-provider": "^3.0.0", "@smithy/util-middleware": "^3.0.3", @@ -3439,12 +2983,12 @@ } }, "node_modules/@aws-sdk/middleware-sdk-sqs": { - "version": "3.622.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-sqs/-/middleware-sdk-sqs-3.622.0.tgz", - "integrity": "sha512-kOPX94jlVcvH7Wutzag99L+BSjT6LjXxW7Ntc02/oywYX6Gft4YdbeUYdcGYYHWDy/IT6jJ2wMJfFUEEh8U/9A==", + "version": "3.635.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-sqs/-/middleware-sdk-sqs-3.635.0.tgz", + "integrity": "sha512-EsrTqso8dBeugdKYyKmF2faqplYoPvW7YNE5wttgFCeSn4HvG8lh+oGt9/ofawTy0GLkQG2Z5eKhUAgYSrP2Ww==", "dependencies": { "@aws-sdk/types": "3.609.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "@smithy/util-hex-encoding": "^3.0.0", "@smithy/util-utf8": "^3.0.0", @@ -3480,12 +3024,12 @@ } }, "node_modules/@aws-sdk/middleware-user-agent": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.632.0.tgz", - "integrity": "sha512-yY/sFsHKwG9yzSf/DTclqWJaGPI2gPBJDCGBujSqTG1zlS7Ot4fqi91DZ6088BFWzbOorDzJFcAhAEFzc6LuQg==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.637.0.tgz", + "integrity": "sha512-EYo0NE9/da/OY8STDsK2LvM4kNa79DBsf4YVtaG4P5pZ615IeFsD8xOHZeuJmUrSMlVQ8ywPRX7WMucUybsKug==", "dependencies": { "@aws-sdk/types": "3.609.0", - "@aws-sdk/util-endpoints": "3.632.0", + "@aws-sdk/util-endpoints": "3.637.0", "@smithy/protocol-http": "^4.1.0", "@smithy/types": "^3.3.0", "tslib": "^2.6.2" @@ -3656,11 +3200,11 @@ } }, "node_modules/@aws-sdk/s3-presigned-post": { - "version": "3.633.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/s3-presigned-post/-/s3-presigned-post-3.633.0.tgz", - "integrity": "sha512-EmfgQKWDbNUWJOjciE3asMKHChjFOKIIEs4aRW6nYol6rvDwp4hyRu+sTUZOu2jdSKqR/1dhan4k+WCiqw/YTQ==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/s3-presigned-post/-/s3-presigned-post-3.637.0.tgz", + "integrity": "sha512-NlsowCavLXx5OulbD8+tqfXpyxVulI2l/4naBI1i5Vj6M+FMuQvqH1Y5OQBgN42/QZlMLJ5Ff5G3aaoZjrb1pw==", "dependencies": { - "@aws-sdk/client-s3": "3.633.0", + "@aws-sdk/client-s3": "3.637.0", "@aws-sdk/types": "3.609.0", "@aws-sdk/util-format-url": "3.609.0", "@smithy/middleware-endpoint": "^3.1.0", @@ -3687,16 +3231,16 @@ } }, "node_modules/@aws-sdk/s3-request-presigner": { - "version": "3.633.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/s3-request-presigner/-/s3-request-presigner-3.633.0.tgz", - "integrity": "sha512-WUcBSdBenzA65y8MCDPcOaKWYhU0+AuocI1hm46TaPcPhE4E2oVoYbk1MeufkaSavR741iM4fm+b16ESUF963A==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/s3-request-presigner/-/s3-request-presigner-3.637.0.tgz", + "integrity": "sha512-URRiEDZEICyfAXmXcXREQCsvZrapITAymvg46p1Xjnuv7PTnUB0SF18B2omPL0E5d/X+T3O9NKdtot+BqJbIWw==", "dependencies": { - "@aws-sdk/signature-v4-multi-region": "3.633.0", + "@aws-sdk/signature-v4-multi-region": "3.635.0", "@aws-sdk/types": "3.609.0", "@aws-sdk/util-format-url": "3.609.0", "@smithy/middleware-endpoint": "^3.1.0", "@smithy/protocol-http": "^4.1.0", - "@smithy/smithy-client": "^3.1.12", + "@smithy/smithy-client": "^3.2.0", "@smithy/types": "^3.3.0", "tslib": "^2.6.2" }, @@ -3718,11 +3262,11 @@ } }, "node_modules/@aws-sdk/signature-v4-multi-region": { - "version": "3.633.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.633.0.tgz", - "integrity": "sha512-96F7Mx4lybMZdE0TTEkw6EKpeB0hxqp3J8fUJasesekTnO7jsklc47GHL5R3whyS/L4/JaPazm0Pi2DEH3kw1w==", + "version": "3.635.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.635.0.tgz", + "integrity": "sha512-J6QY4/invOkpogCHjSaDON1hF03viPpOnsrzVuCvJMmclS/iG62R4EY0wq1alYll0YmSdmKlpJwHMWwGtqK63Q==", "dependencies": { - "@aws-sdk/middleware-sdk-s3": "3.633.0", + "@aws-sdk/middleware-sdk-s3": "3.635.0", "@aws-sdk/types": "3.609.0", "@smithy/protocol-http": "^4.1.0", "@smithy/signature-v4": "^4.1.0", @@ -3913,9 +3457,9 @@ } }, "node_modules/@aws-sdk/util-dynamodb": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-dynamodb/-/util-dynamodb-3.632.0.tgz", - "integrity": "sha512-uvfHEk7y9JKLTOXPOQi+GhQLs0Eo09xNNMGk8ptZUeXS4u/Qs6lHKJK6i1khoeeQ6+ASSxmYmTbDhpPqUKGPEg==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-dynamodb/-/util-dynamodb-3.637.0.tgz", + "integrity": "sha512-C2q8HcGRiahtf46Mhaqydh1gofeksj7m74PJXHYKW+pKBMLPlpou1+w2o5QSpVEp0dSBtKw30eRVQzxhqg/ACA==", "dependencies": { "tslib": "^2.6.2" }, @@ -3923,13 +3467,13 @@ "node": ">=16.0.0" }, "peerDependencies": { - "@aws-sdk/client-dynamodb": "^3.632.0" + "@aws-sdk/client-dynamodb": "^3.637.0" } }, "node_modules/@aws-sdk/util-endpoints": { - "version": "3.632.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.632.0.tgz", - "integrity": "sha512-LlYMU8pAbcEQphOpE6xaNLJ8kPGhklZZTVzZVpVW477NaaGgoGTMYNXTABYHcxeF5E2lLrxql9OmVpvr8GWN8Q==", + "version": "3.637.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.637.0.tgz", + "integrity": "sha512-pAqOKUHeVWHEXXDIp/qoMk/6jyxIb6GGjnK1/f8dKHtKIEs4tKsnnL563gceEvdad53OPXIt86uoevCcCzmBnw==", "dependencies": { "@aws-sdk/types": "3.609.0", "@smithy/types": "^3.3.0", @@ -4200,6 +3744,18 @@ "node": ">=18.0.0" } }, + "node_modules/@azure/core-rest-pipeline/node_modules/agent-base": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", + "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", + "dev": true, + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/@azure/core-rest-pipeline/node_modules/https-proxy-agent": { "version": "7.0.5", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz", @@ -4288,6 +3844,27 @@ "node": ">=18.0.0" } }, + "node_modules/@azure/identity/node_modules/jwa": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.0.tgz", + "integrity": "sha512-jrZ2Qx916EA+fq9cEAeCROWPTfCwi1IVHqT2tapuqLEVVDKFDENFw1oL+MwrTvH6msKxsd1YTDVw6uKEcsrLEA==", + "dev": true, + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/@azure/identity/node_modules/jws": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.0.tgz", + "integrity": "sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==", + "dev": true, + "dependencies": { + "jwa": "^2.0.0", + "safe-buffer": "^5.0.1" + } + }, "node_modules/@azure/logger": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.1.4.tgz", @@ -4432,9 +4009,9 @@ } }, "node_modules/@babel/compat-data": { - "version": "7.25.2", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.25.2.tgz", - "integrity": "sha512-bYcppcpKBvX4znYaPEeFau03bp89ShqNMLs+rmdptMw+heSZh9+z84d2YG+K7cYLbWwzdjtDoW/uqZmPjulClQ==", + "version": "7.25.4", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.25.4.tgz", + "integrity": "sha512-+LGRog6RAsCJrrrg/IO6LGmpphNe5DiK30dGjCoxxeGv49B10/3XYGxPsAwrDlMFcFEvdAUavDT8r9k/hSyQqQ==", "dev": true, "engines": { "node": ">=6.9.0" @@ -4489,11 +4066,11 @@ } }, "node_modules/@babel/generator": { - "version": "7.25.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.25.0.tgz", - "integrity": "sha512-3LEEcj3PVW8pW2R1SR1M89g/qrYk/m/mB/tLqn7dn4sbBUQyTqnlod+II2U4dqiGtUmkcnAmkMDralTFZttRiw==", + "version": "7.25.4", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.25.4.tgz", + "integrity": "sha512-NFtZmZsyzDPJnk9Zg3BbTfKKc9UlHYzD0E//p2Z3B9nCwwtJW9T0gVbCz8+fBngnn4zf1Dr3IK8PHQQHq0lDQw==", "dependencies": { - "@babel/types": "^7.25.0", + "@babel/types": "^7.25.4", "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25", "jsesc": "^2.5.1" @@ -4544,9 +4121,9 @@ } }, "node_modules/@babel/helper-create-class-features-plugin": { - "version": "7.25.0", - "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.25.0.tgz", - "integrity": "sha512-GYM6BxeQsETc9mnct+nIIpf63SAyzvyYN7UB/IlTyd+MBg06afFGp0mIeUqGyWgS2mxad6vqbMrHVlaL3m70sQ==", + "version": "7.25.4", + "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.25.4.tgz", + "integrity": "sha512-ro/bFs3/84MDgDmMwbcHgDa8/E6J3QKNTk4xJJnVeFtGE+tL0K26E3pNxhYz2b67fJpt7Aphw5XcploKXuCvCQ==", "dev": true, "dependencies": { "@babel/helper-annotate-as-pure": "^7.24.7", @@ -4554,7 +4131,7 @@ "@babel/helper-optimise-call-expression": "^7.24.7", "@babel/helper-replace-supers": "^7.25.0", "@babel/helper-skip-transparent-expression-wrappers": "^7.24.7", - "@babel/traverse": "^7.25.0", + "@babel/traverse": "^7.25.4", "semver": "^6.3.1" }, "engines": { @@ -4788,11 +4365,11 @@ } }, "node_modules/@babel/parser": { - "version": "7.25.3", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.25.3.tgz", - "integrity": "sha512-iLTJKDbJ4hMvFPgQwwsVoxtHyWpKKPBrxkANrSYewDPaPpT5py5yeVkgPIJ7XYXhndxJpaA3PyALSXQ7u8e/Dw==", + "version": "7.25.4", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.25.4.tgz", + "integrity": "sha512-nq+eWrOgdtu3jG5Os4TQP3x3cLA8hR8TvJNjD8vnPa20WGycimcparWnLK4jJhElTK6SDyuJo1weMKO/5LpmLA==", "dependencies": { - "@babel/types": "^7.25.2" + "@babel/types": "^7.25.4" }, "bin": { "parser": "bin/babel-parser.js" @@ -5185,15 +4762,15 @@ } }, "node_modules/@babel/plugin-transform-async-generator-functions": { - "version": "7.25.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-7.25.0.tgz", - "integrity": "sha512-uaIi2FdqzjpAMvVqvB51S42oC2JEVgh0LDsGfZVDysWE8LrJtQC2jvKmOqEYThKyB7bDEb7BP1GYWDm7tABA0Q==", + "version": "7.25.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-7.25.4.tgz", + "integrity": "sha512-jz8cV2XDDTqjKPwVPJBIjORVEmSGYhdRa8e5k5+vN+uwcjSrSxUaebBRa4ko1jqNF2uxyg8G6XYk30Jv285xzg==", "dev": true, "dependencies": { "@babel/helper-plugin-utils": "^7.24.8", "@babel/helper-remap-async-to-generator": "^7.25.0", "@babel/plugin-syntax-async-generators": "^7.8.4", - "@babel/traverse": "^7.25.0" + "@babel/traverse": "^7.25.4" }, "engines": { "node": ">=6.9.0" @@ -5250,13 +4827,13 @@ } }, "node_modules/@babel/plugin-transform-class-properties": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-7.24.7.tgz", - "integrity": "sha512-vKbfawVYayKcSeSR5YYzzyXvsDFWU2mD8U5TFeXtbCPLFUqe7GyCgvO6XDHzje862ODrOwy6WCPmKeWHbCFJ4w==", + "version": "7.25.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-7.25.4.tgz", + "integrity": "sha512-nZeZHyCWPfjkdU5pA/uHiTaDAFUEqkpzf1YoQT2NeSynCGYq9rxfyI3XpQbfx/a0hSnFH6TGlEXvae5Vi7GD8g==", "dev": true, "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.24.7", - "@babel/helper-plugin-utils": "^7.24.7" + "@babel/helper-create-class-features-plugin": "^7.25.4", + "@babel/helper-plugin-utils": "^7.24.8" }, "engines": { "node": ">=6.9.0" @@ -5283,16 +4860,16 @@ } }, "node_modules/@babel/plugin-transform-classes": { - "version": "7.25.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.25.0.tgz", - "integrity": "sha512-xyi6qjr/fYU304fiRwFbekzkqVJZ6A7hOjWZd+89FVcBqPV3S9Wuozz82xdpLspckeaafntbzglaW4pqpzvtSw==", + "version": "7.25.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.25.4.tgz", + "integrity": "sha512-oexUfaQle2pF/b6E0dwsxQtAol9TLSO88kQvym6HHBWFliV2lGdrPieX+WgMRLSJDVzdYywk7jXbLPuO2KLTLg==", "dev": true, "dependencies": { "@babel/helper-annotate-as-pure": "^7.24.7", - "@babel/helper-compilation-targets": "^7.24.8", + "@babel/helper-compilation-targets": "^7.25.2", "@babel/helper-plugin-utils": "^7.24.8", "@babel/helper-replace-supers": "^7.25.0", - "@babel/traverse": "^7.25.0", + "@babel/traverse": "^7.25.4", "globals": "^11.1.0" }, "engines": { @@ -5736,13 +5313,13 @@ } }, "node_modules/@babel/plugin-transform-private-methods": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-7.24.7.tgz", - "integrity": "sha512-COTCOkG2hn4JKGEKBADkA8WNb35TGkkRbI5iT845dB+NyqgO8Hn+ajPbSnIQznneJTa3d30scb6iz/DhH8GsJQ==", + "version": "7.25.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-7.25.4.tgz", + "integrity": "sha512-ao8BG7E2b/URaUQGqN3Tlsg+M3KlHY6rJ1O1gXAEUnZoyNQnvKyH87Kfg+FoxSeyWUB8ISZZsC91C44ZuBFytw==", "dev": true, "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.24.7", - "@babel/helper-plugin-utils": "^7.24.7" + "@babel/helper-create-class-features-plugin": "^7.25.4", + "@babel/helper-plugin-utils": "^7.24.8" }, "engines": { "node": ">=6.9.0" @@ -6023,13 +5600,13 @@ } }, "node_modules/@babel/plugin-transform-unicode-sets-regex": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-sets-regex/-/plugin-transform-unicode-sets-regex-7.24.7.tgz", - "integrity": "sha512-2G8aAvF4wy1w/AGZkemprdGMRg5o6zPNhbHVImRz3lss55TYCBd6xStN19rt8XJHq20sqV0JbyWjOWwQRwV/wg==", + "version": "7.25.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-sets-regex/-/plugin-transform-unicode-sets-regex-7.25.4.tgz", + "integrity": "sha512-qesBxiWkgN1Q+31xUE9RcMk79eOXXDCv6tfyGMRSs4RGlioSg2WVyQAm07k726cSE56pa+Kb0y9epX2qaXzTvA==", "dev": true, "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.24.7", - "@babel/helper-plugin-utils": "^7.24.7" + "@babel/helper-create-regexp-features-plugin": "^7.25.2", + "@babel/helper-plugin-utils": "^7.24.8" }, "engines": { "node": ">=6.9.0" @@ -6039,12 +5616,12 @@ } }, "node_modules/@babel/preset-env": { - "version": "7.25.3", - "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.25.3.tgz", - "integrity": "sha512-QsYW7UeAaXvLPX9tdVliMJE7MD7M6MLYVTovRTIwhoYQVFHR1rM4wO8wqAezYi3/BpSD+NzVCZ69R6smWiIi8g==", + "version": "7.25.4", + "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.25.4.tgz", + "integrity": "sha512-W9Gyo+KmcxjGahtt3t9fb14vFRWvPpu5pT6GBlovAK6BTBcxgjfVMSQCfJl4oi35ODrxP6xx2Wr8LNST57Mraw==", "dev": true, "dependencies": { - "@babel/compat-data": "^7.25.2", + "@babel/compat-data": "^7.25.4", "@babel/helper-compilation-targets": "^7.25.2", "@babel/helper-plugin-utils": "^7.24.8", "@babel/helper-validator-option": "^7.24.8", @@ -6073,13 +5650,13 @@ "@babel/plugin-syntax-top-level-await": "^7.14.5", "@babel/plugin-syntax-unicode-sets-regex": "^7.18.6", "@babel/plugin-transform-arrow-functions": "^7.24.7", - "@babel/plugin-transform-async-generator-functions": "^7.25.0", + "@babel/plugin-transform-async-generator-functions": "^7.25.4", "@babel/plugin-transform-async-to-generator": "^7.24.7", "@babel/plugin-transform-block-scoped-functions": "^7.24.7", "@babel/plugin-transform-block-scoping": "^7.25.0", - "@babel/plugin-transform-class-properties": "^7.24.7", + "@babel/plugin-transform-class-properties": "^7.25.4", "@babel/plugin-transform-class-static-block": "^7.24.7", - "@babel/plugin-transform-classes": "^7.25.0", + "@babel/plugin-transform-classes": "^7.25.4", "@babel/plugin-transform-computed-properties": "^7.24.7", "@babel/plugin-transform-destructuring": "^7.24.8", "@babel/plugin-transform-dotall-regex": "^7.24.7", @@ -6107,7 +5684,7 @@ "@babel/plugin-transform-optional-catch-binding": "^7.24.7", "@babel/plugin-transform-optional-chaining": "^7.24.8", "@babel/plugin-transform-parameters": "^7.24.7", - "@babel/plugin-transform-private-methods": "^7.24.7", + "@babel/plugin-transform-private-methods": "^7.25.4", "@babel/plugin-transform-private-property-in-object": "^7.24.7", "@babel/plugin-transform-property-literals": "^7.24.7", "@babel/plugin-transform-regenerator": "^7.24.7", @@ -6120,10 +5697,10 @@ "@babel/plugin-transform-unicode-escapes": "^7.24.7", "@babel/plugin-transform-unicode-property-regex": "^7.24.7", "@babel/plugin-transform-unicode-regex": "^7.24.7", - "@babel/plugin-transform-unicode-sets-regex": "^7.24.7", + "@babel/plugin-transform-unicode-sets-regex": "^7.25.4", "@babel/preset-modules": "0.1.6-no-external-plugins", "babel-plugin-polyfill-corejs2": "^0.4.10", - "babel-plugin-polyfill-corejs3": "^0.10.4", + "babel-plugin-polyfill-corejs3": "^0.10.6", "babel-plugin-polyfill-regenerator": "^0.6.1", "core-js-compat": "^3.37.1", "semver": "^6.3.1" @@ -6238,15 +5815,15 @@ } }, "node_modules/@babel/traverse": { - "version": "7.25.3", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.25.3.tgz", - "integrity": "sha512-HefgyP1x754oGCsKmV5reSmtV7IXj/kpaE1XYY+D9G5PvKKoFfSbiS4M77MdjuwlZKDIKFCffq9rPU+H/s3ZdQ==", + "version": "7.25.4", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.25.4.tgz", + "integrity": "sha512-VJ4XsrD+nOvlXyLzmLzUs/0qjFS4sK30te5yEFlvbbUNEgKaVb2BHZUpAL+ttLPQAHNrsI3zZisbfha5Cvr8vg==", "dependencies": { "@babel/code-frame": "^7.24.7", - "@babel/generator": "^7.25.0", - "@babel/parser": "^7.25.3", + "@babel/generator": "^7.25.4", + "@babel/parser": "^7.25.4", "@babel/template": "^7.25.0", - "@babel/types": "^7.25.2", + "@babel/types": "^7.25.4", "debug": "^4.3.1", "globals": "^11.1.0" }, @@ -6255,9 +5832,9 @@ } }, "node_modules/@babel/types": { - "version": "7.25.2", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.25.2.tgz", - "integrity": "sha512-YTnYtra7W9e6/oAZEHj0bJehPRUlLH9/fbpT5LfB0NhQXyALCRkRs3zH9v07IYhkgpqX6Z78FnuccZr/l4Fs4Q==", + "version": "7.25.4", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.25.4.tgz", + "integrity": "sha512-zQ1ijeeCXVEh+aNL0RlmkPkG8HUiDcU2pzQQFjtbntgAczRASFzj4H+6+bV+dy1ntKR14I/DypeuRG1uma98iQ==", "dependencies": { "@babel/helper-string-parser": "^7.24.8", "@babel/helper-validator-identifier": "^7.24.7", @@ -6295,9 +5872,9 @@ } }, "node_modules/@codegenie/serverless-express": { - "version": "4.15.0", - "resolved": "https://registry.npmjs.org/@codegenie/serverless-express/-/serverless-express-4.15.0.tgz", - "integrity": "sha512-adnKbnW1Tg5LAe0lcbyoRchu8G6+gLwP1rvgwfHvTbCwvBQNfhsgnzq4cKkLn7ZKn2sa4JZNis/Gn/2jWBWa4A==", + "version": "4.14.1", + "resolved": "https://registry.npmjs.org/@codegenie/serverless-express/-/serverless-express-4.14.1.tgz", + "integrity": "sha512-B90/1OmA9mf9bEJnplLj7FGf+N2v2ikB68c/9W9uXmCa4ep/V00ymCiivwGLyeuzQRW33tcj4+KxZ2utfmu39Q==", "dev": true, "engines": { "node": ">=12" @@ -7377,6 +6954,18 @@ "node": ">=16.3.0" } }, + "node_modules/@cypress/puppeteer/node_modules/agent-base": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", + "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", + "dev": true, + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/@cypress/puppeteer/node_modules/chromium-bidi": { "version": "0.5.8", "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-0.5.8.tgz", @@ -7737,14 +7326,14 @@ "integrity": "sha512-30FAj7/EoJ5mwVPOWhAyCX+FPfMDrVecJAM+Iw9NRoSl4BBAQeqj4cApHHUXOVvIPgLVDsCFoz/hGD+5QQD1GQ==" }, "node_modules/@emotion/react": { - "version": "11.13.3", - "resolved": "https://registry.npmjs.org/@emotion/react/-/react-11.13.3.tgz", - "integrity": "sha512-lIsdU6JNrmYfJ5EbUCf4xW1ovy5wKQ2CkPRM4xogziOxH1nXxBSjpC9YqbFAP7circxMfYp+6x676BqWcEiixg==", + "version": "11.13.0", + "resolved": "https://registry.npmjs.org/@emotion/react/-/react-11.13.0.tgz", + "integrity": "sha512-WkL+bw1REC2VNV1goQyfxjx1GYJkcc23CRQkXX+vZNLINyfI7o+uUn/rTGPt/xJ3bJHd5GcljgnxHf4wRw5VWQ==", "dependencies": { "@babel/runtime": "^7.18.3", "@emotion/babel-plugin": "^11.12.0", "@emotion/cache": "^11.13.0", - "@emotion/serialize": "^1.3.1", + "@emotion/serialize": "^1.3.0", "@emotion/use-insertion-effect-with-fallbacks": "^1.1.0", "@emotion/utils": "^1.4.0", "@emotion/weak-memoize": "^0.4.0", @@ -7760,13 +7349,13 @@ } }, "node_modules/@emotion/serialize": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@emotion/serialize/-/serialize-1.3.1.tgz", - "integrity": "sha512-dEPNKzBPU+vFPGa+z3axPRn8XVDetYORmDC0wAiej+TNcOZE70ZMJa0X7JdeoM6q/nWTMZeLpN/fTnD9o8MQBA==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@emotion/serialize/-/serialize-1.3.0.tgz", + "integrity": "sha512-jACuBa9SlYajnpIVXB+XOXnfJHyckDfe6fOpORIM6yhBDlqGuExvDdZYHDQGoDf3bZXGv7tNr+LpLjJqiEQ6EA==", "dependencies": { "@emotion/hash": "^0.9.2", "@emotion/memoize": "^0.9.0", - "@emotion/unitless": "^0.10.0", + "@emotion/unitless": "^0.9.0", "@emotion/utils": "^1.4.0", "csstype": "^3.0.2" } @@ -7777,9 +7366,9 @@ "integrity": "sha512-fTBW9/8r2w3dXWYM4HCB1Rdp8NLibOw2+XELH5m5+AkWiL/KqYX6dc0kKYlaYyKjrQ6ds33MCdMPEwgs2z1rqg==" }, "node_modules/@emotion/unitless": { - "version": "0.10.0", - "resolved": "https://registry.npmjs.org/@emotion/unitless/-/unitless-0.10.0.tgz", - "integrity": "sha512-dFoMUuQA20zvtVTuxZww6OHoJYgrzfKM1t52mVySDJnMSEa08ruEvdYQbhvyu6soU+NeLVd3yKfTfT0NeV6qGg==" + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/@emotion/unitless/-/unitless-0.9.0.tgz", + "integrity": "sha512-TP6GgNZtmtFaFcsOgExdnfxLLpRDla4Q66tnenA9CktvVSdNKDvMVuUah4QvWPIpNjrWsGg3qeGo9a43QooGZQ==" }, "node_modules/@emotion/use-insertion-effect-with-fallbacks": { "version": "1.1.0", @@ -7800,9 +7389,9 @@ "integrity": "sha512-snKqtPW01tN0ui7yu9rGv69aJXr/a/Ywvl11sUjNtEcRc+ng/mQriFL0wLXMef74iHa/EkftbDzU9F8iFbH+zg==" }, "node_modules/@esbuild/aix-ppc64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.23.0.tgz", - "integrity": "sha512-3sG8Zwa5fMcA9bgqB8AfWPQ+HFke6uD3h1s3RIwUNK8EG7a4buxvuFTs3j1IMs2NXAk9F30C/FF4vxRgQCcmoQ==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.23.1.tgz", + "integrity": "sha512-6VhYk1diRqrhBAqpJEdjASR/+WVRtfjpqKuNw11cLiaWpAT/Uu+nokB+UJnevzy/P9C/ty6AOe0dwueMrGh/iQ==", "cpu": [ "ppc64" ], @@ -7816,9 +7405,9 @@ } }, "node_modules/@esbuild/android-arm": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.23.0.tgz", - "integrity": "sha512-+KuOHTKKyIKgEEqKbGTK8W7mPp+hKinbMBeEnNzjJGyFcWsfrXjSTNluJHCY1RqhxFurdD8uNXQDei7qDlR6+g==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.23.1.tgz", + "integrity": "sha512-uz6/tEy2IFm9RYOyvKl88zdzZfwEfKZmnX9Cj1BHjeSGNuGLuMD1kR8y5bteYmwqKm1tj8m4cb/aKEorr6fHWQ==", "cpu": [ "arm" ], @@ -7832,9 +7421,9 @@ } }, "node_modules/@esbuild/android-arm64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.23.0.tgz", - "integrity": "sha512-EuHFUYkAVfU4qBdyivULuu03FhJO4IJN9PGuABGrFy4vUuzk91P2d+npxHcFdpUnfYKy0PuV+n6bKIpHOB3prQ==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.23.1.tgz", + "integrity": "sha512-xw50ipykXcLstLeWH7WRdQuysJqejuAGPd30vd1i5zSyKK3WE+ijzHmLKxdiCMtH1pHz78rOg0BKSYOSB/2Khw==", "cpu": [ "arm64" ], @@ -7848,9 +7437,9 @@ } }, "node_modules/@esbuild/android-x64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.23.0.tgz", - "integrity": "sha512-WRrmKidLoKDl56LsbBMhzTTBxrsVwTKdNbKDalbEZr0tcsBgCLbEtoNthOW6PX942YiYq8HzEnb4yWQMLQuipQ==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.23.1.tgz", + "integrity": "sha512-nlN9B69St9BwUoB+jkyU090bru8L0NA3yFvAd7k8dNsVH8bi9a8cUAUSEcEEgTp2z3dbEDGJGfP6VUnkQnlReg==", "cpu": [ "x64" ], @@ -7864,9 +7453,9 @@ } }, "node_modules/@esbuild/darwin-arm64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.23.0.tgz", - "integrity": "sha512-YLntie/IdS31H54Ogdn+v50NuoWF5BDkEUFpiOChVa9UnKpftgwzZRrI4J132ETIi+D8n6xh9IviFV3eXdxfow==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.23.1.tgz", + "integrity": "sha512-YsS2e3Wtgnw7Wq53XXBLcV6JhRsEq8hkfg91ESVadIrzr9wO6jJDMZnCQbHm1Guc5t/CdDiFSSfWP58FNuvT3Q==", "cpu": [ "arm64" ], @@ -7880,9 +7469,9 @@ } }, "node_modules/@esbuild/darwin-x64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.23.0.tgz", - "integrity": "sha512-IMQ6eme4AfznElesHUPDZ+teuGwoRmVuuixu7sv92ZkdQcPbsNHzutd+rAfaBKo8YK3IrBEi9SLLKWJdEvJniQ==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.23.1.tgz", + "integrity": "sha512-aClqdgTDVPSEGgoCS8QDG37Gu8yc9lTHNAQlsztQ6ENetKEO//b8y31MMu2ZaPbn4kVsIABzVLXYLhCGekGDqw==", "cpu": [ "x64" ], @@ -7896,9 +7485,9 @@ } }, "node_modules/@esbuild/freebsd-arm64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.23.0.tgz", - "integrity": "sha512-0muYWCng5vqaxobq6LB3YNtevDFSAZGlgtLoAc81PjUfiFz36n4KMpwhtAd4he8ToSI3TGyuhyx5xmiWNYZFyw==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.23.1.tgz", + "integrity": "sha512-h1k6yS8/pN/NHlMl5+v4XPfikhJulk4G+tKGFIOwURBSFzE8bixw1ebjluLOjfwtLqY0kewfjLSrO6tN2MgIhA==", "cpu": [ "arm64" ], @@ -7912,9 +7501,9 @@ } }, "node_modules/@esbuild/freebsd-x64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.23.0.tgz", - "integrity": "sha512-XKDVu8IsD0/q3foBzsXGt/KjD/yTKBCIwOHE1XwiXmrRwrX6Hbnd5Eqn/WvDekddK21tfszBSrE/WMaZh+1buQ==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.23.1.tgz", + "integrity": "sha512-lK1eJeyk1ZX8UklqFd/3A60UuZ/6UVfGT2LuGo3Wp4/z7eRTRYY+0xOu2kpClP+vMTi9wKOfXi2vjUpO1Ro76g==", "cpu": [ "x64" ], @@ -7928,9 +7517,9 @@ } }, "node_modules/@esbuild/linux-arm": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.23.0.tgz", - "integrity": "sha512-SEELSTEtOFu5LPykzA395Mc+54RMg1EUgXP+iw2SJ72+ooMwVsgfuwXo5Fn0wXNgWZsTVHwY2cg4Vi/bOD88qw==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.23.1.tgz", + "integrity": "sha512-CXXkzgn+dXAPs3WBwE+Kvnrf4WECwBdfjfeYHpMeVxWE0EceB6vhWGShs6wi0IYEqMSIzdOF1XjQ/Mkm5d7ZdQ==", "cpu": [ "arm" ], @@ -7944,9 +7533,9 @@ } }, "node_modules/@esbuild/linux-arm64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.23.0.tgz", - "integrity": "sha512-j1t5iG8jE7BhonbsEg5d9qOYcVZv/Rv6tghaXM/Ug9xahM0nX/H2gfu6X6z11QRTMT6+aywOMA8TDkhPo8aCGw==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.23.1.tgz", + "integrity": "sha512-/93bf2yxencYDnItMYV/v116zff6UyTjo4EtEQjUBeGiVpMmffDNUyD9UN2zV+V3LRV3/on4xdZ26NKzn6754g==", "cpu": [ "arm64" ], @@ -7960,9 +7549,9 @@ } }, "node_modules/@esbuild/linux-ia32": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.23.0.tgz", - "integrity": "sha512-P7O5Tkh2NbgIm2R6x1zGJJsnacDzTFcRWZyTTMgFdVit6E98LTxO+v8LCCLWRvPrjdzXHx9FEOA8oAZPyApWUA==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.23.1.tgz", + "integrity": "sha512-VTN4EuOHwXEkXzX5nTvVY4s7E/Krz7COC8xkftbbKRYAl96vPiUssGkeMELQMOnLOJ8k3BY1+ZY52tttZnHcXQ==", "cpu": [ "ia32" ], @@ -7976,9 +7565,9 @@ } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.23.0.tgz", - "integrity": "sha512-InQwepswq6urikQiIC/kkx412fqUZudBO4SYKu0N+tGhXRWUqAx+Q+341tFV6QdBifpjYgUndV1hhMq3WeJi7A==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.23.1.tgz", + "integrity": "sha512-Vx09LzEoBa5zDnieH8LSMRToj7ir/Jeq0Gu6qJ/1GcBq9GkfoEAoXvLiW1U9J1qE/Y/Oyaq33w5p2ZWrNNHNEw==", "cpu": [ "loong64" ], @@ -7992,9 +7581,9 @@ } }, "node_modules/@esbuild/linux-mips64el": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.23.0.tgz", - "integrity": "sha512-J9rflLtqdYrxHv2FqXE2i1ELgNjT+JFURt/uDMoPQLcjWQA5wDKgQA4t/dTqGa88ZVECKaD0TctwsUfHbVoi4w==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.23.1.tgz", + "integrity": "sha512-nrFzzMQ7W4WRLNUOU5dlWAqa6yVeI0P78WKGUo7lg2HShq/yx+UYkeNSE0SSfSure0SqgnsxPvmAUu/vu0E+3Q==", "cpu": [ "mips64el" ], @@ -8008,9 +7597,9 @@ } }, "node_modules/@esbuild/linux-ppc64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.23.0.tgz", - "integrity": "sha512-cShCXtEOVc5GxU0fM+dsFD10qZ5UpcQ8AM22bYj0u/yaAykWnqXJDpd77ublcX6vdDsWLuweeuSNZk4yUxZwtw==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.23.1.tgz", + "integrity": "sha512-dKN8fgVqd0vUIjxuJI6P/9SSSe/mB9rvA98CSH2sJnlZ/OCZWO1DJvxj8jvKTfYUdGfcq2dDxoKaC6bHuTlgcw==", "cpu": [ "ppc64" ], @@ -8024,9 +7613,9 @@ } }, "node_modules/@esbuild/linux-riscv64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.23.0.tgz", - "integrity": "sha512-HEtaN7Y5UB4tZPeQmgz/UhzoEyYftbMXrBCUjINGjh3uil+rB/QzzpMshz3cNUxqXN7Vr93zzVtpIDL99t9aRw==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.23.1.tgz", + "integrity": "sha512-5AV4Pzp80fhHL83JM6LoA6pTQVWgB1HovMBsLQ9OZWLDqVY8MVobBXNSmAJi//Csh6tcY7e7Lny2Hg1tElMjIA==", "cpu": [ "riscv64" ], @@ -8040,9 +7629,9 @@ } }, "node_modules/@esbuild/linux-s390x": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.23.0.tgz", - "integrity": "sha512-WDi3+NVAuyjg/Wxi+o5KPqRbZY0QhI9TjrEEm+8dmpY9Xir8+HE/HNx2JoLckhKbFopW0RdO2D72w8trZOV+Wg==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.23.1.tgz", + "integrity": "sha512-9ygs73tuFCe6f6m/Tb+9LtYxWR4c9yg7zjt2cYkjDbDpV/xVn+68cQxMXCjUpYwEkze2RcU/rMnfIXNRFmSoDw==", "cpu": [ "s390x" ], @@ -8056,9 +7645,9 @@ } }, "node_modules/@esbuild/linux-x64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.23.0.tgz", - "integrity": "sha512-a3pMQhUEJkITgAw6e0bWA+F+vFtCciMjW/LPtoj99MhVt+Mfb6bbL9hu2wmTZgNd994qTAEw+U/r6k3qHWWaOQ==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.23.1.tgz", + "integrity": "sha512-EV6+ovTsEXCPAp58g2dD68LxoP/wK5pRvgy0J/HxPGB009omFPv3Yet0HiaqvrIrgPTBuC6wCH1LTOY91EO5hQ==", "cpu": [ "x64" ], @@ -8072,9 +7661,9 @@ } }, "node_modules/@esbuild/netbsd-x64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.23.0.tgz", - "integrity": "sha512-cRK+YDem7lFTs2Q5nEv/HHc4LnrfBCbH5+JHu6wm2eP+d8OZNoSMYgPZJq78vqQ9g+9+nMuIsAO7skzphRXHyw==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.23.1.tgz", + "integrity": "sha512-aevEkCNu7KlPRpYLjwmdcuNz6bDFiE7Z8XC4CPqExjTvrHugh28QzUXVOZtiYghciKUacNktqxdpymplil1beA==", "cpu": [ "x64" ], @@ -8088,9 +7677,9 @@ } }, "node_modules/@esbuild/openbsd-arm64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.23.0.tgz", - "integrity": "sha512-suXjq53gERueVWu0OKxzWqk7NxiUWSUlrxoZK7usiF50C6ipColGR5qie2496iKGYNLhDZkPxBI3erbnYkU0rQ==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.23.1.tgz", + "integrity": "sha512-3x37szhLexNA4bXhLrCC/LImN/YtWis6WXr1VESlfVtVeoFJBRINPJ3f0a/6LV8zpikqoUg4hyXw0sFBt5Cr+Q==", "cpu": [ "arm64" ], @@ -8104,9 +7693,9 @@ } }, "node_modules/@esbuild/openbsd-x64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.23.0.tgz", - "integrity": "sha512-6p3nHpby0DM/v15IFKMjAaayFhqnXV52aEmv1whZHX56pdkK+MEaLoQWj+H42ssFarP1PcomVhbsR4pkz09qBg==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.23.1.tgz", + "integrity": "sha512-aY2gMmKmPhxfU+0EdnN+XNtGbjfQgwZj43k8G3fyrDM/UdZww6xrWxmDkuz2eCZchqVeABjV5BpildOrUbBTqA==", "cpu": [ "x64" ], @@ -8120,9 +7709,9 @@ } }, "node_modules/@esbuild/sunos-x64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.23.0.tgz", - "integrity": "sha512-BFelBGfrBwk6LVrmFzCq1u1dZbG4zy/Kp93w2+y83Q5UGYF1d8sCzeLI9NXjKyujjBBniQa8R8PzLFAUrSM9OA==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.23.1.tgz", + "integrity": "sha512-RBRT2gqEl0IKQABT4XTj78tpk9v7ehp+mazn2HbUeZl1YMdaGAQqhapjGTCe7uw7y0frDi4gS0uHzhvpFuI1sA==", "cpu": [ "x64" ], @@ -8136,9 +7725,9 @@ } }, "node_modules/@esbuild/win32-arm64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.23.0.tgz", - "integrity": "sha512-lY6AC8p4Cnb7xYHuIxQ6iYPe6MfO2CC43XXKo9nBXDb35krYt7KGhQnOkRGar5psxYkircpCqfbNDB4uJbS2jQ==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.23.1.tgz", + "integrity": "sha512-4O+gPR5rEBe2FpKOVyiJ7wNDPA8nGzDuJ6gN4okSA1gEOYZ67N8JPk58tkWtdtPeLz7lBnY6I5L3jdsr3S+A6A==", "cpu": [ "arm64" ], @@ -8152,9 +7741,9 @@ } }, "node_modules/@esbuild/win32-ia32": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.23.0.tgz", - "integrity": "sha512-7L1bHlOTcO4ByvI7OXVI5pNN6HSu6pUQq9yodga8izeuB1KcT2UkHaH6118QJwopExPn0rMHIseCTx1CRo/uNA==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.23.1.tgz", + "integrity": "sha512-BcaL0Vn6QwCwre3Y717nVHZbAa4UBEigzFm6VdsVdT/MbZ38xoj1X9HPkZhbmaBGUD1W8vxAfffbDe8bA6AKnQ==", "cpu": [ "ia32" ], @@ -8168,9 +7757,9 @@ } }, "node_modules/@esbuild/win32-x64": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.23.0.tgz", - "integrity": "sha512-Arm+WgUFLUATuoxCJcahGuk6Yj9Pzxd6l11Zb/2aAuv5kWWvvfhLFo2fni4uSK5vzlUdCGZ/BdV5tH8klj8p8g==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.23.1.tgz", + "integrity": "sha512-BHpFFeslkWrXWyUPnbKm+xYYVYruCinGcftSBaa8zoF9hZO4BcSCFUvHVTtzpIY6YzUnYtuEhZ+C9iEXjxnasg==", "cpu": [ "x64" ], @@ -8351,26 +7940,26 @@ } }, "node_modules/@floating-ui/core": { - "version": "1.6.7", - "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.6.7.tgz", - "integrity": "sha512-yDzVT/Lm101nQ5TCVeK65LtdN7Tj4Qpr9RTXJ2vPFLqtLxwOrpoxAHAJI8J3yYWUc40J0BDBheaitK5SJmno2g==", + "version": "1.6.6", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.6.6.tgz", + "integrity": "sha512-Vkvsw6EcpMHjvZZdMkSY+djMGFbt7CRssW99Ne8tar2WLnZ/l3dbxeTShbLQj+/s35h+Qb4cmnob+EzwtjrXGQ==", "dependencies": { - "@floating-ui/utils": "^0.2.7" + "@floating-ui/utils": "^0.2.6" } }, "node_modules/@floating-ui/dom": { - "version": "1.6.10", - "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.6.10.tgz", - "integrity": "sha512-fskgCFv8J8OamCmyun8MfjB1Olfn+uZKjOKZ0vhYF3gRmEUXcGOjxWL8bBr7i4kIuPZ2KD2S3EUIOxnjC8kl2A==", + "version": "1.6.9", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.6.9.tgz", + "integrity": "sha512-zB1PcI350t4tkm3rvUhSRKa9sT7vH5CrAbQxW+VaPYJXKAO0gsg4CTueL+6Ajp7XzAQC8CW4Jj1Wgqc0sB6oUQ==", "dependencies": { "@floating-ui/core": "^1.6.0", - "@floating-ui/utils": "^0.2.7" + "@floating-ui/utils": "^0.2.6" } }, "node_modules/@floating-ui/utils": { - "version": "0.2.7", - "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.7.tgz", - "integrity": "sha512-X8R8Oj771YRl/w+c1HqAC1szL8zWQRwFvgDwT129k9ACdBoud/+/rX9V0qiMl6LWUdP9voC2nDVZYPMQQsb6eA==" + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.6.tgz", + "integrity": "sha512-0KI3zGxIUs1KDR/pjQPdJH4Z8nGBm0yJ5WRoRfdw1Kzeh45jkIfA0rmD0kBF6fKHH+xaH7g8y4jIXyAV5MGK3g==" }, "node_modules/@fortawesome/fontawesome-common-types": { "version": "0.2.36", @@ -9401,6 +8990,18 @@ "node": "^16.14.0 || >=18.0.0" } }, + "node_modules/@npmcli/agent/node_modules/agent-base": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", + "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", + "dev": true, + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/@npmcli/agent/node_modules/https-proxy-agent": { "version": "7.0.5", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz", @@ -10409,6 +10010,15 @@ "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, + "node_modules/@opentelemetry/exporter-zipkin/node_modules/@opentelemetry/semantic-conventions": { + "version": "1.25.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.25.1.tgz", + "integrity": "sha512-ZDjMJJQRlyk8A1KZFCc+bCbsyrn1wTwdNt56F7twdfUfnHUZUq77/WfONCj8p72NZOyP7pNTdUWSTYC3GTbuuQ==", + "dev": true, + "engines": { + "node": ">=14" + } + }, "node_modules/@opentelemetry/otlp-exporter-base": { "version": "0.41.2", "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.41.2.tgz", @@ -10569,6 +10179,15 @@ "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, + "node_modules/@opentelemetry/resources/node_modules/@opentelemetry/semantic-conventions": { + "version": "1.25.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.25.1.tgz", + "integrity": "sha512-ZDjMJJQRlyk8A1KZFCc+bCbsyrn1wTwdNt56F7twdfUfnHUZUq77/WfONCj8p72NZOyP7pNTdUWSTYC3GTbuuQ==", + "dev": true, + "engines": { + "node": ">=14" + } + }, "node_modules/@opentelemetry/sdk-logs": { "version": "0.41.2", "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-logs/-/sdk-logs-0.41.2.tgz", @@ -10643,6 +10262,15 @@ "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, + "node_modules/@opentelemetry/sdk-metrics/node_modules/@opentelemetry/semantic-conventions": { + "version": "1.25.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.25.1.tgz", + "integrity": "sha512-ZDjMJJQRlyk8A1KZFCc+bCbsyrn1wTwdNt56F7twdfUfnHUZUq77/WfONCj8p72NZOyP7pNTdUWSTYC3GTbuuQ==", + "dev": true, + "engines": { + "node": ">=14" + } + }, "node_modules/@opentelemetry/sdk-trace-base": { "version": "1.25.1", "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.25.1.tgz", @@ -10675,7 +10303,7 @@ "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, - "node_modules/@opentelemetry/semantic-conventions": { + "node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/semantic-conventions": { "version": "1.25.1", "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.25.1.tgz", "integrity": "sha512-ZDjMJJQRlyk8A1KZFCc+bCbsyrn1wTwdNt56F7twdfUfnHUZUq77/WfONCj8p72NZOyP7pNTdUWSTYC3GTbuuQ==", @@ -10684,6 +10312,15 @@ "node": ">=14" } }, + "node_modules/@opentelemetry/semantic-conventions": { + "version": "1.26.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.26.0.tgz", + "integrity": "sha512-U9PJlOswJPSgQVPI+XEuNLElyFWkb0hAiMg+DExD9V0St03X2lPHGMdxMY/LrVmoukuIpXJ12oyrOtEZ4uXFkw==", + "dev": true, + "engines": { + "node": ">=14" + } + }, "node_modules/@pdf-lib/standard-fonts": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/@pdf-lib/standard-fonts/-/standard-fonts-1.0.0.tgz", @@ -10985,9 +10622,9 @@ } }, "node_modules/@sinonjs/text-encoding": { - "version": "0.7.3", - "resolved": "https://registry.npmjs.org/@sinonjs/text-encoding/-/text-encoding-0.7.3.tgz", - "integrity": "sha512-DE427ROAphMQzU4ENbliGYrBSYPXF+TtLg9S8vzeA+OF4ZKzoDdzfL8sxuMUGS/lgRhM6j1URSk9ghf7Xo1tyA==", + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/@sinonjs/text-encoding/-/text-encoding-0.7.2.tgz", + "integrity": "sha512-sXXKG+uL9IrKqViTtao2Ws6dy0znu9sOaP1di/jKGW1M6VssO8vlpXCQcpZ+jisQ1tTFAC5Jo/EOzFbggBagFQ==", "dev": true }, "node_modules/@smithy/abort-controller": { @@ -12886,9 +12523,9 @@ } }, "node_modules/@types/node": { - "version": "22.4.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.4.0.tgz", - "integrity": "sha512-49AbMDwYUz7EXxKU/r7mXOsxwFr4BYbvB7tWYxVuLdb2ibd30ijjXINSMAHiEEZk5PCRBmW1gUeisn2VMKt3cQ==", + "version": "22.5.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.5.0.tgz", + "integrity": "sha512-DkFrJOe+rfdHTqqMg0bSNlGlQ85hSoh2TPzZyhHsXnMtligRWpxUySiyw8FY14ITt24HVCiQPWxS3KO/QlGmWg==", "dependencies": { "undici-types": "~6.19.2" } @@ -12941,9 +12578,9 @@ "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==" }, "node_modules/@types/react": { - "version": "18.3.3", - "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.3.tgz", - "integrity": "sha512-hti/R0pS0q1/xx+TsI73XIqk26eBsISZ2R0wUijXIngRK9R/e7Xw/cXVxQK7R5JjW+SV4zGcn5hXjudkN/pLIw==", + "version": "18.3.4", + "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.4.tgz", + "integrity": "sha512-J7W30FTdfCxDDjmfRM+/JqLHBIyl7xUIp9kwK637FGmY7+mkSFSe6L4jpZzhj5QMfLssSDP4/i75AKkrdC7/Jw==", "dependencies": { "@types/prop-types": "*", "csstype": "^3.0.2" @@ -12958,19 +12595,10 @@ "@types/react": "*" } }, - "node_modules/@types/react-paginate": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/@types/react-paginate/-/react-paginate-7.1.4.tgz", - "integrity": "sha512-6fqZvDzRJHubOGl6c7cGFC9ysgQSWYy0Gpus9HjORpydlcXgPnT8x+aKgqwCdtpZrRTwcBz2Q7JWAOYaRrsXGg==", - "dev": true, - "dependencies": { - "@types/react": "*" - } - }, "node_modules/@types/react-transition-group": { - "version": "4.4.11", - "resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.11.tgz", - "integrity": "sha512-RM05tAniPZ5DZPzzNFP+DmrcOdD0efDUxMy3145oljWSl3x9ZV5vhme98gTxFrj2lhXvmGNnUiuDyJgY9IKkNA==", + "version": "4.4.10", + "resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.10.tgz", + "integrity": "sha512-hT/+s0VQs2ojCX823m60m5f0sL5idt9SO6Tj6Dg+rdphGPIeJbJ6CxvBYkgkGKrYeDjvIpKTR38UzmtHJOGW3Q==", "dependencies": { "@types/react": "*" } @@ -13063,9 +12691,9 @@ } }, "node_modules/@types/yargs": { - "version": "17.0.33", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.33.tgz", - "integrity": "sha512-WpxBCKWPLr4xSsHgz511rFJAM+wS28w2zEO1QDNY5zM/S8ok70NNfztH0xwhqKyaK0OHCbN98LDAZuy1ctxDkA==", + "version": "17.0.32", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.32.tgz", + "integrity": "sha512-xQ67Yc/laOG5uMfX/093MRlGGCIBzZMarVa+gfNKJxWAIgykYpVGkBdbqEzGDDfCrVUj6Hiff4mTZ5BA6TmAog==", "dev": true, "dependencies": { "@types/yargs-parser": "*" @@ -13088,16 +12716,16 @@ } }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.1.0.tgz", - "integrity": "sha512-LlNBaHFCEBPHyD4pZXb35mzjGkuGKXU5eeCA1SxvHfiRES0E82dOounfVpL4DCqYvJEKab0bZIA0gCRpdLKkCw==", + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.2.0.tgz", + "integrity": "sha512-02tJIs655em7fvt9gps/+4k4OsKULYGtLBPJfOsmOq1+3cdClYiF0+d6mHu6qDnTcg88wJBkcPLpQhq7FyDz0A==", "dev": true, "dependencies": { "@eslint-community/regexpp": "^4.10.0", - "@typescript-eslint/scope-manager": "8.1.0", - "@typescript-eslint/type-utils": "8.1.0", - "@typescript-eslint/utils": "8.1.0", - "@typescript-eslint/visitor-keys": "8.1.0", + "@typescript-eslint/scope-manager": "8.2.0", + "@typescript-eslint/type-utils": "8.2.0", + "@typescript-eslint/utils": "8.2.0", + "@typescript-eslint/visitor-keys": "8.2.0", "graphemer": "^1.4.0", "ignore": "^5.3.1", "natural-compare": "^1.4.0", @@ -13121,15 +12749,15 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.1.0.tgz", - "integrity": "sha512-U7iTAtGgJk6DPX9wIWPPOlt1gO57097G06gIcl0N0EEnNw8RGD62c+2/DiP/zL7KrkqnnqF7gtFGR7YgzPllTA==", + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.2.0.tgz", + "integrity": "sha512-j3Di+o0lHgPrb7FxL3fdEy6LJ/j2NE8u+AP/5cQ9SKb+JLH6V6UHDqJ+e0hXBkHP1wn1YDFjYCS9LBQsZDlDEg==", "dev": true, "dependencies": { - "@typescript-eslint/scope-manager": "8.1.0", - "@typescript-eslint/types": "8.1.0", - "@typescript-eslint/typescript-estree": "8.1.0", - "@typescript-eslint/visitor-keys": "8.1.0", + "@typescript-eslint/scope-manager": "8.2.0", + "@typescript-eslint/types": "8.2.0", + "@typescript-eslint/typescript-estree": "8.2.0", + "@typescript-eslint/visitor-keys": "8.2.0", "debug": "^4.3.4" }, "engines": { @@ -13149,13 +12777,13 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.1.0.tgz", - "integrity": "sha512-DsuOZQji687sQUjm4N6c9xABJa7fjvfIdjqpSIIVOgaENf2jFXiM9hIBZOL3hb6DHK9Nvd2d7zZnoMLf9e0OtQ==", + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.2.0.tgz", + "integrity": "sha512-OFn80B38yD6WwpoHU2Tz/fTz7CgFqInllBoC3WP+/jLbTb4gGPTy9HBSTsbDWkMdN55XlVU0mMDYAtgvlUspGw==", "dev": true, "dependencies": { - "@typescript-eslint/types": "8.1.0", - "@typescript-eslint/visitor-keys": "8.1.0" + "@typescript-eslint/types": "8.2.0", + "@typescript-eslint/visitor-keys": "8.2.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -13166,13 +12794,13 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.1.0.tgz", - "integrity": "sha512-oLYvTxljVvsMnldfl6jIKxTaU7ok7km0KDrwOt1RHYu6nxlhN3TIx8k5Q52L6wR33nOwDgM7VwW1fT1qMNfFIA==", + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.2.0.tgz", + "integrity": "sha512-g1CfXGFMQdT5S+0PSO0fvGXUaiSkl73U1n9LTK5aRAFnPlJ8dLKkXr4AaLFvPedW8lVDoMgLLE3JN98ZZfsj0w==", "dev": true, "dependencies": { - "@typescript-eslint/typescript-estree": "8.1.0", - "@typescript-eslint/utils": "8.1.0", + "@typescript-eslint/typescript-estree": "8.2.0", + "@typescript-eslint/utils": "8.2.0", "debug": "^4.3.4", "ts-api-utils": "^1.3.0" }, @@ -13190,9 +12818,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.1.0.tgz", - "integrity": "sha512-q2/Bxa0gMOu/2/AKALI0tCKbG2zppccnRIRCW6BaaTlRVaPKft4oVYPp7WOPpcnsgbr0qROAVCVKCvIQ0tbWog==", + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.2.0.tgz", + "integrity": "sha512-6a9QSK396YqmiBKPkJtxsgZZZVjYQ6wQ/TlI0C65z7vInaETuC6HAHD98AGLC8DyIPqHytvNuS8bBVvNLKyqvQ==", "dev": true, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -13203,13 +12831,13 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.1.0.tgz", - "integrity": "sha512-NTHhmufocEkMiAord/g++gWKb0Fr34e9AExBRdqgWdVBaKoei2dIyYKD9Q0jBnvfbEA5zaf8plUFMUH6kQ0vGg==", + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.2.0.tgz", + "integrity": "sha512-kiG4EDUT4dImplOsbh47B1QnNmXSoUqOjWDvCJw/o8LgfD0yr7k2uy54D5Wm0j4t71Ge1NkynGhpWdS0dEIAUA==", "dev": true, "dependencies": { - "@typescript-eslint/types": "8.1.0", - "@typescript-eslint/visitor-keys": "8.1.0", + "@typescript-eslint/types": "8.2.0", + "@typescript-eslint/visitor-keys": "8.2.0", "debug": "^4.3.4", "globby": "^11.1.0", "is-glob": "^4.0.3", @@ -13231,15 +12859,15 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.1.0.tgz", - "integrity": "sha512-ypRueFNKTIFwqPeJBfeIpxZ895PQhNyH4YID6js0UoBImWYoSjBsahUn9KMiJXh94uOjVBgHD9AmkyPsPnFwJA==", + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.2.0.tgz", + "integrity": "sha512-O46eaYKDlV3TvAVDNcoDzd5N550ckSe8G4phko++OCSC1dYIb9LTc3HDGYdWqWIAT5qDUKphO6sd9RrpIJJPfg==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.4.0", - "@typescript-eslint/scope-manager": "8.1.0", - "@typescript-eslint/types": "8.1.0", - "@typescript-eslint/typescript-estree": "8.1.0" + "@typescript-eslint/scope-manager": "8.2.0", + "@typescript-eslint/types": "8.2.0", + "@typescript-eslint/typescript-estree": "8.2.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -13253,12 +12881,12 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.1.0.tgz", - "integrity": "sha512-ba0lNI19awqZ5ZNKh6wCModMwoZs457StTebQ0q1NP58zSi2F6MOZRXwfKZy+jB78JNJ/WH8GSh2IQNzXX8Nag==", + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.2.0.tgz", + "integrity": "sha512-sbgsPMW9yLvS7IhCi8IpuK1oBmtbWUNP+hBdwl/I9nzqVsszGnNGti5r9dUtF5RLivHUFFIdRvLiTsPhzSyJ3Q==", "dev": true, "dependencies": { - "@typescript-eslint/types": "8.1.0", + "@typescript-eslint/types": "8.2.0", "eslint-visitor-keys": "^3.4.3" }, "engines": { @@ -13569,15 +13197,14 @@ } }, "node_modules/agent-base": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", - "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", - "dev": true, + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", "dependencies": { - "debug": "^4.3.4" + "debug": "4" }, "engines": { - "node": ">= 14" + "node": ">= 6.0.0" } }, "node_modules/agentkeepalive": { @@ -13870,9 +13497,9 @@ } }, "node_modules/archiver/node_modules/async": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", - "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.5.tgz", + "integrity": "sha512-baNZyqaaLhyLVKm/DlvdW051MSgO6b8eVfIezl9E5PqWxFgzLm/wQntEW4zOytVburDEr0JlALEpdOFwvErLsg==", "dev": true }, "node_modules/are-we-there-yet": { @@ -14129,13 +13756,13 @@ } }, "node_modules/artillery": { - "version": "2.0.19", - "resolved": "https://registry.npmjs.org/artillery/-/artillery-2.0.19.tgz", - "integrity": "sha512-NeD5+D7U5l8hZ3lHtUseFTwqxILN2qfl4XlQt4cH0PukA/wsOri7cR0Qg2925usCa5EkD240Dfh9r9wYvuHxlw==", + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/artillery/-/artillery-2.0.20.tgz", + "integrity": "sha512-/lC1q786kaUq2fQFsMZf5G8oKtDDmLcfA1OLEiSA2+lJbBSYMCt9rWlRjLCRkVTKCcv4dDZdrhcRYHmPc6PNVQ==", "dev": true, "dependencies": { - "@artilleryio/int-commons": "2.10.0", - "@artilleryio/int-core": "2.14.0", + "@artilleryio/int-commons": "2.11.0", + "@artilleryio/int-core": "2.15.0", "@aws-sdk/credential-providers": "^3.127.0", "@azure/arm-containerinstance": "^9.1.0", "@azure/identity": "^4.2.0", @@ -14145,14 +13772,14 @@ "@oclif/plugin-help": "^5.2.11", "@oclif/plugin-not-found": "^2.3.1", "archiver": "^5.3.1", - "artillery-engine-playwright": "1.16.0", - "artillery-plugin-apdex": "1.10.0", - "artillery-plugin-ensure": "1.13.0", - "artillery-plugin-expect": "2.13.0", - "artillery-plugin-fake-data": "1.10.0", - "artillery-plugin-metrics-by-endpoint": "1.13.0", - "artillery-plugin-publish-metrics": "2.24.0", - "artillery-plugin-slack": "1.8.0", + "artillery-engine-playwright": "1.17.0", + "artillery-plugin-apdex": "1.11.0", + "artillery-plugin-ensure": "1.14.0", + "artillery-plugin-expect": "2.14.0", + "artillery-plugin-fake-data": "1.11.0", + "artillery-plugin-metrics-by-endpoint": "1.14.0", + "artillery-plugin-publish-metrics": "2.25.0", + "artillery-plugin-slack": "1.9.0", "async": "^2.6.4", "aws-sdk": "^2.1338.0", "chalk": "^2.4.2", @@ -14194,9 +13821,9 @@ } }, "node_modules/artillery-engine-playwright": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/artillery-engine-playwright/-/artillery-engine-playwright-1.16.0.tgz", - "integrity": "sha512-90Gka/neaKABygcWANL/wOrI3U75Xll4yAZmBywQiTONorGL3SIizEEujGXosHLUeOgzc+3OEldP5qXfCynMOg==", + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/artillery-engine-playwright/-/artillery-engine-playwright-1.17.0.tgz", + "integrity": "sha512-sWaQ9OEuvlgVr6ABpAi6gef0c6tDpaqiizg+eeB05TJB0PLyZQoU/0+JQN162Lx3mJW0kiaYNqtot6huxcXK+Q==", "dev": true, "dependencies": { "@playwright/browser-chromium": "1.45.3", @@ -14206,18 +13833,18 @@ } }, "node_modules/artillery-plugin-apdex": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/artillery-plugin-apdex/-/artillery-plugin-apdex-1.10.0.tgz", - "integrity": "sha512-TabM/LXhp5n3AKiCXQHl3ivwCuh7QfdV5vjYpT8di32Rd42f9AahFiOIje4aInW9u5S8qNsB78UU3ov084GxwA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/artillery-plugin-apdex/-/artillery-plugin-apdex-1.11.0.tgz", + "integrity": "sha512-Gng+T4tCGf0aZiNk071VZ6X69kgz/vtFDLuu11EdlePyC4Q9e4truAnYUC49rXg97i/JyYueTxjGHogefWJlRg==", "dev": true, "dependencies": { "tap": "^19.0.2" } }, "node_modules/artillery-plugin-ensure": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/artillery-plugin-ensure/-/artillery-plugin-ensure-1.13.0.tgz", - "integrity": "sha512-/FwOj4a2npaUkNsB+dtHGa5euRqi1ly0mvcqz2UawNia+5SQXVJauL0ue84uQrU0O8ercH/gzsb7cG2/RKYkwg==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/artillery-plugin-ensure/-/artillery-plugin-ensure-1.14.0.tgz", + "integrity": "sha512-kK+artqRYRM8uyJVAvyJX1MYT4j2W1FTIU2wIwNSFufTQbjORFoyQbBBaOeoDyao9g3NCcNO3BBHefE0kfVDgw==", "dev": true, "dependencies": { "chalk": "^2.4.2", @@ -14232,9 +13859,9 @@ "dev": true }, "node_modules/artillery-plugin-expect": { - "version": "2.13.0", - "resolved": "https://registry.npmjs.org/artillery-plugin-expect/-/artillery-plugin-expect-2.13.0.tgz", - "integrity": "sha512-j7beHovPaR9b4tKxn6gq6QXXK+XXtZ2B6DzX3PERqPcZPA07zSPrTJfzmtbwmnAGvQZYLK5jucQ6H+ZzyimiQg==", + "version": "2.14.0", + "resolved": "https://registry.npmjs.org/artillery-plugin-expect/-/artillery-plugin-expect-2.14.0.tgz", + "integrity": "sha512-E3Z7MyKTG/1DJcfCV8wloLAVbsOy0N6TOE8XdxtqpDklfHD4jXm614FbBULrPaLyfHVca0BrPhsBo6IT3HqFWQ==", "dev": true, "dependencies": { "chalk": "^4.1.2", @@ -14275,27 +13902,27 @@ } }, "node_modules/artillery-plugin-fake-data": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/artillery-plugin-fake-data/-/artillery-plugin-fake-data-1.10.0.tgz", - "integrity": "sha512-EQeeiIGJfxpXszn1zH91EyNprblpkME/HuHYloILExTc6My9+tcY5fezd1SEBbQ+jJ4qKB5KJyqQ6RS6HE+oBQ==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/artillery-plugin-fake-data/-/artillery-plugin-fake-data-1.11.0.tgz", + "integrity": "sha512-UA9lqNknWQd/0tQA2iyv+xDaroAlUKuNkwLWjNfcl9fvJLvISubaVMJwErVhlKETEwLb3FTcinYSfW3iIDusUw==", "dev": true, "dependencies": { "@ngneat/falso": "^7.1.1" } }, "node_modules/artillery-plugin-metrics-by-endpoint": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/artillery-plugin-metrics-by-endpoint/-/artillery-plugin-metrics-by-endpoint-1.13.0.tgz", - "integrity": "sha512-1zKp+kIZusPDLIcYE9Yheua5RYekAMNkJr/fQ2odQaeJdSkWyS/gURvroORhYAv41LKRfAvYazW668uUY6WkKA==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/artillery-plugin-metrics-by-endpoint/-/artillery-plugin-metrics-by-endpoint-1.14.0.tgz", + "integrity": "sha512-GXnIq0kluQwMelwrcfPOc5hK3Jim4AAFdYsqvmvi4PdEso2MZNdwD2qnrYI4mcxXJBaUMGV+0jva0L+I7RnxNw==", "dev": true, "dependencies": { "debug": "^4.3.2" } }, "node_modules/artillery-plugin-publish-metrics": { - "version": "2.24.0", - "resolved": "https://registry.npmjs.org/artillery-plugin-publish-metrics/-/artillery-plugin-publish-metrics-2.24.0.tgz", - "integrity": "sha512-7a6vykigjZ5zdk41ma8supGmownU31SdQRD9hxfpKv8gLIOAlTTD25OxnjGmddF4JArhztSAqrPb+J8s/7xXRw==", + "version": "2.25.0", + "resolved": "https://registry.npmjs.org/artillery-plugin-publish-metrics/-/artillery-plugin-publish-metrics-2.25.0.tgz", + "integrity": "sha512-VblhbItYcaN/R35EUasqudwMFdi4Qq+Z/BIBU94UZjxfs794Q96vKE/HV84NHXTbp6EcDd9RXxcis03dWuUHOQ==", "dev": true, "dependencies": { "@aws-sdk/client-cloudwatch": "^3.370.0", @@ -14335,9 +13962,9 @@ } }, "node_modules/artillery-plugin-slack": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/artillery-plugin-slack/-/artillery-plugin-slack-1.8.0.tgz", - "integrity": "sha512-BpZZonGQRBZo1oXw0XNx7itoGKlZDClE+SzNt3SDTTFcQuvdPD6FD05Y9hDfSfG3zdEuuc9joAtCuKMmZALaeg==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/artillery-plugin-slack/-/artillery-plugin-slack-1.9.0.tgz", + "integrity": "sha512-JAwnb+fhwo/Vdr2rWim66Q35MGD1CQetWxuEb6yqYvn7C4RA4F8dWcA9kPW8GQqy73V2LnKuCgl+7+Nu9mVL0g==", "dev": true, "dependencies": { "debug": "^4.3.4", @@ -14587,9 +14214,9 @@ "integrity": "sha512-Gar0ASD4BDyKC4hl4DwHqDrmvjoxWKZigVnAbn5H1owvm4CxCPdb0HQDehwNYMJpla5+M2tPmPARzhtYuwpHow==" }, "node_modules/aws-sdk": { - "version": "2.1679.0", - "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.1679.0.tgz", - "integrity": "sha512-76zSe/U7+5hzyGD7KAs71of1r6tRhrq+tXsOYbCDKPVqqtjxQiy88n0AC0Tcjx29nQSegydyjHxg27YJlcCXOg==", + "version": "2.1668.0", + "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.1668.0.tgz", + "integrity": "sha512-4Vcg3KjNZDHbvG4DI6jusN0DUPpRy3E/tBb6CA6ojlS2V1X5zljU9tkspICtbxXdY1gPFmKUe5COPc34XHG1RA==", "hasInstallScript": true, "dependencies": { "buffer": "4.9.2", @@ -14767,9 +14394,9 @@ } }, "node_modules/axios": { - "version": "1.7.4", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.4.tgz", - "integrity": "sha512-DukmaFRnY6AzAALSH4J2M3k6PkaC+MfaAGdEERRWcC9q3/TWQwLpHR8ZRLKTdQ3aBDL64EdluRDjJqKw+BPZEw==", + "version": "1.7.5", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.5.tgz", + "integrity": "sha512-fZu86yCo+svH3uqJ/yTdQ0QHpQu5oL+/QE+QPSv6BZSkDAoky9vytxp7u5qk83OJFS3kEBcesWni9WTZAv3tSw==", "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", @@ -15110,26 +14737,23 @@ "dev": true }, "node_modules/babel-preset-current-node-syntax": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.1.0.tgz", - "integrity": "sha512-ldYss8SbBlWva1bs28q78Ju5Zq1F+8BrqBZZ0VFhLBvhh6lCpC2o3gDJi/5DRLs9FgYZCnmPYIVFU4lRXCkyUw==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz", + "integrity": "sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ==", "dev": true, "dependencies": { "@babel/plugin-syntax-async-generators": "^7.8.4", "@babel/plugin-syntax-bigint": "^7.8.3", - "@babel/plugin-syntax-class-properties": "^7.12.13", - "@babel/plugin-syntax-class-static-block": "^7.14.5", - "@babel/plugin-syntax-import-attributes": "^7.24.7", - "@babel/plugin-syntax-import-meta": "^7.10.4", + "@babel/plugin-syntax-class-properties": "^7.8.3", + "@babel/plugin-syntax-import-meta": "^7.8.3", "@babel/plugin-syntax-json-strings": "^7.8.3", - "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", + "@babel/plugin-syntax-logical-assignment-operators": "^7.8.3", "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-numeric-separator": "^7.10.4", + "@babel/plugin-syntax-numeric-separator": "^7.8.3", "@babel/plugin-syntax-object-rest-spread": "^7.8.3", "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-syntax-private-property-in-object": "^7.14.5", - "@babel/plugin-syntax-top-level-await": "^7.14.5" + "@babel/plugin-syntax-top-level-await": "^7.8.3" }, "peerDependencies": { "@babel/core": "^7.0.0" @@ -15949,9 +15573,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001651", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001651.tgz", - "integrity": "sha512-9Cf+Xv1jJNe1xPZLGuUXLNkE1BoDkqRqYyFJ9TDYSqhduqA4hu4oR9HluGoWYQC/aj8WHjsGVV+bwkh0+tegRg==", + "version": "1.0.30001649", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001649.tgz", + "integrity": "sha512-fJegqZZ0ZX8HOWr6rcafGr72+xcgJKI9oWfDW5DrD7ExUtgZC7a7R7ZYmZqplh7XDocFdGeIFn7roAxhOeYrPQ==", "dev": true, "funding": [ { @@ -16749,9 +16373,9 @@ } }, "node_modules/core-js": { - "version": "3.38.0", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.38.0.tgz", - "integrity": "sha512-XPpwqEodRljce9KswjZShh95qJ1URisBeKCjUdq27YdenkslVe7OO0ZJhlYXAChW7OhXaRLl8AAba7IBfoIHug==", + "version": "3.38.1", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.38.1.tgz", + "integrity": "sha512-OP35aUorbU3Zvlx7pjsFdu1rGNnD4pgw/CWoYzRY3t2EzoVT7shKHY1dlAy3f41cGIO7ZDPQimhGFTlEYkG/Hw==", "hasInstallScript": true, "funding": { "type": "opencollective", @@ -16759,9 +16383,9 @@ } }, "node_modules/core-js-compat": { - "version": "3.38.1", - "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.38.1.tgz", - "integrity": "sha512-JRH6gfXxGmrzF3tZ57lFx97YARxCXPaMzPo6jELZhv88pBH5VXpQ+y0znKGlFnzuaihqhLbefxSJxWJMPtfDzw==", + "version": "3.38.0", + "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.38.0.tgz", + "integrity": "sha512-75LAicdLa4OJVwFxFbQR3NdnZjNgX6ILpVcVzcC4T2smerB5lELMrJQQQoWV6TiuC/vlaFqgU2tKQx9w5s0e0A==", "dev": true, "dependencies": { "browserslist": "^4.23.3" @@ -17581,9 +17205,9 @@ } }, "node_modules/dayjs": { - "version": "1.11.13", - "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.13.tgz", - "integrity": "sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==" + "version": "1.11.12", + "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.12.tgz", + "integrity": "sha512-Rt2g+nTbLlDWZTwwrIXjy9MeiZmSDI375FvZs72ngxx8PDC6YXOeR3q5LAuPzjZQxhiWdRKac7RKV+YyQYfYIg==" }, "node_modules/debug": { "version": "4.3.6", @@ -18396,9 +18020,9 @@ } }, "node_modules/electron-to-chromium": { - "version": "1.5.13", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.13.tgz", - "integrity": "sha512-lbBcvtIJ4J6sS4tb5TLp1b4LyfCdMkwStzXPyAgVgTRAsep4bvrAGaBOP7ZJtQMNJpSQ9SqG4brWOroNaQtm7Q==", + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.5.tgz", + "integrity": "sha512-QR7/A7ZkMS8tZuoftC/jfqNkZLQO779SSW3YuZHP4eXpj3EffGLFcB/Xu9AAZQzLccTiCV+EmUo3ha4mQ9wnlA==", "dev": true }, "node_modules/element-closest": { @@ -18910,9 +18534,9 @@ } }, "node_modules/esbuild": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.23.0.tgz", - "integrity": "sha512-1lvV17H2bMYda/WaFb2jLPeHU3zml2k4/yagNMG8Q/YtfMjCwEUZa2eXXMgZTVSL5q1n4H7sQ0X6CdJDqqeCFA==", + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.23.1.tgz", + "integrity": "sha512-VVNz/9Sa0bs5SELtn3f7qhJCDPCF5oMEl5cO9/SSinpE9hbPVvxbd572HH5AKiP7WD8INO53GgfDDhRjkylHEg==", "dev": true, "hasInstallScript": true, "bin": { @@ -18922,30 +18546,30 @@ "node": ">=18" }, "optionalDependencies": { - "@esbuild/aix-ppc64": "0.23.0", - "@esbuild/android-arm": "0.23.0", - "@esbuild/android-arm64": "0.23.0", - "@esbuild/android-x64": "0.23.0", - "@esbuild/darwin-arm64": "0.23.0", - "@esbuild/darwin-x64": "0.23.0", - "@esbuild/freebsd-arm64": "0.23.0", - "@esbuild/freebsd-x64": "0.23.0", - "@esbuild/linux-arm": "0.23.0", - "@esbuild/linux-arm64": "0.23.0", - "@esbuild/linux-ia32": "0.23.0", - "@esbuild/linux-loong64": "0.23.0", - "@esbuild/linux-mips64el": "0.23.0", - "@esbuild/linux-ppc64": "0.23.0", - "@esbuild/linux-riscv64": "0.23.0", - "@esbuild/linux-s390x": "0.23.0", - "@esbuild/linux-x64": "0.23.0", - "@esbuild/netbsd-x64": "0.23.0", - "@esbuild/openbsd-arm64": "0.23.0", - "@esbuild/openbsd-x64": "0.23.0", - "@esbuild/sunos-x64": "0.23.0", - "@esbuild/win32-arm64": "0.23.0", - "@esbuild/win32-ia32": "0.23.0", - "@esbuild/win32-x64": "0.23.0" + "@esbuild/aix-ppc64": "0.23.1", + "@esbuild/android-arm": "0.23.1", + "@esbuild/android-arm64": "0.23.1", + "@esbuild/android-x64": "0.23.1", + "@esbuild/darwin-arm64": "0.23.1", + "@esbuild/darwin-x64": "0.23.1", + "@esbuild/freebsd-arm64": "0.23.1", + "@esbuild/freebsd-x64": "0.23.1", + "@esbuild/linux-arm": "0.23.1", + "@esbuild/linux-arm64": "0.23.1", + "@esbuild/linux-ia32": "0.23.1", + "@esbuild/linux-loong64": "0.23.1", + "@esbuild/linux-mips64el": "0.23.1", + "@esbuild/linux-ppc64": "0.23.1", + "@esbuild/linux-riscv64": "0.23.1", + "@esbuild/linux-s390x": "0.23.1", + "@esbuild/linux-x64": "0.23.1", + "@esbuild/netbsd-x64": "0.23.1", + "@esbuild/openbsd-arm64": "0.23.1", + "@esbuild/openbsd-x64": "0.23.1", + "@esbuild/sunos-x64": "0.23.1", + "@esbuild/win32-arm64": "0.23.1", + "@esbuild/win32-ia32": "0.23.1", + "@esbuild/win32-x64": "0.23.1" } }, "node_modules/esbuild-css-modules-plugin": { @@ -20948,9 +20572,9 @@ "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==" }, "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "dev": true, "hasInstallScript": true, "optional": true, @@ -21233,9 +20857,9 @@ } }, "node_modules/getos/node_modules/async": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", - "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.5.tgz", + "integrity": "sha512-baNZyqaaLhyLVKm/DlvdW051MSgO6b8eVfIezl9E5PqWxFgzLm/wQntEW4zOytVburDEr0JlALEpdOFwvErLsg==", "dev": true }, "node_modules/getpass": { @@ -21879,6 +21503,18 @@ "node": ">= 14" } }, + "node_modules/http-proxy-agent/node_modules/agent-base": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", + "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", + "dev": true, + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/http-signature": { "version": "1.3.6", "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.3.6.tgz", @@ -21918,17 +21554,6 @@ "node": ">= 6" } }, - "node_modules/https-proxy-agent/node_modules/agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", - "dependencies": { - "debug": "4" - }, - "engines": { - "node": ">= 6.0.0" - } - }, "node_modules/human-signals": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-1.1.1.tgz", @@ -21963,9 +21588,9 @@ } }, "node_modules/husky": { - "version": "9.1.4", - "resolved": "https://registry.npmjs.org/husky/-/husky-9.1.4.tgz", - "integrity": "sha512-bho94YyReb4JV7LYWRWxZ/xr6TtOTt8cMfmQ39MQYJ7f/YE268s3GdghGwi+y4zAeqewE5zYLvuhV0M0ijsDEA==", + "version": "9.1.5", + "resolved": "https://registry.npmjs.org/husky/-/husky-9.1.5.tgz", + "integrity": "sha512-rowAVRUBfI0b4+niA4SJMhfQwc107VLkBUgEYYAOQAbqDCnra1nYh83hF/MDmhYs9t9n1E3DuKOrs2LYNC+0Ag==", "dev": true, "bin": { "husky": "bin.js" @@ -23296,9 +22921,9 @@ } }, "node_modules/jake/node_modules/async": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", - "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.5.tgz", + "integrity": "sha512-baNZyqaaLhyLVKm/DlvdW051MSgO6b8eVfIezl9E5PqWxFgzLm/wQntEW4zOytVburDEr0JlALEpdOFwvErLsg==", "dev": true }, "node_modules/jake/node_modules/brace-expansion": { @@ -23772,18 +23397,6 @@ } } }, - "node_modules/jest-environment-jsdom/node_modules/agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", - "dev": true, - "dependencies": { - "debug": "4" - }, - "engines": { - "node": ">= 6.0.0" - } - }, "node_modules/jest-environment-jsdom/node_modules/cssstyle": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-2.3.0.tgz", @@ -24791,6 +24404,18 @@ } } }, + "node_modules/jsdom/node_modules/agent-base": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", + "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", + "dev": true, + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/jsdom/node_modules/https-proxy-agent": { "version": "7.0.5", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz", @@ -25008,25 +24633,6 @@ "npm": ">=6" } }, - "node_modules/jsonwebtoken/node_modules/jwa": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", - "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", - "dependencies": { - "buffer-equal-constant-time": "1.0.1", - "ecdsa-sig-formatter": "1.0.11", - "safe-buffer": "^5.0.1" - } - }, - "node_modules/jsonwebtoken/node_modules/jws": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", - "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", - "dependencies": { - "jwa": "^1.4.1", - "safe-buffer": "^5.0.1" - } - }, "node_modules/jsprim": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-2.0.2.tgz", @@ -25082,10 +24688,9 @@ "dev": true }, "node_modules/jwa": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.0.tgz", - "integrity": "sha512-jrZ2Qx916EA+fq9cEAeCROWPTfCwi1IVHqT2tapuqLEVVDKFDENFw1oL+MwrTvH6msKxsd1YTDVw6uKEcsrLEA==", - "dev": true, + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", "dependencies": { "buffer-equal-constant-time": "1.0.1", "ecdsa-sig-formatter": "1.0.11", @@ -25103,12 +24708,11 @@ } }, "node_modules/jws": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.0.tgz", - "integrity": "sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==", - "dev": true, + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", "dependencies": { - "jwa": "^2.0.0", + "jwa": "^1.4.1", "safe-buffer": "^5.0.1" } }, @@ -25375,9 +24979,9 @@ } }, "node_modules/lightningcss": { - "version": "1.26.0", - "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.26.0.tgz", - "integrity": "sha512-a/XZ5hdgifrofQJUArr5AiJjx26SwMam3SJUSMjgebZbESZ96i+6Qsl8tLi0kaUsdMzBWXh9sN1Oe6hp2/dkQw==", + "version": "1.25.1", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.25.1.tgz", + "integrity": "sha512-V0RMVZzK1+rCHpymRv4URK2lNhIRyO8g7U7zOFwVAhJuat74HtkjIQpQRKNCwFEYkRGpafOpmXXLoaoBcyVtBg==", "dev": true, "dependencies": { "detect-libc": "^1.0.3" @@ -25390,216 +24994,15 @@ "url": "https://opencollective.com/parcel" }, "optionalDependencies": { - "lightningcss-darwin-arm64": "1.26.0", - "lightningcss-darwin-x64": "1.26.0", - "lightningcss-freebsd-x64": "1.26.0", - "lightningcss-linux-arm-gnueabihf": "1.26.0", - "lightningcss-linux-arm64-gnu": "1.26.0", - "lightningcss-linux-arm64-musl": "1.26.0", - "lightningcss-linux-x64-gnu": "1.26.0", - "lightningcss-linux-x64-musl": "1.26.0", - "lightningcss-win32-arm64-msvc": "1.26.0", - "lightningcss-win32-x64-msvc": "1.26.0" - } - }, - "node_modules/lightningcss-darwin-arm64": { - "version": "1.26.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.26.0.tgz", - "integrity": "sha512-n4TIvHO1NY1ondKFYpL2ZX0bcC2y6yjXMD6JfyizgR8BCFNEeArINDzEaeqlfX9bXz73Bpz/Ow0nu+1qiDrBKg==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-x64": { - "version": "1.26.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.26.0.tgz", - "integrity": "sha512-Rf9HuHIDi1R6/zgBkJh25SiJHF+dm9axUZW/0UoYCW1/8HV0gMI0blARhH4z+REmWiU1yYT/KyNF3h7tHyRXUg==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-freebsd-x64": { - "version": "1.26.0", - "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.26.0.tgz", - "integrity": "sha512-C/io7POAxp6sZxFSVGezjajMlCKQ8KSwISLLGRq8xLQpQMokYrUoqYEwmIX8mLmF6C/CZPk0gFmRSzd8biWM0g==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm-gnueabihf": { - "version": "1.26.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.26.0.tgz", - "integrity": "sha512-Aag9kqXqkyPSW+dXMgyWk66C984Nay2pY8Nws+67gHlDzV3cWh7TvFlzuaTaVFMVqdDTzN484LSK3u39zFBnzg==", - "cpu": [ - "arm" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-gnu": { - "version": "1.26.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.26.0.tgz", - "integrity": "sha512-iJmZM7fUyVjH+POtdiCtExG+67TtPUTer7K/5A8DIfmPfrmeGvzfRyBltGhQz13Wi15K1lf2cPYoRaRh6vcwNA==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-musl": { - "version": "1.26.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.26.0.tgz", - "integrity": "sha512-XxoEL++tTkyuvu+wq/QS8bwyTXZv2y5XYCMcWL45b8XwkiS8eEEEej9BkMGSRwxa5J4K+LDeIhLrS23CpQyfig==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-gnu": { - "version": "1.26.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.26.0.tgz", - "integrity": "sha512-1dkTfZQAYLj8MUSkd6L/+TWTG8V6Kfrzfa0T1fSlXCXQHrt1HC1/UepXHtKHDt/9yFwyoeayivxXAsApVxn6zA==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-musl": { - "version": "1.26.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.26.0.tgz", - "integrity": "sha512-yX3Rk9m00JGCUzuUhFEojY+jf/6zHs3XU8S8Vk+FRbnr4St7cjyMXdNjuA2LjiT8e7j8xHRCH8hyZ4H/btRE4A==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-arm64-msvc": { - "version": "1.26.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.26.0.tgz", - "integrity": "sha512-X/597/cFnCogy9VItj/+7Tgu5VLbAtDF7KZDPdSw0MaL6FL940th1y3HiOzFIlziVvAtbo0RB3NAae1Oofr+Tw==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-x64-msvc": { - "version": "1.26.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.26.0.tgz", - "integrity": "sha512-pYS3EyGP3JRhfqEFYmfFDiZ9/pVNfy8jVIYtrx9TVNusVyDK3gpW1w/rbvroQ4bDJi7grdUtyrYU6V2xkY/bBw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" + "lightningcss-darwin-arm64": "1.25.1", + "lightningcss-darwin-x64": "1.25.1", + "lightningcss-freebsd-x64": "1.25.1", + "lightningcss-linux-arm-gnueabihf": "1.25.1", + "lightningcss-linux-arm64-gnu": "1.25.1", + "lightningcss-linux-arm64-musl": "1.25.1", + "lightningcss-linux-x64-gnu": "1.25.1", + "lightningcss-linux-x64-musl": "1.25.1", + "lightningcss-win32-x64-msvc": "1.25.1" } }, "node_modules/lightningcss/node_modules/detect-libc": { @@ -27090,18 +26493,6 @@ "node": ">=10.0" } }, - "node_modules/mixpanel/node_modules/agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", - "dev": true, - "dependencies": { - "debug": "4" - }, - "engines": { - "node": ">= 6.0.0" - } - }, "node_modules/mixpanel/node_modules/https-proxy-agent": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.0.tgz", @@ -28494,6 +27885,18 @@ "node": ">= 14" } }, + "node_modules/pac-proxy-agent/node_modules/agent-base": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", + "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", + "dev": true, + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/pac-proxy-agent/node_modules/https-proxy-agent": { "version": "7.0.5", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz", @@ -29242,20 +28645,6 @@ "node": ">=18" } }, - "node_modules/playwright/node_modules/fsevents": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", - "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "dev": true, - "hasInstallScript": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, "node_modules/pngjs": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-7.0.0.tgz", @@ -30547,9 +29936,9 @@ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" }, "node_modules/protobufjs": { - "version": "7.3.2", - "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.3.2.tgz", - "integrity": "sha512-RXyHaACeqXeqAKGLDl68rQKbmObRsTIn4TYVUUug1KfS47YWCo5MacGITEryugIgZqORCvJWEk4l449POg5Txg==", + "version": "7.3.3", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.3.3.tgz", + "integrity": "sha512-HaYi2CVjiPoBR1d2zTVKVHXr9IUnpJizCjUu19vxdD3B8o4z+vfOHpIEB1358w8nv8dfUNEfDHFvMsH7QlLt/Q==", "dev": true, "hasInstallScript": true, "dependencies": { @@ -30601,6 +29990,18 @@ "node": ">= 14" } }, + "node_modules/proxy-agent/node_modules/agent-base": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", + "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", + "dev": true, + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/proxy-agent/node_modules/https-proxy-agent": { "version": "7.0.5", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz", @@ -31187,17 +30588,6 @@ "react-dom": "^0.14 || ^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0" } }, - "node_modules/react-paginate": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/react-paginate/-/react-paginate-8.2.0.tgz", - "integrity": "sha512-sJCz1PW+9PNIjUSn919nlcRVuleN2YPoFBOvL+6TPgrH/3lwphqiSOgdrLafLdyLDxsgK+oSgviqacF4hxsDIw==", - "dependencies": { - "prop-types": "^15" - }, - "peerDependencies": { - "react": "^16 || ^17 || ^18" - } - }, "node_modules/react-quill": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/react-quill/-/react-quill-2.0.0.tgz", @@ -31956,35 +31346,35 @@ }, "node_modules/s3rver": { "name": "@20minutes/s3rver", - "version": "4.0.1", - "resolved": "git+ssh://git@github.com/20minutes/s3rver.git#602411e44b45cd3607385b80142b67822c496b70", + "version": "4.0.0", + "resolved": "git+ssh://git@github.com/20minutes/s3rver.git#6960fcd9915bf68caf9a3081343b4fca79db208b", "dev": true, "dependencies": { - "@koa/router": "^12.0.1", + "@koa/router": "^12.0.0", "busboy": "^1.6.0", - "commander": "^12.1.0", - "fast-xml-parser": "^4.4.1", + "commander": "^11.0.0", + "fast-xml-parser": "^4.3.1", "he": "^1.2.0", - "koa": "^2.15.3", + "koa": "^2.12.1", "koa-logger": "^3.2.0", "lodash": "^4.17.20", "statuses": "^2.0.0", - "winston": "^3.14.1" + "winston": "^3.10.0" }, "bin": { "s3rver": "bin/s3rver.js" }, "engines": { - "node": ">=20" + "node": ">=12.13.0" } }, "node_modules/s3rver/node_modules/commander": { - "version": "12.1.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", - "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz", + "integrity": "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==", "dev": true, "engines": { - "node": ">=18" + "node": ">=16" } }, "node_modules/safe-array-concat": { @@ -32131,334 +31521,6 @@ "sass-embedded-win32-x64": "1.77.8" } }, - "node_modules/sass-embedded-android-arm": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-android-arm/-/sass-embedded-android-arm-1.77.8.tgz", - "integrity": "sha512-GpGL7xZ7V1XpFbnflib/NWbM0euRzineK0iwoo31/ntWKAXGj03iHhGzkSiOwWSFcXgsJJi3eRA5BTmBvK5Q+w==", - "cpu": [ - "arm" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "peer": true, - "bin": { - "sass": "dart-sass/sass" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-android-arm64": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-android-arm64/-/sass-embedded-android-arm64-1.77.8.tgz", - "integrity": "sha512-EmWHLbEx0Zo/f/lTFzMeH2Du+/I4RmSRlEnERSUKQWVp3aBSO04QDvdxfFezgQ+2Yt/ub9WMqBpma9P/8MPsLg==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "peer": true, - "bin": { - "sass": "dart-sass/sass" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-android-ia32": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-android-ia32/-/sass-embedded-android-ia32-1.77.8.tgz", - "integrity": "sha512-+GjfJ3lDezPi4dUUyjQBxlNKXNa+XVWsExtGvVNkv1uKyaOxULJhubVo2G6QTJJU0esJdfeXf5Ca5/J0ph7+7w==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "peer": true, - "bin": { - "sass": "dart-sass/sass" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-android-x64": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-android-x64/-/sass-embedded-android-x64-1.77.8.tgz", - "integrity": "sha512-YZbFDzGe5NhaMCygShqkeCWtzjhkWxGVunc7ULR97wmxYPQLPeVyx7XFQZc84Aj0lKAJBJS4qRZeqphMqZEJsQ==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "peer": true, - "bin": { - "sass": "dart-sass/sass" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-darwin-arm64": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-darwin-arm64/-/sass-embedded-darwin-arm64-1.77.8.tgz", - "integrity": "sha512-aifgeVRNE+i43toIkDFFJc/aPLMo0PJ5s5hKb52U+oNdiJE36n65n2L8F/8z3zZRvCa6eYtFY2b7f1QXR3B0LA==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "darwin" - ], - "peer": true, - "bin": { - "sass": "dart-sass/sass" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-darwin-x64": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-darwin-x64/-/sass-embedded-darwin-x64-1.77.8.tgz", - "integrity": "sha512-/VWZQtcWIOek60Zj6Sxk6HebXA1Qyyt3sD8o5qwbTgZnKitB1iEBuNunyGoAgMNeUz2PRd6rVki6hvbas9hQ6w==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "darwin" - ], - "peer": true, - "bin": { - "sass": "dart-sass/sass" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-linux-arm": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-linux-arm/-/sass-embedded-linux-arm-1.77.8.tgz", - "integrity": "sha512-2edZMB6jf0whx3T0zlgH+p131kOEmWp+I4wnKj7ZMUeokiY4Up05d10hSvb0Q63lOrSjFAWu6P5/pcYUUx8arQ==", - "cpu": [ - "arm" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "bin": { - "sass": "dart-sass/sass" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-linux-arm64": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-linux-arm64/-/sass-embedded-linux-arm64-1.77.8.tgz", - "integrity": "sha512-6iIOIZtBFa2YfMsHqOb3qake3C9d/zlKxjooKKnTSo+6g6z+CLTzMXe1bOfayb7yxeenElmFoK1k54kWD/40+g==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "bin": { - "sass": "dart-sass/sass" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-linux-ia32": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-linux-ia32/-/sass-embedded-linux-ia32-1.77.8.tgz", - "integrity": "sha512-63GsFFHWN5yRLTWiSef32TM/XmjhCBx1DFhoqxmj+Yc6L9Z1h0lDHjjwdG6Sp5XTz5EmsaFKjpDgnQTP9hJX3Q==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "bin": { - "sass": "dart-sass/sass" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-linux-musl-arm": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-linux-musl-arm/-/sass-embedded-linux-musl-arm-1.77.8.tgz", - "integrity": "sha512-nFkhSl3uu9btubm+JBW7uRglNVJ8W8dGfzVqh3fyQJKS1oyBC3vT3VOtfbT9YivXk28wXscSHpqXZwY7bUuopA==", - "cpu": [ - "arm" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-linux-musl-arm64": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-linux-musl-arm64/-/sass-embedded-linux-musl-arm64-1.77.8.tgz", - "integrity": "sha512-j8cgQxNWecYK+aH8ESFsyam/Q6G+9gg8eJegiRVpA9x8yk3ykfHC7UdQWwUcF22ZcuY4zegrjJx8k+thsgsOVA==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-linux-musl-ia32": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-linux-musl-ia32/-/sass-embedded-linux-musl-ia32-1.77.8.tgz", - "integrity": "sha512-oWveMe+8TFlP8WBWPna/+Ec5TV0CE+PxEutyi0ltSruBds2zxRq9dPVOqrpPcDN9QUx50vNZC0Afgch0aQEd0g==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-linux-musl-x64": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-linux-musl-x64/-/sass-embedded-linux-musl-x64-1.77.8.tgz", - "integrity": "sha512-2NtRpMXHeFo9kaYxuZ+Ewwo39CE7BTS2JDfXkTjZTZqd8H+8KC53eBh516YQnn2oiqxSiKxm7a6pxbxGZGwXOQ==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-linux-x64": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-linux-x64/-/sass-embedded-linux-x64-1.77.8.tgz", - "integrity": "sha512-ND5qZLWUCpOn7LJfOf0gLSZUWhNIysY+7NZK1Ctq+pM6tpJky3JM5I1jSMplNxv5H3o8p80n0gSm+fcjsEFfjQ==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "bin": { - "sass": "dart-sass/sass" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-win32-arm64": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-win32-arm64/-/sass-embedded-win32-arm64-1.77.8.tgz", - "integrity": "sha512-7L8zT6xzEvTYj86MvUWnbkWYCNQP+74HvruLILmiPPE+TCgOjgdi750709BtppVJGGZSs40ZuN6mi/YQyGtwXg==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "peer": true, - "bin": { - "sass": "dart-sass/sass.bat" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-win32-ia32": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-win32-ia32/-/sass-embedded-win32-ia32-1.77.8.tgz", - "integrity": "sha512-7Buh+4bP0WyYn6XPbthkIa3M2vtcR8QIsFVg3JElVlr+8Ng19jqe0t0SwggDgbMX6AdQZC+Wj4F1BprZSok42A==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "peer": true, - "bin": { - "sass": "dart-sass/sass.bat" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/sass-embedded-win32-x64": { - "version": "1.77.8", - "resolved": "https://registry.npmjs.org/sass-embedded-win32-x64/-/sass-embedded-win32-x64-1.77.8.tgz", - "integrity": "sha512-rZmLIx4/LLQm+4GW39sRJW0MIlDqmyV0fkRzTmhFP5i/wVC7cuj8TUubPHw18rv2rkHFfBZKZJTCkPjCS5Z+SA==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "peer": true, - "bin": { - "sass": "dart-sass/sass.bat" - }, - "engines": { - "node": ">=14.0.0" - } - }, "node_modules/sass-embedded/node_modules/supports-color": { "version": "8.1.1", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", @@ -32476,9 +31538,9 @@ } }, "node_modules/sass-loader": { - "version": "16.0.0", - "resolved": "https://registry.npmjs.org/sass-loader/-/sass-loader-16.0.0.tgz", - "integrity": "sha512-n13Z+3rU9A177dk4888czcVFiC8CL9dii4qpXWUg3YIIgZEvi9TCFKjOQcbK0kJM7DJu9VucrZFddvNfYCPwtw==", + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/sass-loader/-/sass-loader-16.0.1.tgz", + "integrity": "sha512-xACl1ToTsKnL9Ce5yYpRxrLj9QUDCnwZNhzpC7tKiFyA8zXsd3Ap+HGVnbCgkdQcm43E+i6oKAWBsvGA6ZoiMw==", "dev": true, "dependencies": { "neo-async": "^2.6.2" @@ -33083,6 +32145,18 @@ "node": ">= 14" } }, + "node_modules/socks-proxy-agent/node_modules/agent-base": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", + "integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==", + "dev": true, + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/sonic-boom": { "version": "2.8.0", "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-2.8.0.tgz", @@ -33147,9 +32221,9 @@ } }, "node_modules/spdx-license-ids": { - "version": "3.0.20", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.20.tgz", - "integrity": "sha512-jg25NiDV/1fLtSgEgyvVyDunvaNHbuwF9lfNV17gSmPFAlYzdfNBlLtLzXTevwkPj7DhGbmN9VnmJIgLnhvaBw==", + "version": "3.0.18", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.18.tgz", + "integrity": "sha512-xxRs31BqRYHwiMzudOrpSiHtZ8i/GeionCBDSilhYRj+9gIcI8wCZTlXZKu9vZIVqViP3dcp9qE5G6AlIaD+TQ==", "dev": true }, "node_modules/split2": { @@ -33913,9 +32987,9 @@ } }, "node_modules/stylelint/node_modules/supports-hyperlinks": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-3.1.0.tgz", - "integrity": "sha512-2rn0BZ+/f7puLOHZm1HOJfwBggfaHXUpPUSSG/SWM4TWp5KCfmNYwnC3hruy2rZlMnmWZ+QAGpZfchu3f3695A==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-3.0.0.tgz", + "integrity": "sha512-QBDPHyPQDRTy9ku4URNGY5Lah8PAaXs6tAAwp55sL5WCsSW7GIfdf6W5ixfziW+t7wh3GVvHyHHyQ1ESsoRvaA==", "dev": true, "dependencies": { "has-flag": "^4.0.0", @@ -33923,9 +32997,6 @@ }, "engines": { "node": ">=14.18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/stylelint/node_modules/write-file-atomic": { @@ -34486,9 +33557,9 @@ } }, "node_modules/terser": { - "version": "5.31.6", - "resolved": "https://registry.npmjs.org/terser/-/terser-5.31.6.tgz", - "integrity": "sha512-PQ4DAriWzKj+qgehQ7LK5bQqCFNMmlhjR2PFFLuqGCpuCAauxemVBWwWOxo3UIwWQx8+Pr61Df++r76wDmkQBg==", + "version": "5.31.3", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.31.3.tgz", + "integrity": "sha512-pAfYn3NIZLyZpa83ZKigvj6Rn9c/vd5KfYGX7cN1mnzqgDcxWvrU5ZtAfIKhEXz9nRecw4z3LXkjaq96/qZqAA==", "dev": true, "peer": true, "dependencies": { @@ -34754,21 +33825,21 @@ } }, "node_modules/tldts": { - "version": "6.1.40", - "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.40.tgz", - "integrity": "sha512-SAvDKQxzqoi2gaC14XdC1egLtBqcCnYTe/hKM07FMXSTKw4Tti3fRDcZopWJGAhXK0H6LfuM0QWwZhECUvLKTg==", + "version": "6.1.41", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.41.tgz", + "integrity": "sha512-RNpUkL5fYD2DTQQCdr8QMDp6UL0ThtpXT3q3+qPE05dIT+RK2I3M0VByVbQN1dEhLUGzimivVwxK2By9epLk6w==", "dev": true, "dependencies": { - "tldts-core": "^6.1.40" + "tldts-core": "^6.1.41" }, "bin": { "tldts": "bin/cli.js" } }, "node_modules/tldts-core": { - "version": "6.1.40", - "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.40.tgz", - "integrity": "sha512-csGlF+5GtK0qDvkqhZHbMflIvvMqs7JS3Y3KMrfBuhDAjI+oqH90p4KYMeiCPVF7akTeNoLgFaQ+aPZcGBc1kg==", + "version": "6.1.41", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.41.tgz", + "integrity": "sha512-SkwZgo1ZzMp2ziMBwci5VBnLR9VywCi02jSgMX5TO5kf9fdaBsxZkblLff3NlJNTcH0vfvEsgw2B7jVR556Vgw==", "dev": true }, "node_modules/tmp": { @@ -35445,9 +34516,9 @@ } }, "node_modules/undici-types": { - "version": "6.19.8", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", - "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==" + "version": "6.19.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.6.tgz", + "integrity": "sha512-e/vggGopEfTKSvj4ihnOLTsqhrKRN3LeO6qSN/GxohhuRv8qH9bNQ4B8W7e/vFL+0XTnmHPB4/kegunZGA4Org==" }, "node_modules/unicode-canonical-property-names-ecmascript": { "version": "2.0.0", @@ -35850,9 +34921,9 @@ } }, "node_modules/watchpack": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.2.tgz", - "integrity": "sha512-TnbFSbcOCcDgjZ4piURLCbJ3nJhznVh9kw6F6iokjiFPl8ONxe9A6nMDVXDiNbrSfLILs6vB07F7wLBrwPYzJw==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.1.tgz", + "integrity": "sha512-8wrBCMtVhqcXP2Sup1ctSkga6uc2Bx0IIvKyT7yTFier5AXHooSI+QyQQAtTb7+E0IUCCKyTFmXqdqgum2XWGg==", "dependencies": { "glob-to-regexp": "^0.4.1", "graceful-fs": "^4.1.2" @@ -36245,9 +35316,9 @@ } }, "node_modules/winston/node_modules/async": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", - "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==" + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.5.tgz", + "integrity": "sha512-baNZyqaaLhyLVKm/DlvdW051MSgO6b8eVfIezl9E5PqWxFgzLm/wQntEW4zOytVburDEr0JlALEpdOFwvErLsg==" }, "node_modules/with": { "version": "7.0.2", diff --git a/package.json b/package.json index ac153794d8e..059831bf314 100644 --- a/package.json +++ b/package.json @@ -11,35 +11,35 @@ "dependencies": { "@18f/us-federal-holidays": "4.0.0", "@aws-crypto/sha256-browser": "5.2.0", - "@aws-sdk/client-api-gateway": "3.632.0", - "@aws-sdk/client-apigatewaymanagementapi": "3.632.0", - "@aws-sdk/client-apigatewayv2": "3.632.0", - "@aws-sdk/client-cloudfront": "3.632.0", - "@aws-sdk/client-cloudwatch": "3.632.0", - "@aws-sdk/client-cloudwatch-logs": "3.632.0", - "@aws-sdk/client-cognito-identity-provider": "3.632.0", - "@aws-sdk/client-dynamodb": "3.632.0", - "@aws-sdk/client-dynamodb-streams": "3.632.0", - "@aws-sdk/client-glue": "3.632.0", - "@aws-sdk/client-lambda": "3.632.0", - "@aws-sdk/client-opensearch": "3.632.0", - "@aws-sdk/client-route-53": "3.632.0", - "@aws-sdk/client-s3": "3.633.0", - "@aws-sdk/client-ses": "3.632.0", - "@aws-sdk/client-sns": "3.632.0", - "@aws-sdk/client-sqs": "3.632.0", - "@aws-sdk/client-ssm": "3.632.0", + "@aws-sdk/client-api-gateway": "3.637.0", + "@aws-sdk/client-apigatewaymanagementapi": "3.637.0", + "@aws-sdk/client-apigatewayv2": "3.637.0", + "@aws-sdk/client-cloudfront": "3.637.0", + "@aws-sdk/client-cloudwatch": "3.637.0", + "@aws-sdk/client-cloudwatch-logs": "3.637.0", + "@aws-sdk/client-cognito-identity-provider": "3.637.0", + "@aws-sdk/client-dynamodb": "3.637.0", + "@aws-sdk/client-dynamodb-streams": "3.637.0", + "@aws-sdk/client-glue": "3.637.0", + "@aws-sdk/client-lambda": "3.637.0", + "@aws-sdk/client-opensearch": "3.637.0", + "@aws-sdk/client-route-53": "3.637.0", + "@aws-sdk/client-s3": "3.637.0", + "@aws-sdk/client-ses": "3.637.0", + "@aws-sdk/client-sns": "3.637.0", + "@aws-sdk/client-sqs": "3.637.0", + "@aws-sdk/client-ssm": "3.637.0", "@aws-sdk/cloudfront-signer": "3.621.0", - "@aws-sdk/credential-provider-node": "3.632.0", - "@aws-sdk/lib-dynamodb": "3.632.0", - "@aws-sdk/lib-storage": "3.633.0", + "@aws-sdk/credential-provider-node": "3.637.0", + "@aws-sdk/lib-dynamodb": "3.637.0", + "@aws-sdk/lib-storage": "3.637.0", "@aws-sdk/node-http-handler": "3.374.0", "@aws-sdk/protocol-http": "3.374.0", "@aws-sdk/rds-signer": "^3.637.0", - "@aws-sdk/s3-presigned-post": "3.633.0", - "@aws-sdk/s3-request-presigner": "3.633.0", + "@aws-sdk/s3-presigned-post": "3.637.0", + "@aws-sdk/s3-request-presigner": "3.637.0", "@aws-sdk/signature-v4": "3.374.0", - "@aws-sdk/util-dynamodb": "3.632.0", + "@aws-sdk/util-dynamodb": "3.637.0", "@cerebral/react": "4.2.1", "@fortawesome/fontawesome-svg-core": "1.2.36", "@fortawesome/free-regular-svg-icons": "5.15.4", @@ -51,13 +51,13 @@ "@uswds/uswds": "3.7.1", "aws-lambda": "1.0.7", "aws-xray-sdk": "3.9.0", - "axios": "1.7.4", + "axios": "1.7.5", "broadcast-channel": "7.0.0", "canvas": "2.11.2", "cerebral": "5.2.1", "classnames": "2.5.1", "cookie": "0.6.0", - "core-js": "3.38.0", + "core-js": "3.38.1", "cors": "2.8.5", "csv-stringify": "6.5.1", "deep-freeze": "0.0.1", @@ -89,7 +89,6 @@ "react-dom": "18.3.1", "react-idle-timer": "5.7.2", "react-number-format": "5.4.0", - "react-paginate": "8.2.0", "react-quill": "2.0.0", "react-responsive": "10.0.0", "react-select": "5.8.0", @@ -255,12 +254,12 @@ "ejs": "3.1.10" }, "devDependencies": { - "@aws-sdk/client-iam": "3.632.0", - "@aws-sdk/client-secrets-manager": "3.632.0", + "@aws-sdk/client-iam": "3.637.0", + "@aws-sdk/client-secrets-manager": "3.637.0", "@babel/cli": "7.24.8", "@babel/core": "7.25.2", "@babel/eslint-parser": "7.25.1", - "@babel/preset-env": "7.25.3", + "@babel/preset-env": "7.25.4", "@babel/preset-react": "7.24.7", "@babel/preset-typescript": "7.24.7", "@babel/register": "7.24.6", @@ -271,19 +270,18 @@ "@types/jest": "29.5.12", "@types/lodash": "4.17.7", "@types/luxon": "3.4.2", - "@types/node": "22.4.0", + "@types/node": "22.5.0", "@types/promise-retry": "1.1.6", - "@types/react": "18.3.3", + "@types/react": "18.3.4", "@types/react-dom": "18.3.0", - "@types/react-paginate": "7.1.4", "@types/uuid": "10.0.0", "@types/websocket": "1.0.10", - "@typescript-eslint/eslint-plugin": "8.1.0", - "@typescript-eslint/parser": "8.1.0", + "@typescript-eslint/eslint-plugin": "8.2.0", + "@typescript-eslint/parser": "8.2.0", "@vendia/serverless-express": "4.12.6", "ajv": "8.17.1", - "artillery": "2.0.19", - "artillery-plugin-metrics-by-endpoint": "1.13.0", + "artillery": "2.0.20", + "artillery-plugin-metrics-by-endpoint": "1.14.0", "autoprefixer": "10.4.20", "aws-sdk-client-mock": "4.0.1", "axe-core": "4.10.0", @@ -303,7 +301,7 @@ "decimal.js": "10.4.3", "dynamodb-admin": "4.6.1", "dynamodb-streams-readable": "3.0.0", - "esbuild": "0.23.0", + "esbuild": "0.23.1", "esbuild-css-modules-plugin": "3.1.2", "esbuild-plugin-babel-cached": "0.2.3", "esbuild-plugin-clean": "1.0.1", @@ -330,7 +328,7 @@ "eslint-plugin-spellcheck": "0.0.20", "esm": "3.2.25", "file-loader": "6.2.0", - "husky": "9.1.4", + "husky": "9.1.5", "jest": "29.7.0", "jest-environment-jsdom": "29.7.0", "jest-environment-node": "29.7.0", @@ -356,7 +354,7 @@ "readline": "1.3.0", "s3rver": "github:20minutes/s3rver", "sass": "1.77.8", - "sass-loader": "16.0.0", + "sass-loader": "16.0.1", "shuffle-seed": "1.1.6", "stream-browserify": "3.0.0", "style-loader": "4.0.0", diff --git a/scripts/dynamo/fix-race-condition-served-in-drafts.ts b/scripts/dynamo/fix-race-condition-served-in-drafts.ts index 93ee15220fe..796ae515325 100644 --- a/scripts/dynamo/fix-race-condition-served-in-drafts.ts +++ b/scripts/dynamo/fix-race-condition-served-in-drafts.ts @@ -68,7 +68,7 @@ export const fixRaceConditionServedInDrafts = async ( applicationContext, docketNumber, }); - const caseEntity = new Case(subjectCase, { applicationContext }); + const caseEntity = new Case(subjectCase, { authorizedUser: undefined }); const servedParties = aggregatePartiesForService(caseEntity); @@ -140,7 +140,7 @@ export const fixRaceConditionServedInDrafts = async ( // TODO: figure out index const docketEntry = new DocketEntry(rawDocketEntry, { - applicationContext, + authorizedUser: undefined, }).validate(); docketEntry.setAsServed(servedParties.all); diff --git a/scripts/email/resend-service-email-to-irs-superuser.ts b/scripts/email/resend-service-email-to-irs-superuser.ts index e4b7b1b5f8e..e8b4cdf4c72 100644 --- a/scripts/email/resend-service-email-to-irs-superuser.ts +++ b/scripts/email/resend-service-email-to-irs-superuser.ts @@ -10,8 +10,8 @@ if (!process.argv[2] || !process.argv[3]) { import { Case } from '@shared/business/entities/cases/Case'; import { INITIAL_DOCUMENT_TYPES } from '@shared/business/entities/EntityConstants'; import { createApplicationContext } from '@web-api/applicationContext'; -import { sendIrsSuperuserPetitionEmail } from '@shared/business/useCaseHelper/service/sendIrsSuperuserPetitionEmail'; -import { sendServedPartiesEmails } from '@shared/business/useCaseHelper/service/sendServedPartiesEmails'; +import { sendIrsSuperuserPetitionEmail } from '@web-api/business/useCaseHelper/service/sendIrsSuperuserPetitionEmail'; +import { sendServedPartiesEmails } from '@web-api/business/useCaseHelper/service/sendServedPartiesEmails'; const getCase = async ( applicationContext: IApplicationContext, @@ -24,7 +24,7 @@ const getCase = async ( docketNumber, }); - return new Case(caseToBatch, { applicationContext }); + return new Case(caseToBatch, { authorizedUser: undefined }); }; const resendServiceEmail = async ( diff --git a/scripts/run-once-scripts/add-petioner-role-to-roleless-user.ts b/scripts/run-once-scripts/add-petioner-role-to-roleless-user.ts new file mode 100644 index 00000000000..592e7eac7df --- /dev/null +++ b/scripts/run-once-scripts/add-petioner-role-to-roleless-user.ts @@ -0,0 +1,46 @@ +import { createApplicationContext } from '../../web-api/src/applicationContext'; +import { environment } from '../../web-api/src/environment'; +import { ROLES } from '../../shared/src/business/entities/EntityConstants'; + +async function main() { + const applicationContext = createApplicationContext({}); + const cognito = applicationContext.getCognito(); + const PAGE_SIZE = 10; + + let PaginationToken: string | undefined; + let usersCompleted = 0; + do { + await new Promise(resolve => setTimeout(resolve, 300)); + const response = await cognito.listUsers({ + Limit: PAGE_SIZE, + PaginationToken, + UserPoolId: environment.userPoolId, + }); + + PaginationToken = response.PaginationToken; + response.Users?.forEach(async user => { + const userHasRole = user.Attributes?.find( + cognitoAttribute => cognitoAttribute.Name === 'custom:role', + ); + + if (!userHasRole) { + await cognito.adminUpdateUserAttributes({ + UserAttributes: [ + { + Name: 'custom:role', + Value: ROLES.petitioner, + }, + ], + UserPoolId: environment.userPoolId, + Username: user.Username, + }); + console.log('Updated: ', user.Username); + } + }); + + usersCompleted = usersCompleted + PAGE_SIZE; + console.log('Users Completed: ', usersCompleted); + } while (PaginationToken); +} + +void main(); diff --git a/scripts/run-once-scripts/fix-cognito-users-without-ids-constants.ts b/scripts/run-once-scripts/fix-cognito-users-without-ids-constants.ts new file mode 100644 index 00000000000..2ff2c7a0955 --- /dev/null +++ b/scripts/run-once-scripts/fix-cognito-users-without-ids-constants.ts @@ -0,0 +1,33 @@ +/* eslint-disable max-lines */ +// import { DateTime } from 'luxon'; +import { UserType } from '@aws-sdk/client-cognito-identity-provider'; + +export const usersWithoutUserIds: UserType[] = [ + // { + // Attributes: [ + // { + // Name: 'sub', + // Value: '2e135421-9953-409b-9c69-be05670f4257', + // }, + // { + // Name: 'email_verified', + // Value: 'false', + // }, + // { + // Name: 'name', + // Value: 'John Doe', + // }, + // { + // Name: 'email', + // Value: 'jdoe@example.com', + // }, + // ], + // Enabled: true, + // UserCreateDate: DateTime.fromISO('2024-06-09T02:00:16.418Z').toJSDate(), + // UserLastModifiedDate: DateTime.fromISO( + // '2024-06-09T02:00:16.418Z', + // ).toJSDate(), + // UserStatus: 'UNCONFIRMED', + // Username: '2e135421-9953-409b-9c69-be05670f4257', + // }, +]; diff --git a/scripts/run-once-scripts/fix-cognito-users-without-ids.ts b/scripts/run-once-scripts/fix-cognito-users-without-ids.ts new file mode 100644 index 00000000000..cc40a122d04 --- /dev/null +++ b/scripts/run-once-scripts/fix-cognito-users-without-ids.ts @@ -0,0 +1,101 @@ +import { RawUser } from '@shared/business/entities/User'; +import { + type ServerApplicationContext, + createApplicationContext, +} from '@web-api/applicationContext'; +import { createPetitionerUserRecords } from '@web-api/persistence/dynamo/users/createPetitionerUserRecords'; +import { createUserConfirmation } from '@web-api/business/useCaseHelper/auth/createUserConfirmation'; +import { omit } from 'lodash'; +import { usersWithoutUserIds } from './fix-cognito-users-without-ids-constants'; +import type { UserType } from '@aws-sdk/client-cognito-identity-provider'; + +const getAttributeValue = ( + cognitoUser: UserType, + attr: string, +): string | undefined => { + return cognitoUser.Attributes?.find(attrib => attrib.Name === attr)?.Value; +}; + +const buildRawUser = (cognitoUser: UserType): RawUser | undefined => { + const userId = cognitoUser.Username; + const email = getAttributeValue(cognitoUser, 'email'); + const name = getAttributeValue(cognitoUser, 'name'); + if (!!userId && !!email && !!name) { + return { + email, + entityName: 'User', + name, + role: 'petitioner', + userId, + } as RawUser; + } +}; + +const setUserAttributes = async ({ + applicationContext, + cognitoUser, +}: { + applicationContext: ServerApplicationContext; + cognitoUser: UserType; +}): Promise => { + if (cognitoUser && cognitoUser.Username) { + const cognito = applicationContext.getCognito(); + await cognito.adminUpdateUserAttributes({ + UserAttributes: [ + { + Name: 'custom:userId', + Value: cognitoUser.Username, + }, + { + Name: 'custom:role', + Value: 'petitioner', + }, + ], + UserPoolId: applicationContext.environment.userPoolId, + Username: cognitoUser.Username, + }); + } +}; + +// eslint-disable-next-line @typescript-eslint/no-floating-promises +(async () => { + const applicationContext = createApplicationContext({}); + + const totals = { + emailConfirmationsSent: 0, + userEntitiesCreatedInDynamo: 0, + usersUpdatedInCognito: 0, + }; + for (const cognitoUser of usersWithoutUserIds) { + const user = buildRawUser(cognitoUser); + if (user) { + await setUserAttributes({ applicationContext, cognitoUser }); + console.log(`Updated cognito user attributes for ${user.email}.`); + totals.usersUpdatedInCognito++; + + if (!cognitoUser.Enabled) { + continue; + } + + if (cognitoUser.UserStatus === 'CONFIRMED') { + await createPetitionerUserRecords({ + applicationContext, + user: omit(user, 'userId'), + userId: user.userId, + }); + console.log(`Created petitioner entity in Dynamo for ${user.email}.`); + totals.userEntitiesCreatedInDynamo++; + } + + if (cognitoUser.UserStatus === 'UNCONFIRMED') { + await createUserConfirmation(applicationContext, { + email: user.email!, + userId: user.userId, + }); + console.log(`Sent new email confirmation link to ${user.email}.`); + totals.emailConfirmationsSent++; + } + } + } + console.log('Totals', totals); +})(); diff --git a/scripts/run-once-scripts/verify-cognito-required-attributes.ts b/scripts/run-once-scripts/verify-cognito-required-attributes.ts new file mode 100644 index 00000000000..c74307b4f9d --- /dev/null +++ b/scripts/run-once-scripts/verify-cognito-required-attributes.ts @@ -0,0 +1,69 @@ +import { UserType } from '@aws-sdk/client-cognito-identity-provider'; +import { createApplicationContext } from '../../web-api/src/applicationContext'; +import { environment } from '../../web-api/src/environment'; + +async function main() { + const applicationContext = createApplicationContext({}); + const cognito = applicationContext.getCognito(); + + const expectedAttributes = ['custom:userId', 'name', 'email', 'custom:role']; + const piiFields: (string | undefined)[] = ['name', 'email']; + const usersMissingAttributes: UserType[] = []; + const missingFieldSummary = { + ['custom:userId']: 0, + name: 0, + email: 0, + ['custom:role']: 0, + }; + + let PaginationToken: string | undefined; + let usersCompleted = 0; + do { + const response = await cognito.listUsers({ + Limit: 60, + PaginationToken, + UserPoolId: environment.userPoolId, + }); + + // eslint-disable-next-line prefer-destructuring + PaginationToken = response.PaginationToken; + response.Users?.forEach(user => { + const userHasAllAttributes = expectedAttributes.every( + expectedAttribute => { + const theField = user.Attributes?.find( + cognitoAttribute => cognitoAttribute.Name === expectedAttribute, + ); + + if (!theField) { + missingFieldSummary[expectedAttribute]++; + } + return !!theField; + }, + ); + + if (!userHasAllAttributes) { + user.Attributes?.forEach(cogAttribute => { + if (piiFields.includes(cogAttribute.Name) && cogAttribute.Value) { + cogAttribute.Value = '*******'; + } + }); + usersMissingAttributes.push(user); + } + }); + + usersCompleted = usersCompleted + 60; + console.log('Users Completed: ', usersCompleted); + } while (PaginationToken); + + console.log( + 'Users missing attributes: ', + JSON.stringify(usersMissingAttributes, null, 2), + ); + console.log( + 'Users missing attributes (count): ', + usersMissingAttributes.length, + ); + console.log(missingFieldSummary); +} + +void main(); diff --git a/scripts/verify-terraform-version.sh b/scripts/verify-terraform-version.sh index 3fee6bf7376..27bf9bd3a41 100755 --- a/scripts/verify-terraform-version.sh +++ b/scripts/verify-terraform-version.sh @@ -2,7 +2,7 @@ tf_version=$(terraform --version) -if [[ ${tf_version} != *"1.9.4"* ]]; then - echo "Please set your terraform version to 1.9.4 before deploying." +if [[ ${tf_version} != *"1.9.5"* ]]; then + echo "Please set your terraform version to 1.9.5 before deploying." exit 1 fi diff --git a/shared/admin-tools/aws/migrationWaitHelper.ts b/shared/admin-tools/aws/migrationWaitHelper.ts index ec8bf245817..b38e68a41be 100644 --- a/shared/admin-tools/aws/migrationWaitHelper.ts +++ b/shared/admin-tools/aws/migrationWaitHelper.ts @@ -9,7 +9,7 @@ import { getItem, putItem } from './deployTableHelper'; const cloudwatchClient = new CloudWatchClient({ region: 'us-east-1' }); const env = process.env.STAGE; -const key = 'migration-queue-is-empty'; +const key = 'migration-queue-empty'; export const getMetricStatistics = async ( type: string, diff --git a/shared/admin-tools/glue/glue_migrations/main.tf b/shared/admin-tools/glue/glue_migrations/main.tf index 2c4e0d2921d..e2f62af74f1 100644 --- a/shared/admin-tools/glue/glue_migrations/main.tf +++ b/shared/admin-tools/glue/glue_migrations/main.tf @@ -7,7 +7,7 @@ terraform { } required_providers { - aws = "5.63.0" + aws = "5.63.1" } } diff --git a/shared/admin-tools/glue/remote_role/main.tf b/shared/admin-tools/glue/remote_role/main.tf index e90e4ba76ea..7e21e12f031 100644 --- a/shared/admin-tools/glue/remote_role/main.tf +++ b/shared/admin-tools/glue/remote_role/main.tf @@ -7,7 +7,7 @@ terraform { } required_providers { - aws = "5.63.0" + aws = "5.63.1" } } diff --git a/shared/admin-tools/user/admin.ts b/shared/admin-tools/user/admin.ts index 562ec3c1ce4..9489bbebdb5 100644 --- a/shared/admin-tools/user/admin.ts +++ b/shared/admin-tools/user/admin.ts @@ -124,6 +124,7 @@ export async function createOrUpdateUser( if (userExists) { await applicationContext.getUserGateway().updateUser(applicationContext, { attributesToUpdate: { + name: rawUser.name, role: rawUser.role, }, email: rawUser.email!, diff --git a/shared/src/authorization/authorizationClientService.test.ts b/shared/src/authorization/authorizationClientService.test.ts index f4a1f12c677..30d25235369 100644 --- a/shared/src/authorization/authorizationClientService.test.ts +++ b/shared/src/authorization/authorizationClientService.test.ts @@ -3,30 +3,38 @@ import { ROLE_PERMISSIONS, isAuthorized, } from './authorizationClientService'; -import { ROLES } from '../business/entities/EntityConstants'; +import { + mockAdcUser, + mockCaseServicesSupervisorUser, + mockChambersUser, + mockDocketClerkUser, + mockIrsPractitionerUser, + mockJudgeUser, + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('Authorization client service', () => { it('should return false when the user is undefined', () => { - expect(isAuthorized(undefined, 'unknown action', 'someUser')).toBeFalsy(); + expect( + isAuthorized(undefined, 'unknown action' as any, 'someUser'), + ).toBeFalsy(); }); it('should return true for any user whose userId matches the 3rd owner argument, in this case "someUser" === "someUser"', () => { expect( isAuthorized( - { role: ROLES.petitioner, userId: 'someUser' }, - 'unknown action', - 'someUser', + mockPetitionerUser, + 'unknown action' as any, + mockPetitionerUser.userId, ), ).toBeTruthy(); }); it('should return false when the role provided is not found in the AUTHORIZATION_MAP', () => { - expect( - isAuthorized( - { role: 'NOT_A_ROLE', userId: 'judgebuch' }, - ROLE_PERMISSIONS.WORKITEM, - ), - ).toBe(false); + expect(isAuthorized(mockPetitionerUser, ROLE_PERMISSIONS.WORKITEM)).toBe( + false, + ); }); it('should contain NO falsy values in the AUTHORIZATION_MAP', () => { @@ -39,20 +47,12 @@ describe('Authorization client service', () => { describe('adc role', () => { it('should be authorized for the WORK_ITEM permission', () => { - expect( - isAuthorized( - { role: ROLES.adc, userId: 'adc' }, - ROLE_PERMISSIONS.WORKITEM, - ), - ).toBeTruthy(); + expect(isAuthorized(mockAdcUser, ROLE_PERMISSIONS.WORKITEM)).toBeTruthy(); }); it('should be authorized to stamp a motion', () => { expect( - isAuthorized( - { role: ROLES.adc, userId: 'adc' }, - ROLE_PERMISSIONS.STAMP_MOTION, - ), + isAuthorized(mockAdcUser, ROLE_PERMISSIONS.STAMP_MOTION), ).toBeTruthy(); }); }); @@ -60,10 +60,7 @@ describe('Authorization client service', () => { describe('chambers role', () => { it('should be authorized to stamp a motion', () => { expect( - isAuthorized( - { role: ROLES.chambers, userId: 'chambers1' }, - ROLE_PERMISSIONS.STAMP_MOTION, - ), + isAuthorized(mockChambersUser, ROLE_PERMISSIONS.STAMP_MOTION), ).toBeTruthy(); }); }); @@ -72,19 +69,13 @@ describe('Authorization client service', () => { it('should be authorized to perform both docket clerk and petitions clerk specific actions', () => { expect( isAuthorized( - { - role: ROLES.caseServicesSupervisor, - userId: 'caseServicesSupervisor1', - }, + mockCaseServicesSupervisorUser, ROLE_PERMISSIONS.ADD_EDIT_STATISTICS, ), ).toBeTruthy(); expect( isAuthorized( - { - role: ROLES.caseServicesSupervisor, - userId: 'caseServicesSupervisor1', - }, + mockCaseServicesSupervisorUser, ROLE_PERMISSIONS.QC_PETITION, ), ).toBeTruthy(); @@ -94,37 +85,25 @@ describe('Authorization client service', () => { describe('docketClerk role', () => { it('should be authorized for the WORK_ITEM permission', () => { expect( - isAuthorized( - { role: ROLES.docketClerk, userId: 'docketclerk' }, - ROLE_PERMISSIONS.WORKITEM, - ), + isAuthorized(mockDocketClerkUser, ROLE_PERMISSIONS.WORKITEM), ).toBeTruthy(); }); it('should be authorized to seal an address', () => { expect( - isAuthorized( - { role: ROLES.docketClerk, userId: 'docketclerk' }, - ROLE_PERMISSIONS.SEAL_ADDRESS, - ), + isAuthorized(mockDocketClerkUser, ROLE_PERMISSIONS.SEAL_ADDRESS), ).toBeTruthy(); }); it('should be authorized to perform track items operations', () => { expect( - isAuthorized( - { role: ROLES.docketClerk, userId: 'docketclerk' }, - ROLE_PERMISSIONS.TRACKED_ITEMS, - ), + isAuthorized(mockDocketClerkUser, ROLE_PERMISSIONS.TRACKED_ITEMS), ).toBeTruthy(); }); it('should be authorized to update a case', () => { expect( - isAuthorized( - { role: ROLES.docketClerk, userId: 'docketclerk' }, - ROLE_PERMISSIONS.UPDATE_CASE, - ), + isAuthorized(mockDocketClerkUser, ROLE_PERMISSIONS.UPDATE_CASE), ).toBeTruthy(); }); }); @@ -132,10 +111,7 @@ describe('Authorization client service', () => { describe('irsPractitioner', () => { it('should be authorized to get a case', () => { expect( - isAuthorized( - { role: ROLES.irsPractitioner, userId: 'irsPractitioner' }, - ROLE_PERMISSIONS.GET_CASE, - ), + isAuthorized(mockIrsPractitionerUser, ROLE_PERMISSIONS.GET_CASE), ).toBeTruthy(); }); }); @@ -143,10 +119,7 @@ describe('Authorization client service', () => { describe('judge role', () => { it('should be authorized to stamp a motion', () => { expect( - isAuthorized( - { role: ROLES.judge, userId: 'judgebuch' }, - ROLE_PERMISSIONS.STAMP_MOTION, - ), + isAuthorized(mockJudgeUser, ROLE_PERMISSIONS.STAMP_MOTION), ).toBeTruthy(); }); }); @@ -154,55 +127,37 @@ describe('Authorization client service', () => { describe('petitionsClerk role', () => { it('should be authorized to get a case', () => { expect( - isAuthorized( - { role: ROLES.petitionsClerk, userId: 'petitionsclerk' }, - ROLE_PERMISSIONS.GET_CASE, - ), + isAuthorized(mockPetitionsClerkUser, ROLE_PERMISSIONS.GET_CASE), ).toBeTruthy(); }); it('should be authorized to perform track items operations', () => { expect( - isAuthorized( - { role: ROLES.docketClerk, userId: 'docketclerk' }, - ROLE_PERMISSIONS.TRACKED_ITEMS, - ), + isAuthorized(mockDocketClerkUser, ROLE_PERMISSIONS.TRACKED_ITEMS), ).toBeTruthy(); }); it('should be authorized for the WORK_ITEM permission', () => { expect( - isAuthorized( - { role: ROLES.petitionsClerk, userId: 'petitionsclerk' }, - ROLE_PERMISSIONS.WORKITEM, - ), + isAuthorized(mockPetitionsClerkUser, ROLE_PERMISSIONS.WORKITEM), ).toBeTruthy(); }); it('should be authorized to start a case from paper', () => { expect( - isAuthorized( - { role: ROLES.petitionsClerk, userId: 'petitionsclerk' }, - ROLE_PERMISSIONS.START_PAPER_CASE, - ), + isAuthorized(mockPetitionsClerkUser, ROLE_PERMISSIONS.START_PAPER_CASE), ).toBeTruthy(); }); it('should be authorized to serve a petition', () => { expect( - isAuthorized( - { role: ROLES.petitionsClerk, userId: 'petitionsclerk' }, - ROLE_PERMISSIONS.SERVE_PETITION, - ), + isAuthorized(mockPetitionsClerkUser, ROLE_PERMISSIONS.SERVE_PETITION), ).toBeTruthy(); }); it('should be authorized to seal a docket entry', () => { expect( - isAuthorized( - { role: ROLES.docketClerk, userId: 'docketclerk' }, - ROLE_PERMISSIONS.SEAL_DOCKET_ENTRY, - ), + isAuthorized(mockDocketClerkUser, ROLE_PERMISSIONS.SEAL_DOCKET_ENTRY), ).toBeTruthy(); }); }); diff --git a/shared/src/authorization/authorizationClientService.ts b/shared/src/authorization/authorizationClientService.ts index e79d3e5db5c..cf1962f583c 100644 --- a/shared/src/authorization/authorizationClientService.ts +++ b/shared/src/authorization/authorizationClientService.ts @@ -1,3 +1,9 @@ +import { + AuthUser, + UnknownAuthUser, + isAuthUser, +} from '../business/entities/authUser/AuthUser'; + export const ROLE_PERMISSIONS = { ADD_CASE_TO_TRIAL_SESSION: 'ADD_CASE_TO_TRIAL_SESSION', ADD_EDIT_JUDGE_USER: 'ADD_EDIT_JUDGE_USER', @@ -81,9 +87,12 @@ export const ROLE_PERMISSIONS = { VIEW_SEALED_ADDRESS: 'VIEW_SEALED_ADDRESS', VIEW_SEALED_CASE: 'VIEW_SEALED_CASE', WORKITEM: 'WORKITEM', -}; +} as const; + +export type RolePermission = + (typeof ROLE_PERMISSIONS)[keyof typeof ROLE_PERMISSIONS]; -const allInternalUserPermissions = [ +const allInternalUserPermissions: RolePermission[] = [ ROLE_PERMISSIONS.ADD_CASE_TO_TRIAL_SESSION, ROLE_PERMISSIONS.ADVANCED_SEARCH, ROLE_PERMISSIONS.ARCHIVE_DOCUMENT, @@ -116,7 +125,7 @@ const allInternalUserPermissions = [ ROLE_PERMISSIONS.COLD_CASE_REPORT, ]; -const adcPermissions = [ +const adcPermissions: RolePermission[] = [ ...allInternalUserPermissions, ROLE_PERMISSIONS.CREATE_TRIAL_SESSION, ROLE_PERMISSIONS.STATUS_REPORT_ORDER, @@ -124,14 +133,14 @@ const adcPermissions = [ ROLE_PERMISSIONS.STAMP_MOTION, ]; -const adminPermissions = [ +const adminPermissions: RolePermission[] = [ ROLE_PERMISSIONS.ADD_EDIT_JUDGE_USER, ROLE_PERMISSIONS.ADD_EDIT_PRACTITIONER_USER, ROLE_PERMISSIONS.CREATE_USER, ROLE_PERMISSIONS.MANAGE_PRACTITIONER_USERS, ]; -const admissionsClerkPermissions = [ +const admissionsClerkPermissions: RolePermission[] = [ ...allInternalUserPermissions, ROLE_PERMISSIONS.ADD_EDIT_PRACTITIONER_USER, ROLE_PERMISSIONS.ADD_USER_TO_CASE, @@ -146,7 +155,7 @@ const admissionsClerkPermissions = [ ROLE_PERMISSIONS.VIEW_SEALED_ADDRESS, ]; -const chambersPermissions = [ +const chambersPermissions: RolePermission[] = [ ...allInternalUserPermissions, ROLE_PERMISSIONS.BATCH_DOWNLOAD_TRIAL_SESSION, ROLE_PERMISSIONS.PENDING_MOTIONS_TABLE, @@ -160,7 +169,7 @@ const chambersPermissions = [ ROLE_PERMISSIONS.SEND_RECEIVE_MESSAGES, ]; -const docketClerkPermissions = [ +const docketClerkPermissions: RolePermission[] = [ ...allInternalUserPermissions, ROLE_PERMISSIONS.ADD_EDIT_STATISTICS, ROLE_PERMISSIONS.ADD_PETITIONER_TO_CASE, @@ -188,13 +197,13 @@ const docketClerkPermissions = [ ROLE_PERMISSIONS.VIEW_SEALED_ADDRESS, ]; -const generalUserPermissions = [ +const generalUserPermissions: RolePermission[] = [ ...allInternalUserPermissions, ROLE_PERMISSIONS.CASE_CORRESPONDENCE, ROLE_PERMISSIONS.CREATE_TRIAL_SESSION, ]; -const petitionsClerkPermissions = [ +const petitionsClerkPermissions: RolePermission[] = [ ...allInternalUserPermissions, ROLE_PERMISSIONS.ADD_EDIT_STATISTICS, ROLE_PERMISSIONS.ASSIGN_WORK_ITEM, @@ -215,7 +224,7 @@ const petitionsClerkPermissions = [ ROLE_PERMISSIONS.DISMISS_NOTT_REMINDER, ]; -const irsPractitionerPermissions = [ +const irsPractitionerPermissions: RolePermission[] = [ ROLE_PERMISSIONS.ADVANCED_SEARCH, ROLE_PERMISSIONS.ASSOCIATE_SELF_WITH_CASE, ROLE_PERMISSIONS.EMAIL_MANAGEMENT, @@ -229,7 +238,7 @@ const irsPractitionerPermissions = [ ROLE_PERMISSIONS.VIEW_DOCUMENTS, ]; -const irsSuperuserPermissions = [ +const irsSuperuserPermissions: RolePermission[] = [ ROLE_PERMISSIONS.ADVANCED_SEARCH, ROLE_PERMISSIONS.GET_CASE, ROLE_PERMISSIONS.GET_JUDGES, @@ -239,7 +248,7 @@ const irsSuperuserPermissions = [ ROLE_PERMISSIONS.VIEW_SEALED_CASE, ]; -const judgePermissions = [ +const judgePermissions: RolePermission[] = [ ...allInternalUserPermissions, ROLE_PERMISSIONS.BATCH_DOWNLOAD_TRIAL_SESSION, ROLE_PERMISSIONS.JUDGES_NOTES, @@ -253,7 +262,7 @@ const judgePermissions = [ ROLE_PERMISSIONS.STATUS_REPORT_ORDER, ]; -const petitionerPermissions = [ +const petitionerPermissions: RolePermission[] = [ ROLE_PERMISSIONS.EMAIL_MANAGEMENT, ROLE_PERMISSIONS.FILE_EXTERNAL_DOCUMENT, ROLE_PERMISSIONS.GET_USER_PENDING_EMAIL_STATUS, @@ -264,7 +273,7 @@ const petitionerPermissions = [ ROLE_PERMISSIONS.VIEW_CONSOLIDATED_CASES_CARD, ]; -const privatePractitionerPermissions = [ +const privatePractitionerPermissions: RolePermission[] = [ ROLE_PERMISSIONS.GET_USER_PENDING_EMAIL_STATUS, ROLE_PERMISSIONS.ADVANCED_SEARCH, ROLE_PERMISSIONS.ASSOCIATE_SELF_WITH_CASE, @@ -279,7 +288,7 @@ const privatePractitionerPermissions = [ ROLE_PERMISSIONS.VIEW_DOCUMENTS, ]; -const trialClerkPermissions = [ +const trialClerkPermissions: RolePermission[] = [ ...allInternalUserPermissions, ROLE_PERMISSIONS.BATCH_DOWNLOAD_TRIAL_SESSION, ROLE_PERMISSIONS.CREATE_TRIAL_SESSION, @@ -308,11 +317,11 @@ export const AUTHORIZATION_MAP = { ROLE_PERMISSIONS.SEND_RECEIVE_MESSAGES, ], general: generalUserPermissions, - inactivePractitioner: [], + inactivePractitioner: [] as RolePermission[], irsPractitioner: irsPractitionerPermissions, irsSuperuser: irsSuperuserPermissions, judge: judgePermissions, - legacyJudge: [], + legacyJudge: [] as RolePermission[], petitioner: petitionerPermissions, petitionsclerk: petitionsClerkPermissions, privatePractitioner: privatePractitionerPermissions, @@ -323,31 +332,28 @@ export const AUTHORIZATION_MAP = { trialclerk: trialClerkPermissions, }; -/** - * Checks user permissions for an action - * @param {object} user the user to check for authorization - * @param {string} action the action to verify if the user is authorized for - * @param {string} owner the user id of the owner of the item to verify - * @returns {boolean} true if user is authorized, false otherwise - */ -export const isAuthorized = (user, action, owner?): boolean => { - if (!user) { +export const isAuthorized = ( + user: UnknownAuthUser, + action: RolePermission, + owner?: string, +): user is AuthUser => { + if (!isAuthUser(user)) { return false; } - if (user.userId && user.userId === owner) { + if (user.userId === owner) { return true; } const userRole = user.role; - if (!AUTHORIZATION_MAP[userRole]) { + const permissions = AUTHORIZATION_MAP[userRole]; + if (!permissions) { return false; } - const roleActionIndex = AUTHORIZATION_MAP[userRole].indexOf(action); + const roleActionIndex = permissions.indexOf(action); - const actionInRoleAuthorization = - !!AUTHORIZATION_MAP[userRole][roleActionIndex]; + const actionInRoleAuthorization = !!permissions[roleActionIndex]; return actionInRoleAuthorization; }; diff --git a/shared/src/authorization/getUserPermissions.ts b/shared/src/authorization/getUserPermissions.ts index 4b9d605f7dd..7dca670b56b 100644 --- a/shared/src/authorization/getUserPermissions.ts +++ b/shared/src/authorization/getUserPermissions.ts @@ -1,5 +1,6 @@ import { ROLE_PERMISSIONS, isAuthorized } from './authorizationClientService'; import { RawIrsPractitioner } from '@shared/business/entities/IrsPractitioner'; +import { RawPractitioner } from '@shared/business/entities/Practitioner'; import { RawUser } from '@shared/business/entities/User'; /** diff --git a/shared/src/business/entities/DocketEntry.archive.test.ts b/shared/src/business/entities/DocketEntry.archive.test.ts index cc99e7d6298..d66e4ca6a94 100644 --- a/shared/src/business/entities/DocketEntry.archive.test.ts +++ b/shared/src/business/entities/DocketEntry.archive.test.ts @@ -1,11 +1,10 @@ import { A_VALID_DOCKET_ENTRY } from './DocketEntry.test'; import { DocketEntry } from './DocketEntry'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('archive', () => { it('archives the document', () => { const docketEntry = new DocketEntry(A_VALID_DOCKET_ENTRY, { - applicationContext, + authorizedUser: undefined, petitioners: [ { contactId: '7111b30b-ad38-42c8-9db0-d938cb2cb16b', diff --git a/shared/src/business/entities/DocketEntry.generateFiledBy.test.ts b/shared/src/business/entities/DocketEntry.generateFiledBy.test.ts index d9189a0ea78..467dc45986c 100644 --- a/shared/src/business/entities/DocketEntry.generateFiledBy.test.ts +++ b/shared/src/business/entities/DocketEntry.generateFiledBy.test.ts @@ -1,7 +1,6 @@ import { DocketEntry } from './DocketEntry'; import { MOCK_DOCUMENTS } from '../../test/mockDocketEntry'; import { NOTICE_OF_CHANGE_CONTACT_INFORMATION_MAP } from './EntityConstants'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('generateFiledBy', () => { let mockDocketEntry; @@ -24,7 +23,7 @@ describe('generateFiledBy', () => { ...mockDocketEntry, filers: [mockPrimaryContactId], }, - { applicationContext, petitioners: mockPetitioners }, + { authorizedUser: undefined, petitioners: mockPetitioners }, ); expect(docketEntry.filedBy).toEqual('Petr. Bob'); @@ -37,7 +36,7 @@ describe('generateFiledBy', () => { filers: [mockPrimaryContactId], otherFilingParty: mockOtherFilingParty, }, - { applicationContext, petitioners: mockPetitioners }, + { authorizedUser: undefined, petitioners: mockPetitioners }, ); expect(docketEntry.filedBy).toEqual(`Petr. Bob, ${mockOtherFilingParty}`); @@ -49,7 +48,7 @@ describe('generateFiledBy', () => { ...mockDocketEntry, filers: [mockSecondaryContactId], }, - { applicationContext, petitioners: mockPetitioners }, + { authorizedUser: undefined, petitioners: mockPetitioners }, ); expect(docketEntry.filedBy).toEqual('Petr. Bill'); @@ -62,7 +61,7 @@ describe('generateFiledBy', () => { filers: [mockPrimaryContactId], partyIrsPractitioner: true, }, - { applicationContext, petitioners: mockPetitioners }, + { authorizedUser: undefined, petitioners: mockPetitioners }, ); expect(docketEntry.filedBy).toEqual('Resp. & Petr. Bob'); @@ -76,7 +75,7 @@ describe('generateFiledBy', () => { otherFilingParty: mockOtherFilingParty, partyIrsPractitioner: true, }, - { applicationContext, petitioners: mockPetitioners }, + { authorizedUser: undefined, petitioners: mockPetitioners }, ); expect(docketEntry.filedBy).toEqual( @@ -90,7 +89,7 @@ describe('generateFiledBy', () => { ...mockDocketEntry, otherFilingParty: mockOtherFilingParty, }, - { applicationContext, petitioners: mockPetitioners }, + { authorizedUser: undefined, petitioners: mockPetitioners }, ); expect(docketEntry.filedBy).toEqual(mockOtherFilingParty); @@ -102,7 +101,7 @@ describe('generateFiledBy', () => { ...mockDocketEntry, filers: [mockPrimaryContactId, mockSecondaryContactId], }, - { applicationContext, petitioners: mockPetitioners }, + { authorizedUser: undefined, petitioners: mockPetitioners }, ); expect(docketEntry.filedBy).toEqual('Petrs. Bob & Bill'); @@ -118,7 +117,7 @@ describe('generateFiledBy', () => { name: 'Test Practitioner', }, }, - { applicationContext, petitioners: mockPetitioners }, + { authorizedUser: undefined, petitioners: mockPetitioners }, ); expect(docketEntry.filedBy).toEqual('Resp.'); @@ -137,7 +136,7 @@ describe('generateFiledBy', () => { }, ], }, - { applicationContext, petitioners: mockPetitioners }, + { authorizedUser: undefined, petitioners: mockPetitioners }, ); expect(docketEntry.filedBy).toEqual('Resp.'); @@ -150,7 +149,7 @@ describe('generateFiledBy', () => { filers: [mockPrimaryContactId], partyIrsPractitioner: true, }, - { applicationContext, petitioners: mockPetitioners }, + { authorizedUser: undefined, petitioners: mockPetitioners }, ); expect(docketEntry.filedBy).toEqual('Resp. & Petr. Bob'); @@ -162,7 +161,7 @@ describe('generateFiledBy', () => { ...mockDocketEntry, filers: [mockPrimaryContactId, mockSecondaryContactId], }, - { applicationContext, petitioners: mockPetitioners }, + { authorizedUser: undefined, petitioners: mockPetitioners }, ); expect(docketEntry.filedBy).toEqual('Petrs. Bob & Bill'); @@ -178,7 +177,7 @@ describe('generateFiledBy', () => { ...mockDocketEntry, filers: [mockPrimaryContactId], }, - { applicationContext, petitioners: mockIntervenors }, + { authorizedUser: undefined, petitioners: mockIntervenors }, ); expect(docketEntry.filedBy).toEqual('Intv. Bob'); }); @@ -193,7 +192,7 @@ describe('generateFiledBy', () => { ...mockDocketEntry, filers: [mockPrimaryContactId, mockSecondaryContactId], }, - { applicationContext, petitioners: mockIntervenors }, + { authorizedUser: undefined, petitioners: mockIntervenors }, ); expect(docketEntry.filedBy).toEqual('Intvs. Bob & Bill'); }); @@ -211,7 +210,7 @@ describe('generateFiledBy', () => { }, ], }, - { applicationContext, petitioners: mockPetitioners }, + { authorizedUser: undefined, petitioners: mockPetitioners }, ); expect(docketEntry.filedBy).toEqual('Resp.'); @@ -227,7 +226,7 @@ describe('generateFiledBy', () => { filers: [mockPrimaryContactId], isAutoGenerated: true, }, - { applicationContext, petitioners: mockPetitioners }, + { authorizedUser: undefined, petitioners: mockPetitioners }, ); expect(docketEntry.filedBy).toBeUndefined(); @@ -244,7 +243,7 @@ describe('generateFiledBy', () => { servedAt: undefined, }, { - applicationContext, + authorizedUser: undefined, petitioners: mockPetitioners, }, ); @@ -265,7 +264,7 @@ describe('generateFiledBy', () => { ], }, { - applicationContext, + authorizedUser: undefined, petitioners: mockPetitioners, }, ); @@ -285,7 +284,7 @@ describe('generateFiledBy', () => { servedParties: 'Test Petitioner', }, { - applicationContext, + authorizedUser: undefined, petitioners: mockPetitioners, }, ); diff --git a/shared/src/business/entities/DocketEntry.isAutoServed.test.ts b/shared/src/business/entities/DocketEntry.isAutoServed.test.ts index 2b3eee9437c..ee42750fc34 100644 --- a/shared/src/business/entities/DocketEntry.isAutoServed.test.ts +++ b/shared/src/business/entities/DocketEntry.isAutoServed.test.ts @@ -4,7 +4,6 @@ import { EXTERNAL_DOCUMENT_TYPES, SIMULTANEOUS_DOCUMENT_EVENT_CODES, } from './EntityConstants'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('isAutoServed', () => { it('should return true if the documentType is an external document and the document is not a Simultaneous Document', () => { @@ -14,7 +13,7 @@ describe('isAutoServed', () => { documentTitle: 'Answer to Second Amendment to Petition', documentType: 'Answer to Second Amendment to Petition', }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(docketEntry.isAutoServed()).toBeTruthy(); @@ -27,7 +26,7 @@ describe('isAutoServed', () => { documentTitle: 'Notice of Election to Participate', documentType: 'Notice of Election to Participate', }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(docketEntry.isAutoServed()).toBeTruthy(); @@ -57,7 +56,7 @@ describe('isAutoServed', () => { documentType: EXTERNAL_DOCUMENT_TYPES[0], eventCode: 'AMAT', }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(docketEntry.isAutoServed()).toBeFalsy(); @@ -70,7 +69,7 @@ describe('isAutoServed', () => { documentType: SIMULTANEOUS_DOCUMENT_EVENT_CODES[0], eventCode: 'SIAB', }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(docketEntry.isAutoServed()).toBeFalsy(); @@ -83,7 +82,7 @@ describe('isAutoServed', () => { documentTitle: 'Application for Examination Pursuant to Rule 73', documentType: 'Application for Examination Pursuant to Rule 73', }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(docketEntry.isAutoServed()).toBeFalsy(); diff --git a/shared/src/business/entities/DocketEntry.isCourtIssued.test.ts b/shared/src/business/entities/DocketEntry.isCourtIssued.test.ts index b5476dad2b7..b5cbe34ba72 100644 --- a/shared/src/business/entities/DocketEntry.isCourtIssued.test.ts +++ b/shared/src/business/entities/DocketEntry.isCourtIssued.test.ts @@ -1,15 +1,20 @@ import { DocketEntry } from './DocketEntry'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('isCourtIssued', () => { it('should return false when the docketEntry.eventCode is NOT in the list of court issued documents', () => { - const doc1 = new DocketEntry({ eventCode: 'PMT' }, { applicationContext }); + const doc1 = new DocketEntry( + { eventCode: 'PMT' }, + { authorizedUser: undefined }, + ); expect(doc1.isCourtIssued()).toBeFalsy(); }); it('should return true when the docketEntry.eventCode is in the list of court issued documents', () => { - const doc1 = new DocketEntry({ eventCode: 'O' }, { applicationContext }); + const doc1 = new DocketEntry( + { eventCode: 'O' }, + { authorizedUser: undefined }, + ); expect(doc1.isCourtIssued()).toBeTruthy(); }); diff --git a/shared/src/business/entities/DocketEntry.isMinuteEntry.test.ts b/shared/src/business/entities/DocketEntry.isMinuteEntry.test.ts index eac084fa798..a6e5af456e7 100644 --- a/shared/src/business/entities/DocketEntry.isMinuteEntry.test.ts +++ b/shared/src/business/entities/DocketEntry.isMinuteEntry.test.ts @@ -1,6 +1,5 @@ import { DocketEntry } from './DocketEntry'; import { MINUTE_ENTRIES_MAP } from './EntityConstants'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('isMinuteEntry', () => { describe('non RQT event codes', () => { @@ -13,7 +12,7 @@ describe('isMinuteEntry', () => { eventCode => { const minuteEntry = new DocketEntry( { eventCode }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(DocketEntry.isMinuteEntry(minuteEntry)).toBe(true); @@ -23,7 +22,7 @@ describe('isMinuteEntry', () => { it('should return false when the docketEntry eventCode is NOT in the list of minute entries', () => { const orderDocketEntry = new DocketEntry( { eventCode: 'O', isFileAttached: true }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(DocketEntry.isMinuteEntry(orderDocketEntry)).toBe(false); @@ -34,7 +33,7 @@ describe('isMinuteEntry', () => { it('should return false when there is a file attached', () => { const orderDocketEntry = new DocketEntry( { eventCode: 'RQT', isFileAttached: true }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(DocketEntry.isMinuteEntry(orderDocketEntry)).toBe(false); @@ -43,7 +42,7 @@ describe('isMinuteEntry', () => { it('should return true when there is a not file attached', () => { const orderDocketEntry = new DocketEntry( { eventCode: 'RQT', isFileAttached: false }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(DocketEntry.isMinuteEntry(orderDocketEntry)).toBe(true); diff --git a/shared/src/business/entities/DocketEntry.isPendingOnCreation.test.ts b/shared/src/business/entities/DocketEntry.isPendingOnCreation.test.ts index 5e0230f145e..8d2d72d6714 100644 --- a/shared/src/business/entities/DocketEntry.isPendingOnCreation.test.ts +++ b/shared/src/business/entities/DocketEntry.isPendingOnCreation.test.ts @@ -1,5 +1,4 @@ import { DocketEntry } from './DocketEntry'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('isPendingOnCreation', () => { beforeAll(() => { @@ -12,11 +11,11 @@ describe('isPendingOnCreation', () => { it('respects any defined "pending" value', () => { const raw1 = { eventCode: 'FOO', pending: true }; - const doc1 = new DocketEntry(raw1, { applicationContext }); + const doc1 = new DocketEntry(raw1, { authorizedUser: undefined }); expect(doc1.pending).toBeTruthy(); const raw2 = { eventCode: 'FOO', pending: false }; - const doc2 = new DocketEntry(raw2, { applicationContext }); + const doc2 = new DocketEntry(raw2, { authorizedUser: undefined }); expect(doc2.pending).toBeFalsy(); expect(DocketEntry.isPendingOnCreation).not.toHaveBeenCalled(); @@ -24,13 +23,13 @@ describe('isPendingOnCreation', () => { it('sets pending to false for non-matching event code', () => { const raw1 = { eventCode: 'ABC' }; - const doc1 = new DocketEntry(raw1, { applicationContext }); + const doc1 = new DocketEntry(raw1, { authorizedUser: undefined }); expect(doc1.pending).toBe(false); expect(DocketEntry.isPendingOnCreation).toHaveBeenCalled(); const raw2 = { color: 'blue', sport: 'Ice Hockey' }; - const doc2 = new DocketEntry(raw2, { applicationContext }); + const doc2 = new DocketEntry(raw2, { authorizedUser: undefined }); expect(doc2.pending).toBe(false); expect(DocketEntry.isPendingOnCreation).toHaveBeenCalled(); @@ -42,21 +41,21 @@ describe('isPendingOnCreation', () => { documentType: 'some kind of motion', eventCode: 'M006', }; - const doc1 = new DocketEntry(raw1, { applicationContext }); + const doc1 = new DocketEntry(raw1, { authorizedUser: undefined }); expect(doc1.pending).toBeTruthy(); const raw2 = { documentType: 'it is a proposed stipulated decision', eventCode: 'PSDE', }; - const doc2 = new DocketEntry(raw2, { applicationContext }); + const doc2 = new DocketEntry(raw2, { authorizedUser: undefined }); expect(doc2.pending).toBeTruthy(); const raw3 = { documentType: 'it is an order to show cause', eventCode: 'OSC', }; - const doc3 = new DocketEntry(raw3, { applicationContext }); + const doc3 = new DocketEntry(raw3, { authorizedUser: undefined }); expect(doc3.pending).toBeTruthy(); const raw4 = { @@ -64,7 +63,7 @@ describe('isPendingOnCreation', () => { documentType: 'Application for Waiver of Filing Fee', eventCode: 'APW', }; - const doc4 = new DocketEntry(raw4, { applicationContext }); + const doc4 = new DocketEntry(raw4, { authorizedUser: undefined }); expect(doc4.pending).toBeTruthy(); }); }); diff --git a/shared/src/business/entities/DocketEntry.isServed.test.ts b/shared/src/business/entities/DocketEntry.isServed.test.ts index 9012e6415f1..23e4cfc8cc5 100644 --- a/shared/src/business/entities/DocketEntry.isServed.test.ts +++ b/shared/src/business/entities/DocketEntry.isServed.test.ts @@ -1,11 +1,10 @@ import { DocketEntry } from './DocketEntry'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('isServed', () => { it('should return false when servedAt is undefined and isLegacyServed is false', () => { const doc1 = new DocketEntry( { isLegacyServed: undefined, servedAt: undefined }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(DocketEntry.isServed(doc1)).toBeFalsy(); @@ -14,7 +13,7 @@ describe('isServed', () => { it('should return true when servedAt is defined', () => { const doc1 = new DocketEntry( { isLegacyServed: undefined, servedAt: '2020-07-17T19:28:29.675Z' }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(DocketEntry.isServed(doc1)).toBeTruthy(); @@ -23,7 +22,7 @@ describe('isServed', () => { it('should return true when servedAt is undefined and isLegacyServed is true', () => { const doc1 = new DocketEntry( { isLegacyServed: true, servedAt: undefined }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(DocketEntry.isServed(doc1)).toBeTruthy(); diff --git a/shared/src/business/entities/DocketEntry.isUnservable.test.ts b/shared/src/business/entities/DocketEntry.isUnservable.test.ts index e422b8b9b78..9be233c3f7b 100644 --- a/shared/src/business/entities/DocketEntry.isUnservable.test.ts +++ b/shared/src/business/entities/DocketEntry.isUnservable.test.ts @@ -1,13 +1,12 @@ import { DocketEntry } from './DocketEntry'; import { UNSERVABLE_EVENT_CODES } from './EntityConstants'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('isUnservable', () => { UNSERVABLE_EVENT_CODES.forEach(eventCode => { it(`returns true when the docketEntry event code is in the list of unservable event codes (${eventCode})`, () => { const unservableDocketEntry = new DocketEntry( { eventCode }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(DocketEntry.isUnservable(unservableDocketEntry)).toBe(true); @@ -17,7 +16,7 @@ describe('isUnservable', () => { it('should return false when the docketEntry event code is NOT in the list of unservable event codes', () => { const servableDocketEntry = new DocketEntry( { eventCode: 'O' }, // O is the Order event code, Orders are servable - { applicationContext }, + { authorizedUser: undefined }, ); expect(DocketEntry.isUnservable(servableDocketEntry)).toBe(false); diff --git a/shared/src/business/entities/DocketEntry.sealEntry.test.ts b/shared/src/business/entities/DocketEntry.sealEntry.test.ts index 4f6a13566f1..100d077b053 100644 --- a/shared/src/business/entities/DocketEntry.sealEntry.test.ts +++ b/shared/src/business/entities/DocketEntry.sealEntry.test.ts @@ -1,12 +1,11 @@ import { A_VALID_DOCKET_ENTRY } from './DocketEntry.test'; import { DOCKET_ENTRY_SEALED_TO_TYPES } from './EntityConstants'; import { DocketEntry } from './DocketEntry'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('sealEntry', () => { it('should set the sealedTo property of the docket entry', () => { const docketEntry = new DocketEntry(A_VALID_DOCKET_ENTRY, { - applicationContext, + authorizedUser: undefined, }); docketEntry.sealEntry({ sealedTo: DOCKET_ENTRY_SEALED_TO_TYPES.PUBLIC }); expect(docketEntry.sealedTo).toEqual(DOCKET_ENTRY_SEALED_TO_TYPES.PUBLIC); @@ -16,7 +15,7 @@ describe('sealEntry', () => { const docketEntry = new DocketEntry( { ...A_VALID_DOCKET_ENTRY, isSealed: undefined }, { - applicationContext, + authorizedUser: undefined, }, ); docketEntry.sealEntry({ sealedTo: DOCKET_ENTRY_SEALED_TO_TYPES.PUBLIC }); diff --git a/shared/src/business/entities/DocketEntry.setAsProcessingStatusAsCompleted.test.ts b/shared/src/business/entities/DocketEntry.setAsProcessingStatusAsCompleted.test.ts index 523a01fb485..c962f25c774 100644 --- a/shared/src/business/entities/DocketEntry.setAsProcessingStatusAsCompleted.test.ts +++ b/shared/src/business/entities/DocketEntry.setAsProcessingStatusAsCompleted.test.ts @@ -1,7 +1,6 @@ import { A_VALID_DOCKET_ENTRY } from './DocketEntry.test'; import { DOCUMENT_PROCESSING_STATUS_OPTIONS } from './EntityConstants'; import { DocketEntry } from './DocketEntry'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('setAsProcessingStatusAsCompleted', () => { it('sets the docket entry processing status as completed', () => { @@ -11,7 +10,7 @@ describe('setAsProcessingStatusAsCompleted', () => { processingStatus: DOCUMENT_PROCESSING_STATUS_OPTIONS.PENDING, }, { - applicationContext, + authorizedUser: undefined, petitioners: [ { contactId: '7111b30b-ad38-42c8-9db0-d938cb2cb16b', diff --git a/shared/src/business/entities/DocketEntry.setAsServed.test.ts b/shared/src/business/entities/DocketEntry.setAsServed.test.ts index 08861c7f366..d35c74fbd58 100644 --- a/shared/src/business/entities/DocketEntry.setAsServed.test.ts +++ b/shared/src/business/entities/DocketEntry.setAsServed.test.ts @@ -4,7 +4,6 @@ import { PARTIES_CODES, ROLES, } from '@shared/business/entities/EntityConstants'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('setAsServed', () => { it('sets the Document as served', () => { @@ -15,7 +14,7 @@ describe('setAsServed', () => { documentContents: 'Yee to the haw', }, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); docketEntry.setAsServed(); @@ -28,7 +27,7 @@ describe('setAsServed', () => { { ...A_VALID_DOCKET_ENTRY, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); docketEntry.setAsServed([ @@ -47,7 +46,7 @@ describe('setAsServed', () => { ...A_VALID_DOCKET_ENTRY, eventCode: 'ATP', }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); docketEntry.setAsServed([ diff --git a/shared/src/business/entities/DocketEntry.setNumberOfPages.test.ts b/shared/src/business/entities/DocketEntry.setNumberOfPages.test.ts index e13a3a5f938..a7ee16f72b3 100644 --- a/shared/src/business/entities/DocketEntry.setNumberOfPages.test.ts +++ b/shared/src/business/entities/DocketEntry.setNumberOfPages.test.ts @@ -1,5 +1,4 @@ import { DocketEntry } from './DocketEntry'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('setNumberOfPages', () => { it('sets the number of pages', () => { @@ -11,7 +10,7 @@ describe('setNumberOfPages', () => { filingDate: '9000-01-01T00:00:00.000Z', index: 1, }, - { applicationContext }, + { authorizedUser: undefined }, ); docketEntry.setNumberOfPages(13); expect(docketEntry.numberOfPages).toEqual(13); diff --git a/shared/src/business/entities/DocketEntry.setQCed.test.ts b/shared/src/business/entities/DocketEntry.setQCed.test.ts index e29c888729b..5acd967e213 100644 --- a/shared/src/business/entities/DocketEntry.setQCed.test.ts +++ b/shared/src/business/entities/DocketEntry.setQCed.test.ts @@ -1,11 +1,10 @@ import { A_VALID_DOCKET_ENTRY, MOCK_PETITIONERS } from './DocketEntry.test'; import { DocketEntry } from './DocketEntry'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('setQCed', () => { it('updates the document QC information with user name, id, and date', () => { const docketEntry = new DocketEntry(A_VALID_DOCKET_ENTRY, { - applicationContext, + authorizedUser: undefined, petitioners: MOCK_PETITIONERS, }); const user = { diff --git a/shared/src/business/entities/DocketEntry.setWorkItem.test.ts b/shared/src/business/entities/DocketEntry.setWorkItem.test.ts index e8d0316644e..df4f32acee9 100644 --- a/shared/src/business/entities/DocketEntry.setWorkItem.test.ts +++ b/shared/src/business/entities/DocketEntry.setWorkItem.test.ts @@ -2,7 +2,6 @@ import { A_VALID_DOCKET_ENTRY, MOCK_PETITIONERS } from './DocketEntry.test'; import { CASE_STATUS_TYPES, PETITIONS_SECTION } from './EntityConstants'; import { DocketEntry } from './DocketEntry'; import { WorkItem } from './WorkItem'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('setWorkItem', () => { it('should set work item on docket entry to the passed in work item and validate the nested work item', () => { @@ -10,27 +9,24 @@ describe('setWorkItem', () => { { ...A_VALID_DOCKET_ENTRY, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, - ); - const workItem = new WorkItem( - { - assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', - assigneeName: 'bob', - caseStatus: CASE_STATUS_TYPES.new, - caseTitle: 'Johnny Joe Jacobson', - docketEntry: A_VALID_DOCKET_ENTRY, - docketNumber: '101-18', - section: PETITIONS_SECTION, - sentBy: 'bob', - }, - { applicationContext }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); + const workItem = new WorkItem({ + assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', + assigneeName: 'bob', + caseStatus: CASE_STATUS_TYPES.new, + caseTitle: 'Johnny Joe Jacobson', + docketEntry: A_VALID_DOCKET_ENTRY, + docketNumber: '101-18', + section: PETITIONS_SECTION, + sentBy: 'bob', + }); myDoc.setWorkItem(workItem); expect(myDoc.isValid()).toBeTruthy(); - myDoc.setWorkItem(new WorkItem({}, { applicationContext })); + myDoc.setWorkItem(new WorkItem({})); expect(myDoc.isValid()).toBeFalsy(); }); diff --git a/shared/src/business/entities/DocketEntry.shouldAutoGenerateDeadline.test.ts b/shared/src/business/entities/DocketEntry.shouldAutoGenerateDeadline.test.ts index 59aae802596..753fe74c94f 100644 --- a/shared/src/business/entities/DocketEntry.shouldAutoGenerateDeadline.test.ts +++ b/shared/src/business/entities/DocketEntry.shouldAutoGenerateDeadline.test.ts @@ -1,6 +1,5 @@ import { AUTO_GENERATED_DEADLINE_DOCUMENT_TYPES } from './EntityConstants'; import { DocketEntry } from './DocketEntry'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('shouldAutoGenerateDeadline', () => { AUTO_GENERATED_DEADLINE_DOCUMENT_TYPES.forEach(item => { @@ -9,7 +8,7 @@ describe('shouldAutoGenerateDeadline', () => { { eventCode: item.eventCode, }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(mockDocketEntry.shouldAutoGenerateDeadline()).toBe(true); @@ -21,7 +20,7 @@ describe('shouldAutoGenerateDeadline', () => { { eventCode: 'O', }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(mockDocketEntry.shouldAutoGenerateDeadline()).toBe(false); diff --git a/shared/src/business/entities/DocketEntry.strikeEntry.test.ts b/shared/src/business/entities/DocketEntry.strikeEntry.test.ts index 4610f39a4bf..e112cd65da2 100644 --- a/shared/src/business/entities/DocketEntry.strikeEntry.test.ts +++ b/shared/src/business/entities/DocketEntry.strikeEntry.test.ts @@ -1,5 +1,4 @@ import { DocketEntry } from './DocketEntry'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('strikeEntry', () => { it('strikes a document if isOnDocketRecord is true', () => { @@ -12,7 +11,7 @@ describe('strikeEntry', () => { index: 1, isOnDocketRecord: true, }, - { applicationContext }, + { authorizedUser: undefined }, ); docketEntry.strikeEntry({ name: 'Test User', @@ -36,7 +35,7 @@ describe('strikeEntry', () => { index: 1, isOnDocketRecord: false, }, - { applicationContext }, + { authorizedUser: undefined }, ); let error; try { diff --git a/shared/src/business/entities/DocketEntry.test.ts b/shared/src/business/entities/DocketEntry.test.ts index ac23fceaca9..d88ad6c5d0f 100644 --- a/shared/src/business/entities/DocketEntry.test.ts +++ b/shared/src/business/entities/DocketEntry.test.ts @@ -38,7 +38,7 @@ describe('DocketEntry entity', () => { const entry = new DocketEntry( { ...A_VALID_DOCKET_ENTRY, stampData: undefined }, { - applicationContext, + authorizedUser: undefined, petitioners: MOCK_PETITIONERS, }, ); @@ -54,7 +54,7 @@ describe('DocketEntry entity', () => { eventCode: 'NOT', signedAt: null, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(myDoc.signedAt).toBeTruthy(); @@ -67,7 +67,7 @@ describe('DocketEntry entity', () => { eventCode: 'NOT', signedAt: '2019-08-25T05:00:00.000Z', }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(myDoc.signedAt).toEqual('2019-08-25T05:00:00.000Z'); @@ -80,7 +80,7 @@ describe('DocketEntry entity', () => { eventCode: 'O', signedAt: null, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(myDoc.signedAt).toEqual(null); @@ -95,7 +95,7 @@ describe('DocketEntry entity', () => { eventCode: 'NOT', signedAt: null, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(myDoc.isDraft).toBe(false); @@ -105,7 +105,7 @@ describe('DocketEntry entity', () => { describe('isValid', () => { it('Creates a valid docket entry', () => { const myDoc = new DocketEntry(A_VALID_DOCKET_ENTRY, { - applicationContext, + authorizedUser: undefined, petitioners: MOCK_PETITIONERS, }); myDoc.docketEntryId = 'a6b81f4d-1e47-423a-8caf-6d2fdc3d3859'; @@ -118,7 +118,7 @@ describe('DocketEntry entity', () => { { userId: '02323349-87fe-4d29-91fe-8dd6916d2fda', }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(myDoc.isValid()).toBeFalsy(); }); @@ -128,7 +128,7 @@ describe('DocketEntry entity', () => { { documentType: 'Petition', }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(myDoc.isValid()).toBeFalsy(); }); @@ -138,7 +138,7 @@ describe('DocketEntry entity', () => { { serviceDate: 'undefined-undefined-undefined', }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(myDoc.isValid()).toBeFalsy(); }); @@ -147,7 +147,7 @@ describe('DocketEntry entity', () => { describe('unsignDocument', () => { it('signs and unsigns the document', () => { const docketEntry = new DocketEntry(A_VALID_DOCKET_ENTRY, { - applicationContext, + authorizedUser: undefined, petitioners: MOCK_PETITIONERS, }); docketEntry.setSigned('abc-123', 'Joe Exotic'); @@ -180,7 +180,7 @@ describe('DocketEntry entity', () => { }, ], }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(createdDocketEntry.isValid()).toEqual(true); @@ -197,7 +197,7 @@ describe('DocketEntry entity', () => { servedAt: undefined, servedParties: undefined, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(createdDocketEntry.isValid()).toEqual(true); @@ -211,7 +211,7 @@ describe('DocketEntry entity', () => { servedAt: undefined, servedParties: undefined, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(createdDocketEntry.getFormattedValidationErrors()).toEqual({ @@ -228,7 +228,7 @@ describe('DocketEntry entity', () => { scenario: 'Standard', secondaryDocument: {}, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(createdDocketEntry.secondaryDocument).toBeUndefined(); expect(createdDocketEntry.isValid()).toEqual(true); @@ -240,7 +240,7 @@ describe('DocketEntry entity', () => { ...A_VALID_DOCKET_ENTRY, scenario: 'Standard', }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); createdDocketEntry.secondaryDocument = { secondaryDocumentInfo: 'was set by accessor rather than init', @@ -258,7 +258,7 @@ describe('DocketEntry entity', () => { scenario: 'Standard', secondaryDocument: undefined, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(createdDocketEntry.isValid()).toEqual(true); }); @@ -270,7 +270,7 @@ describe('DocketEntry entity', () => { scenario: 'Nonstandard H', secondaryDocument: undefined, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(createdDocketEntry.isValid()).toEqual(true); @@ -287,7 +287,7 @@ describe('DocketEntry entity', () => { eventCode: 'P', }, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(createdDocketEntry.isValid()).toEqual(true); }); @@ -299,7 +299,7 @@ describe('DocketEntry entity', () => { scenario: 'Nonstandard H', secondaryDocument: {}, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(createdDocketEntry.isValid()).toEqual(false); expect( @@ -324,7 +324,7 @@ describe('DocketEntry entity', () => { }, ], }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(createdDocketEntry.isValid()).toEqual(true); expect(createdDocketEntry.servedParties).toEqual([ @@ -349,7 +349,7 @@ describe('DocketEntry entity', () => { role: 'irsSuperuser', }, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(createdDocketEntry.isValid()).toEqual(false); expect(createdDocketEntry.getFormattedValidationErrors()).toEqual({ @@ -370,7 +370,7 @@ describe('DocketEntry entity', () => { isOnDocketRecord: true, userId: '02323349-87fe-4d29-91fe-8dd6916d2fda', }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(docketEntry.isValid()).toBe(true); @@ -386,7 +386,7 @@ describe('DocketEntry entity', () => { ...A_VALID_DOCKET_ENTRY, judgeUserId: mockJudgeUserId, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(docketEntry).toMatchObject({ @@ -401,7 +401,7 @@ describe('DocketEntry entity', () => { ...A_VALID_DOCKET_ENTRY, judgeUserId: undefined, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(docketEntry.judgeUserId).toBeUndefined(); expect(docketEntry.isValid()).toBeTruthy(); @@ -418,7 +418,7 @@ describe('DocketEntry entity', () => { isDraft: true, judgeUserId: mockJudgeUserId, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(docketEntry.isValid()).toBeTruthy(); @@ -433,7 +433,7 @@ describe('DocketEntry entity', () => { isDraft: true, judgeUserId: mockJudgeUserId, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(docketEntry.isValid()).toBeTruthy(); @@ -448,7 +448,7 @@ describe('DocketEntry entity', () => { isDraft: false, judgeUserId: mockJudgeUserId, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(docketEntry.isValid()).toBeFalsy(); @@ -465,7 +465,7 @@ describe('DocketEntry entity', () => { isDraft: true, judgeUserId: mockJudgeUserId, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(docketEntry.isValid()).toBeTruthy(); @@ -480,7 +480,7 @@ describe('DocketEntry entity', () => { isDraft: true, judgeUserId: mockJudgeUserId, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(docketEntry.isValid()).toBeTruthy(); @@ -495,7 +495,7 @@ describe('DocketEntry entity', () => { isDraft: false, judgeUserId: mockJudgeUserId, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(docketEntry.isValid()).toBeFalsy(); @@ -513,7 +513,7 @@ describe('DocketEntry entity', () => { isDraft: true, judgeUserId: mockJudgeUserId, }, - { applicationContext, petitioners: MOCK_PETITIONERS }, + { authorizedUser: undefined, petitioners: MOCK_PETITIONERS }, ); expect(docketEntry.isValid()).toBeTruthy(); }); @@ -548,7 +548,6 @@ describe('DocketEntry entity', () => { }; const docketEntryEntity = new DocketEntry(docketEntry, { - applicationContext, authorizedUser: mockDocketClerkUser, filtered: true, petitioners: MOCK_PETITIONERS, @@ -584,7 +583,7 @@ describe('DocketEntry entity', () => { ); expect(docketEntryEntity.userId).toEqual(docketEntry.userId); expect(docketEntryEntity.workItem).toEqual( - new WorkItem(docketEntry.workItem, { applicationContext }), + new WorkItem(docketEntry.workItem), ); }); @@ -616,7 +615,6 @@ describe('DocketEntry entity', () => { }; const docketEntryEntity = new DocketEntry(docketEntry, { - applicationContext, authorizedUser: mockPetitionerUser, filtered: true, petitioners: MOCK_PETITIONERS, diff --git a/shared/src/business/entities/DocketEntry.ts b/shared/src/business/entities/DocketEntry.ts index 3dd6f85b278..83ef7ff1433 100644 --- a/shared/src/business/entities/DocketEntry.ts +++ b/shared/src/business/entities/DocketEntry.ts @@ -34,14 +34,15 @@ import { } from '@shared/business/entities/cases/Case'; import { DOCKET_ENTRY_VALIDATION_RULES } from './EntityValidationConstants'; import { JoiValidationEntity } from '@shared/business/entities/JoiValidationEntity'; -import { RawUser, User } from './User'; import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { User } from './User'; import { WorkItem } from './WorkItem'; import { calculateISODate, createISODateAtStartOfDayEST, createISODateString, } from '../utilities/DateHandler'; +import { getUniqueId } from '@shared/sharedAppContext'; type PractitionerRole = 'irsPractitioner' | 'privatePractitioner'; @@ -168,27 +169,19 @@ export class DocketEntry extends JoiValidationEntity { constructor( rawDocketEntry, { - applicationContext, authorizedUser, filtered = false, petitioners = [], }: { - authorizedUser?: UnknownAuthUser; - applicationContext: IApplicationContext; + authorizedUser: UnknownAuthUser; petitioners?: any[]; filtered?: boolean; }, ) { super('DocketEntry'); - if (!applicationContext) { - throw new TypeError('applicationContext must be defined'); - } - const currentUser = authorizedUser || applicationContext.getCurrentUser(); - if (!filtered || User.isInternalUser(currentUser.role)) { - this.initForUnfilteredForInternalUsers(rawDocketEntry, { - applicationContext, - }); + if (!filtered || User.isInternalUser(authorizedUser?.role)) { + this.initForUnfilteredForInternalUsers(rawDocketEntry); } this.action = rawDocketEntry.action; @@ -204,8 +197,7 @@ export class DocketEntry extends JoiValidationEntity { this.certificateOfServiceDate = rawDocketEntry.certificateOfServiceDate; this.createdAt = rawDocketEntry.createdAt || createISODateString(); this.date = rawDocketEntry.date; - this.docketEntryId = - rawDocketEntry.docketEntryId || applicationContext.getUniqueId(); + this.docketEntryId = rawDocketEntry.docketEntryId || getUniqueId(); this.docketNumber = rawDocketEntry.docketNumber; this.docketNumbers = rawDocketEntry.docketNumbers; this.documentContentsId = rawDocketEntry.documentContentsId; @@ -257,7 +249,7 @@ export class DocketEntry extends JoiValidationEntity { this.supportingDocument = rawDocketEntry.supportingDocument; this.trialLocation = rawDocketEntry.trialLocation; // only share the userId with an external user if it is the logged in user - if (currentUser.userId === rawDocketEntry.userId) { + if (authorizedUser?.userId === rawDocketEntry.userId) { this.userId = rawDocketEntry.userId; } @@ -292,7 +284,7 @@ export class DocketEntry extends JoiValidationEntity { this.generateFiledBy(petitioners); } - initForUnfilteredForInternalUsers(rawDocketEntry, { applicationContext }) { + private initForUnfilteredForInternalUsers(rawDocketEntry) { this.editState = rawDocketEntry.editState; this.draftOrderState = rawDocketEntry.draftOrderState; this.stampData = rawDocketEntry.stampData || {}; @@ -320,7 +312,7 @@ export class DocketEntry extends JoiValidationEntity { this.strickenByUserId = rawDocketEntry.strickenByUserId; this.userId = rawDocketEntry.userId; this.workItem = rawDocketEntry.workItem - ? new WorkItem(rawDocketEntry.workItem, { applicationContext }) + ? new WorkItem(rawDocketEntry.workItem) : undefined; } @@ -792,7 +784,7 @@ export class DocketEntry extends JoiValidationEntity { this.numberOfPages = numberOfPages; } - setFiledBy(user: RawUser) { + setFiledBy(user: { userId: string; role: Role }): void { this.userId = user.userId; this.filedByRole = user.role; } diff --git a/shared/src/business/entities/DocketEntry.unsealEntry.test.ts b/shared/src/business/entities/DocketEntry.unsealEntry.test.ts index e88c1ba7a18..6d75f427148 100644 --- a/shared/src/business/entities/DocketEntry.unsealEntry.test.ts +++ b/shared/src/business/entities/DocketEntry.unsealEntry.test.ts @@ -1,7 +1,6 @@ import { A_VALID_DOCKET_ENTRY } from './DocketEntry.test'; import { DOCKET_ENTRY_SEALED_TO_TYPES } from './EntityConstants'; import { DocketEntry } from './DocketEntry'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('unsealEntry', () => { it('should clear the sealedTo property from the docket entry', () => { @@ -11,7 +10,7 @@ describe('unsealEntry', () => { sealedTo: DOCKET_ENTRY_SEALED_TO_TYPES.EXTERNAL, }, { - applicationContext, + authorizedUser: undefined, }, ); docketEntry.unsealEntry(); @@ -22,7 +21,7 @@ describe('unsealEntry', () => { const docketEntry = new DocketEntry( { ...A_VALID_DOCKET_ENTRY, isSealed: undefined }, { - applicationContext, + authorizedUser: undefined, }, ); docketEntry.unsealEntry(); @@ -34,7 +33,7 @@ describe('unsealEntry', () => { const docketEntry = new DocketEntry( { ...A_VALID_DOCKET_ENTRY, isLegacySealed: true }, { - applicationContext, + authorizedUser: undefined, }, ); docketEntry.unsealEntry(); diff --git a/shared/src/business/entities/DocketEntry.unsignDocument.test.ts b/shared/src/business/entities/DocketEntry.unsignDocument.test.ts index 1d774a14eb2..ec5b2e0c013 100644 --- a/shared/src/business/entities/DocketEntry.unsignDocument.test.ts +++ b/shared/src/business/entities/DocketEntry.unsignDocument.test.ts @@ -1,11 +1,10 @@ import { A_VALID_DOCKET_ENTRY } from './DocketEntry.test'; import { DocketEntry } from './DocketEntry'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('unsignDocument', () => { it('signs and unsigns the document', () => { const docketEntry = new DocketEntry(A_VALID_DOCKET_ENTRY, { - applicationContext, + authorizedUser: undefined, petitioners: [ { contactId: '7111b30b-ad38-42c8-9db0-d938cb2cb16b', diff --git a/shared/src/business/entities/DocketEntry.validate.test.ts b/shared/src/business/entities/DocketEntry.validate.test.ts index ef0a5631d08..70b5b5ed198 100644 --- a/shared/src/business/entities/DocketEntry.validate.test.ts +++ b/shared/src/business/entities/DocketEntry.validate.test.ts @@ -258,7 +258,7 @@ describe('validate', () => { const docketEntry = new DocketEntry( { ...A_VALID_DOCKET_ENTRY, ...item.docketEntry }, { - applicationContext, + authorizedUser: undefined, petitioners: MOCK_PETITIONERS, }, ).validate(); @@ -457,7 +457,7 @@ describe('validate', () => { const docketEntry = new DocketEntry( { ...A_VALID_DOCKET_ENTRY, ...item.docketEntry }, { - applicationContext, + authorizedUser: undefined, petitioners: MOCK_PETITIONERS, }, ); @@ -473,7 +473,7 @@ describe('validate', () => { it('should throw an error on invalid docket entries', () => { expect(() => { - new DocketEntry({}, { applicationContext }).validate(); + new DocketEntry({}, { authorizedUser: undefined }).validate(); }).toThrow('The DocketEntry entity was invalid'); }); }); diff --git a/shared/src/business/entities/IrsPractitioner.ts b/shared/src/business/entities/IrsPractitioner.ts index 8afe334c3f6..bc67c4a4469 100644 --- a/shared/src/business/entities/IrsPractitioner.ts +++ b/shared/src/business/entities/IrsPractitioner.ts @@ -8,8 +8,8 @@ export class IrsPractitioner extends User { public barNumber: string; public serviceIndicator: string; - constructor(rawUser, options?) { - super(rawUser, options); + constructor(rawUser, { filtered = false } = {}) { + super(rawUser, { filtered }); this.entityName = IrsPractitioner.ENTITY_NAME; diff --git a/shared/src/business/entities/JoiValidationEntity.ts b/shared/src/business/entities/JoiValidationEntity.ts index a36012fd274..f826965f8ae 100644 --- a/shared/src/business/entities/JoiValidationEntity.ts +++ b/shared/src/business/entities/JoiValidationEntity.ts @@ -192,14 +192,18 @@ export abstract class JoiValidationEntity { return this.validate({ applicationContext, logErrors: true }); } - static validateRawCollection( - this: new (someVar: any, someArgs: any) => T, + static validateRawCollection any>( + this: ClassType, collection: any[] = [], - args: any, + ...args: Tail> ) { return collection.map( rawEntity => - new this(rawEntity, args).validate().toRawObject() as ExcludeMethods, + new this(rawEntity, ...args).validate().toRawObject() as ExcludeMethods< + InstanceType + >, ); } } + +type Tail = T extends [any, ...infer Rest] ? Rest : never; diff --git a/shared/src/business/entities/Penalty.test.ts b/shared/src/business/entities/Penalty.test.ts index 7a9854e4b3d..88784baa823 100644 --- a/shared/src/business/entities/Penalty.test.ts +++ b/shared/src/business/entities/Penalty.test.ts @@ -1,20 +1,16 @@ import { PENALTY_TYPES } from './EntityConstants'; import { Penalty } from './Penalty'; -import { applicationContext } from '../test/createTestApplicationContext'; describe('Penalty', () => { describe('validation', () => { let mockStatisticId = '5666ad04-4814-4b0c-8090-ba01683917ac'; it('should fail if name is undefined', () => { - const penalty = new Penalty( - { - irsPenaltyAmount: 100.0, - name: undefined, - statisticId: mockStatisticId, - }, - { applicationContext }, - ); + const penalty = new Penalty({ + irsPenaltyAmount: 100.0, + name: undefined, + statisticId: mockStatisticId, + }); expect(penalty.isValid()).toBeFalsy(); expect(Object.keys(penalty.getFormattedValidationErrors()!)).toContain( @@ -23,15 +19,12 @@ describe('Penalty', () => { }); it('should fail if penaltyAmount is undefined', () => { - const penalty = new Penalty( - { - name: 'Penalty 1 (IRS)', - penaltyAmount: undefined, - penaltyType: PENALTY_TYPES.IRS_PENALTY_AMOUNT, - statisticId: mockStatisticId, - }, - { applicationContext }, - ); + const penalty = new Penalty({ + name: 'Penalty 1 (IRS)', + penaltyAmount: undefined, + penaltyType: PENALTY_TYPES.IRS_PENALTY_AMOUNT, + statisticId: mockStatisticId, + }); expect(penalty.isValid()).toBe(false); expect(Object.keys(penalty.getFormattedValidationErrors()!)).toContain( @@ -40,15 +33,12 @@ describe('Penalty', () => { }); it('should fail if penaltyAmount is not a number', () => { - const penalty = new Penalty( - { - name: 'Penalty 1 (IRS)', - penaltyAmount: 'something', - penaltyType: PENALTY_TYPES.IRS_PENALTY_AMOUNT, - statisticId: mockStatisticId, - }, - { applicationContext }, - ); + const penalty = new Penalty({ + name: 'Penalty 1 (IRS)', + penaltyAmount: 'something', + penaltyType: PENALTY_TYPES.IRS_PENALTY_AMOUNT, + statisticId: mockStatisticId, + }); expect(penalty.isValid()).toBe(false); expect(Object.keys(penalty.getFormattedValidationErrors()!)).toContain( @@ -57,15 +47,12 @@ describe('Penalty', () => { }); it('should fail if penaltyType is undefined', () => { - const penalty = new Penalty( - { - name: 'Penalty 1 (IRS)', - penaltyAmount: 100.0, - penaltyType: undefined, - statisticId: mockStatisticId, - }, - { applicationContext }, - ); + const penalty = new Penalty({ + name: 'Penalty 1 (IRS)', + penaltyAmount: 100.0, + penaltyType: undefined, + statisticId: mockStatisticId, + }); expect(penalty.isValid()).toBe(false); expect(Object.keys(penalty.getFormattedValidationErrors()!)).toContain( @@ -74,15 +61,12 @@ describe('Penalty', () => { }); it('should fail with statisticId undefined', () => { - const penalty = new Penalty( - { - name: 'Penalty 1 (IRS)', - penaltyAmount: 100.0, - penaltyType: PENALTY_TYPES.IRS_PENALTY_AMOUNT, - statisticId: undefined, - }, - { applicationContext }, - ); + const penalty = new Penalty({ + name: 'Penalty 1 (IRS)', + penaltyAmount: 100.0, + penaltyType: PENALTY_TYPES.IRS_PENALTY_AMOUNT, + statisticId: undefined, + }); expect(penalty.isValid()).toBe(false); expect(Object.keys(penalty.getFormattedValidationErrors()!)).toContain( @@ -91,43 +75,34 @@ describe('Penalty', () => { }); it('should pass with valid values and irsPenaltyAmount type', () => { - const penalty = new Penalty( - { - name: 'Penalty 1 (IRS)', - penaltyAmount: 100.0, - penaltyType: PENALTY_TYPES.IRS_PENALTY_AMOUNT, - statisticId: mockStatisticId, - }, - { applicationContext }, - ); + const penalty = new Penalty({ + name: 'Penalty 1 (IRS)', + penaltyAmount: 100.0, + penaltyType: PENALTY_TYPES.IRS_PENALTY_AMOUNT, + statisticId: mockStatisticId, + }); expect(penalty.isValid()).toBe(true); }); it('should pass with valid values and determinationPenaltyAmount type', () => { - const penalty = new Penalty( - { - name: 'Penalty 1 (Court)', - penaltyAmount: 100.0, - penaltyType: PENALTY_TYPES.DETERMINATION_PENALTY_AMOUNT, - statisticId: mockStatisticId, - }, - { applicationContext }, - ); + const penalty = new Penalty({ + name: 'Penalty 1 (Court)', + penaltyAmount: 100.0, + penaltyType: PENALTY_TYPES.DETERMINATION_PENALTY_AMOUNT, + statisticId: mockStatisticId, + }); expect(penalty.isValid()).toBe(true); }); it('should pass if penaltyAmount is a negative number', () => { - const penalty = new Penalty( - { - name: 'Penalty 1 (IRS)', - penaltyAmount: -422.68, - penaltyType: PENALTY_TYPES.IRS_PENALTY_AMOUNT, - statisticId: mockStatisticId, - }, - { applicationContext }, - ); + const penalty = new Penalty({ + name: 'Penalty 1 (IRS)', + penaltyAmount: -422.68, + penaltyType: PENALTY_TYPES.IRS_PENALTY_AMOUNT, + statisticId: mockStatisticId, + }); expect(penalty.isValid()).toBe(true); }); diff --git a/shared/src/business/entities/Penalty.ts b/shared/src/business/entities/Penalty.ts index 43574275a3f..e6b0262ee26 100644 --- a/shared/src/business/entities/Penalty.ts +++ b/shared/src/business/entities/Penalty.ts @@ -1,6 +1,7 @@ import { JoiValidationConstants } from './JoiValidationConstants'; import { JoiValidationEntity } from '@shared/business/entities/JoiValidationEntity'; import { PENALTY_TYPES } from './EntityConstants'; +import { getUniqueId } from '@shared/sharedAppContext'; import joi from 'joi'; export class Penalty extends JoiValidationEntity { @@ -10,17 +11,13 @@ export class Penalty extends JoiValidationEntity { public penaltyType: string; public statisticId: string; - constructor(rawProps, { applicationContext }) { + constructor(rawProps) { super('Penalty'); - if (!applicationContext) { - throw new TypeError('applicationContext must be defined'); - } - this.name = rawProps.name; this.penaltyType = rawProps.penaltyType; this.penaltyAmount = rawProps.penaltyAmount; - this.penaltyId = rawProps.penaltyId || applicationContext.getUniqueId(); + this.penaltyId = rawProps.penaltyId || getUniqueId(); this.statisticId = rawProps.statisticId; } diff --git a/shared/src/business/entities/PrivatePractitioner.ts b/shared/src/business/entities/PrivatePractitioner.ts index b4d320cea9a..42109ee8a68 100644 --- a/shared/src/business/entities/PrivatePractitioner.ts +++ b/shared/src/business/entities/PrivatePractitioner.ts @@ -11,8 +11,8 @@ export class PrivatePractitioner extends User { public representing: string; public serviceIndicator: string; - constructor(rawUser, options?) { - super(rawUser, options); + constructor(rawUser, { filtered = false } = {}) { + super(rawUser, { filtered }); this.entityName = PrivatePractitioner.ENTITY_NAME; this.barNumber = rawUser.barNumber; this.firmName = rawUser.firmName; diff --git a/shared/src/business/entities/Statistic.test.ts b/shared/src/business/entities/Statistic.test.ts index ab9cf9da900..a5eef767595 100644 --- a/shared/src/business/entities/Statistic.test.ts +++ b/shared/src/business/entities/Statistic.test.ts @@ -1,22 +1,13 @@ import { Statistic } from './Statistic'; -import { applicationContext } from '../test/createTestApplicationContext'; +import { getUniqueId } from '@shared/sharedAppContext'; describe('Statistic', () => { - it('throws an error if applicationContext is not provided on construction', () => { - expect(() => new Statistic({}, {} as any)).toThrow( - 'applicationContext must be defined', - ); - }); - describe('validation', () => { it("fails validation if a yearOrPeriod is not 'year' or 'period'", () => { - const statistic = new Statistic( - { - penalties: [{ irsPenaltyAmount: 100.0, name: 'Penalty1' }], - yearOrPeriod: 'something else', - }, - { applicationContext }, - ); + const statistic = new Statistic({ + penalties: [{ irsPenaltyAmount: 100.0, name: 'Penalty1' }], + yearOrPeriod: 'something else', + }); expect(statistic.isValid()).toBeFalsy(); expect(Object.keys(statistic.getFormattedValidationErrors()!)).toContain( @@ -25,43 +16,37 @@ describe('Statistic', () => { }); it('passes validation with minimal required information', () => { - const statistic = new Statistic( - { - irsDeficiencyAmount: 1, - irsTotalPenalties: 1, - penalties: [ - { - name: 'Penalty 1(IRS)', - penaltyAmount: 100.0, - penaltyType: 'irsPenaltyAmount', - }, - ], - year: '2001', - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + const statistic = new Statistic({ + irsDeficiencyAmount: 1, + irsTotalPenalties: 1, + penalties: [ + { + name: 'Penalty 1(IRS)', + penaltyAmount: 100.0, + penaltyType: 'irsPenaltyAmount', + }, + ], + year: '2001', + yearOrPeriod: 'Year', + }); expect(statistic.isValid()).toBeTruthy(); }); it('fails validation if a irsDeficiencyAmount, irsTotalPenalties, or year are not numbers', () => { - const statistic = new Statistic( - { - irsDeficiencyAmount: 'something else', - irsTotalPenalties: 'something else', - penalties: [ - { - name: 'Penalty 1(IRS)', - penaltyAmount: 100.0, - penaltyType: 'irsPenaltyAmount', - }, - ], - year: 'something else', - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + const statistic = new Statistic({ + irsDeficiencyAmount: 'something else', + irsTotalPenalties: 'something else', + penalties: [ + { + name: 'Penalty 1(IRS)', + penaltyAmount: 100.0, + penaltyType: 'irsPenaltyAmount', + }, + ], + year: 'something else', + yearOrPeriod: 'Year', + }); expect(statistic.isValid()).toBeFalsy(); expect(Object.keys(statistic.getFormattedValidationErrors()!)).toEqual([ @@ -72,22 +57,19 @@ describe('Statistic', () => { }); it('should be invalid when one of the penalties in the statistic is NOT valid', () => { - const statistic = new Statistic( - { - irsDeficiencyAmount: 1, - irsTotalPenalties: 1, - penalties: [ - { - name: 'Penalty 1(IRS)', - penaltyAmount: undefined, // This is a required field - penaltyType: 'irsPenaltyAmount', - }, - ], - year: '2001', - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + const statistic = new Statistic({ + irsDeficiencyAmount: 1, + irsTotalPenalties: 1, + penalties: [ + { + name: 'Penalty 1(IRS)', + penaltyAmount: undefined, // This is a required field + penaltyType: 'irsPenaltyAmount', + }, + ], + year: '2001', + yearOrPeriod: 'Year', + }); expect(statistic.getFormattedValidationErrors()!).toEqual({ penalties: [ @@ -100,22 +82,19 @@ describe('Statistic', () => { }); it('should be invalid when one of the penalties in the statistic is NOT valid', () => { - const statistic = new Statistic( - { - irsDeficiencyAmount: 1, - irsTotalPenalties: 1, - penalties: [ - { - name: 'Penalty 1(IRS)', - penaltyAmount: undefined, // This is a required field - penaltyType: 'irsPenaltyAmount', - }, - ], - year: '2001', - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + const statistic = new Statistic({ + irsDeficiencyAmount: 1, + irsTotalPenalties: 1, + penalties: [ + { + name: 'Penalty 1(IRS)', + penaltyAmount: undefined, // This is a required field + penaltyType: 'irsPenaltyAmount', + }, + ], + year: '2001', + yearOrPeriod: 'Year', + }); expect(statistic.getFormattedValidationErrors()!).toEqual({ penalties: [ @@ -128,16 +107,13 @@ describe('Statistic', () => { }); it('fails validation if a lastDateOfPeriod is a date in the future', () => { - const statistic = new Statistic( - { - irsDeficiencyAmount: 1, - irsTotalPenalties: 1, - lastDateOfPeriod: '2050-03-01T21:40:46.415Z', - penalties: [{ irsPenaltyAmount: 100.0, name: 'Penalty1' }], - yearOrPeriod: 'Period', - }, - { applicationContext }, - ); + const statistic = new Statistic({ + irsDeficiencyAmount: 1, + irsTotalPenalties: 1, + lastDateOfPeriod: '2050-03-01T21:40:46.415Z', + penalties: [{ irsPenaltyAmount: 100.0, name: 'Penalty1' }], + yearOrPeriod: 'Period', + }); expect(statistic.isValid()).toBeFalsy(); expect(statistic.getFormattedValidationErrors()).toMatchObject({ @@ -146,22 +122,19 @@ describe('Statistic', () => { }); it('fails validation if a year is in the future', () => { - const statistic = new Statistic( - { - irsDeficiencyAmount: 1, - irsTotalPenalties: 1, - penalties: [ - { - name: 'Penalty 1(IRS)', - penaltyAmount: 100.0, - penaltyType: 'irsPenaltyAmount', - }, - ], - year: 2050, - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + const statistic = new Statistic({ + irsDeficiencyAmount: 1, + irsTotalPenalties: 1, + penalties: [ + { + name: 'Penalty 1(IRS)', + penaltyAmount: 100.0, + penaltyType: 'irsPenaltyAmount', + }, + ], + year: 2050, + yearOrPeriod: 'Year', + }); expect(statistic.isValid()).toBeFalsy(); expect(Object.keys(statistic.getFormattedValidationErrors()!)).toEqual([ @@ -170,69 +143,60 @@ describe('Statistic', () => { }); it('passes validation with valid values', () => { - const statistic = new Statistic( - { - irsDeficiencyAmount: 654.32, - irsTotalPenalties: 123.45, - lastDateOfPeriod: '2015-03-01T21:40:46.415Z', - penalties: [ - { - name: 'Penalty 1(IRS)', - penaltyAmount: 100.0, - penaltyType: 'irsPenaltyAmount', - }, - ], - year: 2015, - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + const statistic = new Statistic({ + irsDeficiencyAmount: 654.32, + irsTotalPenalties: 123.45, + lastDateOfPeriod: '2015-03-01T21:40:46.415Z', + penalties: [ + { + name: 'Penalty 1(IRS)', + penaltyAmount: 100.0, + penaltyType: 'irsPenaltyAmount', + }, + ], + year: 2015, + yearOrPeriod: 'Year', + }); expect(statistic.isValid()).toBeTruthy(); }); it('passes validation if an irsDeficiencyAmount, irsTotalPenalties, determinationTotalPenalties, and/or determinationDeficiencyAmount include negative numbers', () => { - const statistic = new Statistic( - { - determinationDeficiencyAmount: -4352.32, - determinationTotalPenalties: 0, - irsDeficiencyAmount: -2.0, - irsTotalPenalties: -222.22, - penalties: [ - { - name: 'Penalty 1(IRS)', - penaltyAmount: -222.22, - penaltyType: 'irsPenaltyAmount', - }, - ], - year: 2015, - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + const statistic = new Statistic({ + determinationDeficiencyAmount: -4352.32, + determinationTotalPenalties: 0, + irsDeficiencyAmount: -2.0, + irsTotalPenalties: -222.22, + penalties: [ + { + name: 'Penalty 1(IRS)', + penaltyAmount: -222.22, + penaltyType: 'irsPenaltyAmount', + }, + ], + year: 2015, + yearOrPeriod: 'Year', + }); expect(statistic.isValid()).toBeTruthy(); }); it('requires determinationDeficiencyAmount be defined if determinationTotalPenalties is set', () => { - const statistic = new Statistic( - { - determinationTotalPenalties: 100.11, - irsDeficiencyAmount: 654.32, - irsTotalPenalties: 123.45, - lastDateOfPeriod: '2015-03-01T21:40:46.415Z', - penalties: [ - { - name: 'Penalty 1(IRS)', - penaltyAmount: 100.0, - penaltyType: 'irsPenaltyAmount', - }, - ], - year: 2015, - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + const statistic = new Statistic({ + determinationTotalPenalties: 100.11, + irsDeficiencyAmount: 654.32, + irsTotalPenalties: 123.45, + lastDateOfPeriod: '2015-03-01T21:40:46.415Z', + penalties: [ + { + name: 'Penalty 1(IRS)', + penaltyAmount: 100.0, + penaltyType: 'irsPenaltyAmount', + }, + ], + year: 2015, + yearOrPeriod: 'Year', + }); expect(statistic.isValid()).toBeFalsy(); expect(Object.keys(statistic.getFormattedValidationErrors()!)).toEqual([ @@ -241,24 +205,21 @@ describe('Statistic', () => { }); it('requires determinationTotalPenalties be defined if determinationDeficiencyAmount is set', () => { - const statistic = new Statistic( - { - determinationDeficiencyAmount: 100.11, - irsDeficiencyAmount: 654.32, - irsTotalPenalties: 123.45, - lastDateOfPeriod: '2015-03-01T21:40:46.415Z', - penalties: [ - { - name: 'Penalty 1(IRS)', - penaltyAmount: 100.0, - penaltyType: 'irsPenaltyAmount', - }, - ], - year: 2015, - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + const statistic = new Statistic({ + determinationDeficiencyAmount: 100.11, + irsDeficiencyAmount: 654.32, + irsTotalPenalties: 123.45, + lastDateOfPeriod: '2015-03-01T21:40:46.415Z', + penalties: [ + { + name: 'Penalty 1(IRS)', + penaltyAmount: 100.0, + penaltyType: 'irsPenaltyAmount', + }, + ], + year: 2015, + yearOrPeriod: 'Year', + }); expect(statistic.isValid()).toBeFalsy(); expect(Object.keys(statistic.getFormattedValidationErrors()!)).toEqual([ @@ -269,7 +230,7 @@ describe('Statistic', () => { describe('Penalties', () => { let statistic; - let statisticId = applicationContext.getUniqueId(); + let statisticId = getUniqueId(); let penaltyArrayLength; const MOCK_PENALTY_WITH_STATISTIC_ID = { entityName: 'Penalty', @@ -296,30 +257,26 @@ describe('Statistic', () => { }; beforeEach(() => { - statistic = new Statistic( - { - irsDeficiencyAmount: 1, - irsTotalPenalties: 1, - penalties: [ - { - irsPenaltyAmount: 100.0, - name: 'Penalty 1', - penaltyId: '123408f8-8b01-4e49-b437-123a581a12bb', - statisticId, - }, - ], - statisticId, - year: '2001', - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + statistic = new Statistic({ + irsDeficiencyAmount: 1, + irsTotalPenalties: 1, + penalties: [ + { + irsPenaltyAmount: 100.0, + name: 'Penalty 1', + penaltyId: '123408f8-8b01-4e49-b437-123a581a12bb', + statisticId, + }, + ], + statisticId, + year: '2001', + yearOrPeriod: 'Year', + }); penaltyArrayLength = statistic.penalties.length; }); it('should add a penalty with a statistics id to the penalties array', () => { statistic.addPenalty({ - applicationContext, rawPenalty: MOCK_PENALTY_WITH_STATISTIC_ID, }); @@ -329,7 +286,6 @@ describe('Statistic', () => { it('should add a penalty without a statistics id to the penalties array and add the parent statisticId to the penalty', () => { statistic.addPenalty({ - applicationContext, rawPenalty: MOCK_PENALTY_WITHOUT_STATISTIC_ID, }); @@ -350,17 +306,14 @@ describe('Statistic', () => { }); it('should itemize both determinationTotalPenalties and irsTotalPenalties created prior to penalty itemization', () => { - const preItemizationStatistic = new Statistic( - { - determinationTotalPenalties: 3000, - irsDeficiencyAmount: 1, - irsTotalPenalties: 2000, - statisticId, - year: '2001', - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + const preItemizationStatistic = new Statistic({ + determinationTotalPenalties: 3000, + irsDeficiencyAmount: 1, + irsTotalPenalties: 2000, + statisticId, + year: '2001', + yearOrPeriod: 'Year', + }); const expectedPenalties = [ { @@ -386,16 +339,13 @@ describe('Statistic', () => { }); it('should itemize only irsTotalPenalties created prior to penalty itemization, if determinationTotalPenalties does not exist', () => { - const preItemizationStatistic = new Statistic( - { - irsDeficiencyAmount: 1, - irsTotalPenalties: 2000, - statisticId, - year: '2001', - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + const preItemizationStatistic = new Statistic({ + irsDeficiencyAmount: 1, + irsTotalPenalties: 2000, + statisticId, + year: '2001', + yearOrPeriod: 'Year', + }); const expectedPenalties = [ { diff --git a/shared/src/business/entities/Statistic.ts b/shared/src/business/entities/Statistic.ts index ae668994966..3a575568c27 100644 --- a/shared/src/business/entities/Statistic.ts +++ b/shared/src/business/entities/Statistic.ts @@ -2,6 +2,7 @@ import { JoiValidationConstants } from './JoiValidationConstants'; import { JoiValidationEntity } from '@shared/business/entities/JoiValidationEntity'; import { PENALTY_TYPES } from './EntityConstants'; import { Penalty } from './Penalty'; +import { getUniqueId } from '@shared/sharedAppContext'; import joi from 'joi'; /** @@ -21,11 +22,8 @@ export class Statistic extends JoiValidationEntity { public statisticId: string; public penalties: any[]; - constructor(rawStatistic, { applicationContext }) { + constructor(rawStatistic) { super('Statistic'); - if (!applicationContext) { - throw new TypeError('applicationContext must be defined'); - } this.determinationDeficiencyAmount = rawStatistic.determinationDeficiencyAmount; @@ -35,8 +33,7 @@ export class Statistic extends JoiValidationEntity { this.lastDateOfPeriod = rawStatistic.lastDateOfPeriod; this.year = rawStatistic.year; this.yearOrPeriod = rawStatistic.yearOrPeriod; - this.statisticId = - rawStatistic.statisticId || applicationContext.getUniqueId(); + this.statisticId = rawStatistic.statisticId || getUniqueId(); this.penalties = []; if ( rawStatistic.penalties && @@ -44,13 +41,11 @@ export class Statistic extends JoiValidationEntity { rawStatistic.irsTotalPenalties ) { assignPenalties(this, { - applicationContext, rawPenalties: rawStatistic.penalties, statisticId: this.statisticId, }); } else if (rawStatistic.irsTotalPenalties) { itemizeTotalPenalties(this, { - applicationContext, determinationTotalPenalties: this.determinationTotalPenalties, irsTotalPenalties: this.irsTotalPenalties, }); @@ -133,12 +128,12 @@ export class Statistic extends JoiValidationEntity { * @param {Object} penalty the Penalty object to add * @returns {void} modifies the penalties array on the Statistic */ - addPenalty({ applicationContext, rawPenalty }) { + addPenalty({ rawPenalty }) { const rawPenaltyCopy = { ...rawPenalty }; if (!rawPenaltyCopy.statisticId) { rawPenaltyCopy.statisticId = this.statisticId; } - const penalty = new Penalty(rawPenaltyCopy, { applicationContext }); + const penalty = new Penalty(rawPenaltyCopy); this.penalties.push(penalty); } @@ -161,15 +156,11 @@ export class Statistic extends JoiValidationEntity { } } -const assignPenalties = ( - obj, - { applicationContext, rawPenalties, statisticId }, -) => { +const assignPenalties = (obj, { rawPenalties, statisticId }) => { rawPenalties.forEach(penalty => { penalty.statisticId - ? obj.addPenalty({ applicationContext, rawPenalty: penalty }) + ? obj.addPenalty({ rawPenalty: penalty }) : obj.addPenalty({ - applicationContext, rawPenalty: { ...penalty, statisticId }, }); }); @@ -177,10 +168,9 @@ const assignPenalties = ( const itemizeTotalPenalties = function ( obj, - { applicationContext, determinationTotalPenalties, irsTotalPenalties }, + { determinationTotalPenalties, irsTotalPenalties }, ) { obj.addPenalty({ - applicationContext, rawPenalty: { name: 'Penalty 1 (IRS)', penaltyAmount: irsTotalPenalties, @@ -191,7 +181,6 @@ const itemizeTotalPenalties = function ( if (determinationTotalPenalties) { obj.addPenalty({ - applicationContext, rawPenalty: { name: 'Penalty 1 (Court)', penaltyAmount: determinationTotalPenalties, diff --git a/shared/src/business/entities/User.ts b/shared/src/business/entities/User.ts index 04d4ae99767..689aa0e01e2 100644 --- a/shared/src/business/entities/User.ts +++ b/shared/src/business/entities/User.ts @@ -176,8 +176,8 @@ export class User extends JoiValidationEntity { return externalRoles.includes(role); } - static isInternalUser(role: Role): boolean { - const internalRoles: Role[] = [ + static isInternalUser(role?: Role): boolean { + const internalRoles: (Role | undefined)[] = [ ROLES.adc, ROLES.admissionsClerk, ROLES.chambers, diff --git a/shared/src/business/entities/WorkItem.test.ts b/shared/src/business/entities/WorkItem.test.ts index a54b062aa2c..997178f08ff 100644 --- a/shared/src/business/entities/WorkItem.test.ts +++ b/shared/src/business/entities/WorkItem.test.ts @@ -5,7 +5,6 @@ import { } from './EntityConstants'; import { MOCK_CASE } from '../../test/mockCase'; import { WorkItem } from './WorkItem'; -import { applicationContext } from '../test/createTestApplicationContext'; import { cloneDeep } from 'lodash'; describe('WorkItem', () => { @@ -27,87 +26,75 @@ describe('WorkItem', () => { }); it('Creates a valid workitem', () => { - const workItem = new WorkItem(aValidWorkItem, { applicationContext }); + const workItem = new WorkItem(aValidWorkItem); expect(workItem.isValid()).toBeTruthy(); }); it('Creates a valid workitem when using setStatus', () => { - const workItem = new WorkItem( - { - assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', - assigneeName: 'bob', - caseTitle: 'Johnny Joe Jacobson', - docketEntry: {}, - docketNumber: '101-18', - docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, - section: DOCKET_SECTION, - sentBy: 'bob', - }, - { applicationContext }, - ); + const workItem = new WorkItem({ + assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', + assigneeName: 'bob', + caseTitle: 'Johnny Joe Jacobson', + docketEntry: {}, + docketNumber: '101-18', + docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, + section: DOCKET_SECTION, + sentBy: 'bob', + }); workItem.setStatus(CASE_STATUS_TYPES.new); expect(workItem.caseStatus).toEqual(CASE_STATUS_TYPES.new); expect(workItem.isValid()).toBeTruthy(); }); it('Update a valid workitem with a workItemId', () => { - const workItem = new WorkItem( - { - assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', - assigneeName: 'bob', - caseStatus: CASE_STATUS_TYPES.new, - caseTitle: 'Johnny Joe Jacobson', - docketEntry: {}, - docketNumber: '101-18', - docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, - section: DOCKET_SECTION, - sentBy: 'bob', - workItemId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', - }, - { applicationContext }, - ); + const workItem = new WorkItem({ + assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', + assigneeName: 'bob', + caseStatus: CASE_STATUS_TYPES.new, + caseTitle: 'Johnny Joe Jacobson', + docketEntry: {}, + docketNumber: '101-18', + docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, + section: DOCKET_SECTION, + sentBy: 'bob', + workItemId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', + }); expect(workItem.isValid()).toBeTruthy(); }); it('Update a valid workitem with a isRead', () => { - const workItem = new WorkItem( - { - assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', - assigneeName: 'bob', - caseStatus: CASE_STATUS_TYPES.new, - caseTitle: 'Johnny Joe Jacobson', - docketEntry: {}, - docketNumber: '101-18', - docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, - isRead: true, - section: DOCKET_SECTION, - sentBy: 'bob', - workItemId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', - }, - { applicationContext }, - ); + const workItem = new WorkItem({ + assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', + assigneeName: 'bob', + caseStatus: CASE_STATUS_TYPES.new, + caseTitle: 'Johnny Joe Jacobson', + docketEntry: {}, + docketNumber: '101-18', + docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, + isRead: true, + section: DOCKET_SECTION, + sentBy: 'bob', + workItemId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', + }); expect(workItem.isValid()).toBeTruthy(); }); it('should create a valid workitem when caseStatus is calendared', () => { - const workItem = new WorkItem( - { - assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', - assigneeName: 'bob', - caseStatus: CASE_STATUS_TYPES.calendared, - caseTitle: 'Johnny Joe Jacobson', - docketEntry: {}, - docketNumber: '101-18', - docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, - isRead: true, - section: DOCKET_SECTION, - sentBy: 'bob', - trialDate: '2018-11-21T20:49:28.192Z', - trialLocation: 'Fairbanks, Alaska', - workItemId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', - }, - { applicationContext }, - ); + const workItem = new WorkItem({ + assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', + assigneeName: 'bob', + caseStatus: CASE_STATUS_TYPES.calendared, + caseTitle: 'Johnny Joe Jacobson', + docketEntry: {}, + docketNumber: '101-18', + docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, + isRead: true, + section: DOCKET_SECTION, + sentBy: 'bob', + trialDate: '2018-11-21T20:49:28.192Z', + trialLocation: 'Fairbanks, Alaska', + workItemId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', + }); expect(workItem.isValid()).toBe(true); }); @@ -128,11 +115,7 @@ describe('WorkItem', () => { mockCase.trialDate = '2018-11-21T20:49:28.192Z'; mockCase.trialLocation = 'Seattle, WA'; - const workItem = new WorkItem( - aValidWorkItem, - { applicationContext }, - mockCase, - ); + const workItem = new WorkItem(aValidWorkItem, { caseEntity: mockCase }); expect(workItem.isValid()).toBeTruthy(); expect(workItem.associatedJudge).toBe(mockCase.associatedJudge); @@ -148,19 +131,16 @@ describe('WorkItem', () => { }); it('assigns user provided to `assignUser`', () => { - const workItem = new WorkItem( - { - assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', - assigneeName: 'bob', - caseStatus: CASE_STATUS_TYPES.new, - caseTitle: 'Johnny Joe Jacobson', - docketEntry: {}, - docketNumber: '101-18', - docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, - sentBy: 'bob', - }, - { applicationContext }, - ); + const workItem = new WorkItem({ + assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', + assigneeName: 'bob', + caseStatus: CASE_STATUS_TYPES.new, + caseTitle: 'Johnny Joe Jacobson', + docketEntry: {}, + docketNumber: '101-18', + docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, + sentBy: 'bob', + }); const assignment = { assigneeId: '111cd447-6278-461b-b62b-d9e357eea62c', @@ -175,87 +155,75 @@ describe('WorkItem', () => { }); it('is set high priority if case is calendared or overridden', () => { - let workItem = new WorkItem( - { - assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', - assigneeName: 'bob', - caseStatus: CASE_STATUS_TYPES.new, - caseTitle: 'Johnny Joe Jacobson', - docketEntry: {}, - docketNumber: '101-18', - docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, - section: DOCKET_SECTION, - sentBy: 'bob', - }, - { applicationContext }, - ); + let workItem = new WorkItem({ + assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', + assigneeName: 'bob', + caseStatus: CASE_STATUS_TYPES.new, + caseTitle: 'Johnny Joe Jacobson', + docketEntry: {}, + docketNumber: '101-18', + docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, + section: DOCKET_SECTION, + sentBy: 'bob', + }); expect(workItem.highPriority).toBe(false); - workItem = new WorkItem( - { - assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', - assigneeName: 'bob', - caseStatus: CASE_STATUS_TYPES.calendared, - caseTitle: 'Johnny Joe Jacobson', - docketEntry: {}, - docketNumber: '101-18', - docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, - section: DOCKET_SECTION, - sentBy: 'bob', - }, - { applicationContext }, - ); + workItem = new WorkItem({ + assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', + assigneeName: 'bob', + caseStatus: CASE_STATUS_TYPES.calendared, + caseTitle: 'Johnny Joe Jacobson', + docketEntry: {}, + docketNumber: '101-18', + docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, + section: DOCKET_SECTION, + sentBy: 'bob', + }); expect(workItem.highPriority).toBe(true); - workItem = new WorkItem( - { - assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', - assigneeName: 'bob', - caseStatus: CASE_STATUS_TYPES.new, - caseTitle: 'Johnny Joe Jacobson', - docketEntry: {}, - docketNumber: '101-18', - docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, - highPriority: true, - section: DOCKET_SECTION, - sentBy: 'bob', - }, - { applicationContext }, - ); + workItem = new WorkItem({ + assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', + assigneeName: 'bob', + caseStatus: CASE_STATUS_TYPES.new, + caseTitle: 'Johnny Joe Jacobson', + docketEntry: {}, + docketNumber: '101-18', + docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, + highPriority: true, + section: DOCKET_SECTION, + sentBy: 'bob', + }); expect(workItem.highPriority).toBe(true); }); it('creates a workItem containing a docketEntry with only the picked fields', () => { - const workItem = new WorkItem( - { - assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', - assigneeName: 'bob', - caseStatus: CASE_STATUS_TYPES.new, - caseTitle: 'Johnny Joe Jacobson', - docketEntry: { - createdAt: '2018-11-21T20:49:28.192Z', - docketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', - docketNumber: '101-18', - documentTitle: 'Proposed Stipulated Decision', - documentType: 'Proposed Stipulated Decision', - editState: {}, - eventCode: 'PSDE', - filedBy: 'Test Petitioner', - filingDate: '2018-03-01T00:01:00.000Z', - index: 5, - isFileAttached: true, - processingStatus: 'pending', - receivedAt: '2018-03-01T00:01:00.000Z', - servedAt: '2019-08-25T05:00:00.000Z', - }, + const workItem = new WorkItem({ + assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', + assigneeName: 'bob', + caseStatus: CASE_STATUS_TYPES.new, + caseTitle: 'Johnny Joe Jacobson', + docketEntry: { + createdAt: '2018-11-21T20:49:28.192Z', + docketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', docketNumber: '101-18', - docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, - leadDocketNumber: '101-18', - section: DOCKET_SECTION, - sentBy: 'bob', + documentTitle: 'Proposed Stipulated Decision', + documentType: 'Proposed Stipulated Decision', + editState: {}, + eventCode: 'PSDE', + filedBy: 'Test Petitioner', + filingDate: '2018-03-01T00:01:00.000Z', + index: 5, + isFileAttached: true, + processingStatus: 'pending', + receivedAt: '2018-03-01T00:01:00.000Z', + servedAt: '2019-08-25T05:00:00.000Z', }, - { applicationContext }, - ); + docketNumber: '101-18', + docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, + leadDocketNumber: '101-18', + section: DOCKET_SECTION, + sentBy: 'bob', + }); expect(workItem.docketEntry.docketNumber).toBeUndefined(); expect(workItem.docketEntry.editState).toBeUndefined(); expect(workItem.docketEntry.processingStatus).toBeUndefined(); @@ -266,20 +234,17 @@ describe('WorkItem', () => { describe('markAsRead', () => { it('should set isRead to true', () => { - const workItem = new WorkItem( - { - assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', - assigneeName: 'bob', - caseStatus: CASE_STATUS_TYPES.new, - caseTitle: 'Johnny Joe Jacobson', - docketEntry: {}, - docketNumber: '101-18', - docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, - section: DOCKET_SECTION, - sentBy: 'bob', - }, - { applicationContext }, - ); + const workItem = new WorkItem({ + assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', + assigneeName: 'bob', + caseStatus: CASE_STATUS_TYPES.new, + caseTitle: 'Johnny Joe Jacobson', + docketEntry: {}, + docketNumber: '101-18', + docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL, + section: DOCKET_SECTION, + sentBy: 'bob', + }); expect(workItem.isRead).toBeFalsy(); diff --git a/shared/src/business/entities/WorkItem.ts b/shared/src/business/entities/WorkItem.ts index 68255c99389..56340631067 100644 --- a/shared/src/business/entities/WorkItem.ts +++ b/shared/src/business/entities/WorkItem.ts @@ -3,6 +3,7 @@ import { Case } from '@shared/business/entities/cases/Case'; import { JoiValidationEntity } from '@shared/business/entities/JoiValidationEntity'; import { WORK_ITEM_VALIDATION_RULES } from './EntityValidationConstants'; import { createISODateString } from '../utilities/DateHandler'; +import { getUniqueId } from '@shared/sharedAppContext'; import { pick } from 'lodash'; export class WorkItem extends JoiValidationEntity { @@ -36,13 +37,9 @@ export class WorkItem extends JoiValidationEntity { public updatedAt: string; public workItemId: string; - constructor(rawWorkItem, { applicationContext }, caseEntity?: Case) { + constructor(rawWorkItem, { caseEntity }: { caseEntity?: Case } = {}) { super('WorkItem'); - if (!applicationContext) { - throw new TypeError('applicationContext must be defined'); - } - this.assigneeId = rawWorkItem.assigneeId; this.assigneeName = rawWorkItem.assigneeName; this.associatedJudge = @@ -104,8 +101,7 @@ export class WorkItem extends JoiValidationEntity { ? caseEntity.trialLocation : rawWorkItem.trialLocation; this.updatedAt = rawWorkItem.updatedAt || createISODateString(); - this.workItemId = - rawWorkItem.workItemId || applicationContext.getUniqueId(); + this.workItemId = rawWorkItem.workItemId || getUniqueId(); } assignToUser({ diff --git a/shared/src/business/entities/cases/Case.addCorrespondence.test.ts b/shared/src/business/entities/cases/Case.addCorrespondence.test.ts index ba74dc1c5f4..9c12be6c2a7 100644 --- a/shared/src/business/entities/cases/Case.addCorrespondence.test.ts +++ b/shared/src/business/entities/cases/Case.addCorrespondence.test.ts @@ -1,10 +1,12 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('addCorrespondence', () => { it('should successfully add correspondence', () => { - const caseEntity = new Case(MOCK_CASE, { applicationContext }); + const caseEntity = new Case(MOCK_CASE, { + authorizedUser: mockDocketClerkUser, + }); caseEntity.fileCorrespondence({ correspondenceId: 'yeehaw', diff --git a/shared/src/business/entities/cases/Case.addDocketEntry.test.ts b/shared/src/business/entities/cases/Case.addDocketEntry.test.ts index aef110eb270..bb9adcb7860 100644 --- a/shared/src/business/entities/cases/Case.addDocketEntry.test.ts +++ b/shared/src/business/entities/cases/Case.addDocketEntry.test.ts @@ -1,12 +1,12 @@ import { Case } from './Case'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('addDocketEntry', () => { it('should throw when docket entry to be added to the docket record is a STIN', () => { const caseToVerify = new Case( { docketNumber: '123-45' }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); expect(() => { @@ -24,7 +24,7 @@ describe('addDocketEntry', () => { const caseToVerify = new Case( { docketNumber: '123-45' }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); caseToVerify.addDocketEntry({ @@ -45,7 +45,7 @@ describe('addDocketEntry', () => { const caseToVerify = new Case( { docketNumber: '123-45' }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); caseToVerify.addDocketEntry({ diff --git a/shared/src/business/entities/cases/Case.addPetitioner.test.ts b/shared/src/business/entities/cases/Case.addPetitioner.test.ts index 31ac1a3ba04..b06a2aa99ab 100644 --- a/shared/src/business/entities/cases/Case.addPetitioner.test.ts +++ b/shared/src/business/entities/cases/Case.addPetitioner.test.ts @@ -7,31 +7,26 @@ import { import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; import { Petitioner } from '../contacts/Petitioner'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockAdmissionsClerkUser } from '@shared/test/mockAuthUsers'; describe('addPetitioner', () => { it('should add the petitioner to the petitioners array and return the updated case', () => { const caseEntity = new Case( { ...MOCK_CASE, status: CASE_STATUS_TYPES.generalDocket }, - { applicationContext }, + { authorizedUser: mockAdmissionsClerkUser }, ); - const petitionerEntity = new Petitioner( - { - address1: '123 Tomato Street', - city: 'Tomatotown', - contactType: CONTACT_TYPES.otherPetitioner, - countryType: COUNTRY_TYPES.DOMESTIC, - name: 'Susie Tomato', - phone: '123456', - postalCode: '99999', - serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, - state: 'KS', - }, - { - applicationContext, - }, - ); + const petitionerEntity = new Petitioner({ + address1: '123 Tomato Street', + city: 'Tomatotown', + contactType: CONTACT_TYPES.otherPetitioner, + countryType: COUNTRY_TYPES.DOMESTIC, + name: 'Susie Tomato', + phone: '123456', + postalCode: '99999', + serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + state: 'KS', + }); expect(caseEntity.petitioners.length).toEqual(1); diff --git a/shared/src/business/entities/cases/Case.addStatistic.test.ts b/shared/src/business/entities/cases/Case.addStatistic.test.ts index b4cb8565c63..05bdbcd0355 100644 --- a/shared/src/business/entities/cases/Case.addStatistic.test.ts +++ b/shared/src/business/entities/cases/Case.addStatistic.test.ts @@ -1,23 +1,19 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; import { Statistic } from '../Statistic'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('addStatistic', () => { it('should successfully add a statistic', () => { - const caseEntity = new Case(MOCK_CASE, { applicationContext }); + const caseEntity = new Case(MOCK_CASE, { authorizedUser: undefined }); - const statisticToAdd = new Statistic( - { - determinationDeficiencyAmount: 567, - determinationTotalPenalties: 789, - irsDeficiencyAmount: 11.2, - irsTotalPenalties: 66.87, - year: 2012, - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + const statisticToAdd = new Statistic({ + determinationDeficiencyAmount: 567, + determinationTotalPenalties: 789, + irsDeficiencyAmount: 11.2, + irsTotalPenalties: 66.87, + year: 2012, + yearOrPeriod: 'Year', + }); caseEntity.addStatistic(statisticToAdd); @@ -31,20 +27,17 @@ describe('addStatistic', () => { ...MOCK_CASE, statistics: statisticsWithMaxLength, }, - { applicationContext }, + { authorizedUser: undefined }, ); - const statisticToAdd = new Statistic( - { - determinationDeficiencyAmount: 567, - determinationTotalPenalties: 789, - irsDeficiencyAmount: 11.2, - irsTotalPenalties: 66.87, - year: 2012, - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + const statisticToAdd = new Statistic({ + determinationDeficiencyAmount: 567, + determinationTotalPenalties: 789, + irsDeficiencyAmount: 11.2, + irsTotalPenalties: 66.87, + year: 2012, + yearOrPeriod: 'Year', + }); let error; try { diff --git a/shared/src/business/entities/cases/Case.archiveCorrespondence.test.ts b/shared/src/business/entities/cases/Case.archiveCorrespondence.test.ts index ef442197d04..152f586975e 100644 --- a/shared/src/business/entities/cases/Case.archiveCorrespondence.test.ts +++ b/shared/src/business/entities/cases/Case.archiveCorrespondence.test.ts @@ -1,7 +1,7 @@ import { Case } from './Case'; import { Correspondence } from '../Correspondence'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('archiveCorrespondence', () => { let caseRecord; @@ -19,14 +19,14 @@ describe('archiveCorrespondence', () => { correspondence: [correspondenceToArchive], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); }); it('marks the correspondence document as archived', () => { caseRecord.archiveCorrespondence(correspondenceToArchive, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); const archivedDocketEntry = caseRecord.archivedCorrespondences.find( d => d.correspondenceId === correspondenceToArchive.correspondenceId, @@ -36,7 +36,7 @@ describe('archiveCorrespondence', () => { it('adds the provided document to the case archivedDocketEntries', () => { caseRecord.archiveCorrespondence(correspondenceToArchive, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect( diff --git a/shared/src/business/entities/cases/Case.archiveDocketEntry.test.ts b/shared/src/business/entities/cases/Case.archiveDocketEntry.test.ts index a0da852f6a7..348ba74ba68 100644 --- a/shared/src/business/entities/cases/Case.archiveDocketEntry.test.ts +++ b/shared/src/business/entities/cases/Case.archiveDocketEntry.test.ts @@ -2,8 +2,8 @@ import { Case } from './Case'; import { DocketEntry } from '../DocketEntry'; import { MOCK_CASE } from '../../../test/mockCase'; import { PENDING_DOCKET_ENTRY } from '../../../test/mockDocketEntry'; -import { applicationContext } from '../../test/createTestApplicationContext'; import { cloneDeep } from 'lodash'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('archiveDocketEntry', () => { let caseRecord: Case; @@ -11,7 +11,7 @@ describe('archiveDocketEntry', () => { beforeEach(() => { docketEntryToArchive = new DocketEntry(cloneDeep(PENDING_DOCKET_ENTRY), { - applicationContext, + authorizedUser: undefined, }); docketEntryToArchive.servedAt = undefined; @@ -21,7 +21,7 @@ describe('archiveDocketEntry', () => { docketEntries: [...MOCK_CASE.docketEntries, docketEntryToArchive], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); }); diff --git a/shared/src/business/entities/cases/Case.attachIrsPractitioner.test.ts b/shared/src/business/entities/cases/Case.attachIrsPractitioner.test.ts index 2c2e6618d6f..27d04298da1 100644 --- a/shared/src/business/entities/cases/Case.attachIrsPractitioner.test.ts +++ b/shared/src/business/entities/cases/Case.attachIrsPractitioner.test.ts @@ -1,13 +1,13 @@ import { Case } from './Case'; import { IrsPractitioner } from '../IrsPractitioner'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('attachIrsPractitioner', () => { it('adds the user to the irsPractitioners', () => { const caseToVerify = new Case( {}, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); caseToVerify.attachIrsPractitioner( diff --git a/shared/src/business/entities/cases/Case.attachPrivatePractitioner.test.ts b/shared/src/business/entities/cases/Case.attachPrivatePractitioner.test.ts index dcf50e5a799..0ffa04b17f3 100644 --- a/shared/src/business/entities/cases/Case.attachPrivatePractitioner.test.ts +++ b/shared/src/business/entities/cases/Case.attachPrivatePractitioner.test.ts @@ -1,13 +1,13 @@ import { Case } from './Case'; import { PrivatePractitioner } from '../PrivatePractitioner'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('attachPrivatePractitioner', () => { it('adds the user to the privatePractitioners', () => { const caseToVerify = new Case( {}, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); caseToVerify.attachPrivatePractitioner( diff --git a/shared/src/business/entities/cases/Case.canConsolidate.test.ts b/shared/src/business/entities/cases/Case.canConsolidate.test.ts index 71110d6e27a..0f41a0b18ab 100644 --- a/shared/src/business/entities/cases/Case.canConsolidate.test.ts +++ b/shared/src/business/entities/cases/Case.canConsolidate.test.ts @@ -1,7 +1,7 @@ import { CASE_STATUS_TYPES } from '../EntityConstants'; import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('canConsolidate', () => { let caseEntity; @@ -10,7 +10,7 @@ describe('canConsolidate', () => { caseEntity = new Case( { ...MOCK_CASE, status: CASE_STATUS_TYPES.submitted }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); }); diff --git a/shared/src/business/entities/cases/Case.checkForReadyForTrial.test.ts b/shared/src/business/entities/cases/Case.checkForReadyForTrial.test.ts index 0096f3fba31..cf2d9def13c 100644 --- a/shared/src/business/entities/cases/Case.checkForReadyForTrial.test.ts +++ b/shared/src/business/entities/cases/Case.checkForReadyForTrial.test.ts @@ -4,11 +4,11 @@ import { CASE_STATUS_TYPES, } from '../EntityConstants'; import { Case } from './Case'; -import { applicationContext } from '../../test/createTestApplicationContext'; import { calculateISODate, prepareDateFromString, } from '../../utilities/DateHandler'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('checkForReadyForTrial', () => { it('should not change the status if no answer docketEntries have been filed', () => { @@ -18,7 +18,7 @@ describe('checkForReadyForTrial', () => { status: CASE_STATUS_TYPES.generalDocket, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ).checkForReadyForTrial(); expect(caseToCheck.status).toEqual(CASE_STATUS_TYPES.generalDocket); @@ -36,7 +36,7 @@ describe('checkForReadyForTrial', () => { status: CASE_STATUS_TYPES.generalDocket, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ).checkForReadyForTrial(); expect(caseToCheck.status).toEqual(CASE_STATUS_TYPES.generalDocket); @@ -54,7 +54,7 @@ describe('checkForReadyForTrial', () => { status: CASE_STATUS_TYPES.generalDocket, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ).checkForReadyForTrial(); expect(caseToCheck.status).toEqual(CASE_STATUS_TYPES.generalDocket); @@ -81,7 +81,7 @@ describe('checkForReadyForTrial', () => { status: CASE_STATUS_TYPES.generalDocket, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ).checkForReadyForTrial(); @@ -107,7 +107,7 @@ describe('checkForReadyForTrial', () => { status: CASE_STATUS_TYPES.new, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ).checkForReadyForTrial(); @@ -131,7 +131,7 @@ describe('checkForReadyForTrial', () => { status: CASE_STATUS_TYPES.generalDocket, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ).checkForReadyForTrial(); diff --git a/shared/src/business/entities/cases/Case.deleteCorrespondenceById.test.ts b/shared/src/business/entities/cases/Case.deleteCorrespondenceById.test.ts index 8029326bb16..49a9b14afdd 100644 --- a/shared/src/business/entities/cases/Case.deleteCorrespondenceById.test.ts +++ b/shared/src/business/entities/cases/Case.deleteCorrespondenceById.test.ts @@ -2,7 +2,7 @@ import { Case } from './Case'; import { Correspondence } from '../Correspondence'; import { MOCK_CASE } from '../../../test/mockCase'; import { MOCK_USERS } from '../../../test/mockUsers'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('deleteCorrespondenceById', () => { const mockCorrespondence = new Correspondence({ @@ -15,7 +15,7 @@ describe('deleteCorrespondenceById', () => { const myCase = new Case( { ...MOCK_CASE, correspondence: [mockCorrespondence] }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -37,7 +37,7 @@ describe('deleteCorrespondenceById', () => { const myCase = new Case( { ...MOCK_CASE, correspondence: [mockCorrespondence] }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); expect(myCase.correspondence!.length).toEqual(1); diff --git a/shared/src/business/entities/cases/Case.deleteDocketEntryById.test.ts b/shared/src/business/entities/cases/Case.deleteDocketEntryById.test.ts index 2e187187d6d..6ab8272bc99 100644 --- a/shared/src/business/entities/cases/Case.deleteDocketEntryById.test.ts +++ b/shared/src/business/entities/cases/Case.deleteDocketEntryById.test.ts @@ -1,12 +1,12 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; import { MOCK_DOCUMENTS } from '../../../test/mockDocketEntry'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('deleteDocketEntryById', () => { it('should delete the document with the given id', () => { const myCase = new Case(MOCK_CASE, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); const docketEntryIdToDelete = MOCK_DOCUMENTS[1].docketEntryId; expect(myCase.docketEntries.length).toEqual(4); @@ -21,7 +21,7 @@ describe('deleteDocketEntryById', () => { it('should not delete a document if a document with the given id does not exist', () => { const myCase = new Case(MOCK_CASE, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); const docketEntryIdToDelete = '016fda7d-eb0a-4194-b603-ef422c898122'; expect(myCase.docketEntries.length).toEqual(4); diff --git a/shared/src/business/entities/cases/Case.deleteStatistic.test.ts b/shared/src/business/entities/cases/Case.deleteStatistic.test.ts index 34fab0c8c69..32329736d8c 100644 --- a/shared/src/business/entities/cases/Case.deleteStatistic.test.ts +++ b/shared/src/business/entities/cases/Case.deleteStatistic.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('deleteStatistic', () => { it('should successfully delete a statistic', () => { @@ -32,7 +32,7 @@ describe('deleteStatistic', () => { ...MOCK_CASE, statistics: originalStatistics, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); caseEntity.deleteStatistic(statistic0Id); @@ -70,7 +70,7 @@ describe('deleteStatistic', () => { ...MOCK_CASE, statistics: originalStatistics, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); caseEntity.deleteStatistic('16fc02bc-f00a-453c-a19c-e5597a8850ba'); diff --git a/shared/src/business/entities/cases/Case.generateNextDocketRecordIndex.test.ts b/shared/src/business/entities/cases/Case.generateNextDocketRecordIndex.test.ts index bf4110f2da7..2069073e7e5 100644 --- a/shared/src/business/entities/cases/Case.generateNextDocketRecordIndex.test.ts +++ b/shared/src/business/entities/cases/Case.generateNextDocketRecordIndex.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockPetitionsClerkUser } from '@shared/test/mockAuthUsers'; describe('generateNextDocketRecordIndex', () => { it('returns the next possible index based on the current docket record array', () => { @@ -9,7 +9,7 @@ describe('generateNextDocketRecordIndex', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockPetitionsClerkUser, }, ); @@ -24,7 +24,7 @@ describe('generateNextDocketRecordIndex', () => { docketEntries: [], }, { - applicationContext, + authorizedUser: mockPetitionsClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.generateTrialSortTags.test.ts b/shared/src/business/entities/cases/Case.generateTrialSortTags.test.ts index 1c8f7a73b01..04a612c73e6 100644 --- a/shared/src/business/entities/cases/Case.generateTrialSortTags.test.ts +++ b/shared/src/business/entities/cases/Case.generateTrialSortTags.test.ts @@ -1,7 +1,7 @@ import { CASE_TYPES_MAP } from '../EntityConstants'; import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('generateTrialSortTags', () => { it('should generate sort tags for a regular case', () => { @@ -11,7 +11,7 @@ describe('generateTrialSortTags', () => { receivedAt: '2018-12-12T05:00:00.000Z', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); expect(myCase.generateTrialSortTags()).toEqual({ @@ -28,7 +28,7 @@ describe('generateTrialSortTags', () => { receivedAt: '2018-12-12T05:00:00.000Z', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); expect(myCase.generateTrialSortTags()).toEqual({ @@ -45,7 +45,7 @@ describe('generateTrialSortTags', () => { receivedAt: '2018-12-12T05:00:00.000Z', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); expect(myCase.generateTrialSortTags()).toEqual({ @@ -62,7 +62,7 @@ describe('generateTrialSortTags', () => { receivedAt: '2018-12-12T05:00:00.000Z', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); expect(myCase.generateTrialSortTags()).toEqual({ @@ -80,7 +80,7 @@ describe('generateTrialSortTags', () => { receivedAt: '2018-12-12T05:00:00.000Z', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); expect(myCase.generateTrialSortTags()).toEqual({ diff --git a/shared/src/business/entities/cases/Case.getAttachmentDocumentById.test.ts b/shared/src/business/entities/cases/Case.getAttachmentDocumentById.test.ts index 6c6033b2095..ba5a7b22574 100644 --- a/shared/src/business/entities/cases/Case.getAttachmentDocumentById.test.ts +++ b/shared/src/business/entities/cases/Case.getAttachmentDocumentById.test.ts @@ -1,12 +1,12 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; import { MOCK_DOCUMENTS } from '../../../test/mockDocketEntry'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('getAttachmentDocumentById', () => { it('should get a docket entry document', () => { const myCase = new Case(MOCK_CASE, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); const result = Case.getAttachmentDocumentById({ caseDetail: myCase.toRawObject(), @@ -31,7 +31,7 @@ describe('getAttachmentDocumentById', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); const result = Case.getAttachmentDocumentById({ @@ -49,7 +49,7 @@ describe('getAttachmentDocumentById', () => { docketEntries: [], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); const result = Case.getAttachmentDocumentById({ @@ -68,7 +68,7 @@ describe('getAttachmentDocumentById', () => { docketEntries: [], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); const result = Case.getAttachmentDocumentById({ @@ -94,7 +94,7 @@ describe('getAttachmentDocumentById', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); const result = Case.getAttachmentDocumentById({ diff --git a/shared/src/business/entities/cases/Case.getCaseConfirmationGeneratedPdfFileName.test.ts b/shared/src/business/entities/cases/Case.getCaseConfirmationGeneratedPdfFileName.test.ts index 23e42539a57..25fcd907fc9 100644 --- a/shared/src/business/entities/cases/Case.getCaseConfirmationGeneratedPdfFileName.test.ts +++ b/shared/src/business/entities/cases/Case.getCaseConfirmationGeneratedPdfFileName.test.ts @@ -1,5 +1,5 @@ import { Case } from './Case'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('getCaseConfirmationGeneratedPdfFileName', () => { it('generates the correct name for the case confirmation pdf', () => { @@ -8,7 +8,7 @@ describe('getCaseConfirmationGeneratedPdfFileName', () => { docketNumber: '123-20', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); expect(caseToVerify.getCaseConfirmationGeneratedPdfFileName()).toEqual( diff --git a/shared/src/business/entities/cases/Case.getConsolidationStatus.test.ts b/shared/src/business/entities/cases/Case.getConsolidationStatus.test.ts index 79a2c3a24be..cd53553d36c 100644 --- a/shared/src/business/entities/cases/Case.getConsolidationStatus.test.ts +++ b/shared/src/business/entities/cases/Case.getConsolidationStatus.test.ts @@ -1,7 +1,6 @@ import { CASE_STATUS_TYPES } from '../EntityConstants'; import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('getConsolidationStatus', () => { let leadCaseEntity; @@ -14,7 +13,7 @@ describe('getConsolidationStatus', () => { procedureType: 'Regular', status: CASE_STATUS_TYPES.submitted, }, - { applicationContext }, + { authorizedUser: undefined }, ); pendingCaseEntity = new Case( @@ -24,7 +23,7 @@ describe('getConsolidationStatus', () => { procedureType: 'Regular', status: CASE_STATUS_TYPES.submitted, }, - { applicationContext }, + { authorizedUser: undefined }, ); }); diff --git a/shared/src/business/entities/cases/Case.getCorrespondenceById.test.ts b/shared/src/business/entities/cases/Case.getCorrespondenceById.test.ts index f9d914bfc54..3880b18518e 100644 --- a/shared/src/business/entities/cases/Case.getCorrespondenceById.test.ts +++ b/shared/src/business/entities/cases/Case.getCorrespondenceById.test.ts @@ -1,7 +1,7 @@ import { Case } from './Case'; import { Correspondence } from '../Correspondence'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('getCorrespondenceById', () => { it('should get a correspondence document by id', () => { @@ -13,7 +13,7 @@ describe('getCorrespondenceById', () => { const myCase = new Case( { ...MOCK_CASE, correspondence: [mockCorrespondence] }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.getDocketEntryById.test.ts b/shared/src/business/entities/cases/Case.getDocketEntryById.test.ts index f2258f70f1c..4dc329c31ec 100644 --- a/shared/src/business/entities/cases/Case.getDocketEntryById.test.ts +++ b/shared/src/business/entities/cases/Case.getDocketEntryById.test.ts @@ -1,12 +1,12 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; import { MOCK_DOCUMENTS } from '../../../test/mockDocketEntry'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('getDocketEntryById', () => { it('should get the docket entry by an Id', () => { const myCase = new Case(MOCK_CASE, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); const result = myCase.getDocketEntryById({ docketEntryId: MOCK_DOCUMENTS[0].docketEntryId, diff --git a/shared/src/business/entities/cases/Case.getIrsSendDate.test.ts b/shared/src/business/entities/cases/Case.getIrsSendDate.test.ts index 14e18111bd4..1111ceaae1c 100644 --- a/shared/src/business/entities/cases/Case.getIrsSendDate.test.ts +++ b/shared/src/business/entities/cases/Case.getIrsSendDate.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('getIrsSendDate', () => { it('should get the IRS send date from the petition docket entry', () => { @@ -12,7 +12,7 @@ describe('getIrsSendDate', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); const result = myCase.getIrsSendDate(); @@ -26,7 +26,7 @@ describe('getIrsSendDate', () => { docketEntries: [{ documentType: 'Petition' }], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); const result = myCase.getIrsSendDate(); @@ -42,7 +42,7 @@ describe('getIrsSendDate', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); const result = myCase.getIrsSendDate(); diff --git a/shared/src/business/entities/cases/Case.getOtherFilers.test.ts b/shared/src/business/entities/cases/Case.getOtherFilers.test.ts index 5966b628eaf..55426aff663 100644 --- a/shared/src/business/entities/cases/Case.getOtherFilers.test.ts +++ b/shared/src/business/entities/cases/Case.getOtherFilers.test.ts @@ -6,7 +6,7 @@ import { } from '../EntityConstants'; import { Case, getContactPrimary } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('getOtherFilers', () => { it('sets a valid value of otherFilers on the case', () => { @@ -46,7 +46,7 @@ describe('getOtherFilers', () => { status: CASE_STATUS_TYPES.generalDocket, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.getPetitionDocketEntry.test.ts b/shared/src/business/entities/cases/Case.getPetitionDocketEntry.test.ts index cbe7b477f1c..ce3aca242c3 100644 --- a/shared/src/business/entities/cases/Case.getPetitionDocketEntry.test.ts +++ b/shared/src/business/entities/cases/Case.getPetitionDocketEntry.test.ts @@ -1,12 +1,12 @@ import { Case, getPetitionDocketEntry } from './Case'; import { INITIAL_DOCUMENT_TYPES } from '../EntityConstants'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('getPetitionDocketEntry', () => { it('should get the petition docket entry by documentType', () => { const myCase = new Case(MOCK_CASE, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); const result = myCase.getPetitionDocketEntry(); expect(result.documentType).toEqual( diff --git a/shared/src/business/entities/cases/Case.getPetitionerByEmail.test.ts b/shared/src/business/entities/cases/Case.getPetitionerByEmail.test.ts index f12421e29c6..227e7779451 100644 --- a/shared/src/business/entities/cases/Case.getPetitionerByEmail.test.ts +++ b/shared/src/business/entities/cases/Case.getPetitionerByEmail.test.ts @@ -1,17 +1,17 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('getPetitionerByEmail', () => { const mockContactEmail = 'petitioner@example.com'; it('returns petitioner with matching email from petitioners array', () => { - const myCase = new Case(MOCK_CASE, { applicationContext }); + const myCase = new Case(MOCK_CASE, { authorizedUser: mockDocketClerkUser }); expect(myCase.getPetitionerByEmail(mockContactEmail)).toBeDefined(); }); it('returns undefined if matching petitioner is not found', () => { - const myCase = new Case(MOCK_CASE, { applicationContext }); + const myCase = new Case(MOCK_CASE, { authorizedUser: mockDocketClerkUser }); expect(myCase.getPetitionerByEmail('nobody@example.com')).toBeUndefined(); }); diff --git a/shared/src/business/entities/cases/Case.getPetitionerById.test.ts b/shared/src/business/entities/cases/Case.getPetitionerById.test.ts index 485b710caed..1bdfcd0d6a4 100644 --- a/shared/src/business/entities/cases/Case.getPetitionerById.test.ts +++ b/shared/src/business/entities/cases/Case.getPetitionerById.test.ts @@ -1,6 +1,6 @@ import { Case, getContactPrimary } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('getPetitionerById', () => { it('returns petitioner with matching contactId from petitioners array', () => { @@ -13,7 +13,7 @@ describe('getPetitionerById', () => { { ...getContactPrimary(MOCK_CASE), contactId: mockContactId }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.getPetitionerById(mockContactId)).toBeDefined(); @@ -32,7 +32,7 @@ describe('getPetitionerById', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.getPetitionerById(mockNonExistingContactId)).toBeUndefined(); diff --git a/shared/src/business/entities/cases/Case.getPractitionersRepresenting.test.ts b/shared/src/business/entities/cases/Case.getPractitionersRepresenting.test.ts index 9e91f3cd2ae..42a6bd11355 100644 --- a/shared/src/business/entities/cases/Case.getPractitionersRepresenting.test.ts +++ b/shared/src/business/entities/cases/Case.getPractitionersRepresenting.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('getPractitionersRepresenting', () => { it('should return the practitioner associated with the contactId provided', () => { @@ -9,7 +9,7 @@ describe('getPractitionersRepresenting', () => { ...MOCK_CASE, privatePractitioners: [{ representing: ['567'], userId: '567' }], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); const practitioner = caseEntity.getPractitionersRepresenting('567'); @@ -28,7 +28,7 @@ describe('getPractitionersRepresenting', () => { ...MOCK_CASE, privatePractitioners: [{ representing: ['123'], userId: '567' }], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); const practitioner = caseEntity.getPractitionersRepresenting('567'); diff --git a/shared/src/business/entities/cases/Case.hasPartyWithServiceType.test.ts b/shared/src/business/entities/cases/Case.hasPartyWithServiceType.test.ts index b5273cc54e5..5718063e7cf 100644 --- a/shared/src/business/entities/cases/Case.hasPartyWithServiceType.test.ts +++ b/shared/src/business/entities/cases/Case.hasPartyWithServiceType.test.ts @@ -5,7 +5,7 @@ import { } from '../EntityConstants'; import { Case, getContactPrimary } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('hasPartyWithServiceType', () => { it('should return true if contactPrimary service indicator is paper', () => { @@ -19,7 +19,7 @@ describe('hasPartyWithServiceType', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); const hasPartyWithPaperService = myCase.hasPartyWithServiceType( @@ -46,7 +46,7 @@ describe('hasPartyWithServiceType', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); const hasPartyWithPaperService = myCase.hasPartyWithServiceType( @@ -68,7 +68,7 @@ describe('hasPartyWithServiceType', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); const hasPartyWithPaperService = myCase.hasPartyWithServiceType( @@ -90,7 +90,7 @@ describe('hasPartyWithServiceType', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); const hasPartyWithPaperService = myCase.hasPartyWithServiceType( @@ -111,7 +111,7 @@ describe('hasPartyWithServiceType', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); const hasPartyWithPaperService = myCase.hasPartyWithServiceType( diff --git a/shared/src/business/entities/cases/Case.hasPendingItems.test.ts b/shared/src/business/entities/cases/Case.hasPendingItems.test.ts index 14483bb83cc..c041e9a5b15 100644 --- a/shared/src/business/entities/cases/Case.hasPendingItems.test.ts +++ b/shared/src/business/entities/cases/Case.hasPendingItems.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { MOCK_CASE, MOCK_CASE_WITHOUT_PENDING } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('hasPendingItems', () => { it('should not show the case as having pending items if no docketEntries are pending', () => { @@ -9,7 +9,7 @@ describe('hasPendingItems', () => { ...MOCK_CASE_WITHOUT_PENDING, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -30,7 +30,7 @@ describe('hasPendingItems', () => { }; const caseToUpdate = new Case(mockCase, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(caseToUpdate.hasPendingItems).toEqual(false); @@ -51,7 +51,7 @@ describe('hasPendingItems', () => { }; const caseToUpdate = new Case(mockCase, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(caseToUpdate.hasPendingItems).toEqual(true); @@ -73,7 +73,7 @@ describe('hasPendingItems', () => { }; const caseToUpdate = new Case(mockCase, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(caseToUpdate.hasPendingItems).toEqual(true); diff --git a/shared/src/business/entities/cases/Case.hasPrivatePractitioners.test.ts b/shared/src/business/entities/cases/Case.hasPrivatePractitioners.test.ts index d02893a4a55..cfa69ba6896 100644 --- a/shared/src/business/entities/cases/Case.hasPrivatePractitioners.test.ts +++ b/shared/src/business/entities/cases/Case.hasPrivatePractitioners.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('hasPrivatePractitioners', () => { it('returns true when there are privatePractitioners on the case', () => { @@ -31,7 +31,7 @@ describe('hasPrivatePractitioners', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -45,7 +45,7 @@ describe('hasPrivatePractitioners', () => { privatePractitioners: [], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.isAssociatedUser.test.ts b/shared/src/business/entities/cases/Case.isAssociatedUser.test.ts index 35b4b097f7f..32472459d69 100644 --- a/shared/src/business/entities/cases/Case.isAssociatedUser.test.ts +++ b/shared/src/business/entities/cases/Case.isAssociatedUser.test.ts @@ -1,17 +1,13 @@ import { Case, getContactPrimary, isAssociatedUser } from './Case'; import { INITIAL_DOCUMENT_TYPES, PARTY_TYPES, ROLES } from '../EntityConstants'; import { MOCK_CASE } from '../../../test/mockCase'; -import { MOCK_USERS } from '../../../test/mockUsers'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('isAssociatedUser', () => { let caseEntity; const CONTACT_ID = '3855b2dd-4094-4526-acc0-b48d7eed1f28'; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue( - MOCK_USERS['a7d90c05-f6cd-442c-a168-202db587f16f'], - ); caseEntity = new Case( { ...MOCK_CASE, @@ -28,7 +24,7 @@ describe('isAssociatedUser', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); }); diff --git a/shared/src/business/entities/cases/Case.isClosed.test.ts b/shared/src/business/entities/cases/Case.isClosed.test.ts index f46b0b34ccd..1f531046c20 100644 --- a/shared/src/business/entities/cases/Case.isClosed.test.ts +++ b/shared/src/business/entities/cases/Case.isClosed.test.ts @@ -1,14 +1,14 @@ import { CASE_STATUS_TYPES, CLOSED_CASE_STATUSES } from '../EntityConstants'; import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('isClosed', () => { it(`should return false when the case status is NOT one of ${CLOSED_CASE_STATUSES}`, () => { const caseEntity = new Case( { ...MOCK_CASE, status: CASE_STATUS_TYPES.generalDocket }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -21,7 +21,7 @@ describe('isClosed', () => { const caseEntity = new Case( { ...MOCK_CASE, status: undefined }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -34,7 +34,7 @@ describe('isClosed', () => { const caseEntity = new Case( { ...MOCK_CASE, status: CASE_STATUS_TYPES.closed }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -47,7 +47,7 @@ describe('isClosed', () => { const caseEntity = new Case( { ...MOCK_CASE, status: CASE_STATUS_TYPES.closedDismissed }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.isHearing.test.ts b/shared/src/business/entities/cases/Case.isHearing.test.ts index 42186fc5ea2..082f8b05eb2 100644 --- a/shared/src/business/entities/cases/Case.isHearing.test.ts +++ b/shared/src/business/entities/cases/Case.isHearing.test.ts @@ -1,30 +1,27 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; import { TrialSession } from '../trialSessions/TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('isHearing', () => { it('checks if the given trialSessionId is a hearing (true)', () => { - const trialSessionHearing = new TrialSession( - { - isCalendared: true, - judge: { name: 'Judge Buch' }, - maxCases: 100, - sessionType: 'Regular', - startDate: '2025-03-01T00:00:00.000Z', - term: 'Fall', - termYear: '2025', - trialLocation: 'Birmingham, Alabama', - }, - { applicationContext }, - ); + const trialSessionHearing = new TrialSession({ + isCalendared: true, + judge: { name: 'Judge Buch' }, + maxCases: 100, + sessionType: 'Regular', + startDate: '2025-03-01T00:00:00.000Z', + term: 'Fall', + termYear: '2025', + trialLocation: 'Birmingham, Alabama', + }); const caseToUpdate = new Case( { ...MOCK_CASE, hearings: [trialSessionHearing], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -34,25 +31,22 @@ describe('isHearing', () => { }); it('checks if the given trialSessionId is a hearing (false)', () => { - const trialSessionHearing = new TrialSession( - { - isCalendared: true, - judge: { name: 'Judge Buch' }, - maxCases: 100, - sessionType: 'Regular', - startDate: '2025-03-01T00:00:00.000Z', - term: 'Fall', - termYear: '2025', - trialLocation: 'Birmingham, Alabama', - }, - { applicationContext }, - ); + const trialSessionHearing = new TrialSession({ + isCalendared: true, + judge: { name: 'Judge Buch' }, + maxCases: 100, + sessionType: 'Regular', + startDate: '2025-03-01T00:00:00.000Z', + term: 'Fall', + termYear: '2025', + trialLocation: 'Birmingham, Alabama', + }); const caseToUpdate = new Case( { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); caseToUpdate.setAsCalendared(trialSessionHearing); diff --git a/shared/src/business/entities/cases/Case.isPractitioner.test.ts b/shared/src/business/entities/cases/Case.isPractitioner.test.ts index e7b995a2d22..23dfe251e1c 100644 --- a/shared/src/business/entities/cases/Case.isPractitioner.test.ts +++ b/shared/src/business/entities/cases/Case.isPractitioner.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { MOCK_ELIGIBLE_CASE_WITH_PRACTITIONERS } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('isPractitioner', () => { it('returns true if the contactId is a privatePractitioner on the case', () => { @@ -9,7 +9,7 @@ describe('isPractitioner', () => { ...MOCK_ELIGIBLE_CASE_WITH_PRACTITIONERS, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); expect( @@ -23,7 +23,7 @@ describe('isPractitioner', () => { ...MOCK_ELIGIBLE_CASE_WITH_PRACTITIONERS, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); expect( @@ -37,7 +37,7 @@ describe('isPractitioner', () => { ...MOCK_ELIGIBLE_CASE_WITH_PRACTITIONERS, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); expect( diff --git a/shared/src/business/entities/cases/Case.isUserIdRepresentedByPrivatePractitioner.test.ts b/shared/src/business/entities/cases/Case.isUserIdRepresentedByPrivatePractitioner.test.ts index 693249f6016..b8f518189ec 100644 --- a/shared/src/business/entities/cases/Case.isUserIdRepresentedByPrivatePractitioner.test.ts +++ b/shared/src/business/entities/cases/Case.isUserIdRepresentedByPrivatePractitioner.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('isUserIdRepresentedByPrivatePractitioner', () => { let caseEntity; @@ -21,7 +21,7 @@ describe('isUserIdRepresentedByPrivatePractitioner', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); }); @@ -53,7 +53,7 @@ describe('isUserIdRepresentedByPrivatePractitioner', () => { privatePractitioners: undefined, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.markAsSentToIRS.test.ts b/shared/src/business/entities/cases/Case.markAsSentToIRS.test.ts index 10642a80ea0..4a98d4e76b8 100644 --- a/shared/src/business/entities/cases/Case.markAsSentToIRS.test.ts +++ b/shared/src/business/entities/cases/Case.markAsSentToIRS.test.ts @@ -4,7 +4,7 @@ import { MOCK_CASE, MOCK_CASE_WITH_SECONDARY_OTHERS, } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('markAsSentToIRS', () => { it('updates case status to general docket not at issue', () => { @@ -13,7 +13,7 @@ describe('markAsSentToIRS', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); caseRecord.markAsSentToIRS(); @@ -26,7 +26,7 @@ describe('markAsSentToIRS', () => { ...MOCK_CASE_WITH_SECONDARY_OTHERS, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -46,7 +46,7 @@ describe('markAsSentToIRS', () => { ...MOCK_CASE_WITH_SECONDARY_OTHERS, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.removeConsolidation.test.ts b/shared/src/business/entities/cases/Case.removeConsolidation.test.ts index 77ad0f178af..43559f39d03 100644 --- a/shared/src/business/entities/cases/Case.removeConsolidation.test.ts +++ b/shared/src/business/entities/cases/Case.removeConsolidation.test.ts @@ -1,7 +1,7 @@ import { CASE_STATUS_TYPES } from '../EntityConstants'; import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('removeConsolidation', () => { it('Should unset the leadDocketNumber on the given case', () => { @@ -13,7 +13,7 @@ describe('removeConsolidation', () => { procedureType: 'Regular', status: CASE_STATUS_TYPES.submitted, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); const result = caseEntity.removeConsolidation(); diff --git a/shared/src/business/entities/cases/Case.removeFromHearing.test.ts b/shared/src/business/entities/cases/Case.removeFromHearing.test.ts index 3e2ea386680..4a89549b8d3 100644 --- a/shared/src/business/entities/cases/Case.removeFromHearing.test.ts +++ b/shared/src/business/entities/cases/Case.removeFromHearing.test.ts @@ -1,30 +1,27 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; import { TrialSession } from '../trialSessions/TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('removeFromHearing', () => { it('removes the hearing from the case', () => { - const trialSessionHearing = new TrialSession( - { - isCalendared: true, - judge: { name: 'Judge Buch' }, - maxCases: 100, - sessionType: 'Regular', - startDate: '2025-03-01T00:00:00.000Z', - term: 'Fall', - termYear: '2025', - trialLocation: 'Birmingham, Alabama', - }, - { applicationContext }, - ); + const trialSessionHearing = new TrialSession({ + isCalendared: true, + judge: { name: 'Judge Buch' }, + maxCases: 100, + sessionType: 'Regular', + startDate: '2025-03-01T00:00:00.000Z', + term: 'Fall', + termYear: '2025', + trialLocation: 'Birmingham, Alabama', + }); const caseToUpdate = new Case( { ...MOCK_CASE, hearings: [trialSessionHearing], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); caseToUpdate.removeFromHearing(trialSessionHearing.trialSessionId); diff --git a/shared/src/business/entities/cases/Case.removeFromTrial.test.ts b/shared/src/business/entities/cases/Case.removeFromTrial.test.ts index 28d8fb4b96c..dc50e186da8 100644 --- a/shared/src/business/entities/cases/Case.removeFromTrial.test.ts +++ b/shared/src/business/entities/cases/Case.removeFromTrial.test.ts @@ -2,7 +2,7 @@ import { CASE_STATUS_TYPES, CHIEF_JUDGE } from '../EntityConstants'; import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; import { TrialSession } from '../trialSessions/TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('removeFromTrial', () => { it('removes the case from trial, unsetting trial details and setting status to general docket ready for trial', () => { @@ -11,22 +11,19 @@ describe('removeFromTrial', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); - const trialSession = new TrialSession( - { - isCalendared: true, - judge: { name: 'Judge Buch', userId: 'judge-user-id' }, - maxCases: 100, - sessionType: 'Regular', - startDate: '2025-03-01T00:00:00.000Z', - term: 'Fall', - termYear: '2025', - trialLocation: 'Birmingham, Alabama', - }, - { applicationContext }, - ); + const trialSession = new TrialSession({ + isCalendared: true, + judge: { name: 'Judge Buch', userId: 'judge-user-id' }, + maxCases: 100, + sessionType: 'Regular', + startDate: '2025-03-01T00:00:00.000Z', + term: 'Fall', + termYear: '2025', + trialLocation: 'Birmingham, Alabama', + }); const user = 'Petitions Clerk'; caseToUpdate.setAsCalendared(trialSession); @@ -64,22 +61,19 @@ describe('removeFromTrial', () => { ...MOCK_CASE, }, { - applicationContext, - }, - ); - const trialSession = new TrialSession( - { - isCalendared: true, - judge: { name: 'Judge Buch', userId: 'judge-user-id' }, - maxCases: 100, - sessionType: 'Regular', - startDate: '2025-03-01T00:00:00.000Z', - term: 'Fall', - termYear: '2025', - trialLocation: 'Birmingham, Alabama', + authorizedUser: mockDocketClerkUser, }, - { applicationContext }, ); + const trialSession = new TrialSession({ + isCalendared: true, + judge: { name: 'Judge Buch', userId: 'judge-user-id' }, + maxCases: 100, + sessionType: 'Regular', + startDate: '2025-03-01T00:00:00.000Z', + term: 'Fall', + termYear: '2025', + trialLocation: 'Birmingham, Alabama', + }); caseToUpdate.setAsCalendared(trialSession); expect(caseToUpdate.status).toEqual(CASE_STATUS_TYPES.calendared); @@ -102,22 +96,19 @@ describe('removeFromTrial', () => { ...MOCK_CASE, }, { - applicationContext, - }, - ); - const trialSession = new TrialSession( - { - isCalendared: true, - judge: { name: 'Judge Buch', userId: 'judge-user-id' }, - maxCases: 100, - sessionType: 'Regular', - startDate: '2025-03-01T00:00:00.000Z', - term: 'Fall', - termYear: '2025', - trialLocation: 'Birmingham, Alabama', + authorizedUser: mockDocketClerkUser, }, - { applicationContext }, ); + const trialSession = new TrialSession({ + isCalendared: true, + judge: { name: 'Judge Buch', userId: 'judge-user-id' }, + maxCases: 100, + sessionType: 'Regular', + startDate: '2025-03-01T00:00:00.000Z', + term: 'Fall', + termYear: '2025', + trialLocation: 'Birmingham, Alabama', + }); caseToUpdate.setAsCalendared(trialSession); expect(caseToUpdate.status).toEqual(CASE_STATUS_TYPES.calendared); diff --git a/shared/src/business/entities/cases/Case.removeFromTrialWithAssociatedJudge.test.ts b/shared/src/business/entities/cases/Case.removeFromTrialWithAssociatedJudge.test.ts index 8d0a21f87e9..3f66e82b0dd 100644 --- a/shared/src/business/entities/cases/Case.removeFromTrialWithAssociatedJudge.test.ts +++ b/shared/src/business/entities/cases/Case.removeFromTrialWithAssociatedJudge.test.ts @@ -2,7 +2,7 @@ import { CASE_STATUS_TYPES } from '../EntityConstants'; import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; import { TrialSession } from '../trialSessions/TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('removeFromTrialWithAssociatedJudge', () => { it('removes the case from trial, updating the associated judge if one is passed in', () => { @@ -11,22 +11,19 @@ describe('removeFromTrialWithAssociatedJudge', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); - const trialSession = new TrialSession( - { - isCalendared: true, - judge: { name: 'Judge Buch', userId: 'buch_id' }, - maxCases: 100, - sessionType: 'Regular', - startDate: '2025-03-01T00:00:00.000Z', - term: 'Fall', - termYear: '2025', - trialLocation: 'Birmingham, Alabama', - }, - { applicationContext }, - ); + const trialSession = new TrialSession({ + isCalendared: true, + judge: { name: 'Judge Buch', userId: 'buch_id' }, + maxCases: 100, + sessionType: 'Regular', + startDate: '2025-03-01T00:00:00.000Z', + term: 'Fall', + termYear: '2025', + trialLocation: 'Birmingham, Alabama', + }); caseToUpdate.setAsCalendared(trialSession); expect(caseToUpdate.status).toEqual(CASE_STATUS_TYPES.calendared); @@ -56,22 +53,19 @@ describe('removeFromTrialWithAssociatedJudge', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); - const trialSession = new TrialSession( - { - isCalendared: true, - judge: { name: 'Judge Buch', userId: 'buch-id' }, - maxCases: 100, - sessionType: 'Regular', - startDate: '2025-03-01T00:00:00.000Z', - term: 'Fall', - termYear: '2025', - trialLocation: 'Birmingham, Alabama', - }, - { applicationContext }, - ); + const trialSession = new TrialSession({ + isCalendared: true, + judge: { name: 'Judge Buch', userId: 'buch-id' }, + maxCases: 100, + sessionType: 'Regular', + startDate: '2025-03-01T00:00:00.000Z', + term: 'Fall', + termYear: '2025', + trialLocation: 'Birmingham, Alabama', + }); caseToUpdate.setAsCalendared(trialSession); expect(caseToUpdate.status).toEqual(CASE_STATUS_TYPES.calendared); diff --git a/shared/src/business/entities/cases/Case.removeIrsPractitioner.test.ts b/shared/src/business/entities/cases/Case.removeIrsPractitioner.test.ts index 2949a1cb00e..4bb76e28c24 100644 --- a/shared/src/business/entities/cases/Case.removeIrsPractitioner.test.ts +++ b/shared/src/business/entities/cases/Case.removeIrsPractitioner.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { IrsPractitioner } from '../IrsPractitioner'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('removeIrsPractitioner', () => { it('does not remove a practitioner if not found in irsPractitioners array', () => { @@ -13,7 +13,7 @@ describe('removeIrsPractitioner', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -33,7 +33,7 @@ describe('removeIrsPractitioner', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.removePetitioner.test.ts b/shared/src/business/entities/cases/Case.removePetitioner.test.ts index 7b90cdf5e96..30cf26d6b22 100644 --- a/shared/src/business/entities/cases/Case.removePetitioner.test.ts +++ b/shared/src/business/entities/cases/Case.removePetitioner.test.ts @@ -1,10 +1,12 @@ import { Case, getContactPrimary } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockAdmissionsClerkUser } from '@shared/test/mockAuthUsers'; describe('removePetitioner', () => { it('should remove the petitioner by contactId from the petitioners array', () => { - const caseEntity = new Case(MOCK_CASE, { applicationContext }); + const caseEntity = new Case(MOCK_CASE, { + authorizedUser: mockAdmissionsClerkUser, + }); const numberOfPetitionersOnCase = caseEntity.petitioners.length; expect(caseEntity.petitioners.length).toEqual(numberOfPetitionersOnCase); diff --git a/shared/src/business/entities/cases/Case.removePrivatePractitioner.test.ts b/shared/src/business/entities/cases/Case.removePrivatePractitioner.test.ts index 9ee30840187..53324d8b77e 100644 --- a/shared/src/business/entities/cases/Case.removePrivatePractitioner.test.ts +++ b/shared/src/business/entities/cases/Case.removePrivatePractitioner.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { PrivatePractitioner } from '../PrivatePractitioner'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockAdmissionsClerkUser } from '@shared/test/mockAuthUsers'; describe('removePrivatePractitioner', () => { it('does not remove a practitioner if not found in the associated case privatePractioners array', () => { @@ -13,7 +13,7 @@ describe('removePrivatePractitioner', () => { ], }, { - applicationContext, + authorizedUser: mockAdmissionsClerkUser, }, ); @@ -34,7 +34,7 @@ describe('removePrivatePractitioner', () => { ], }, { - applicationContext, + authorizedUser: mockAdmissionsClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.removeRepresentingFromPractitioners.test.ts b/shared/src/business/entities/cases/Case.removeRepresentingFromPractitioners.test.ts index 7cc46975fc6..1d7ebb92b1f 100644 --- a/shared/src/business/entities/cases/Case.removeRepresentingFromPractitioners.test.ts +++ b/shared/src/business/entities/cases/Case.removeRepresentingFromPractitioners.test.ts @@ -1,5 +1,5 @@ import { Case } from './Case'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockAdmissionsClerkUser } from '@shared/test/mockAuthUsers'; describe('removeRepresentingFromPractitioners', () => { it('does not remove a practitioner if not found in the associated case privatePractioners array', () => { @@ -18,7 +18,7 @@ describe('removeRepresentingFromPractitioners', () => { ], }, { - applicationContext, + authorizedUser: mockAdmissionsClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.setAdditionalNameOnPetitioners.test.ts b/shared/src/business/entities/cases/Case.setAdditionalNameOnPetitioners.test.ts index 6c064579d9f..75834b3554d 100644 --- a/shared/src/business/entities/cases/Case.setAdditionalNameOnPetitioners.test.ts +++ b/shared/src/business/entities/cases/Case.setAdditionalNameOnPetitioners.test.ts @@ -2,11 +2,10 @@ import { CASE_STATUS_TYPES, CONTACT_TYPES, PARTY_TYPES, - ROLES, } from '../EntityConstants'; import { Case, getContactPrimary } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('setAdditionalNameOnPetitioners', () => { const mockSecondaryName = 'Test Secondary Name'; @@ -24,12 +23,6 @@ describe('setAdditionalNameOnPetitioners', () => { PARTY_TYPES.trust, ]; - beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - }); - }); - partyTypesWithSecondaryName.forEach(partyType => { it(`should set additionalName as secondaryName when party type is ${partyType}`, () => { const myCase = new Case( @@ -45,7 +38,7 @@ describe('setAdditionalNameOnPetitioners', () => { ], status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.petitioners[0].additionalName).toBe(mockSecondaryName); @@ -67,7 +60,7 @@ describe('setAdditionalNameOnPetitioners', () => { ], status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.petitioners[0].additionalName).toBe( @@ -90,7 +83,7 @@ describe('setAdditionalNameOnPetitioners', () => { ], status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.petitioners[0].additionalName).toBe(mockSecondaryName); @@ -111,7 +104,7 @@ describe('setAdditionalNameOnPetitioners', () => { ], status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.petitioners[0].additionalName).toEqual(''); @@ -131,7 +124,7 @@ describe('setAdditionalNameOnPetitioners', () => { ], status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.petitioners[0].additionalName).toBe(`c/o ${mockInCareOf}`); @@ -151,7 +144,7 @@ describe('setAdditionalNameOnPetitioners', () => { ], status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.petitioners[0].additionalName).toBe(mockSecondaryName); @@ -171,7 +164,7 @@ describe('setAdditionalNameOnPetitioners', () => { ], status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.petitioners[0].additionalName).toBe(mockSecondaryName); @@ -191,7 +184,7 @@ describe('setAdditionalNameOnPetitioners', () => { ], status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.petitioners[0].additionalName).toBe(`c/o ${mockInCareOf}`); @@ -211,7 +204,7 @@ describe('setAdditionalNameOnPetitioners', () => { ], status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.petitioners[0].additionalName).toBe(`c/o ${mockInCareOf}`); @@ -234,7 +227,7 @@ describe('setAdditionalNameOnPetitioners', () => { ], status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.petitioners[0].additionalName).toBe( diff --git a/shared/src/business/entities/cases/Case.setAsBlocked.test.ts b/shared/src/business/entities/cases/Case.setAsBlocked.test.ts index 3e5a09e1229..769283469ba 100644 --- a/shared/src/business/entities/cases/Case.setAsBlocked.test.ts +++ b/shared/src/business/entities/cases/Case.setAsBlocked.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('setAsBlocked', () => { it('sets the case as blocked with a blocked reason', () => { @@ -9,7 +9,7 @@ describe('setAsBlocked', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.setAsCalendared.test.ts b/shared/src/business/entities/cases/Case.setAsCalendared.test.ts index f40dce69d33..797b07e18f4 100644 --- a/shared/src/business/entities/cases/Case.setAsCalendared.test.ts +++ b/shared/src/business/entities/cases/Case.setAsCalendared.test.ts @@ -2,12 +2,12 @@ import { CASE_STATUS_TYPES, CHIEF_JUDGE } from '../EntityConstants'; import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; import { TrialSession } from '../trialSessions/TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('setAsCalendared', () => { it('should set case as calendared with only judge and trialSessionId if the trial session is calendared', () => { const myCase = new Case(MOCK_CASE, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); myCase.setAsCalendared({ isCalendared: true, @@ -26,22 +26,19 @@ describe('setAsCalendared', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); - const trialSession = new TrialSession( - { - isCalendared: true, - judge: { name: 'Judge Buch', userId: 'buch-id' }, - maxCases: 100, - sessionType: 'Regular', - startDate: '2025-03-01T00:00:00.000Z', - term: 'Fall', - termYear: '2025', - trialLocation: 'Birmingham, Alabama', - }, - { applicationContext }, - ); + const trialSession = new TrialSession({ + isCalendared: true, + judge: { name: 'Judge Buch', userId: 'buch-id' }, + maxCases: 100, + sessionType: 'Regular', + startDate: '2025-03-01T00:00:00.000Z', + term: 'Fall', + termYear: '2025', + trialLocation: 'Birmingham, Alabama', + }); myCase.setAsCalendared(trialSession); expect(myCase.status).toEqual(CASE_STATUS_TYPES.calendared); @@ -59,22 +56,19 @@ describe('setAsCalendared', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); - const trialSession = new TrialSession( - { - isCalendared: false, - judge: { name: 'Judge Buch', userId: 'buch-id' }, - maxCases: 100, - sessionType: 'Regular', - startDate: '2025-03-01T00:00:00.000Z', - term: 'Fall', - termYear: '2025', - trialLocation: 'Birmingham, Alabama', - }, - { applicationContext }, - ); + const trialSession = new TrialSession({ + isCalendared: false, + judge: { name: 'Judge Buch', userId: 'buch-id' }, + maxCases: 100, + sessionType: 'Regular', + startDate: '2025-03-01T00:00:00.000Z', + term: 'Fall', + termYear: '2025', + trialLocation: 'Birmingham, Alabama', + }); myCase.setAsCalendared(trialSession); expect(myCase.status).toEqual(CASE_STATUS_TYPES.new); diff --git a/shared/src/business/entities/cases/Case.setAsHighPriority.test.ts b/shared/src/business/entities/cases/Case.setAsHighPriority.test.ts index 8681723bc25..744731c35c5 100644 --- a/shared/src/business/entities/cases/Case.setAsHighPriority.test.ts +++ b/shared/src/business/entities/cases/Case.setAsHighPriority.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('setAsHighPriority', () => { it('sets the case as high priority with a high priority reason', () => { @@ -9,7 +9,7 @@ describe('setAsHighPriority', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.setAsUnsealed.test.ts b/shared/src/business/entities/cases/Case.setAsUnsealed.test.ts index 41e666af182..edcfbb5737e 100644 --- a/shared/src/business/entities/cases/Case.setAsUnsealed.test.ts +++ b/shared/src/business/entities/cases/Case.setAsUnsealed.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('setAsUnsealed', () => { it('should set isSealed to false and sealedDate to undefined', () => { @@ -9,7 +9,7 @@ describe('setAsUnsealed', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.setCaseCaption.test.ts b/shared/src/business/entities/cases/Case.setCaseCaption.test.ts index 7c8f03aa283..a89a0667076 100644 --- a/shared/src/business/entities/cases/Case.setCaseCaption.test.ts +++ b/shared/src/business/entities/cases/Case.setCaseCaption.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('setCaseCaption', () => { it('should set the case caption and update the case title', () => { @@ -9,7 +9,7 @@ describe('setCaseCaption', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.setCaseStatus.test.ts b/shared/src/business/entities/cases/Case.setCaseStatus.test.ts index 9c1ee103e15..ce2e3a2a5e7 100644 --- a/shared/src/business/entities/cases/Case.setCaseStatus.test.ts +++ b/shared/src/business/entities/cases/Case.setCaseStatus.test.ts @@ -5,8 +5,8 @@ import { } from '../EntityConstants'; import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; import { createISODateString } from '../../utilities/DateHandler'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; jest.mock('../../utilities/DateHandler', () => { const originalModule = jest.requireActual('../../utilities/DateHandler'); @@ -27,7 +27,7 @@ describe('setCaseStatus', () => { associatedJudgeId: 'judge_user_id', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -49,7 +49,7 @@ describe('setCaseStatus', () => { associatedJudgeId: 'judge_user_id', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -73,7 +73,7 @@ describe('setCaseStatus', () => { associatedJudgeId: 'judge_user_id', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -95,7 +95,7 @@ describe('setCaseStatus', () => { associatedJudgeId: 'judge_user_id', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -117,7 +117,7 @@ describe('setCaseStatus', () => { status: CLOSED_CASE_STATUSES[0], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -139,7 +139,7 @@ describe('setCaseStatus', () => { status: CLOSED_CASE_STATUSES[0], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.setLeadCase.test.ts b/shared/src/business/entities/cases/Case.setLeadCase.test.ts index 2ed31bf7566..afa7f4f84eb 100644 --- a/shared/src/business/entities/cases/Case.setLeadCase.test.ts +++ b/shared/src/business/entities/cases/Case.setLeadCase.test.ts @@ -1,7 +1,7 @@ import { CASE_STATUS_TYPES } from '../EntityConstants'; import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('setLeadCase', () => { it('Should set the leadDocketNumber on the given case', () => { @@ -13,7 +13,7 @@ describe('setLeadCase', () => { procedureType: 'Regular', status: CASE_STATUS_TYPES.submitted, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); const result = caseEntity.setLeadCase(leadDocketNumber); diff --git a/shared/src/business/entities/cases/Case.setNoticeOfTrialDate.test.ts b/shared/src/business/entities/cases/Case.setNoticeOfTrialDate.test.ts index f5623c8eaae..73d558d59ee 100644 --- a/shared/src/business/entities/cases/Case.setNoticeOfTrialDate.test.ts +++ b/shared/src/business/entities/cases/Case.setNoticeOfTrialDate.test.ts @@ -1,26 +1,27 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { createISODateString } from '@shared/business/utilities/DateHandler'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('setNoticeOfTrialDate', () => { it('should set noticeOfTrialDate on the given case', () => { - const caseEntity = new Case(MOCK_CASE, { applicationContext }); + const caseEntity = new Case(MOCK_CASE, { + authorizedUser: mockDocketClerkUser, + }); const result = caseEntity.setNoticeOfTrialDate(); expect(result.isValid()).toBeTruthy(); }); it('should set noticeOfTrialDate when passed through Case constructor', () => { - const isoDateString = applicationContext - .getUtilities() - .createISODateString(); + const isoDateString = createISODateString(); const caseEntity = new Case( { ...MOCK_CASE, noticeOfTrialDate: isoDateString, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(caseEntity.isValid()).toBeTruthy(); diff --git a/shared/src/business/entities/cases/Case.setQcCompleteForTrial.test.ts b/shared/src/business/entities/cases/Case.setQcCompleteForTrial.test.ts index e92fe0ad000..dbf51768870 100644 --- a/shared/src/business/entities/cases/Case.setQcCompleteForTrial.test.ts +++ b/shared/src/business/entities/cases/Case.setQcCompleteForTrial.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('setQcCompleteForTrial', () => { it('should set qcCompleteForTrial on the given case for the given trial session id', () => { @@ -9,7 +9,7 @@ describe('setQcCompleteForTrial', () => { ...MOCK_CASE, qcCompleteForTrial: { 'd6fdd6e7-8dfa-463a-8a17-ed4512d1a68d': false }, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); const result = caseEntity.setQcCompleteForTrial({ qcCompleteForTrial: true, @@ -28,7 +28,7 @@ describe('setQcCompleteForTrial', () => { { ...MOCK_CASE, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(caseEntity.isValid()).toBeTruthy(); @@ -41,7 +41,7 @@ describe('setQcCompleteForTrial', () => { ...MOCK_CASE, qcCompleteForTrial: { '80950eee-7efd-4374-a642-65a8262135ab': true }, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(caseEntity.isValid()).toBeTruthy(); diff --git a/shared/src/business/entities/cases/Case.shouldGenerateNoticesForCase.test.ts b/shared/src/business/entities/cases/Case.shouldGenerateNoticesForCase.test.ts index a6505a6fd49..52dbaab8d74 100644 --- a/shared/src/business/entities/cases/Case.shouldGenerateNoticesForCase.test.ts +++ b/shared/src/business/entities/cases/Case.shouldGenerateNoticesForCase.test.ts @@ -1,8 +1,8 @@ import { CASE_STATUS_TYPES } from '../EntityConstants'; import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; import { calculateISODate } from '../../utilities/DateHandler'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('shouldGenerateNoticesForCase', () => { it('checks if the case is eligible for service (true)', () => { @@ -12,7 +12,7 @@ describe('shouldGenerateNoticesForCase', () => { status: CASE_STATUS_TYPES.generalDocket, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -26,7 +26,7 @@ describe('shouldGenerateNoticesForCase', () => { status: CASE_STATUS_TYPES.new, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -41,7 +41,7 @@ describe('shouldGenerateNoticesForCase', () => { status: CASE_STATUS_TYPES.closed, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -59,7 +59,7 @@ describe('shouldGenerateNoticesForCase', () => { status: CASE_STATUS_TYPES.closed, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.test.ts b/shared/src/business/entities/cases/Case.test.ts index 69b2737ffe3..1933bc1d3e3 100644 --- a/shared/src/business/entities/cases/Case.test.ts +++ b/shared/src/business/entities/cases/Case.test.ts @@ -10,23 +10,20 @@ import { OTHER_FILER_TYPES, PARTY_TYPES, PAYMENT_STATUS, - ROLES, SERVICE_INDICATOR_TYPES, UNIQUE_OTHER_FILER_TYPE, } from '../EntityConstants'; import { Case, getContactPrimary } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; import { MOCK_DOCUMENTS } from '../../../test/mockDocketEntry'; -import { applicationContext } from '../../test/createTestApplicationContext'; import { createISODateString } from '../../utilities/DateHandler'; import { - docketClerkUser, - irsSuperuserUser, - petitionerUser, - petitionsClerkUser, - privatePractitionerUser, -} from '../../../test/mockUsers'; -import { mockPetitionerUser } from '@shared/test/mockAuthUsers'; + mockDocketClerkUser, + mockIrsSuperuser, + mockPetitionerUser, + mockPetitionsClerkUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; jest.mock('../../utilities/DateHandler', () => { const originalModule = jest.requireActual('../../utilities/DateHandler'); @@ -40,19 +37,18 @@ jest.mock('../../utilities/DateHandler', () => { describe('Case entity', () => { describe('init', () => { it('should add case status information including the internal users NAME to the `caseStatusHistory` if a new case is created by an internal user', () => { - applicationContext.getCurrentUser.mockReturnValueOnce(docketClerkUser); const mockCreateIsoDateString = createISODateString as jest.Mock; mockCreateIsoDateString.mockReturnValue('2019-08-25T05:00:00.000Z'); const expectedCaseStatus = { - changedBy: docketClerkUser.name, + changedBy: mockDocketClerkUser.name, date: createISODateString(), updatedCaseStatus: CASE_STATUS_TYPES.new, }; const myCase = new Case( { ...MOCK_CASE, isPaper: true, status: undefined }, { - applicationContext, + authorizedUser: mockDocketClerkUser, isNewCase: true, }, ); @@ -63,7 +59,6 @@ describe('Case entity', () => { }); it('should add case status information including the petitioners ROLE to the `caseStatusHistory` if a new case is created by an petitioner', () => { - applicationContext.getCurrentUser.mockReturnValueOnce(petitionerUser); const mockCreateIsoDateString = createISODateString as jest.Mock; mockCreateIsoDateString.mockReturnValue('2019-08-25T05:00:00.000Z'); @@ -75,7 +70,7 @@ describe('Case entity', () => { const myCase = new Case( { ...MOCK_CASE, isPaper: false, status: undefined }, { - applicationContext, + authorizedUser: mockPetitionerUser, isNewCase: true, }, ); @@ -97,7 +92,6 @@ describe('Case entity', () => { const myCase = new Case( { ...MOCK_CASE, isPaper: false, status: undefined }, { - applicationContext, authorizedUser: mockPetitionerUser, isNewCase: true, }, @@ -109,9 +103,6 @@ describe('Case entity', () => { }); it('should add case status information including a private practitioners ROLE to the `caseStatusHistory` if a new case is created by an private practitioners', () => { - applicationContext.getCurrentUser.mockReturnValueOnce( - privatePractitionerUser, - ); const mockCreateIsoDateString = createISODateString as jest.Mock; mockCreateIsoDateString.mockReturnValue('2019-08-25T05:00:00.000Z'); @@ -123,7 +114,7 @@ describe('Case entity', () => { const myCase = new Case( { ...MOCK_CASE, isPaper: false, status: undefined }, { - applicationContext, + authorizedUser: mockPrivatePractitionerUser, isNewCase: true, }, ); @@ -133,12 +124,9 @@ describe('Case entity', () => { }); }); }); - it('should throw an error if app context is not passed in', () => { - expect(() => new Case({}, {} as any)).toThrow(); - }); it('defaults the orders to false', () => { - const myCase = new Case(MOCK_CASE, { applicationContext }); + const myCase = new Case(MOCK_CASE, { authorizedUser: mockDocketClerkUser }); expect(myCase).toMatchObject({ isSealed: false, @@ -167,7 +155,7 @@ describe('Case entity', () => { orderToShowCause: true, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -192,7 +180,7 @@ describe('Case entity', () => { { filingDate: '2019-01-05T01:02:03.004Z' }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.correspondence).toMatchObject([ @@ -215,7 +203,7 @@ describe('Case entity', () => { ], status: CASE_STATUS_TYPES.new, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.petitioners[0].additionalName).toBeUndefined(); @@ -240,7 +228,7 @@ describe('Case entity', () => { ], status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.petitioners[0].additionalName).toBeDefined(); @@ -273,7 +261,7 @@ describe('Case entity', () => { ...MOCK_CASE, hearings: [mockhearing1, mockhearing2, mockhearing3], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(newCase.hearings[0].createdAt).toEqual(mockhearing2.createdAt); @@ -286,7 +274,7 @@ describe('Case entity', () => { { ...MOCK_CASE, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(newCase.hearings).toEqual([]); @@ -295,8 +283,6 @@ describe('Case entity', () => { describe('filtered', () => { it('does not return private data if filtered is true and the user is external', () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - const myCase = new Case( { ...MOCK_CASE, @@ -305,7 +291,7 @@ describe('Case entity', () => { associatedJudgeId: 'CHIEF_JUDGE_ID', }, { - applicationContext, + authorizedUser: mockPetitionerUser, filtered: true, }, ); @@ -316,8 +302,6 @@ describe('Case entity', () => { }); it('returns private data if filtered is true and the user is internal', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const myCase = new Case( { ...MOCK_CASE, @@ -326,7 +310,7 @@ describe('Case entity', () => { associatedJudgeId: 'CHIEF_JUDGE_ID', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, filtered: true, }, ); @@ -337,8 +321,6 @@ describe('Case entity', () => { }); it('returns private data if filtered is false and the user is external', () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - const myCase = new Case( { ...MOCK_CASE, @@ -346,7 +328,7 @@ describe('Case entity', () => { associatedJudgeId: 'CHIEF_JUDGE_ID', }, { - applicationContext, + authorizedUser: mockPetitionerUser, filtered: false, }, ); @@ -356,8 +338,6 @@ describe('Case entity', () => { }); it('returns private data if filtered is false and the user is internal', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const myCase = new Case( { ...MOCK_CASE, @@ -365,7 +345,7 @@ describe('Case entity', () => { associatedJudgeId: 'CHIEF_JUDGE_ID', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, filtered: false, }, ); @@ -375,12 +355,10 @@ describe('Case entity', () => { }); it('returns STIN docket entry if filtered is false and the user is docketclerk', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const myCase = new Case( { ...MOCK_CASE }, { - applicationContext, + authorizedUser: mockDocketClerkUser, filtered: false, }, ); @@ -392,12 +370,10 @@ describe('Case entity', () => { }); it('returns STIN docket entry if filtered is true and the user is IRS superuser', () => { - applicationContext.getCurrentUser.mockReturnValue(irsSuperuserUser); - const myCase = new Case( { ...MOCK_CASE }, { - applicationContext, + authorizedUser: mockIrsSuperuser, filtered: true, }, ); @@ -409,12 +385,10 @@ describe('Case entity', () => { }); it('returns STIN docket entry if filtered is true and the user is petitionsclerk and the petition is not served', () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - const myCase = new Case( { ...MOCK_CASE }, { - applicationContext, + authorizedUser: mockPetitionsClerkUser, filtered: true, }, ); @@ -426,12 +400,10 @@ describe('Case entity', () => { }); it('does not return STIN docket entry if filtered is true and the user is docketclerk and the petition is not served', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const myCase = new Case( { ...MOCK_CASE }, { - applicationContext, + authorizedUser: mockDocketClerkUser, filtered: true, }, ); @@ -443,8 +415,6 @@ describe('Case entity', () => { }); it('does not return STIN docket entry if filtered is true and the user is petitionsclerk and the petition is served', () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - const myCase = new Case( { ...MOCK_CASE, @@ -471,7 +441,7 @@ describe('Case entity', () => { ], }, { - applicationContext, + authorizedUser: mockPetitionsClerkUser, filtered: true, }, ); @@ -524,7 +494,7 @@ describe('Case entity', () => { status: CASE_STATUS_TYPES.generalDocket, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -544,7 +514,7 @@ describe('Case entity', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -553,16 +523,13 @@ describe('Case entity', () => { }); it('creates a valid case without a petition docket entry and does not throw an error', () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - }); const myCase = new Case( { ...MOCK_CASE, docketEntries: [MOCK_CASE.docketEntries[1]], }, { - applicationContext, + authorizedUser: mockPetitionsClerkUser, filtered: true, }, ); @@ -572,7 +539,7 @@ describe('Case entity', () => { it('Creates a valid case from an already existing case json', () => { const myCase = new Case(MOCK_CASE, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(myCase.getFormattedValidationErrors()).toEqual(null); @@ -582,7 +549,7 @@ describe('Case entity', () => { const myCase = new Case( { ...MOCK_CASE, docketNumber: '00101-20' }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -598,7 +565,7 @@ describe('Case entity', () => { trialSessionId: undefined, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -615,7 +582,7 @@ describe('Case entity', () => { petitioners: [{}], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -634,7 +601,7 @@ describe('Case entity', () => { petitioners: [{ name: 'Test Petitioner' }], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -647,7 +614,7 @@ describe('Case entity', () => { docketEntries: [], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -658,7 +625,7 @@ describe('Case entity', () => { const myCase = new Case( {}, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -671,7 +638,7 @@ describe('Case entity', () => { petitioners: [], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -699,7 +666,7 @@ describe('Case entity', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -720,7 +687,7 @@ describe('Case entity', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -734,7 +701,7 @@ describe('Case entity', () => { trialTime: '91:30', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -748,7 +715,7 @@ describe('Case entity', () => { blocked: true, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -763,7 +730,7 @@ describe('Case entity', () => { blockedDate: '2019-03-01T21:42:29.073Z', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -779,7 +746,7 @@ describe('Case entity', () => { blockedReason: 'something', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); expect(myCase.isValid()).toBeFalsy(); @@ -792,7 +759,7 @@ describe('Case entity', () => { blocked: false, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -808,7 +775,7 @@ describe('Case entity', () => { blockedReason: 'something', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -822,7 +789,7 @@ describe('Case entity', () => { trialTime: '9:30', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -838,7 +805,7 @@ describe('Case entity', () => { automaticBlockedReason: AUTOMATIC_BLOCKED_REASONS.pending, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -854,7 +821,7 @@ describe('Case entity', () => { automaticBlockedReason: 'Some Other Reason Not Valid', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -868,7 +835,7 @@ describe('Case entity', () => { highPriority: true, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -883,7 +850,7 @@ describe('Case entity', () => { highPriorityReason: 'something', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -897,7 +864,7 @@ describe('Case entity', () => { status: CASE_STATUS_TYPES.closed, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -914,7 +881,7 @@ describe('Case entity', () => { status: CASE_STATUS_TYPES.closedDismissed, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -932,7 +899,7 @@ describe('Case entity', () => { status: CASE_STATUS_TYPES.closed, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -946,7 +913,7 @@ describe('Case entity', () => { sealedDate: '2019-09-19T16:42:00.000Z', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -961,7 +928,7 @@ describe('Case entity', () => { petitionPaymentStatus: PAYMENT_STATUS.PAID, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -978,7 +945,7 @@ describe('Case entity', () => { petitionPaymentStatus: PAYMENT_STATUS.WAIVED, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -997,7 +964,7 @@ describe('Case entity', () => { petitionPaymentStatus: PAYMENT_STATUS.PAID, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -1014,7 +981,7 @@ describe('Case entity', () => { petitionPaymentWaivedDate: '2050-10-01T21:40:46.415Z', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -1028,7 +995,7 @@ describe('Case entity', () => { it('should do nothing if valid', () => { expect(() => new Case(MOCK_CASE, { - applicationContext, + authorizedUser: mockDocketClerkUser, }).validate(), ).not.toThrow(); }); @@ -1038,7 +1005,7 @@ describe('Case entity', () => { new Case( {}, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ).validate(), ).toThrow(); @@ -1052,7 +1019,7 @@ describe('Case entity', () => { petitioners: [], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -1091,7 +1058,7 @@ describe('Case entity', () => { petitioners: [], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -1121,7 +1088,7 @@ describe('Case entity', () => { consolidatedCases: [invalidConsolidatedCase], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -1137,7 +1104,7 @@ describe('Case entity', () => { associatedJudgeId: undefined, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -1153,7 +1120,7 @@ describe('Case entity', () => { associatedJudgeId: undefined, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -1169,7 +1136,7 @@ describe('Case entity', () => { associatedJudgeId: 'dabbad02-18d0-43ec-bafb-654e83405416', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -1185,7 +1152,7 @@ describe('Case entity', () => { associatedJudgeId: 'uuid', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -1202,7 +1169,7 @@ describe('Case entity', () => { associatedJudgeId: undefined, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -1219,7 +1186,9 @@ describe('Case entity', () => { ...MOCK_CASE, trialSessionId: '0762e545-8cbc-4a18-ab7a-27d205c83f60', }; - const myCase = new Case(blockedCalendaredCase, { applicationContext }); + const myCase = new Case(blockedCalendaredCase, { + authorizedUser: mockDocketClerkUser, + }); expect(myCase.getFormattedValidationErrors()).toEqual({ trialDate: '"trialDate" is required', }); @@ -1231,7 +1200,9 @@ describe('Case entity', () => { status: CASE_STATUS_TYPES.calendared, trialDate: '2019-03-01T21:40:46.415Z', }; - const myCase = new Case(blockedCalendaredCase, { applicationContext }); + const myCase = new Case(blockedCalendaredCase, { + authorizedUser: mockDocketClerkUser, + }); expect(myCase.getFormattedValidationErrors()).toEqual({ trialSessionId: '"trialSessionId" is required', }); @@ -1244,7 +1215,9 @@ describe('Case entity', () => { trialDate: undefined, trialSessionId: undefined, }; - const myCase = new Case(blockedCalendaredCase, { applicationContext }); + const myCase = new Case(blockedCalendaredCase, { + authorizedUser: mockDocketClerkUser, + }); expect(myCase.getFormattedValidationErrors()).toBe(null); }); @@ -1255,7 +1228,9 @@ describe('Case entity', () => { trialDate: '2019-03-01T21:40:46.415Z', trialSessionId: '0762e545-8cbc-4a18-ab7a-27d205c83f60', }; - const myCase = new Case(blockedCalendaredCase, { applicationContext }); + const myCase = new Case(blockedCalendaredCase, { + authorizedUser: mockDocketClerkUser, + }); expect(myCase.getFormattedValidationErrors()).toBe(null); }); }); @@ -1264,7 +1239,7 @@ describe('Case entity', () => { const myCase = new Case( {}, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -1288,7 +1263,7 @@ describe('Case entity', () => { statistics: [], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -1305,7 +1280,7 @@ describe('Case entity', () => { hasVerifiedIrsNotice: false, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -1320,7 +1295,7 @@ describe('Case entity', () => { hasVerifiedIrsNotice: true, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -1330,7 +1305,10 @@ describe('Case entity', () => { describe('secondary contact', () => { it('does not create a secondary contact when one is not needed by the party type', () => { - const myCase = new Case({ ...MOCK_CASE }, { applicationContext }); + const myCase = new Case( + { ...MOCK_CASE }, + { authorizedUser: mockDocketClerkUser }, + ); expect(myCase.getContactSecondary()).toBeUndefined(); }); @@ -1341,7 +1319,7 @@ describe('Case entity', () => { ...MOCK_CASE, partyType: PARTY_TYPES.petitionerSpouse, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.getFormattedValidationErrors()).toMatchObject({ @@ -1369,7 +1347,7 @@ describe('Case entity', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase.getFormattedValidationErrors()).toMatchObject({ @@ -1389,7 +1367,7 @@ describe('Case entity', () => { const myCase = new Case( { ...MOCK_CASE, judgeUserId: mockJudgeUserId }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(myCase).toMatchObject({ @@ -1399,7 +1377,9 @@ describe('Case entity', () => { }); it('does not fail validation without a judgeUserId', () => { - const myCase = new Case(MOCK_CASE, { applicationContext }); + const myCase = new Case(MOCK_CASE, { + authorizedUser: mockDocketClerkUser, + }); expect(myCase.judgeUserId).toBeUndefined(); expect(myCase.getFormattedValidationErrors()).toEqual(null); @@ -1420,7 +1400,9 @@ describe('Case entity', () => { trialSessionId: mockTrialSessionId, }; - const myCase = new Case(blockedCalendaredCase, { applicationContext }); + const myCase = new Case(blockedCalendaredCase, { + authorizedUser: mockDocketClerkUser, + }); expect(myCase.getFormattedValidationErrors()).toEqual({ blocked: '"blocked" contains an invalid value', @@ -1436,7 +1418,9 @@ describe('Case entity', () => { trialSessionId: mockTrialSessionId, }; - const myCase = new Case(calendaredCase, { applicationContext }); + const myCase = new Case(calendaredCase, { + authorizedUser: mockDocketClerkUser, + }); expect(myCase.getFormattedValidationErrors()).toBe(null); }); @@ -1453,7 +1437,7 @@ describe('Case entity', () => { }; const myCase = new Case(blockedReadyForTrialCase, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(myCase.getFormattedValidationErrors()).toBe(null); diff --git a/shared/src/business/entities/cases/Case.toRawObject.test.ts b/shared/src/business/entities/cases/Case.toRawObject.test.ts index 0bac37bd23b..cacf6c28280 100644 --- a/shared/src/business/entities/cases/Case.toRawObject.test.ts +++ b/shared/src/business/entities/cases/Case.toRawObject.test.ts @@ -1,5 +1,5 @@ import { Case } from './Case'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('toRawObject', () => { beforeEach(() => { @@ -11,7 +11,7 @@ describe('toRawObject', () => { }); it('calls own function to update values after decorated toRawObject', () => { - const myCase = new Case({}, { applicationContext }); + const myCase = new Case({}, { authorizedUser: mockDocketClerkUser }); const result = myCase.toRawObject(); @@ -20,7 +20,7 @@ describe('toRawObject', () => { }); it('does not call own function to update values if flag is set to false after decorated toRawObject', () => { - const myCase = new Case({}, { applicationContext }); + const myCase = new Case({}, { authorizedUser: mockDocketClerkUser }); const result = myCase.toRawObject(false); expect(Case.prototype.doesHavePendingItems).not.toHaveBeenCalled(); diff --git a/shared/src/business/entities/cases/Case.ts b/shared/src/business/entities/cases/Case.ts index 545a9255d06..635f4d9e7f0 100644 --- a/shared/src/business/entities/cases/Case.ts +++ b/shared/src/business/entities/cases/Case.ts @@ -27,6 +27,10 @@ import { TRIAL_CITY_STRINGS, TRIAL_LOCATION_MATCHER, } from '../EntityConstants'; +import { + AuthUser, + UnknownAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; import { CASE_CAPTION_RULE, CASE_DOCKET_NUMBER_RULE, @@ -64,7 +68,6 @@ import { PrivatePractitioner } from '../PrivatePractitioner'; import { PublicCase } from '@shared/business/entities/cases/PublicCase'; import { Statistic } from '../Statistic'; import { TrialSession } from '../trialSessions/TrialSession'; -import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { UnprocessableEntityError } from '../../../../../web-api/src/errors/errors'; import { User } from '../User'; import { clone, compact, includes, isEmpty, startCase } from 'lodash'; @@ -149,47 +152,50 @@ export class Case extends JoiValidationEntity { constructor( rawCase: any, { - applicationContext, authorizedUser, filtered = false, isNewCase = false, }: { - applicationContext: IApplicationContext; - authorizedUser?: UnknownAuthUser; + authorizedUser: UnknownAuthUser; filtered?: boolean; isNewCase?: boolean; }, ) { super('Case'); - if (!applicationContext) { - throw new TypeError('applicationContext must be defined'); - } - this.petitioners = []; this.correspondence = []; - const currentUser = authorizedUser || applicationContext.getCurrentUser(); - if (!filtered || User.isInternalUser(currentUser.role)) { + if (!filtered || User.isInternalUser(authorizedUser?.role)) { this.assignFieldsForInternalUsers({ - applicationContext, + authorizedUser, rawCase, }); } - const params = { applicationContext, authorizedUser, filtered, rawCase }; - // assignContacts needs to come first before assignDocketEntries this.assignConsolidatedCases({ rawCase }); - this.assignContacts(params); - this.assignDocketEntries(params); - this.assignHearings(params); - this.assignPractitioners(params); - this.assignFieldsForAllUsers(params); + this.assignContacts({ + rawCase, + }); + this.assignDocketEntries({ + authorizedUser, + filtered, + rawCase, + }); + this.assignHearings({ + rawCase, + }); + this.assignPractitioners({ + rawCase, + }); + this.assignFieldsForAllUsers({ + rawCase, + }); if (isNewCase) { const changedBy = rawCase.isPaper - ? currentUser.name - : startCase(currentUser.role); + ? authorizedUser?.name + : startCase(authorizedUser?.role); this.setCaseStatus({ changedBy, @@ -294,7 +300,13 @@ export class Case extends JoiValidationEntity { ); } - assignFieldsForInternalUsers({ applicationContext, rawCase }) { + private assignFieldsForInternalUsers({ + authorizedUser, + rawCase, + }: { + authorizedUser: UnknownAuthUser; + rawCase: any; + }): void { this.associatedJudge = rawCase.associatedJudge || CHIEF_JUDGE; this.associatedJudgeId = rawCase.associatedJudgeId; this.automaticBlocked = rawCase.automaticBlocked; @@ -322,8 +334,11 @@ export class Case extends JoiValidationEntity { this.orderForRatification = rawCase.orderForRatification || false; this.orderToShowCause = rawCase.orderToShowCause || false; - this.assignArchivedDocketEntries({ applicationContext, rawCase }); - this.assignStatistics({ applicationContext, rawCase }); + this.assignArchivedDocketEntries({ + authorizedUser, + rawCase, + }); + this.assignStatistics({ rawCase }); this.assignCorrespondences({ rawCase }); } @@ -768,12 +783,18 @@ export class Case extends JoiValidationEntity { this.canAllowPrintableDocketRecord = rawCase.canAllowPrintableDocketRecord; } - assignArchivedDocketEntries({ applicationContext, rawCase }) { + private assignArchivedDocketEntries({ + authorizedUser, + rawCase, + }: { + authorizedUser: UnknownAuthUser; + rawCase: any; + }) { if (Array.isArray(rawCase.archivedDocketEntries)) { this.archivedDocketEntries = rawCase.archivedDocketEntries.map( docketEntry => new DocketEntry(docketEntry, { - applicationContext, + authorizedUser, petitioners: this.petitioners, }), ); @@ -782,18 +803,21 @@ export class Case extends JoiValidationEntity { } } - assignDocketEntries({ - applicationContext, + private assignDocketEntries({ authorizedUser, filtered, rawCase, + }: { + authorizedUser: UnknownAuthUser; + filtered: boolean; + rawCase: any; }) { if (Array.isArray(rawCase.docketEntries)) { this.docketEntries = rawCase.docketEntries .map( docketEntry => new DocketEntry(docketEntry, { - applicationContext, + authorizedUser, filtered, petitioners: this.petitioners, }), @@ -802,13 +826,11 @@ export class Case extends JoiValidationEntity { this.isSealed = isSealedCase(rawCase); - const user = authorizedUser || applicationContext.getCurrentUser(); - if ( filtered && - user.role !== ROLES.irsSuperuser && - ((user.role !== ROLES.petitionsClerk && - user.role !== ROLES.caseServicesSupervisor) || + authorizedUser?.role !== ROLES.irsSuperuser && + ((authorizedUser?.role !== ROLES.petitionsClerk && + authorizedUser?.role !== ROLES.caseServicesSupervisor) || this.getIrsSendDate()) ) { this.docketEntries = this.docketEntries.filter( @@ -820,10 +842,10 @@ export class Case extends JoiValidationEntity { } } - assignHearings({ applicationContext, rawCase }) { + private assignHearings({ rawCase }) { if (Array.isArray(rawCase.hearings)) { this.hearings = rawCase.hearings - .map(hearing => new TrialSession(hearing, { applicationContext })) + .map(hearing => new TrialSession(hearing)) .sort((a, b) => compareStrings(a.createdAt, b.createdAt)); } else { this.hearings = []; @@ -834,10 +856,9 @@ export class Case extends JoiValidationEntity { return this.privatePractitioners && this.privatePractitioners.length > 0; } - assignContacts({ applicationContext, rawCase }) { + private assignContacts({ rawCase }: { rawCase: any }): void { if (!rawCase.status || rawCase.status === CASE_STATUS_TYPES.new) { const contacts = ContactFactory({ - applicationContext, contactInfo: { primary: getContactPrimary(rawCase) || rawCase.contactPrimary, secondary: getContactSecondary(rawCase) || rawCase.contactSecondary, @@ -852,7 +873,7 @@ export class Case extends JoiValidationEntity { } else { if (Array.isArray(rawCase.petitioners)) { this.petitioners = rawCase.petitioners.map( - petitioner => new Petitioner(petitioner, { applicationContext }), + petitioner => new Petitioner(petitioner), ); setAdditionalNameOnPetitioners({ obj: this, rawCase }); @@ -878,10 +899,10 @@ export class Case extends JoiValidationEntity { } } - assignStatistics({ applicationContext, rawCase }) { + private assignStatistics({ rawCase }) { if (Array.isArray(rawCase.statistics)) { this.statistics = rawCase.statistics.map( - statistic => new Statistic(statistic, { applicationContext }), + statistic => new Statistic(statistic), ); } else { this.statistics = []; @@ -1118,12 +1139,10 @@ export class Case extends JoiValidationEntity { * @returns {Case} the updated case entity */ updateCaseCaptionDocketRecord({ - applicationContext, authorizedUser, }: { - applicationContext: any; - authorizedUser?: UnknownAuthUser; - }) { + authorizedUser: AuthUser; + }): Case { const caseCaptionRegex = /^Caption of case is amended from '(.*)' to '(.*)'/; let lastCaption = this.initialCaption; @@ -1140,8 +1159,6 @@ export class Case extends JoiValidationEntity { this.initialCaption && lastCaption !== this.caseCaption && !this.isPaper; if (needsCaptionChangedRecord) { - const user = authorizedUser || applicationContext.getCurrentUser(); - const mincDocketEntry = new DocketEntry( { documentTitle: `Caption of case is amended from '${lastCaption} ${CASE_CAPTION_POSTFIX}' to '${this.caseCaption} ${CASE_CAPTION_POSTFIX}'`, @@ -1152,10 +1169,10 @@ export class Case extends JoiValidationEntity { isOnDocketRecord: true, processingStatus: 'complete', }, - { applicationContext, petitioners: this.petitioners }, + { authorizedUser, petitioners: this.petitioners }, ); - mincDocketEntry.setFiledBy(user); + mincDocketEntry.setFiledBy(authorizedUser); this.addDocketEntry(mincDocketEntry); } @@ -1167,13 +1184,7 @@ export class Case extends JoiValidationEntity { * * @returns {Case} the updated case entity */ - updateDocketNumberRecord({ - applicationContext, - authorizedUser, - }: { - applicationContext: any; - authorizedUser?: UnknownAuthUser; - }) { + updateDocketNumberRecord({ authorizedUser }: { authorizedUser: AuthUser }) { const docketNumberRegex = /^Docket Number is amended from '(.*)' to '(.*)'/; let lastDocketNumber = @@ -1196,8 +1207,6 @@ export class Case extends JoiValidationEntity { lastDocketNumber !== newDocketNumber && !this.isPaper; if (needsDocketNumberChangeRecord) { - const user = authorizedUser || applicationContext.getCurrentUser(); - const mindDocketEntry = new DocketEntry( { documentTitle: `Docket Number is amended from '${lastDocketNumber}' to '${newDocketNumber}'`, @@ -1208,10 +1217,10 @@ export class Case extends JoiValidationEntity { isOnDocketRecord: true, processingStatus: 'complete', }, - { applicationContext, petitioners: this.petitioners }, + { authorizedUser, petitioners: this.petitioners }, ); - mindDocketEntry.setFiledBy(user); + mindDocketEntry.setFiledBy(authorizedUser); this.addDocketEntry(mindDocketEntry); } diff --git a/shared/src/business/entities/cases/Case.unsetAsBlocked.test.ts b/shared/src/business/entities/cases/Case.unsetAsBlocked.test.ts index ab804ed6ec7..d94c6f811ca 100644 --- a/shared/src/business/entities/cases/Case.unsetAsBlocked.test.ts +++ b/shared/src/business/entities/cases/Case.unsetAsBlocked.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('unsetAsBlocked', () => { it('unsets the case as blocked', () => { @@ -11,7 +11,7 @@ describe('unsetAsBlocked', () => { blockedReason: 'because reasons', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.unsetAsHighPriority.test.ts b/shared/src/business/entities/cases/Case.unsetAsHighPriority.test.ts index 7212e503a16..7f099dbadc7 100644 --- a/shared/src/business/entities/cases/Case.unsetAsHighPriority.test.ts +++ b/shared/src/business/entities/cases/Case.unsetAsHighPriority.test.ts @@ -1,6 +1,6 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('unsetAsHighPriority', () => { it('unsets the case as high priority', () => { @@ -11,7 +11,7 @@ describe('unsetAsHighPriority', () => { highPriorityReason: 'because reasons', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.updateAutomaticBlocked.test.ts b/shared/src/business/entities/cases/Case.updateAutomaticBlocked.test.ts index 84f444629ff..171f7435acd 100644 --- a/shared/src/business/entities/cases/Case.updateAutomaticBlocked.test.ts +++ b/shared/src/business/entities/cases/Case.updateAutomaticBlocked.test.ts @@ -1,7 +1,7 @@ import { AUTOMATIC_BLOCKED_REASONS } from '../EntityConstants'; import { Case } from './Case'; import { MOCK_CASE, MOCK_CASE_WITHOUT_PENDING } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('updateAutomaticBlocked', () => { it('sets the case as automaticBlocked with a valid blocked reason', () => { @@ -10,7 +10,7 @@ describe('updateAutomaticBlocked', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -34,7 +34,7 @@ describe('updateAutomaticBlocked', () => { automaticBlockedReason: 'because reasons', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.updateCaseCaptionDocketRecord.test.ts b/shared/src/business/entities/cases/Case.updateCaseCaptionDocketRecord.test.ts index de8d645e56c..4d360048cb1 100644 --- a/shared/src/business/entities/cases/Case.updateCaseCaptionDocketRecord.test.ts +++ b/shared/src/business/entities/cases/Case.updateCaseCaptionDocketRecord.test.ts @@ -1,16 +1,16 @@ import { CASE_STATUS_TYPES } from '../EntityConstants'; import { Case } from './Case'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('updateCaseCaptionDocketRecord', () => { it('should not add a notice of caption changed document when the caption is not set', () => { const caseToVerify = new Case( {}, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ).updateCaseCaptionDocketRecord({ - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(caseToVerify.docketEntries.length).toEqual(0); }); @@ -21,10 +21,10 @@ describe('updateCaseCaptionDocketRecord', () => { caseCaption: 'Caption', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ).updateCaseCaptionDocketRecord({ - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(caseToVerify.docketEntries.length).toEqual(0); }); @@ -36,10 +36,10 @@ describe('updateCaseCaptionDocketRecord', () => { initialCaption: 'Caption', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ).updateCaseCaptionDocketRecord({ - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(caseToVerify.docketEntries.length).toEqual(0); }); @@ -52,10 +52,10 @@ describe('updateCaseCaptionDocketRecord', () => { status: CASE_STATUS_TYPES.generalDocket, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ).updateCaseCaptionDocketRecord({ - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(caseToVerify.docketEntries.length).toEqual(1); expect(caseToVerify.docketEntries[0].eventCode).toEqual('MINC'); @@ -82,10 +82,10 @@ describe('updateCaseCaptionDocketRecord', () => { initialCaption: 'Caption', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ).updateCaseCaptionDocketRecord({ - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(caseToVerify.docketEntries.length).toEqual(2); }); @@ -112,10 +112,10 @@ describe('updateCaseCaptionDocketRecord', () => { status: CASE_STATUS_TYPES.generalDocket, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ).updateCaseCaptionDocketRecord({ - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(caseToVerify.docketEntries.length).toEqual(3); expect(caseToVerify.docketEntries[2]).toMatchObject({ diff --git a/shared/src/business/entities/cases/Case.updateCorrespondence.test.ts b/shared/src/business/entities/cases/Case.updateCorrespondence.test.ts index 9fc2bfb1e63..df323ad4c91 100644 --- a/shared/src/business/entities/cases/Case.updateCorrespondence.test.ts +++ b/shared/src/business/entities/cases/Case.updateCorrespondence.test.ts @@ -1,7 +1,7 @@ import { Case } from './Case'; import { Correspondence } from '../Correspondence'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('updateCorrespondence', () => { it('should update a correspondence document', () => { @@ -13,7 +13,7 @@ describe('updateCorrespondence', () => { const myCase = new Case( { ...MOCK_CASE, correspondence: [mockCorrespondence] }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -38,7 +38,7 @@ describe('updateCorrespondence', () => { const myCase = new Case( { ...MOCK_CASE, correspondence: [mockCorrespondence] }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.updateDocketEntry.test.ts b/shared/src/business/entities/cases/Case.updateDocketEntry.test.ts index 142a7b91e4a..698e70647d1 100644 --- a/shared/src/business/entities/cases/Case.updateDocketEntry.test.ts +++ b/shared/src/business/entities/cases/Case.updateDocketEntry.test.ts @@ -2,12 +2,12 @@ import { Case } from './Case'; import { DOCUMENT_PROCESSING_STATUS_OPTIONS } from '../EntityConstants'; import { MOCK_CASE } from '../../../test/mockCase'; import { MOCK_DOCUMENTS } from '../../../test/mockDocketEntry'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('updateDocketEntry', () => { it('should replace the docket entry with the exact object provided', () => { const myCase = new Case(MOCK_CASE, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); myCase.updateDocketEntry({ @@ -27,7 +27,7 @@ describe('updateDocketEntry', () => { it('should not change any docketEntries if no match is found', () => { const myCase = new Case(MOCK_CASE, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); myCase.updateDocketEntry({ diff --git a/shared/src/business/entities/cases/Case.updateDocketNumberRecord.test.ts b/shared/src/business/entities/cases/Case.updateDocketNumberRecord.test.ts index a6a6418ac70..05554b389e4 100644 --- a/shared/src/business/entities/cases/Case.updateDocketNumberRecord.test.ts +++ b/shared/src/business/entities/cases/Case.updateDocketNumberRecord.test.ts @@ -1,7 +1,7 @@ import { CASE_STATUS_TYPES, DOCKET_NUMBER_SUFFIXES } from '../EntityConstants'; import { Case } from './Case'; import { DocketEntry } from '@shared/business/entities/DocketEntry'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('updateDocketNumberRecord records suffix changes', () => { it('should create a notice of docket number change document when the suffix updates for an electronically created case', () => { @@ -13,13 +13,13 @@ describe('updateDocketNumberRecord records suffix changes', () => { status: CASE_STATUS_TYPES.generalDocket, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); expect(caseToVerify.initialDocketNumberSuffix).toEqual('S'); caseToVerify.docketNumberSuffix = DOCKET_NUMBER_SUFFIXES.WHISTLEBLOWER; caseToVerify.updateDocketNumberRecord({ - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(caseToVerify.docketEntries.length).toEqual(1); expect(caseToVerify.docketEntries[0]).toMatchObject({ @@ -39,12 +39,12 @@ describe('updateDocketNumberRecord records suffix changes', () => { status: CASE_STATUS_TYPES.generalDocket, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); expect(caseToVerify.initialDocketNumberSuffix).toEqual('_'); caseToVerify.updateDocketNumberRecord({ - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(caseToVerify.docketEntries.length).toEqual(0); }); @@ -53,12 +53,12 @@ describe('updateDocketNumberRecord records suffix changes', () => { const caseToVerify = new Case( { docketNumber: '123-19' }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); expect(caseToVerify.initialDocketNumberSuffix).toEqual('_'); caseToVerify.updateDocketNumberRecord({ - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(caseToVerify.docketEntries.length).toEqual(0); }); @@ -85,12 +85,12 @@ describe('updateDocketNumberRecord records suffix changes', () => { status: CASE_STATUS_TYPES.generalDocket, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); caseToVerify.docketNumberSuffix = DOCKET_NUMBER_SUFFIXES.WHISTLEBLOWER; caseToVerify.updateDocketNumberRecord({ - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(caseToVerify.docketEntries.length).toEqual(3); expect(caseToVerify.docketEntries[2].documentTitle).toEqual( diff --git a/shared/src/business/entities/cases/Case.updateIrsPractitioner.test.ts b/shared/src/business/entities/cases/Case.updateIrsPractitioner.test.ts index 612d8cdda66..b4582cdfdc1 100644 --- a/shared/src/business/entities/cases/Case.updateIrsPractitioner.test.ts +++ b/shared/src/business/entities/cases/Case.updateIrsPractitioner.test.ts @@ -1,7 +1,7 @@ import { Case } from './Case'; import { IrsPractitioner } from '../IrsPractitioner'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('updateIrsPractitioner', () => { let myCase; @@ -13,7 +13,7 @@ describe('updateIrsPractitioner', () => { irsPractitioners: [{ name: 'Christopher Walken', userId: '123' }], privatePractitioners: [{ name: 'Slim Shady', userId: '567' }], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); }); @@ -28,7 +28,7 @@ describe('updateIrsPractitioner', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.updatePetitioner.test.ts b/shared/src/business/entities/cases/Case.updatePetitioner.test.ts index 240efa03c86..5aff3f80dd9 100644 --- a/shared/src/business/entities/cases/Case.updatePetitioner.test.ts +++ b/shared/src/business/entities/cases/Case.updatePetitioner.test.ts @@ -1,7 +1,7 @@ import { CONTACT_TYPES, PARTY_TYPES } from '../EntityConstants'; import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('updatePetitioner', () => { it('should throw an error when the petitioner to update is not found on the case', () => { @@ -9,7 +9,7 @@ describe('updatePetitioner', () => { { ...MOCK_CASE, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(() => myCase.updatePetitioner({ contactId: 'badId' })).toThrow( @@ -22,7 +22,7 @@ describe('updatePetitioner', () => { { ...MOCK_CASE, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); myCase.updatePetitioner({ @@ -35,7 +35,7 @@ describe('updatePetitioner', () => { // send back through the constructor so contacts are recreated as entities const updatedCaseEntity = new Case(updatedCaseRaw, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(updatedCaseEntity.petitioners[0]).toMatchObject({ @@ -61,7 +61,7 @@ describe('updatePetitioner', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); myCase.updatePetitioner({ @@ -74,7 +74,7 @@ describe('updatePetitioner', () => { // send back through the constructor so contacts are recreated as entities const updatedCaseEntity = new Case(updatedCaseRaw, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); expect(updatedCaseEntity.isValid()).toBeFalsy(); diff --git a/shared/src/business/entities/cases/Case.updatePrivatePractitioner.test.ts b/shared/src/business/entities/cases/Case.updatePrivatePractitioner.test.ts index d3c35963480..fa83f3c091f 100644 --- a/shared/src/business/entities/cases/Case.updatePrivatePractitioner.test.ts +++ b/shared/src/business/entities/cases/Case.updatePrivatePractitioner.test.ts @@ -1,7 +1,7 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; import { PrivatePractitioner } from '../PrivatePractitioner'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('updatePrivatePractitioner', () => { let myCase; @@ -13,7 +13,7 @@ describe('updatePrivatePractitioner', () => { irsPractitioners: [{ name: 'Christopher Walken', userId: '123' }], privatePractitioners: [{ name: 'Slim Shady', userId: '567' }], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); }); @@ -28,7 +28,7 @@ describe('updatePrivatePractitioner', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/business/entities/cases/Case.updateStatistic.test.ts b/shared/src/business/entities/cases/Case.updateStatistic.test.ts index f4915849423..e8e54688b05 100644 --- a/shared/src/business/entities/cases/Case.updateStatistic.test.ts +++ b/shared/src/business/entities/cases/Case.updateStatistic.test.ts @@ -1,7 +1,7 @@ import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; import { Statistic } from '../Statistic'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('updateStatistic', () => { it('should successfully update a statistic', () => { @@ -22,21 +22,18 @@ describe('updateStatistic', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); - const statisticToUpdate = new Statistic( - { - determinationDeficiencyAmount: 1, - determinationTotalPenalties: 1, - irsDeficiencyAmount: 1, - irsTotalPenalties: 1, - statisticId, - year: 2012, - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + const statisticToUpdate = new Statistic({ + determinationDeficiencyAmount: 1, + determinationTotalPenalties: 1, + irsDeficiencyAmount: 1, + irsTotalPenalties: 1, + statisticId, + year: 2012, + yearOrPeriod: 'Year', + }); caseEntity.updateStatistic(statisticToUpdate, statisticId); @@ -60,21 +57,18 @@ describe('updateStatistic', () => { ...MOCK_CASE, statistics: [originalStatistic], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); - const statisticToUpdate = new Statistic( - { - determinationDeficiencyAmount: 1, - determinationTotalPenalties: 1, - irsDeficiencyAmount: 1, - irsTotalPenalties: 1, - statisticId: '9f23dac6-4a9d-4e66-aafc-b6d3c892d907', - year: 2012, - yearOrPeriod: 'Year', - }, - { applicationContext }, - ); + const statisticToUpdate = new Statistic({ + determinationDeficiencyAmount: 1, + determinationTotalPenalties: 1, + irsDeficiencyAmount: 1, + irsTotalPenalties: 1, + statisticId: '9f23dac6-4a9d-4e66-aafc-b6d3c892d907', + year: 2012, + yearOrPeriod: 'Year', + }); caseEntity.updateStatistic( statisticToUpdate, diff --git a/shared/src/business/entities/cases/Case.updateTrialSessionInformation.test.ts b/shared/src/business/entities/cases/Case.updateTrialSessionInformation.test.ts index 8ae07a1a495..ad96e765950 100644 --- a/shared/src/business/entities/cases/Case.updateTrialSessionInformation.test.ts +++ b/shared/src/business/entities/cases/Case.updateTrialSessionInformation.test.ts @@ -2,14 +2,14 @@ import { CASE_STATUS_TYPES, CHIEF_JUDGE } from '../EntityConstants'; import { Case } from './Case'; import { MOCK_CASE } from '../../../test/mockCase'; import { TrialSession } from '../trialSessions/TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('updateTrialSessionInformation', () => { it('should not change the status of the case', () => { const myCase = new Case( { ...MOCK_CASE, status: CASE_STATUS_TYPES.closed }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); myCase.updateTrialSessionInformation({ @@ -24,7 +24,7 @@ describe('updateTrialSessionInformation', () => { it('should set only judge and trialSessionId if the trial session is calendared', () => { const myCase = new Case(MOCK_CASE, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); myCase.updateTrialSessionInformation({ isCalendared: false, @@ -42,22 +42,19 @@ describe('updateTrialSessionInformation', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); - const trialSession = new TrialSession( - { - isCalendared: true, - judge: { name: 'Judge Buch', userId: 'buch_id' }, - maxCases: 100, - sessionType: 'Regular', - startDate: '2025-03-01T00:00:00.000Z', - term: 'Fall', - termYear: '2025', - trialLocation: 'Birmingham, Alabama', - }, - { applicationContext }, - ); + const trialSession = new TrialSession({ + isCalendared: true, + judge: { name: 'Judge Buch', userId: 'buch_id' }, + maxCases: 100, + sessionType: 'Regular', + startDate: '2025-03-01T00:00:00.000Z', + term: 'Fall', + termYear: '2025', + trialLocation: 'Birmingham, Alabama', + }); myCase.updateTrialSessionInformation(trialSession); expect(myCase.trialDate).toBeTruthy(); @@ -74,22 +71,19 @@ describe('updateTrialSessionInformation', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); - const trialSession = new TrialSession( - { - isCalendared: false, - judge: { name: 'Judge Buch' }, - maxCases: 100, - sessionType: 'Regular', - startDate: '2025-03-01T00:00:00.000Z', - term: 'Fall', - termYear: '2025', - trialLocation: 'Birmingham, Alabama', - }, - { applicationContext }, - ); + const trialSession = new TrialSession({ + isCalendared: false, + judge: { name: 'Judge Buch' }, + maxCases: 100, + sessionType: 'Regular', + startDate: '2025-03-01T00:00:00.000Z', + term: 'Fall', + termYear: '2025', + trialLocation: 'Birmingham, Alabama', + }); myCase.setAsCalendared(trialSession); expect(myCase.status).toEqual(CASE_STATUS_TYPES.new); diff --git a/shared/src/business/entities/cases/CaseQC.test.ts b/shared/src/business/entities/cases/CaseQC.test.ts index 9d8b6eb6c17..3c065cf42a8 100644 --- a/shared/src/business/entities/cases/CaseQC.test.ts +++ b/shared/src/business/entities/cases/CaseQC.test.ts @@ -1,15 +1,14 @@ import { CaseQC } from './CaseQC'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('CaseQC entity', () => { describe('validation', () => { - it('throws an exception when not provided an application context', () => { - expect(() => new CaseQC({}, {} as any)).toThrow(); - }); - it('returns the expected set of errors for an empty object', () => { - const caseQcEntity = new CaseQC({}, { applicationContext }); + const caseQcEntity = new CaseQC( + {}, + { authorizedUser: mockDocketClerkUser }, + ); expect(caseQcEntity.getFormattedValidationErrors()).toEqual({ caseCaption: 'Enter a case caption', @@ -28,7 +27,7 @@ describe('CaseQC entity', () => { ...MOCK_CASE, hasVerifiedIrsNotice: false, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); expect(caseQcEntity.getFormattedValidationErrors()).toEqual(null); diff --git a/shared/src/business/entities/cases/CaseQC.ts b/shared/src/business/entities/cases/CaseQC.ts index fc930d68b0b..7f9dfcb404b 100644 --- a/shared/src/business/entities/cases/CaseQC.ts +++ b/shared/src/business/entities/cases/CaseQC.ts @@ -1,11 +1,18 @@ import { Case } from './Case'; import { JoiValidationConstants } from '../JoiValidationConstants'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import joi from 'joi'; export class CaseQC extends Case { - constructor(rawCase, { applicationContext, filtered = false }) { + constructor( + rawCase, + { + authorizedUser, + filtered = false, + }: { authorizedUser: UnknownAuthUser; filtered?: boolean }, + ) { super(rawCase, { - applicationContext, + authorizedUser, filtered, }); this.entityName = 'CaseQC'; diff --git a/shared/src/business/entities/cases/ElectronicPetition.test.ts b/shared/src/business/entities/cases/ElectronicPetition.test.ts index 4768e35e7ca..d3057c8954d 100644 --- a/shared/src/business/entities/cases/ElectronicPetition.test.ts +++ b/shared/src/business/entities/cases/ElectronicPetition.test.ts @@ -7,23 +7,19 @@ import { PETITION_TYPES, } from '../EntityConstants'; import { ElectronicPetition } from './ElectronicPetition'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('ElectronicPetition entity', () => { describe('isValid', () => { it('requires corporate disclosure if filing type is a business', () => { - const electronicPetition = new ElectronicPetition( - { - businessType: PARTY_TYPES.corporation, - caseType: CASE_TYPES_MAP.other, - filingType: 'A business', - hasIrsNotice: false, - petitionType: undefined, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + businessType: PARTY_TYPES.corporation, + caseType: CASE_TYPES_MAP.other, + filingType: 'A business', + hasIrsNotice: false, + petitionType: undefined, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()! @@ -32,15 +28,12 @@ describe('ElectronicPetition entity', () => { }); it('does not require corporate disclosure if filing type not set', () => { - const petition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - hasIrsNotice: false, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const petition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + hasIrsNotice: false, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( petition.getFormattedValidationErrors()!.corporateDisclosureFile, @@ -48,16 +41,13 @@ describe('ElectronicPetition entity', () => { }); it('does not require corporate disclosure if filing type not a business', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'not a biz', - hasIrsNotice: false, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'not a biz', + hasIrsNotice: false, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()! @@ -66,17 +56,14 @@ describe('ElectronicPetition entity', () => { }); it('requires stinFile', () => { - const electronicPetition = new ElectronicPetition( - { - businessType: PARTY_TYPES.corporation, - caseType: CASE_TYPES_MAP.other, - filingType: 'A business', - hasIrsNotice: false, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + businessType: PARTY_TYPES.corporation, + caseType: CASE_TYPES_MAP.other, + filingType: 'A business', + hasIrsNotice: false, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()!.stinFile, @@ -86,19 +73,16 @@ describe('ElectronicPetition entity', () => { describe('Petition file size', () => { it('should inform you if petition file size is greater than the PDF max file size', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: MAX_FILE_SIZE_BYTES + 5, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: MAX_FILE_SIZE_BYTES + 5, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()!.petitionFileSize, @@ -108,19 +92,16 @@ describe('ElectronicPetition entity', () => { }); it('should inform you if petition file size is zero', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - petitionFile: {}, - petitionFileSize: 0, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + petitionFile: {}, + petitionFileSize: 0, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()!.petitionFileSize, @@ -128,17 +109,14 @@ describe('ElectronicPetition entity', () => { }); it('should not error on petitionFileSize when petitionFile is undefined', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()!.petitionFileSize, @@ -146,18 +124,15 @@ describe('ElectronicPetition entity', () => { }); it('should error on petitionFileSize when petitionFile is defined', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - petitionFile: new File([], 'testPetitionFile.pdf'), - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + petitionFile: new File([], 'testPetitionFile.pdf'), + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()!.petitionFileSize, @@ -167,19 +142,16 @@ describe('ElectronicPetition entity', () => { describe('STIN file size', () => { it('should inform you if stin file size is greater than the file max size', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - stinFile: new File([], 'test.pdf'), - stinFileSize: MAX_FILE_SIZE_BYTES + 5, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + stinFile: new File([], 'test.pdf'), + stinFileSize: MAX_FILE_SIZE_BYTES + 5, + }); expect( electronicPetition.getFormattedValidationErrors()!.stinFileSize, @@ -189,19 +161,16 @@ describe('ElectronicPetition entity', () => { }); it('should inform you if stin file size is zero', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - stinFile: new File([], 'test.pdf'), - stinFileSize: 0, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + stinFile: new File([], 'test.pdf'), + stinFileSize: 0, + }); expect( electronicPetition.getFormattedValidationErrors()!.stinFileSize, @@ -209,17 +178,14 @@ describe('ElectronicPetition entity', () => { }); it('should not error on stinFileSize when stinFile is undefined', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()!.stinFileSize, @@ -227,19 +193,16 @@ describe('ElectronicPetition entity', () => { }); it('should error on stinFileSize when stinFile is undefined', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - stinFile: new File([], 'testStinFile.pdf'), - stinFileSize: undefined, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + stinFile: new File([], 'testStinFile.pdf'), + stinFileSize: undefined, + }); expect( electronicPetition.getFormattedValidationErrors()!.stinFileSize, @@ -249,19 +212,16 @@ describe('ElectronicPetition entity', () => { describe('ATP file size', () => { it('should inform you if atp file size is greater than the file max size', () => { - const electronicPetition = new ElectronicPetition( - { - attachmentToPetitionFile: new File([], 'test.pdf'), - attachmentToPetitionFileSize: MAX_FILE_SIZE_BYTES + 5, - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + attachmentToPetitionFile: new File([], 'test.pdf'), + attachmentToPetitionFileSize: MAX_FILE_SIZE_BYTES + 5, + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()! @@ -272,20 +232,17 @@ describe('ElectronicPetition entity', () => { }); it('should inform you if atp file size is zero', () => { - const electronicPetition = new ElectronicPetition( - { - attachmentToPetitionFile: new File([], 'test.pdf'), - attachmentToPetitionFileSize: 0, - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + attachmentToPetitionFile: new File([], 'test.pdf'), + attachmentToPetitionFileSize: 0, + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()! @@ -294,17 +251,14 @@ describe('ElectronicPetition entity', () => { }); it('should not error on attachmentToPetitionFileSize when attachmentToPetitionFile is undefined', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()! @@ -313,19 +267,16 @@ describe('ElectronicPetition entity', () => { }); it('should error on attachmentToPetitionFileSize when attachmentToPetitionFile is undefined', () => { - const electronicPetition = new ElectronicPetition( - { - attachmentToPetitionFile: new File([], 'testStinFile.pdf'), - attachmentToPetitionFileSize: undefined, - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + attachmentToPetitionFile: new File([], 'testStinFile.pdf'), + attachmentToPetitionFileSize: undefined, + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()! @@ -336,19 +287,16 @@ describe('ElectronicPetition entity', () => { describe('corporate disclosure file size', () => { it('should inform you if corporate disclosure file size is greater than the PDF max file size', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - corporateDisclosureFile: new File([], 'cdsFile.pdf'), - corporateDisclosureFileSize: MAX_FILE_SIZE_BYTES + 5, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + corporateDisclosureFile: new File([], 'cdsFile.pdf'), + corporateDisclosureFileSize: MAX_FILE_SIZE_BYTES + 5, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()! @@ -359,19 +307,16 @@ describe('ElectronicPetition entity', () => { }); it('should inform you if corporate disclosure file size is zero', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - corporateDisclosureFile: new File([], 'test.pdf'), - corporateDisclosureFileSize: 0, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + corporateDisclosureFile: new File([], 'test.pdf'), + corporateDisclosureFileSize: 0, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()! @@ -380,17 +325,14 @@ describe('ElectronicPetition entity', () => { }); it('should not error on corporateDisclosureFileSize when corporateDisclosureFile is undefined', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()! @@ -403,19 +345,16 @@ describe('ElectronicPetition entity', () => { }); it('should error on corporateDisclosureFileSize when corporateDisclosureFile is undefined', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - corporateDisclosureFile: new File([], 'testStinFile.pdf'), - corporateDisclosureFileSize: undefined, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.nextFriendForMinor, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + corporateDisclosureFile: new File([], 'testStinFile.pdf'), + corporateDisclosureFileSize: undefined, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.nextFriendForMinor, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + }); expect( electronicPetition.getFormattedValidationErrors()! @@ -426,16 +365,13 @@ describe('ElectronicPetition entity', () => { describe('Secondary contact phone', () => { it('should use secondary contact phone when provided', () => { - const electronicPetition = new ElectronicPetition( - { - contactSecondary: { - contactType: CONTACT_TYPES.secondary, - phone: '123-234-3456', - }, - partyType: PARTY_TYPES.petitionerSpouse, + const electronicPetition = new ElectronicPetition({ + contactSecondary: { + contactType: CONTACT_TYPES.secondary, + phone: '123-234-3456', }, - { applicationContext }, - ); + partyType: PARTY_TYPES.petitionerSpouse, + }); const secondaryContact = electronicPetition .toRawObject() .petitioners.find(p => p.contactType === CONTACT_TYPES.secondary); @@ -443,15 +379,12 @@ describe('ElectronicPetition entity', () => { }); it('should use default secondary contact phone when no phone is provided', () => { - const electronicPetition = new ElectronicPetition( - { - contactSecondary: { - contactType: CONTACT_TYPES.secondary, - }, - partyType: PARTY_TYPES.petitionerSpouse, + const electronicPetition = new ElectronicPetition({ + contactSecondary: { + contactType: CONTACT_TYPES.secondary, }, - { applicationContext }, - ); + partyType: PARTY_TYPES.petitionerSpouse, + }); const secondaryContact = electronicPetition .toRawObject() .petitioners.find(p => p.contactType === CONTACT_TYPES.secondary); diff --git a/shared/src/business/entities/cases/ElectronicPetition.ts b/shared/src/business/entities/cases/ElectronicPetition.ts index 00a528db64e..394adcdd8f9 100644 --- a/shared/src/business/entities/cases/ElectronicPetition.ts +++ b/shared/src/business/entities/cases/ElectronicPetition.ts @@ -43,7 +43,7 @@ export class ElectronicPetition extends JoiValidationEntity { public attachmentToPetitionFileSize?: number; public petitionType: string; - constructor(rawCase, { applicationContext }) { + constructor(rawCase) { super('ElectronicPetition'); this.attachmentToPetitionFile = rawCase.attachmentToPetitionFile; @@ -69,7 +69,6 @@ export class ElectronicPetition extends JoiValidationEntity { this.corporateDisclosureFileSize = rawCase.corporateDisclosureFileSize; const contacts = ContactFactory({ - applicationContext, contactInfo: { primary: getContactPrimary(rawCase) || rawCase.contactPrimary, secondary: getContactSecondary(rawCase) || rawCase.contactSecondary, diff --git a/shared/src/business/entities/cases/ElectronicPetitionForCorporationContacts.test.ts b/shared/src/business/entities/cases/ElectronicPetitionForCorporationContacts.test.ts index 097dcdc28b5..d171485724e 100644 --- a/shared/src/business/entities/cases/ElectronicPetitionForCorporationContacts.test.ts +++ b/shared/src/business/entities/cases/ElectronicPetitionForCorporationContacts.test.ts @@ -1,90 +1,80 @@ import { CASE_TYPES_MAP, COUNTRY_TYPES, PARTY_TYPES } from '../EntityConstants'; import { ElectronicPetition } from './ElectronicPetition'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('ElectronicPetition', () => { describe('for Corporation Contacts', () => { it('should not validate without contact', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.corporation, - petitionFile: {}, - petitionFileSize: 1, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, - stinFile: {}, - stinFileSize: 1, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.corporation, + petitionFile: {}, + petitionFileSize: 1, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + stinFile: {}, + stinFileSize: 1, + }); expect(electronicPetition.isValid()).toEqual(false); }); it('should not validate without inCareOf', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - contactPrimary: { - address1: '876 12th Ave', - city: 'Nashville', - country: 'USA', - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'someone@example.com', - name: 'Jimmy Dean', - phone: '1234567890', - postalCode: '05198', - state: 'AK', - }, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.corporation, - petitionFile: {}, - petitionFileSize: 1, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + contactPrimary: { + address1: '876 12th Ave', + city: 'Nashville', + country: 'USA', + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'someone@example.com', + name: 'Jimmy Dean', + phone: '1234567890', + postalCode: '05198', + state: 'AK', }, - { applicationContext }, - ); + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.corporation, + petitionFile: {}, + petitionFileSize: 1, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + }); expect(electronicPetition.isValid()).toEqual(false); }); it('can validate primary contact', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - contactPrimary: { - address1: '876 12th Ave', - city: 'Nashville', - country: 'USA', - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'someone@example.com', - inCareOf: 'USTC', - name: 'Jimmy Dean', - phone: '1234567890', - postalCode: '05198', - state: 'AK', - }, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.corporation, - petitionFile: {}, - petitionFileSize: 1, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, - stinFile: {}, - stinFileSize: 1, + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + contactPrimary: { + address1: '876 12th Ave', + city: 'Nashville', + country: 'USA', + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'someone@example.com', + inCareOf: 'USTC', + name: 'Jimmy Dean', + phone: '1234567890', + postalCode: '05198', + state: 'AK', }, - { applicationContext }, - ); + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.corporation, + petitionFile: {}, + petitionFileSize: 1, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + stinFile: {}, + stinFileSize: 1, + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); }); diff --git a/shared/src/business/entities/cases/ElectronicPetitionForEstateWithoutExecutorContacts.test.ts b/shared/src/business/entities/cases/ElectronicPetitionForEstateWithoutExecutorContacts.test.ts index 12ce16100f1..004fc1259df 100644 --- a/shared/src/business/entities/cases/ElectronicPetitionForEstateWithoutExecutorContacts.test.ts +++ b/shared/src/business/entities/cases/ElectronicPetitionForEstateWithoutExecutorContacts.test.ts @@ -1,92 +1,82 @@ import { CASE_TYPES_MAP, COUNTRY_TYPES, PARTY_TYPES } from '../EntityConstants'; import { ElectronicPetition } from './ElectronicPetition'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('ElectronicPetition', () => { describe('for Estate without an Executor/Personal Representative/Fiduciary/etc. Contacts', () => { it('should not validate without contact', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.estateWithoutExecutor, - petitionFile: {}, - petitionFileSize: 1, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, - stinFile: {}, - stinFileSize: 1, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.estateWithoutExecutor, + petitionFile: {}, + petitionFileSize: 1, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + stinFile: {}, + stinFileSize: 1, + }); expect(electronicPetition.isValid()).toEqual(false); }); it('should validate without inCareOf', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - contactPrimary: { - address1: '876 12th Ave', - city: 'Nashville', - country: 'USA', - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'someone@example.com', - name: 'Jimmy Dean', - phone: '1234567890', - postalCode: '05198', - state: 'AK', - }, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.estateWithoutExecutor, - petitionFile: {}, - petitionFileSize: 1, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, - stinFile: {}, - stinFileSize: 1, + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + contactPrimary: { + address1: '876 12th Ave', + city: 'Nashville', + country: 'USA', + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'someone@example.com', + name: 'Jimmy Dean', + phone: '1234567890', + postalCode: '05198', + state: 'AK', }, - { applicationContext }, - ); + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.estateWithoutExecutor, + petitionFile: {}, + petitionFileSize: 1, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + stinFile: {}, + stinFileSize: 1, + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); it('can validate primary contact', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - contactPrimary: { - address1: '876 12th Ave', - city: 'Nashville', - country: 'USA', - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'someone@example.com', - inCareOf: 'USTC', - name: 'Jimmy Dean', - phone: '1234567890', - postalCode: '05198', - state: 'AK', - }, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.estateWithoutExecutor, - petitionFile: {}, - petitionFileSize: 1, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, - stinFile: {}, - stinFileSize: 1, + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + contactPrimary: { + address1: '876 12th Ave', + city: 'Nashville', + country: 'USA', + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'someone@example.com', + inCareOf: 'USTC', + name: 'Jimmy Dean', + phone: '1234567890', + postalCode: '05198', + state: 'AK', }, - { applicationContext }, - ); + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.estateWithoutExecutor, + petitionFile: {}, + petitionFileSize: 1, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + stinFile: {}, + stinFileSize: 1, + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); }); diff --git a/shared/src/business/entities/cases/ElectronicPetitionForInternationalContacts.test.ts b/shared/src/business/entities/cases/ElectronicPetitionForInternationalContacts.test.ts index fcb7f44ff8f..78d24487594 100644 --- a/shared/src/business/entities/cases/ElectronicPetitionForInternationalContacts.test.ts +++ b/shared/src/business/entities/cases/ElectronicPetitionForInternationalContacts.test.ts @@ -5,41 +5,37 @@ import { PARTY_TYPES, } from '../EntityConstants'; import { ElectronicPetition } from './ElectronicPetition'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('ElectronicPetition', () => { describe('for (international) Contacts', () => { it('should not validate without country', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.petitioner, - petitionFile: {}, - petitionFileSize: 1, - petitioners: [ - { - address1: '876 12th Ave', - city: 'Nashville', - contactType: CONTACT_TYPES.primary, - countryType: COUNTRY_TYPES.INTERNATIONAL, - email: 'someone@example.com', - name: 'Jimmy Dean', - phone: '1234567890', - postalCode: '05198', - state: 'AK', - }, - ], - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, - stinFile: {}, - stinFileSize: 1, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.petitioner, + petitionFile: {}, + petitionFileSize: 1, + petitioners: [ + { + address1: '876 12th Ave', + city: 'Nashville', + contactType: CONTACT_TYPES.primary, + countryType: COUNTRY_TYPES.INTERNATIONAL, + email: 'someone@example.com', + name: 'Jimmy Dean', + phone: '1234567890', + postalCode: '05198', + state: 'AK', + }, + ], + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + stinFile: {}, + stinFileSize: 1, + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual({ petitioners: [ { @@ -51,37 +47,34 @@ describe('ElectronicPetition', () => { }); it('can validate the primary contact in the petitioners array', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.petitioner, - petitionFile: {}, - petitionFileSize: 1, - petitioners: [ - { - address1: '876 12th Ave', - city: 'Nashville', - contactType: CONTACT_TYPES.primary, - country: 'USA', - countryType: COUNTRY_TYPES.INTERNATIONAL, - email: 'someone@example.com', - name: 'Jimmy Dean', - phone: '1234567890', - postalCode: '05198', - state: 'AK', - }, - ], - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, - stinFile: {}, - stinFileSize: 1, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.petitioner, + petitionFile: {}, + petitionFileSize: 1, + petitioners: [ + { + address1: '876 12th Ave', + city: 'Nashville', + contactType: CONTACT_TYPES.primary, + country: 'USA', + countryType: COUNTRY_TYPES.INTERNATIONAL, + email: 'someone@example.com', + name: 'Jimmy Dean', + phone: '1234567890', + postalCode: '05198', + state: 'AK', + }, + ], + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + stinFile: {}, + stinFileSize: 1, + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); }); diff --git a/shared/src/business/entities/cases/ElectronicPetitionForMinorWithoutGuardianContacts.test.ts b/shared/src/business/entities/cases/ElectronicPetitionForMinorWithoutGuardianContacts.test.ts index 9e1bedc2f86..06d6834f5a7 100644 --- a/shared/src/business/entities/cases/ElectronicPetitionForMinorWithoutGuardianContacts.test.ts +++ b/shared/src/business/entities/cases/ElectronicPetitionForMinorWithoutGuardianContacts.test.ts @@ -1,60 +1,53 @@ import { CASE_TYPES_MAP, COUNTRY_TYPES, PARTY_TYPES } from '../EntityConstants'; import { ElectronicPetition } from './ElectronicPetition'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('ElectronicPetition', () => { describe('for Minor without Guardian Contacts', () => { it('should not validate without contacts', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.nextFriendForMinor, - petitionFile: {}, - petitionFileSize: 1, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, - stinFile: {}, - stinFileSize: 1, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.nextFriendForMinor, + petitionFile: {}, + petitionFileSize: 1, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + stinFile: {}, + stinFileSize: 1, + }); expect(electronicPetition.isValid()).toEqual(false); }); it('can validate contacts', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - contactPrimary: { - address1: '876 12th Ave', - city: 'Nashville', - country: 'USA', - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'someone@example.com', - name: 'Jimmy Dean', - phone: '1234567890', - postalCode: '05198', - secondaryName: 'Jimmy Dean', - state: 'AK', - }, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.nextFriendForMinor, - petitionFile: {}, - petitionFileSize: 1, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, - stinFile: {}, - stinFileSize: 1, + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + contactPrimary: { + address1: '876 12th Ave', + city: 'Nashville', + country: 'USA', + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'someone@example.com', + name: 'Jimmy Dean', + phone: '1234567890', + postalCode: '05198', + secondaryName: 'Jimmy Dean', + state: 'AK', }, - { applicationContext }, - ); + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.nextFriendForMinor, + petitionFile: {}, + petitionFileSize: 1, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + stinFile: {}, + stinFileSize: 1, + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); }); diff --git a/shared/src/business/entities/cases/ElectronicPetitionForPartnershipTaxMattersPartnerContacts.test.ts b/shared/src/business/entities/cases/ElectronicPetitionForPartnershipTaxMattersPartnerContacts.test.ts index 9048a1d45e2..553c3f2e15d 100644 --- a/shared/src/business/entities/cases/ElectronicPetitionForPartnershipTaxMattersPartnerContacts.test.ts +++ b/shared/src/business/entities/cases/ElectronicPetitionForPartnershipTaxMattersPartnerContacts.test.ts @@ -1,60 +1,53 @@ import { CASE_TYPES_MAP, COUNTRY_TYPES, PARTY_TYPES } from '../EntityConstants'; import { ElectronicPetition } from './ElectronicPetition'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('ElectronicPetition', () => { describe('for Partnership (as the Tax Matters Partner) Contacts', () => { it('should not validate without contacts', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.partnershipAsTaxMattersPartner, - petitionFile: {}, - petitionFileSize: 1, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, - stinFile: {}, - stinFileSize: 1, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.partnershipAsTaxMattersPartner, + petitionFile: {}, + petitionFileSize: 1, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + stinFile: {}, + stinFileSize: 1, + }); expect(electronicPetition.isValid()).toEqual(false); }); it('can validate contacts', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - contactPrimary: { - address1: '876 12th Ave', - city: 'Nashville', - country: 'USA', - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'someone@example.com', - name: 'Jimmy Dean', - phone: '1234567890', - postalCode: '05198', - secondaryName: 'Jimmy Dean', - state: 'AK', - }, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.partnershipAsTaxMattersPartner, - petitionFile: {}, - petitionFileSize: 1, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, - stinFile: {}, - stinFileSize: 1, + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + contactPrimary: { + address1: '876 12th Ave', + city: 'Nashville', + country: 'USA', + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'someone@example.com', + name: 'Jimmy Dean', + phone: '1234567890', + postalCode: '05198', + secondaryName: 'Jimmy Dean', + state: 'AK', }, - { applicationContext }, - ); + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.partnershipAsTaxMattersPartner, + petitionFile: {}, + petitionFileSize: 1, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + stinFile: {}, + stinFileSize: 1, + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); }); diff --git a/shared/src/business/entities/cases/ElectronicPetitionForPetitionerAndDeceasedSpouseContacts.test.ts b/shared/src/business/entities/cases/ElectronicPetitionForPetitionerAndDeceasedSpouseContacts.test.ts index f82f3e46cf3..11ef5b06368 100644 --- a/shared/src/business/entities/cases/ElectronicPetitionForPetitionerAndDeceasedSpouseContacts.test.ts +++ b/shared/src/business/entities/cases/ElectronicPetitionForPetitionerAndDeceasedSpouseContacts.test.ts @@ -1,68 +1,61 @@ import { CASE_TYPES_MAP, COUNTRY_TYPES, PARTY_TYPES } from '../EntityConstants'; import { ElectronicPetition } from './ElectronicPetition'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('ElectronicPetition', () => { describe('for Petitioner And Deceased Spouse Contacts', () => { it('should not validate without contacts', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.petitionerDeceasedSpouse, - petitionFile: {}, - petitionFileSize: 1, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, - stinFile: {}, - stinFileSize: 1, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.petitionerDeceasedSpouse, + petitionFile: {}, + petitionFileSize: 1, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + stinFile: {}, + stinFileSize: 1, + }); expect(electronicPetition.isValid()).toEqual(false); }); it('can validate primary contact name', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - contactPrimary: { - address1: '876 12th Ave', - city: 'Nashville', - country: 'USA', - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'someone@example.com', - name: 'Jimmy Dean', - phone: '1234567890', - postalCode: '05198', - state: 'AK', - }, - contactSecondary: { - address1: '1599 Pennsylvania Ave', - city: 'Walla Walla', - countryType: COUNTRY_TYPES.DOMESTIC, - inCareOf: 'USTC', - name: 'Betty Crocker', - postalCode: '78774', - state: 'WA', - }, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.petitionerDeceasedSpouse, - petitionFile: {}, - petitionFileSize: 1, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, - stinFile: {}, - stinFileSize: 1, + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + contactPrimary: { + address1: '876 12th Ave', + city: 'Nashville', + country: 'USA', + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'someone@example.com', + name: 'Jimmy Dean', + phone: '1234567890', + postalCode: '05198', + state: 'AK', + }, + contactSecondary: { + address1: '1599 Pennsylvania Ave', + city: 'Walla Walla', + countryType: COUNTRY_TYPES.DOMESTIC, + inCareOf: 'USTC', + name: 'Betty Crocker', + postalCode: '78774', + state: 'WA', }, - { applicationContext }, - ); + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.petitionerDeceasedSpouse, + petitionFile: {}, + petitionFileSize: 1, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + stinFile: {}, + stinFileSize: 1, + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); }); diff --git a/shared/src/business/entities/cases/ElectronicPetitionForPetitionerAndSpouseContacts.test.ts b/shared/src/business/entities/cases/ElectronicPetitionForPetitionerAndSpouseContacts.test.ts index bf528c2e903..174525a556a 100644 --- a/shared/src/business/entities/cases/ElectronicPetitionForPetitionerAndSpouseContacts.test.ts +++ b/shared/src/business/entities/cases/ElectronicPetitionForPetitionerAndSpouseContacts.test.ts @@ -1,69 +1,62 @@ import { CASE_TYPES_MAP, COUNTRY_TYPES, PARTY_TYPES } from '../EntityConstants'; import { ElectronicPetition } from './ElectronicPetition'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('ElectronicPetition', () => { describe('for Petitioner And Spouse Contacts', () => { it('should not validate without contacts', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.petitionerSpouse, - petitionFile: {}, - petitionFileSize: 1, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, - stinFile: {}, - stinFileSize: 1, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.petitionerSpouse, + petitionFile: {}, + petitionFileSize: 1, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + stinFile: {}, + stinFileSize: 1, + }); expect(electronicPetition.isValid()).toEqual(false); }); it('can validate primary contact name', () => { - const electronicPetition = new ElectronicPetition( - { - caseType: CASE_TYPES_MAP.other, - contactPrimary: { - address1: '876 12th Ave', - city: 'Nashville', - country: 'USA', - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'someone@example.com', - name: 'Jimmy Dean', - phone: '1234567890', - postalCode: '05198', - state: 'AK', - }, - contactSecondary: { - address1: '1599 Pennsylvania Ave', - city: 'Walla Walla', - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'someone@example.com', - name: 'Betty Crocker', - phone: '1234567890', - postalCode: '78774', - state: 'WA', - }, - filingType: 'Myself', - hasIrsNotice: true, - irsNoticeDate: '2009-10-13', - partyType: PARTY_TYPES.petitionerSpouse, - petitionFile: {}, - petitionFileSize: 1, - preferredTrialCity: 'Memphis, Tennessee', - procedureType: 'Small', - signature: true, - stinFile: {}, - stinFileSize: 1, + const electronicPetition = new ElectronicPetition({ + caseType: CASE_TYPES_MAP.other, + contactPrimary: { + address1: '876 12th Ave', + city: 'Nashville', + country: 'USA', + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'someone@example.com', + name: 'Jimmy Dean', + phone: '1234567890', + postalCode: '05198', + state: 'AK', + }, + contactSecondary: { + address1: '1599 Pennsylvania Ave', + city: 'Walla Walla', + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'someone@example.com', + name: 'Betty Crocker', + phone: '1234567890', + postalCode: '78774', + state: 'WA', }, - { applicationContext }, - ); + filingType: 'Myself', + hasIrsNotice: true, + irsNoticeDate: '2009-10-13', + partyType: PARTY_TYPES.petitionerSpouse, + petitionFile: {}, + petitionFileSize: 1, + preferredTrialCity: 'Memphis, Tennessee', + procedureType: 'Small', + signature: true, + stinFile: {}, + stinFileSize: 1, + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); }); diff --git a/shared/src/business/entities/cases/ElectronicPetitionInformationFactory.test.ts b/shared/src/business/entities/cases/ElectronicPetitionInformationFactory.test.ts index 7ae0f72a765..23b0f424bfd 100644 --- a/shared/src/business/entities/cases/ElectronicPetitionInformationFactory.test.ts +++ b/shared/src/business/entities/cases/ElectronicPetitionInformationFactory.test.ts @@ -8,16 +8,10 @@ import { PETITION_TYPES, } from '../EntityConstants'; import { ElectronicPetitionInformationFactory } from './ElectronicPetitionInformationFactory'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('ElectronicPetitionInformationFactory entity', () => { it('requires wizard step', () => { - const electronicPetition = new ElectronicPetitionInformationFactory( - {}, - { - applicationContext, - }, - ); + const electronicPetition = new ElectronicPetitionInformationFactory({}); expect( electronicPetition.getFormattedValidationErrors()!!.wizardStep, ).toEqual('"wizardStep" is required'); @@ -26,45 +20,30 @@ describe('ElectronicPetitionInformationFactory entity', () => { describe('wizard step 1', () => { it('requires stinFile', () => { - const electronicPetition = new ElectronicPetitionInformationFactory( - { - wizardStep: '1', - }, - { - applicationContext, - }, - ); + const electronicPetition = new ElectronicPetitionInformationFactory({ + wizardStep: '1', + }); expect( electronicPetition.getFormattedValidationErrors()!.stinFile, ).toEqual('Upload a Statement of Taxpayer Identification Number (STIN)'); }); it('should be valid if all step 1 and step 2 params are present', () => { - const electronicPetition = new ElectronicPetitionInformationFactory( - { - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, - wizardStep: '1', - }, - { - applicationContext, - }, - ); + const electronicPetition = new ElectronicPetitionInformationFactory({ + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, + wizardStep: '1', + }); expect(electronicPetition.getFormattedValidationErrors()!).toEqual(null); }); describe('STIN file size', () => { it('should inform you if stin file size is greater than the PDF max file size', () => { - const electronicPetition = new ElectronicPetitionInformationFactory( - { - stinFile: new File([], 'test.pdf'), - stinFileSize: MAX_FILE_SIZE_BYTES + 5, - wizardStep: '1', - }, - { - applicationContext, - }, - ); + const electronicPetition = new ElectronicPetitionInformationFactory({ + stinFile: new File([], 'test.pdf'), + stinFileSize: MAX_FILE_SIZE_BYTES + 5, + wizardStep: '1', + }); expect( electronicPetition.getFormattedValidationErrors()!.stinFileSize, @@ -74,45 +53,30 @@ describe('ElectronicPetitionInformationFactory entity', () => { }); it('should inform you if stin file size is zero', () => { - const electronicPetition = new ElectronicPetitionInformationFactory( - { - stinFile: new File([], 'test.pdf'), - stinFileSize: 0, - wizardStep: '1', - }, - { - applicationContext, - }, - ); + const electronicPetition = new ElectronicPetitionInformationFactory({ + stinFile: new File([], 'test.pdf'), + stinFileSize: 0, + wizardStep: '1', + }); expect( electronicPetition.getFormattedValidationErrors()!.stinFileSize, ).toEqual('Your STIN file size is empty'); }); it('should not error on stinFileSize when stinFile is undefined', () => { - const electronicPetition = new ElectronicPetitionInformationFactory( - { - wizardStep: '1', - }, - { - applicationContext, - }, - ); + const electronicPetition = new ElectronicPetitionInformationFactory({ + wizardStep: '1', + }); expect( electronicPetition.getFormattedValidationErrors()!.stinFileSize, ).toBeUndefined(); }); it('should error on stinFileSize when stinFile is defined', () => { - const electronicPetition = new ElectronicPetitionInformationFactory( - { - stinFile: new File([], 'testStinFile.pdf'), - wizardStep: '1', - }, - { - applicationContext, - }, - ); + const electronicPetition = new ElectronicPetitionInformationFactory({ + stinFile: new File([], 'testStinFile.pdf'), + wizardStep: '1', + }); expect( electronicPetition.getFormattedValidationErrors()!.stinFileSize, ).toEqual('Your STIN file size is empty'); @@ -122,29 +86,19 @@ describe('ElectronicPetitionInformationFactory entity', () => { describe('wizard step 2', () => { it('requires all wizard step 1 and 2 items', () => { - let electronicPetition = new ElectronicPetitionInformationFactory( - { - wizardStep: '2', - }, - { - applicationContext, - }, - ); + let electronicPetition = new ElectronicPetitionInformationFactory({ + wizardStep: '2', + }); expect(electronicPetition.getFormattedValidationErrors()!).toEqual({ hasIrsNotice: 'Indicate whether you received an IRS notice', petitionFile: 'Upload a Petition', stinFile: 'Upload a Statement of Taxpayer Identification Number (STIN)', }); - electronicPetition = new ElectronicPetitionInformationFactory( - { - stinFile: new File([], 'test.pdf'), - wizardStep: '2', - }, - { - applicationContext, - }, - ); + electronicPetition = new ElectronicPetitionInformationFactory({ + stinFile: new File([], 'test.pdf'), + wizardStep: '2', + }); expect(electronicPetition.getFormattedValidationErrors()!).toEqual({ hasIrsNotice: 'Indicate whether you received an IRS notice', petitionFile: 'Upload a Petition', @@ -153,16 +107,11 @@ describe('ElectronicPetitionInformationFactory entity', () => { }); it('requires hasIrsNotice and petitionFile if no params from step 2 are present', () => { - const electronicPetition = new ElectronicPetitionInformationFactory( - { - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, - wizardStep: '2', - }, - { - applicationContext, - }, - ); + const electronicPetition = new ElectronicPetitionInformationFactory({ + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, + wizardStep: '2', + }); expect(electronicPetition.getFormattedValidationErrors()!).toEqual({ hasIrsNotice: 'Indicate whether you received an IRS notice', petitionFile: 'Upload a Petition', @@ -170,64 +119,49 @@ describe('ElectronicPetitionInformationFactory entity', () => { }); it('requires caseType if hasIrsNotice is present', () => { - const electronicPetition = new ElectronicPetitionInformationFactory( - { - hasIrsNotice: true, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 1, - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, - wizardStep: '2', - }, - { - applicationContext, - }, - ); + const electronicPetition = new ElectronicPetitionInformationFactory({ + hasIrsNotice: true, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 1, + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, + wizardStep: '2', + }); expect(electronicPetition.getFormattedValidationErrors()!).toEqual({ caseType: 'Select a case type', }); }); it('should be valid if all step 1 and step 2 params are present', () => { - const electronicPetition = new ElectronicPetitionInformationFactory( - { - caseType: CASE_TYPES_MAP.deficiency, - hasIrsNotice: true, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 1, - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, - wizardStep: '2', - }, - { - applicationContext, - }, - ); + const electronicPetition = new ElectronicPetitionInformationFactory({ + caseType: CASE_TYPES_MAP.deficiency, + hasIrsNotice: true, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 1, + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, + wizardStep: '2', + }); expect(electronicPetition.getFormattedValidationErrors()!).toEqual(null); }); it('should be valid if all step 1 and step 2 params are present, but a partyType and invalid contactPrimary are present', () => { - const electronicPetition = new ElectronicPetitionInformationFactory( - { - caseType: CASE_TYPES_MAP.deficiency, - hasIrsNotice: true, - partyType: PARTY_TYPES.petitioner, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 1, - petitionType: undefined, - petitioners: [ - { - name: 'Something', - }, - ], - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, - wizardStep: '2', - }, - { - applicationContext, - }, - ); + const electronicPetition = new ElectronicPetitionInformationFactory({ + caseType: CASE_TYPES_MAP.deficiency, + hasIrsNotice: true, + partyType: PARTY_TYPES.petitioner, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 1, + petitionType: undefined, + petitioners: [ + { + name: 'Something', + }, + ], + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, + wizardStep: '2', + }); expect(electronicPetition.getFormattedValidationErrors()!).toEqual(null); expect(electronicPetition.petitionType).toEqual( PETITION_TYPES.userUploaded, @@ -237,14 +171,9 @@ describe('ElectronicPetitionInformationFactory entity', () => { describe('wizard step 3', () => { it('requires all wizard step 1, 2, and 3 items', () => { - let electronicPetition = new ElectronicPetitionInformationFactory( - { - wizardStep: '3', - }, - { - applicationContext, - }, - ); + let electronicPetition = new ElectronicPetitionInformationFactory({ + wizardStep: '3', + }); expect(electronicPetition.getFormattedValidationErrors()!).toEqual({ filingType: 'Select on whose behalf you are filing', hasIrsNotice: 'Indicate whether you received an IRS notice', @@ -253,17 +182,12 @@ describe('ElectronicPetitionInformationFactory entity', () => { stinFile: 'Upload a Statement of Taxpayer Identification Number (STIN)', }); - electronicPetition = new ElectronicPetitionInformationFactory( - { - hasIrsNotice: true, - petitionFile: new File([], 'test.pdf'), - stinFile: new File([], 'test.pdf'), - wizardStep: '3', - }, - { - applicationContext, - }, - ); + electronicPetition = new ElectronicPetitionInformationFactory({ + hasIrsNotice: true, + petitionFile: new File([], 'test.pdf'), + stinFile: new File([], 'test.pdf'), + wizardStep: '3', + }); expect(electronicPetition.getFormattedValidationErrors()!).toEqual({ caseType: 'Select a case type', filingType: 'Select on whose behalf you are filing', @@ -274,20 +198,15 @@ describe('ElectronicPetitionInformationFactory entity', () => { }); it('requires filingType and partyType if wizard step 1 and 2 required fields are present', () => { - let electronicPetition = new ElectronicPetitionInformationFactory( - { - caseType: CASE_TYPES_MAP.deficiency, - hasIrsNotice: true, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 1, - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, - wizardStep: '3', - }, - { - applicationContext, - }, - ); + let electronicPetition = new ElectronicPetitionInformationFactory({ + caseType: CASE_TYPES_MAP.deficiency, + hasIrsNotice: true, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 1, + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, + wizardStep: '3', + }); expect(electronicPetition.getFormattedValidationErrors()!).toEqual({ filingType: 'Select on whose behalf you are filing', partyType: 'Select a party type', @@ -295,22 +214,17 @@ describe('ElectronicPetitionInformationFactory entity', () => { }); it('requires corporateDisclosureFile if filingType is A business', () => { - let electronicPetition = new ElectronicPetitionInformationFactory( - { - caseType: CASE_TYPES_MAP.deficiency, - filingType: 'A business', - hasIrsNotice: true, - partyType: PARTY_TYPES.corporation, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 1, - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, - wizardStep: '3', - }, - { - applicationContext, - }, - ); + let electronicPetition = new ElectronicPetitionInformationFactory({ + caseType: CASE_TYPES_MAP.deficiency, + filingType: 'A business', + hasIrsNotice: true, + partyType: PARTY_TYPES.corporation, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 1, + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, + wizardStep: '3', + }); expect( electronicPetition.getFormattedValidationErrors()! .corporateDisclosureFile, @@ -318,22 +232,17 @@ describe('ElectronicPetitionInformationFactory entity', () => { }); it('does not require corporateDisclosureFile if filingType is not A business', () => { - let electronicPetition = new ElectronicPetitionInformationFactory( - { - caseType: CASE_TYPES_MAP.deficiency, - filingType: 'something else', - hasIrsNotice: true, - partyType: PARTY_TYPES.corporation, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 1, - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, - wizardStep: '3', - }, - { - applicationContext, - }, - ); + let electronicPetition = new ElectronicPetitionInformationFactory({ + caseType: CASE_TYPES_MAP.deficiency, + filingType: 'something else', + hasIrsNotice: true, + partyType: PARTY_TYPES.corporation, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 1, + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, + wizardStep: '3', + }); expect( electronicPetition.getFormattedValidationErrors()! .corporateDisclosureFile, @@ -341,22 +250,17 @@ describe('ElectronicPetitionInformationFactory entity', () => { }); it('requires only contactPrimary if partyType is Petitioner', () => { - let electronicPetition = new ElectronicPetitionInformationFactory( - { - caseType: CASE_TYPES_MAP.deficiency, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.petitioner, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 1, - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, - wizardStep: '3', - }, - { - applicationContext, - }, - ); + let electronicPetition = new ElectronicPetitionInformationFactory({ + caseType: CASE_TYPES_MAP.deficiency, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.petitioner, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 1, + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, + wizardStep: '3', + }); expect(electronicPetition.getFormattedValidationErrors()!).toEqual({ petitioners: [ { @@ -374,22 +278,17 @@ describe('ElectronicPetitionInformationFactory entity', () => { }); it('requires contactPrimary and contactSecondary if partyType is Petitioner & Spouse', () => { - let electronicPetition = new ElectronicPetitionInformationFactory( - { - caseType: CASE_TYPES_MAP.deficiency, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.petitionerSpouse, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 1, - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, - wizardStep: '3', - }, - { - applicationContext, - }, - ); + let electronicPetition = new ElectronicPetitionInformationFactory({ + caseType: CASE_TYPES_MAP.deficiency, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.petitionerSpouse, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 1, + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, + wizardStep: '3', + }); expect( electronicPetition.getFormattedValidationErrors()!.petitioners, ).toBeDefined(); @@ -398,14 +297,9 @@ describe('ElectronicPetitionInformationFactory entity', () => { describe('wizard step 4', () => { it('requires all wizard step 1, 2, 3, and 4 items', () => { - let electronicPetition = new ElectronicPetitionInformationFactory( - { - wizardStep: '4', - }, - { - applicationContext, - }, - ); + let electronicPetition = new ElectronicPetitionInformationFactory({ + wizardStep: '4', + }); expect(electronicPetition.getFormattedValidationErrors()!).toEqual({ filingType: 'Select on whose behalf you are filing', hasIrsNotice: 'Indicate whether you received an IRS notice', @@ -416,19 +310,14 @@ describe('ElectronicPetitionInformationFactory entity', () => { stinFile: 'Upload a Statement of Taxpayer Identification Number (STIN)', }); - electronicPetition = new ElectronicPetitionInformationFactory( - { - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.petitionerSpouse, - petitionFile: new File([], 'test.pdf'), - stinFile: new File([], 'test.pdf'), - wizardStep: '4', - }, - { - applicationContext, - }, - ); + electronicPetition = new ElectronicPetitionInformationFactory({ + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.petitionerSpouse, + petitionFile: new File([], 'test.pdf'), + stinFile: new File([], 'test.pdf'), + wizardStep: '4', + }); expect(electronicPetition.getFormattedValidationErrors()!).toEqual({ caseType: 'Select a case type', petitionFileSize: 'Your Petition file size is empty', @@ -460,45 +349,40 @@ describe('ElectronicPetitionInformationFactory entity', () => { }); it('returns no validation errors if all required fields from all steps are present', () => { - let electronicPetition = new ElectronicPetitionInformationFactory( - { - caseType: CASE_TYPES_MAP.deficiency, - contactSecondary: { + let electronicPetition = new ElectronicPetitionInformationFactory({ + caseType: CASE_TYPES_MAP.deficiency, + contactSecondary: { + address1: '123 Main St', + city: 'Somewhere', + countryType: COUNTRY_TYPES.DOMESTIC, + name: 'Test Secondary', + phone: '1234567890', + postalCode: '12345', + state: 'CA', + }, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.petitionerSpouse, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 1, + petitioners: [ + { address1: '123 Main St', city: 'Somewhere', + contactType: CONTACT_TYPES.primary, countryType: COUNTRY_TYPES.DOMESTIC, - name: 'Test Secondary', + name: 'Test Primary', phone: '1234567890', postalCode: '12345', state: 'CA', }, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.petitionerSpouse, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 1, - petitioners: [ - { - address1: '123 Main St', - city: 'Somewhere', - contactType: CONTACT_TYPES.primary, - countryType: COUNTRY_TYPES.DOMESTIC, - name: 'Test Primary', - phone: '1234567890', - postalCode: '12345', - state: 'CA', - }, - ], - preferredTrialCity: 'Boise, Idaho', - procedureType: 'Regular', - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, - wizardStep: '4', - }, - { - applicationContext, - }, - ); + ], + preferredTrialCity: 'Boise, Idaho', + procedureType: 'Regular', + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, + wizardStep: '4', + }); expect(electronicPetition.getFormattedValidationErrors()!).toEqual(null); expect(electronicPetition.isValid()).toBeTruthy(); }); diff --git a/shared/src/business/entities/cases/ElectronicPetitionInformationFactory.ts b/shared/src/business/entities/cases/ElectronicPetitionInformationFactory.ts index 89f6f6b1d79..497085ef7e5 100644 --- a/shared/src/business/entities/cases/ElectronicPetitionInformationFactory.ts +++ b/shared/src/business/entities/cases/ElectronicPetitionInformationFactory.ts @@ -34,7 +34,7 @@ export class ElectronicPetitionInformationFactory extends JoiValidationEntity { public wizardStep: number; public petitionType: string; - constructor(rawCase, { applicationContext }) { + constructor(rawCase) { super('ElectronicPetitionInformationFactory'); this.attachmentToPetitionFile = rawCase.attachmentToPetitionFile; @@ -58,7 +58,6 @@ export class ElectronicPetitionInformationFactory extends JoiValidationEntity { if (+this.wizardStep >= 3) { const contacts = ContactFactory({ - applicationContext, contactInfo: { primary: getContactPrimary(rawCase) || rawCase.contactPrimary, secondary: getContactSecondary(rawCase) || rawCase.contactSecondary, diff --git a/shared/src/business/entities/cases/PaperPetition.test.ts b/shared/src/business/entities/cases/PaperPetition.test.ts index 30dc5a9c654..d4af1b3d4e2 100644 --- a/shared/src/business/entities/cases/PaperPetition.test.ts +++ b/shared/src/business/entities/cases/PaperPetition.test.ts @@ -8,16 +8,17 @@ import { } from '../EntityConstants'; import { Correspondence } from '../Correspondence'; import { PaperPetition } from './PaperPetition'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { createISODateString } from '@shared/business/utilities/DateHandler'; +import { getUniqueId } from '@shared/sharedAppContext'; +import { mockPetitionsClerkUser } from '@shared/test/mockAuthUsers'; describe('paperPetition entity', () => { describe('validation', () => { - it('throws an exception when not provided an application context', () => { - expect(() => new PaperPetition({}, {} as any)).toThrow(); - }); - it('returns the expected set of errors for an empty object', () => { - const paperPetition = new PaperPetition({}, { applicationContext }); + const paperPetition = new PaperPetition( + {}, + { authorizedUser: mockPetitionsClerkUser }, + ); expect(paperPetition.getFormattedValidationErrors()).toEqual({ caseCaption: 'Enter a case caption', caseType: 'Select a case type', @@ -58,7 +59,7 @@ describe('paperPetition entity', () => { ], preferredTrialCity: 'Boise, Idaho', procedureType: 'Small', - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), requestForPlaceOfTrialFile: { anObject: true }, requestForPlaceOfTrialFileSize: 1, statistics: [ @@ -70,7 +71,7 @@ describe('paperPetition entity', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect(paperPetition.getFormattedValidationErrors()).toEqual(null); @@ -113,7 +114,7 @@ describe('paperPetition entity', () => { ], preferredTrialCity: 'Boise, Idaho', procedureType: 'Small', - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), requestForPlaceOfTrialFile: { anObject: true }, requestForPlaceOfTrialFileSize: 1, statistics: [ @@ -125,7 +126,7 @@ describe('paperPetition entity', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect(paperPetition.getFormattedValidationErrors()).toEqual(null); @@ -162,9 +163,9 @@ describe('paperPetition entity', () => { }, ], procedureType: 'Small', - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect(paperPetition.getFormattedValidationErrors()).toEqual(null); @@ -200,9 +201,9 @@ describe('paperPetition entity', () => { }, ], procedureType: 'Small', - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect(paperPetition.getFormattedValidationErrors()).toEqual(null); @@ -217,7 +218,7 @@ describe('paperPetition entity', () => { petitionFileSize: 1, receivedAt: '9999-01-01T00:00:00.000Z', }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect(paperPetition.getFormattedValidationErrors()).not.toEqual(null); }); @@ -227,9 +228,9 @@ describe('paperPetition entity', () => { { caseCaption: 'Dr. Leo Marvin, Petitioner', petitionFile: new File([], 'test.pdf'), - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect( @@ -242,9 +243,9 @@ describe('paperPetition entity', () => { { caseCaption: 'Dr. Leo Marvin, Petitioner', petitionPaymentStatus: PAYMENT_STATUS.WAIVED, - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect( @@ -258,7 +259,7 @@ describe('paperPetition entity', () => { { partyType: PARTY_TYPES.corporation, }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect( @@ -272,7 +273,7 @@ describe('paperPetition entity', () => { orderForCds: false, partyType: PARTY_TYPES.partnershipAsTaxMattersPartner, }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect( @@ -285,9 +286,9 @@ describe('paperPetition entity', () => { { applicationForWaiverOfFilingFeeFile: new File([], 'test.pdf'), caseCaption: 'Dr. Leo Marvin, Petitioner', - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect( @@ -300,10 +301,10 @@ describe('paperPetition entity', () => { const paperPetition = new PaperPetition( { caseCaption: 'Dr. Leo Marvin, Petitioner', - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), stinFile: new File([], 'test.pdf'), }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect( @@ -316,9 +317,9 @@ describe('paperPetition entity', () => { { attachmentToPetitionFile: new File([], 'test.pdf'), caseCaption: 'Dr. Leo Marvin, Petitioner', - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect( @@ -332,9 +333,9 @@ describe('paperPetition entity', () => { { caseCaption: 'Dr. Leo Marvin, Petitioner', corporateDisclosureFile: new File([], 'test.pdf'), - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect( @@ -347,10 +348,10 @@ describe('paperPetition entity', () => { const paperPetition = new PaperPetition( { caseCaption: 'Dr. Leo Marvin, Petitioner', - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), requestForPlaceOfTrialFile: new File([], 'test.pdf'), }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect( @@ -363,10 +364,10 @@ describe('paperPetition entity', () => { const paperPetition = new PaperPetition( { caseCaption: 'Dr. Leo Marvin, Petitioner', - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), requestForPlaceOfTrialFile: new File([], 'test.pdf'), }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect( @@ -379,9 +380,9 @@ describe('paperPetition entity', () => { { caseCaption: 'Dr. Roslindis Angelino, Petitioner', preferredTrialCity: 'Flavortown, AR', - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect( @@ -419,11 +420,11 @@ describe('paperPetition entity', () => { }, ], procedureType: 'Small', - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), stinFile: { anObject: true }, stinFileSize: 1, }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect(paperPetition.isValid()).toEqual(false); @@ -463,11 +464,11 @@ describe('paperPetition entity', () => { }, ], procedureType: 'Small', - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), stinFile: { anObject: true }, stinFileSize: 1, }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect(paperPetition.isValid()).toEqual(false); @@ -486,14 +487,14 @@ describe('paperPetition entity', () => { contactSecondary: {}, partyType: PARTY_TYPES.petitionerDeceasedSpouse, }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect(paperPetition.petitioners[1].phone).toEqual('N/A'); }); }); it('should populate archivedCorrespondences', () => { - const mockGuid = applicationContext.getUniqueId(); + const mockGuid = getUniqueId(); const mockCorrespondence = new Correspondence({ correspondenceId: mockGuid, documentTitle: 'My Correspondence', @@ -527,7 +528,7 @@ describe('paperPetition entity', () => { ], preferredTrialCity: 'Boise, Idaho', procedureType: 'Small', - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), requestForPlaceOfTrialFile: { anObject: true }, requestForPlaceOfTrialFileSize: 1, statistics: [ @@ -539,7 +540,7 @@ describe('paperPetition entity', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); expect(paperPetition.getFormattedValidationErrors()).toEqual(null); diff --git a/shared/src/business/entities/cases/PaperPetition.ts b/shared/src/business/entities/cases/PaperPetition.ts index 17e3ec0ccc1..21bab2e5ba1 100644 --- a/shared/src/business/entities/cases/PaperPetition.ts +++ b/shared/src/business/entities/cases/PaperPetition.ts @@ -15,6 +15,7 @@ import { DocketEntry } from '../DocketEntry'; import { JoiValidationConstants } from '../JoiValidationConstants'; import { JoiValidationEntity } from '../JoiValidationEntity'; import { Statistic } from '../Statistic'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import joi from 'joi'; /** @@ -64,10 +65,10 @@ export class PaperPetition extends JoiValidationEntity { public archivedCorrespondences: any; public docketEntries: DocketEntry[]; - constructor(rawProps, { applicationContext }) { - if (!applicationContext) { - throw new TypeError('applicationContext must be defined'); - } + constructor( + rawProps, + { authorizedUser }: { authorizedUser: UnknownAuthUser }, + ) { super('PaperPetition'); this.attachmentToPetitionFile = rawProps.attachmentToPetitionFile; this.attachmentToPetitionFileSize = rawProps.attachmentToPetitionFileSize; @@ -117,14 +118,15 @@ export class PaperPetition extends JoiValidationEntity { this.docketEntries = rawProps.docketEntries || []; this.statistics = Array.isArray(rawProps.statistics) - ? rawProps.statistics.map( - statistic => new Statistic(statistic, { applicationContext }), - ) + ? rawProps.statistics.map(statistic => new Statistic(statistic)) : []; this.archivedDocketEntries = Array.isArray(rawProps.archivedDocketEntries) ? rawProps.archivedDocketEntries.map( - doc => new DocketEntry(doc, { applicationContext }), + doc => + new DocketEntry(doc, { + authorizedUser, + }), ) : []; @@ -137,7 +139,6 @@ export class PaperPetition extends JoiValidationEntity { : []; const contacts = ContactFactory({ - applicationContext, contactInfo: { primary: getContactPrimary(rawProps) || rawProps.contactPrimary, secondary: getContactSecondary(rawProps) || rawProps.contactSecondary, diff --git a/shared/src/business/entities/cases/PublicCase.test.ts b/shared/src/business/entities/cases/PublicCase.test.ts index d1703a86ce9..acdd360175f 100644 --- a/shared/src/business/entities/cases/PublicCase.test.ts +++ b/shared/src/business/entities/cases/PublicCase.test.ts @@ -10,20 +10,17 @@ import { } from '../EntityConstants'; import { MOCK_CASE } from '../../../test/mockCase'; import { MOCK_COMPLEX_CASE } from '../../../test/mockComplexCase'; -import { MOCK_USERS } from '../../../test/mockUsers'; import { PublicCase } from './PublicCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; import { getContactSecondary } from './Case'; -import { mockPrivatePractitionerUser } from '@shared/test/mockAuthUsers'; +import { + mockIrsPractitionerUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; describe('PublicCase', () => { const mockContactId = 'b430f7f9-06f3-4a25-915d-5f51adab2f29'; const mockContactIdSecond = '39a359e9-dde3-409e-b40e-77a4959b6f2c'; - it('should throw an error when applicationContext is not provided to the constructor', () => { - expect(() => new PublicCase({}, {} as any)).toThrow(TypeError); - }); - describe('validation', () => { it('should validate when all information is provided and case is not sealed', () => { const entity = new PublicCase( @@ -45,7 +42,7 @@ describe('PublicCase', () => { receivedAt: '2020-01-05T03:30:45.007Z', status: CASE_STATUS_TYPES.calendared, }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(entity.getFormattedValidationErrors()).toBe(null); @@ -63,7 +60,7 @@ describe('PublicCase', () => { receivedAt: '2020-01-05T03:30:45.007Z', sealedDate: '2020-01-05T03:30:45.007Z', }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(entity.getFormattedValidationErrors()).toMatchObject({ @@ -106,7 +103,7 @@ describe('PublicCase', () => { receivedAt: 'testing', status: CASE_STATUS_TYPES.new, }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(entity.toRawObject()).toEqual({ @@ -163,7 +160,7 @@ describe('PublicCase', () => { receivedAt: 'testing', status: CASE_STATUS_TYPES.calendared, }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(entity.toRawObject()).toEqual({ @@ -207,7 +204,7 @@ describe('PublicCase', () => { { docketEntryId: '987', eventCode: TRANSCRIPT_EVENT_CODE }, ], }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(entity.toRawObject().docketEntries).toMatchObject([ @@ -243,7 +240,7 @@ describe('PublicCase', () => { ...MOCK_CASE, docketEntries: [docketEntry1, docketEntry2, docketEntry3], }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(entity.docketEntries).toMatchObject([ @@ -261,7 +258,7 @@ describe('PublicCase', () => { docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.SMALL_LIEN_LEVY, docketNumberWithSuffix: null, }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(entity.docketNumberWithSuffix).toBe('102-20SL'); }); @@ -274,13 +271,15 @@ describe('PublicCase', () => { docketNumberSuffix: null, docketNumberWithSuffix: null, }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(entity.docketNumberWithSuffix).toBe('102-20'); }); it('should correctly ingest a complex case', () => { - const entity = new PublicCase(MOCK_COMPLEX_CASE, { applicationContext }); + const entity = new PublicCase(MOCK_COMPLEX_CASE, { + authorizedUser: undefined, + }); expect(() => entity.validate()).not.toThrow(); expect(() => entity.validateForMigration()).not.toThrow(); @@ -294,7 +293,7 @@ describe('PublicCase', () => { petitioners: [{ contactType: CONTACT_TYPES.primary }], sealedDate: 'some date', }, - { applicationContext }, + { authorizedUser: undefined }, ); expect(entity.isSealed).toBe(true); @@ -304,10 +303,6 @@ describe('PublicCase', () => { }); it('should not show leadDocketNumber if user is does not have IRS Practitioner role', () => { - applicationContext.getCurrentUser.mockReturnValueOnce({ - role: ROLES.privatePractitioner, - }); - const rawCase = { ...MOCK_CASE, irsPractitioners: [ @@ -336,7 +331,9 @@ describe('PublicCase', () => { }, ], }; - const entity = new PublicCase(rawCase, { applicationContext }); + const entity = new PublicCase(rawCase, { + authorizedUser: mockPrivatePractitionerUser, + }); expect(entity.irsPractitioners).toBeUndefined(); expect(entity.privatePractitioners).toBeUndefined(); @@ -373,7 +370,6 @@ describe('PublicCase', () => { ], }; const entity = new PublicCase(rawCase, { - applicationContext, authorizedUser: mockPrivatePractitionerUser, }); @@ -383,12 +379,6 @@ describe('PublicCase', () => { }); describe('irsPractitioner', () => { - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue( - MOCK_USERS['f7d90c05-f6cd-442c-a168-202db587f16f'], - ); - }); - it('an irsPractitioner should be able to see otherPetitioners and otherFilers', () => { const mockOtherFiler = { address1: '42 Lamb Sauce Blvd', @@ -426,7 +416,7 @@ describe('PublicCase', () => { mockOtherPetitioner, ], }, - { applicationContext }, + { authorizedUser: mockIrsPractitionerUser }, ); expect(entity.petitioners).toEqual( @@ -439,10 +429,6 @@ describe('PublicCase', () => { }); it('should show all contact and practitioner information if user has IRS Practitioner role', () => { - applicationContext.getCurrentUser.mockReturnValueOnce({ - role: ROLES.irsPractitioner, - }); - const rawContactPrimary = { address1: '907 West Rocky Cowley Parkway', address2: '104 West 120th Street', @@ -534,7 +520,9 @@ describe('PublicCase', () => { ], receivedAt: 'testing', }; - const entity = new PublicCase(rawCase, { applicationContext }); + const entity = new PublicCase(rawCase, { + authorizedUser: mockIrsPractitionerUser, + }); expect(entity.toRawObject()).toMatchObject({ caseCaption: 'testing', @@ -551,10 +539,6 @@ describe('PublicCase', () => { }); it('should not show practitioner and other filer information if user has IRS Practitioner role and the case is sealed', () => { - applicationContext.getCurrentUser.mockReturnValueOnce({ - role: ROLES.irsPractitioner, - }); - const rawCase = { ...MOCK_CASE, irsPractitioners: [ @@ -582,7 +566,9 @@ describe('PublicCase', () => { }, ], }; - const entity = new PublicCase(rawCase, { applicationContext }); + const entity = new PublicCase(rawCase, { + authorizedUser: mockIrsPractitionerUser, + }); expect(entity.irsPractitioners).toBeUndefined(); expect(entity.privatePractitioners).toBeUndefined(); @@ -590,10 +576,6 @@ describe('PublicCase', () => { }); it('should show leadDocketNumber if user is has IRS Practitioner role', () => { - applicationContext.getCurrentUser.mockReturnValueOnce({ - role: ROLES.irsPractitioner, - }); - const rawCase = { ...MOCK_CASE, irsPractitioners: [ @@ -622,7 +604,9 @@ describe('PublicCase', () => { }, ], }; - const entity = new PublicCase(rawCase, { applicationContext }); + const entity = new PublicCase(rawCase, { + authorizedUser: mockIrsPractitionerUser, + }); expect(entity.irsPractitioners).toBeDefined(); expect(entity.privatePractitioners).toBeDefined(); diff --git a/shared/src/business/entities/cases/PublicCase.ts b/shared/src/business/entities/cases/PublicCase.ts index e55a7984679..67f3e2a46cf 100644 --- a/shared/src/business/entities/cases/PublicCase.ts +++ b/shared/src/business/entities/cases/PublicCase.ts @@ -38,19 +38,13 @@ export class PublicCase extends JoiValidationEntity { constructor( rawCase: any, { - applicationContext, authorizedUser, }: { - applicationContext: IApplicationContext; - authorizedUser?: UnknownAuthUser; + authorizedUser: UnknownAuthUser; }, ) { super('PublicCase'); - if (!applicationContext) { - throw new TypeError('applicationContext must be defined'); - } - this.entityName = 'PublicCase'; this.canAllowDocumentService = rawCase.canAllowDocumentService; this.canAllowPrintableDocketRecord = rawCase.canAllowPrintableDocketRecord; @@ -73,9 +67,7 @@ export class PublicCase extends JoiValidationEntity { this.isSealed = isSealedCase(rawCase); - const currentUser = authorizedUser || applicationContext.getCurrentUser(); - - if (currentUser.role === ROLES.irsPractitioner && !this.isSealed) { + if (authorizedUser?.role === ROLES.irsPractitioner && !this.isSealed) { this.petitioners = rawCase.petitioners; this.irsPractitioners = (rawCase.irsPractitioners || []).map( diff --git a/shared/src/business/entities/contacts/Contact.test.ts b/shared/src/business/entities/contacts/Contact.test.ts index ec8ae91ed2c..b50bfd1e4ba 100644 --- a/shared/src/business/entities/contacts/Contact.test.ts +++ b/shared/src/business/entities/contacts/Contact.test.ts @@ -1,6 +1,5 @@ import { Contact } from './Contact'; import { MOCK_CONTACT_PRIMARY } from '../../../test/mockContact'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('Contact', () => { describe('hasEAccess validation', () => { @@ -12,7 +11,6 @@ describe('Contact', () => { hasEAccess: true, }, 'PetitionerPrimaryContact', - { applicationContext }, ); expect(contact.getFormattedValidationErrors()!.email).toEqual( @@ -28,7 +26,6 @@ describe('Contact', () => { hasEAccess: false, }, 'PetitionerPrimaryContact', - { applicationContext }, ); expect(contact.getFormattedValidationErrors()?.email).toEqual(undefined); diff --git a/shared/src/business/entities/contacts/Contact.ts b/shared/src/business/entities/contacts/Contact.ts index e754b61b79f..34e7c667cc4 100644 --- a/shared/src/business/entities/contacts/Contact.ts +++ b/shared/src/business/entities/contacts/Contact.ts @@ -10,6 +10,7 @@ import { import { JoiValidationConstants } from '../JoiValidationConstants'; import { JoiValidationEntity } from '../JoiValidationEntity'; import { formatPhoneNumber } from '../../utilities/formatPhoneNumber'; +import { getUniqueId } from '@shared/sharedAppContext'; import joi from 'joi'; export class Contact extends JoiValidationEntity { @@ -38,17 +39,10 @@ export class Contact extends JoiValidationEntity { public hasEAccess?: boolean; public placeOfLegalResidence?: string; - constructor( - rawContact, - contactName: string, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { + constructor(rawContact, contactName: string) { super(contactName); - if (!applicationContext) { - throw new TypeError('applicationContext must be defined'); - } - this.contactId = rawContact.contactId || applicationContext.getUniqueId(); + this.contactId = rawContact.contactId || getUniqueId(); this.address1 = rawContact.address1; this.address2 = rawContact.address2 || undefined; this.address3 = rawContact.address3 || undefined; diff --git a/shared/src/business/entities/contacts/ContactFactory.test.ts b/shared/src/business/entities/contacts/ContactFactory.test.ts index e21f0a605a0..4a81c8a29bd 100644 --- a/shared/src/business/entities/contacts/ContactFactory.test.ts +++ b/shared/src/business/entities/contacts/ContactFactory.test.ts @@ -7,7 +7,6 @@ import { } from '../EntityConstants'; import { ContactFactory } from './ContactFactory'; import { ElectronicPetition } from '../cases/ElectronicPetition'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('ContactFactory', () => { const baseElectronicPetition = { @@ -43,167 +42,128 @@ describe('ContactFactory', () => { state: 'AK', }; - it('should throw an error if app context is not passed in', () => { - expect( - () => new ElectronicPetition(baseElectronicPetition, {} as any), - ).toThrow(); - }); - describe('for Corporation Contacts', () => { it('should not validate without contact when the case status is new', () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType: PARTY_TYPES.corporation, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType: PARTY_TYPES.corporation, + }); expect(electronicPetition.isValid()).toEqual(false); }); it('can validate primary contact when the case is not served', () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType: PARTY_TYPES.corporation, - petitioners: [baseContact], - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType: PARTY_TYPES.corporation, + petitioners: [baseContact], + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); }); it('can validate Petitioner contact when the case is not served', () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType: PARTY_TYPES.petitioner, - petitioners: [baseContact], - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType: PARTY_TYPES.petitioner, + petitioners: [baseContact], + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); it('passes validation when primary contact is defined and everything else is valid on an unserved case', () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType: PARTY_TYPES.estateWithoutExecutor, - petitioners: [baseContact], - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType: PARTY_TYPES.estateWithoutExecutor, + petitioners: [baseContact], + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); it('passes validation when in care of is undefined and everything else is valid on a served case', () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType: PARTY_TYPES.estateWithoutExecutor, - petitioners: [ - { - ...baseContact, - contactType: CONTACT_TYPES.petitioner, - inCareOf: undefined, - }, - ], - status: CASE_STATUS_TYPES.generalDocketReadyForTrial, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType: PARTY_TYPES.estateWithoutExecutor, + petitioners: [ + { + ...baseContact, + contactType: CONTACT_TYPES.petitioner, + inCareOf: undefined, + }, + ], + status: CASE_STATUS_TYPES.generalDocketReadyForTrial, + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); it('returns false for isValid if primary contact is missing', () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType: PARTY_TYPES.estate, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType: PARTY_TYPES.estate, + }); expect(electronicPetition.isValid()).toEqual(false); }); it('defaults isAddressSealed to false when no value is specified', () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType: PARTY_TYPES.estate, - petitioners: [baseContact], - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType: PARTY_TYPES.estate, + petitioners: [baseContact], + }); expect(electronicPetition.getContactPrimary().isAddressSealed).toBe(false); }); it('sets the value of isAddressSealed when a value is specified', () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType: PARTY_TYPES.estate, - petitioners: [ - { - ...baseContact, - isAddressSealed: true, - }, - ], - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType: PARTY_TYPES.estate, + petitioners: [ + { + ...baseContact, + isAddressSealed: true, + }, + ], + }); expect(electronicPetition.getContactPrimary().isAddressSealed).toBe(true); }); it('defaults sealedAndUnavailable to false when no value is specified', () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType: PARTY_TYPES.estate, - petitioners: [baseContact], - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType: PARTY_TYPES.estate, + petitioners: [baseContact], + }); expect(electronicPetition.getContactPrimary().sealedAndUnavailable).toBe( false, ); }); it('sets the value of sealedAndUnavailable when a value is specified', () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType: PARTY_TYPES.estate, - petitioners: [ - { - ...baseContact, - sealedAndUnavailable: true, - }, - ], - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType: PARTY_TYPES.estate, + petitioners: [ + { + ...baseContact, + sealedAndUnavailable: true, + }, + ], + }); expect(electronicPetition.getContactPrimary().sealedAndUnavailable).toBe( true, ); }); it('formats phone number string', () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - petitioners: [ - { - ...baseContact, - phone: '4444444444', - }, - ], - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + petitioners: [ + { + ...baseContact, + phone: '4444444444', + }, + ], + }); expect(electronicPetition.getContactPrimary().phone).toEqual( '444-444-4444', @@ -211,46 +171,35 @@ describe('ContactFactory', () => { }); it('returns false for isValid if serviceIndicator is an invalid value', () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType: PARTY_TYPES.estate, - petitioners: [ - { - ...baseContact, - serviceIndicator: 'WHAT', - }, - ], - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType: PARTY_TYPES.estate, + petitioners: [ + { + ...baseContact, + serviceIndicator: 'WHAT', + }, + ], + }); expect(electronicPetition.isValid()).toEqual(false); }); it('a valid case returns true for isValid when status is new', () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType: PARTY_TYPES.estate, - petitioners: [baseContact], - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType: PARTY_TYPES.estate, + petitioners: [baseContact], + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); it('a valid case returns true for isValid when status is not new', () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType: PARTY_TYPES.estate, - petitioners: [ - { ...baseContact, contactType: CONTACT_TYPES.petitioner }, - ], - status: CASE_STATUS_TYPES.generalDocketReadyForTrial, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType: PARTY_TYPES.estate, + petitioners: [{ ...baseContact, contactType: CONTACT_TYPES.petitioner }], + status: CASE_STATUS_TYPES.generalDocketReadyForTrial, + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); @@ -274,25 +223,19 @@ describe('ContactFactory', () => { PARTY_TYPES.trust, ].forEach(partyType => { it(`can validate invalid ${partyType} contact`, () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType, + }); expect(electronicPetition.isValid()).toEqual(false); }); it(`can validate valid ${partyType} contact`, () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType, - petitioners: [baseContact], - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType, + petitioners: [baseContact], + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); }); @@ -300,31 +243,25 @@ describe('ContactFactory', () => { [PARTY_TYPES.petitionerDeceasedSpouse, PARTY_TYPES.petitionerSpouse].forEach( partyType => { it(`can validate invalid ${partyType} contact`, () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType, - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType, + }); expect(electronicPetition.isValid()).toEqual(false); }); it(`can validate valid ${partyType} contact`, () => { - const electronicPetition = new ElectronicPetition( - { - ...baseElectronicPetition, - partyType, - petitioners: [ - baseContact, - { - ...baseContact, - contactType: CONTACT_TYPES.secondary, - }, - ], - }, - { applicationContext }, - ); + const electronicPetition = new ElectronicPetition({ + ...baseElectronicPetition, + partyType, + petitioners: [ + baseContact, + { + ...baseContact, + contactType: CONTACT_TYPES.secondary, + }, + ], + }); expect(electronicPetition.getFormattedValidationErrors()).toEqual(null); }); }, @@ -332,14 +269,11 @@ describe('ContactFactory', () => { it('throws an Error (upon construction) if `partyType` is defined but not found in the available list', () => { expect(() => { - new ElectronicPetition( - { - ...baseElectronicPetition, - partyType: 'SOME INVALID PARTY TYPE', - petitioners: [baseContact], - }, - { applicationContext }, - ); + new ElectronicPetition({ + ...baseElectronicPetition, + partyType: 'SOME INVALID PARTY TYPE', + petitioners: [baseContact], + }); }).toThrow('Unrecognized party type "SOME INVALID PARTY TYPE"'); }); diff --git a/shared/src/business/entities/contacts/ContactFactory.ts b/shared/src/business/entities/contacts/ContactFactory.ts index c9e152270b3..e14a18bda1e 100644 --- a/shared/src/business/entities/contacts/ContactFactory.ts +++ b/shared/src/business/entities/contacts/ContactFactory.ts @@ -17,11 +17,9 @@ import { PetitionerTrustContact } from './PetitionerTrustContact'; import { SurvivingSpouseContact } from './SurvivingSpouseContact'; export function ContactFactory({ - applicationContext, contactInfo, partyType, }: { - applicationContext: IApplicationContext; contactInfo: any; partyType: PartyType; }) { @@ -30,135 +28,135 @@ export function ContactFactory({ case PARTY_TYPES.transferee: case PARTY_TYPES.petitioner: return { - primary: new PetitionerPrimaryContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), + primary: new PetitionerPrimaryContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), secondary: null, }; case PARTY_TYPES.conservator: return { - primary: new PetitionerConservatorContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), + primary: new PetitionerConservatorContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), }; case PARTY_TYPES.corporation: return { - primary: new PetitionerCorporationContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), + primary: new PetitionerCorporationContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), secondary: null, }; case PARTY_TYPES.custodian: return { - primary: new PetitionerCustodianContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), + primary: new PetitionerCustodianContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), secondary: null, }; case PARTY_TYPES.estate: return { - primary: new PetitionerEstateWithExecutorPrimaryContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), + primary: new PetitionerEstateWithExecutorPrimaryContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), secondary: null, }; case PARTY_TYPES.estateWithoutExecutor: return { - primary: new PetitionerIntermediaryContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), + primary: new PetitionerIntermediaryContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), secondary: null, }; case PARTY_TYPES.guardian: return { - primary: new PetitionerGuardianContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), + primary: new PetitionerGuardianContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), secondary: null, }; case PARTY_TYPES.nextFriendForIncompetentPerson: return { - primary: new NextFriendForIncompetentPersonContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), + primary: new NextFriendForIncompetentPersonContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), secondary: null, }; case PARTY_TYPES.nextFriendForMinor: return { - primary: new NextFriendForMinorContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), + primary: new NextFriendForMinorContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), secondary: null, }; case PARTY_TYPES.partnershipAsTaxMattersPartner: return { - primary: new PartnershipAsTaxMattersPartnerPrimaryContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), + primary: new PartnershipAsTaxMattersPartnerPrimaryContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), secondary: null, }; case PARTY_TYPES.partnershipBBA: return { - primary: new PartnershipBBAPrimaryContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), + primary: new PartnershipBBAPrimaryContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), secondary: null, }; case PARTY_TYPES.partnershipOtherThanTaxMatters: return { - primary: new PartnershipOtherThanTaxMattersPrimaryContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), + primary: new PartnershipOtherThanTaxMattersPrimaryContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), secondary: null, }; case PARTY_TYPES.petitionerDeceasedSpouse: return { - primary: new PetitionerPrimaryContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), - secondary: new PetitionerDeceasedSpouseContact( - { ...contactInfo.secondary, contactType: CONTACT_TYPES.secondary }, - { applicationContext }, - ), + primary: new PetitionerPrimaryContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), + secondary: new PetitionerDeceasedSpouseContact({ + ...contactInfo.secondary, + contactType: CONTACT_TYPES.secondary, + }), }; case PARTY_TYPES.petitionerSpouse: return { - primary: new PetitionerPrimaryContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), - secondary: new PetitionerSpouseContact( - { ...contactInfo.secondary, contactType: CONTACT_TYPES.secondary }, - { applicationContext }, - ), + primary: new PetitionerPrimaryContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), + secondary: new PetitionerSpouseContact({ + ...contactInfo.secondary, + contactType: CONTACT_TYPES.secondary, + }), }; case PARTY_TYPES.survivingSpouse: return { - primary: new SurvivingSpouseContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), + primary: new SurvivingSpouseContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), secondary: null, }; case PARTY_TYPES.trust: return { - primary: new PetitionerTrustContact( - { ...contactInfo.primary, contactType: CONTACT_TYPES.primary }, - { applicationContext }, - ), + primary: new PetitionerTrustContact({ + ...contactInfo.primary, + contactType: CONTACT_TYPES.primary, + }), secondary: null, }; default: diff --git a/shared/src/business/entities/contacts/NextFriendForIncompetentPersonContact.ts b/shared/src/business/entities/contacts/NextFriendForIncompetentPersonContact.ts index 6f5297ffaa4..7802a9b56c5 100644 --- a/shared/src/business/entities/contacts/NextFriendForIncompetentPersonContact.ts +++ b/shared/src/business/entities/contacts/NextFriendForIncompetentPersonContact.ts @@ -2,13 +2,8 @@ import { Contact } from './Contact'; import { JoiValidationConstants } from '../JoiValidationConstants'; export class NextFriendForIncompetentPersonContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'NextFriendForIncompetentPersonContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'NextFriendForIncompetentPersonContact'); } getValidationRules() { diff --git a/shared/src/business/entities/contacts/NextFriendForMinorContact.ts b/shared/src/business/entities/contacts/NextFriendForMinorContact.ts index d6970f252fb..8fcdadd1211 100644 --- a/shared/src/business/entities/contacts/NextFriendForMinorContact.ts +++ b/shared/src/business/entities/contacts/NextFriendForMinorContact.ts @@ -2,13 +2,8 @@ import { Contact } from './Contact'; import { JoiValidationConstants } from '../JoiValidationConstants'; export class NextFriendForMinorContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'NextFriendForMinorContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'NextFriendForMinorContact'); } getValidationRules() { diff --git a/shared/src/business/entities/contacts/PartnershipAsTaxMattersPartnerContact.ts b/shared/src/business/entities/contacts/PartnershipAsTaxMattersPartnerContact.ts index efd2c481fb2..ab3e825c406 100644 --- a/shared/src/business/entities/contacts/PartnershipAsTaxMattersPartnerContact.ts +++ b/shared/src/business/entities/contacts/PartnershipAsTaxMattersPartnerContact.ts @@ -2,13 +2,8 @@ import { Contact } from './Contact'; import { JoiValidationConstants } from '../JoiValidationConstants'; export class PartnershipAsTaxMattersPartnerPrimaryContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'PartnershipAsTaxMattersPartnerPrimaryContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'PartnershipAsTaxMattersPartnerPrimaryContact'); } getValidationRules() { diff --git a/shared/src/business/entities/contacts/PartnershipBBAContact.ts b/shared/src/business/entities/contacts/PartnershipBBAContact.ts index 1b56f06cf93..6833430870c 100644 --- a/shared/src/business/entities/contacts/PartnershipBBAContact.ts +++ b/shared/src/business/entities/contacts/PartnershipBBAContact.ts @@ -2,13 +2,8 @@ import { Contact } from './Contact'; import { JoiValidationConstants } from '../JoiValidationConstants'; export class PartnershipBBAPrimaryContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'PartnershipBBAPrimaryContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'PartnershipBBAPrimaryContact'); } getValidationRules() { diff --git a/shared/src/business/entities/contacts/PartnershipOtherThanTaxMattersContact.ts b/shared/src/business/entities/contacts/PartnershipOtherThanTaxMattersContact.ts index b60ba6bdcca..61b50dc1720 100644 --- a/shared/src/business/entities/contacts/PartnershipOtherThanTaxMattersContact.ts +++ b/shared/src/business/entities/contacts/PartnershipOtherThanTaxMattersContact.ts @@ -2,13 +2,8 @@ import { Contact } from './Contact'; import { JoiValidationConstants } from '../JoiValidationConstants'; export class PartnershipOtherThanTaxMattersPrimaryContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'PartnershipOtherThanTaxMattersPrimaryContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'PartnershipOtherThanTaxMattersPrimaryContact'); } getValidationRules() { diff --git a/shared/src/business/entities/contacts/Petitioner.test.ts b/shared/src/business/entities/contacts/Petitioner.test.ts index 7daea00e120..78bf8dbe757 100644 --- a/shared/src/business/entities/contacts/Petitioner.test.ts +++ b/shared/src/business/entities/contacts/Petitioner.test.ts @@ -4,7 +4,6 @@ import { SERVICE_INDICATOR_TYPES, } from '../EntityConstants'; import { Petitioner } from './Petitioner'; -import { applicationContext } from '../../test/createTestApplicationContext'; import { getTextByCount } from '../../utilities/getTextByCount'; describe('Petitioner', () => { @@ -20,21 +19,12 @@ describe('Petitioner', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, }; - it('should throw an error when applicationContext is not provided to the importructor', () => { - expect(() => new Petitioner(mockValidPetitioner, {} as any)).toThrow( - 'applicationContext must be defined', - ); - }); - describe('validate', () => { it('should be false when serviceIndicator is undefined', () => { - const entity = new Petitioner( - { - ...mockValidPetitioner, - serviceIndicator: undefined, - }, - { applicationContext }, - ); + const entity = new Petitioner({ + ...mockValidPetitioner, + serviceIndicator: undefined, + }); expect(entity.isValid()).toBe(false); expect(entity.getFormattedValidationErrors()).toEqual({ @@ -43,13 +33,10 @@ describe('Petitioner', () => { }); it('should be false when name field is too long', () => { - const entity = new Petitioner( - { - ...mockValidPetitioner, - name: getTextByCount(101), - }, - { applicationContext }, - ); + const entity = new Petitioner({ + ...mockValidPetitioner, + name: getTextByCount(101), + }); expect(entity.isValid()).toBe(false); expect(entity.getFormattedValidationErrors()).toEqual({ @@ -58,13 +45,10 @@ describe('Petitioner', () => { }); it('should be false when additionalName field is too long', () => { - const entity = new Petitioner( - { - ...mockValidPetitioner, - additionalName: getTextByCount(601), - }, - { applicationContext }, - ); + const entity = new Petitioner({ + ...mockValidPetitioner, + additionalName: getTextByCount(601), + }); expect(entity.isValid()).toBe(false); expect(entity.getFormattedValidationErrors()).toEqual({ @@ -74,22 +58,17 @@ describe('Petitioner', () => { }); it('should be true when all required fields have been provided', () => { - const entity = new Petitioner(mockValidPetitioner, { - applicationContext, - }); + const entity = new Petitioner(mockValidPetitioner); expect(entity.isValid()).toBe(true); expect(entity.getFormattedValidationErrors()).toEqual(null); }); it('should be false when title is longer than 100 chars', () => { - const entity = new Petitioner( - { - ...mockValidPetitioner, - title: getTextByCount(101), - }, - { applicationContext }, - ); + const entity = new Petitioner({ + ...mockValidPetitioner, + title: getTextByCount(101), + }); expect(entity.isValid()).toBe(false); expect(entity.getFormattedValidationErrors()).toEqual({ @@ -101,13 +80,10 @@ describe('Petitioner', () => { describe('phone number formatting', () => { it('should format phone number string', () => { - const entity = new Petitioner( - { - ...mockValidPetitioner, - phone: '1234567890', - }, - { applicationContext }, - ); + const entity = new Petitioner({ + ...mockValidPetitioner, + phone: '1234567890', + }); expect(entity.phone).toEqual('123-456-7890'); }); @@ -117,13 +93,10 @@ describe('Petitioner', () => { it('should populate paperPetitionEmail when one is provided', () => { const mockEmail = 'petitioner@example.com'; - const entity = new Petitioner( - { - ...mockValidPetitioner, - paperPetitionEmail: mockEmail, - }, - { applicationContext }, - ); + const entity = new Petitioner({ + ...mockValidPetitioner, + paperPetitionEmail: mockEmail, + }); expect(entity.paperPetitionEmail).toEqual(mockEmail); }); @@ -131,13 +104,10 @@ describe('Petitioner', () => { it('should populate hasConsentedToEService when one is provided', () => { const mockHasConsentedToEService = false; - const entity = new Petitioner( - { - ...mockValidPetitioner, - hasConsentedToEService: mockHasConsentedToEService, - }, - { applicationContext }, - ); + const entity = new Petitioner({ + ...mockValidPetitioner, + hasConsentedToEService: mockHasConsentedToEService, + }); expect(entity.hasConsentedToEService).toEqual(mockHasConsentedToEService); }); diff --git a/shared/src/business/entities/contacts/Petitioner.ts b/shared/src/business/entities/contacts/Petitioner.ts index 673fe6898b5..41653e4e4f8 100644 --- a/shared/src/business/entities/contacts/Petitioner.ts +++ b/shared/src/business/entities/contacts/Petitioner.ts @@ -3,6 +3,7 @@ import { JoiValidationConstants } from '../JoiValidationConstants'; import { JoiValidationEntity } from '../JoiValidationEntity'; import { User } from '@shared/business/entities/User'; import { formatPhoneNumber } from '../../utilities/formatPhoneNumber'; +import { getUniqueId } from '@shared/sharedAppContext'; import joi from 'joi'; export class Petitioner extends JoiValidationEntity { @@ -31,22 +32,15 @@ export class Petitioner extends JoiValidationEntity { public title?: string; public placeOfLegalResidence?: string; - constructor( - rawProps, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { + constructor(rawProps) { super('Petitioner'); - if (!applicationContext) { - throw new TypeError('applicationContext must be defined'); - } - this.additionalName = rawProps.additionalName; this.address1 = rawProps.address1; this.address2 = rawProps.address2 || undefined; this.address3 = rawProps.address3 || undefined; this.city = rawProps.city; - this.contactId = rawProps.contactId || applicationContext.getUniqueId(); + this.contactId = rawProps.contactId || getUniqueId(); this.contactType = rawProps.contactType; this.country = rawProps.country; this.countryType = rawProps.countryType; diff --git a/shared/src/business/entities/contacts/PetitionerConservatorContact.ts b/shared/src/business/entities/contacts/PetitionerConservatorContact.ts index 7be6929bc9f..cb3ce928afa 100644 --- a/shared/src/business/entities/contacts/PetitionerConservatorContact.ts +++ b/shared/src/business/entities/contacts/PetitionerConservatorContact.ts @@ -2,13 +2,8 @@ import { Contact } from './Contact'; import { JoiValidationConstants } from '../JoiValidationConstants'; export class PetitionerConservatorContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'PetitionerConservatorContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'PetitionerConservatorContact'); } getValidationRules() { diff --git a/shared/src/business/entities/contacts/PetitionerCorporationContact.ts b/shared/src/business/entities/contacts/PetitionerCorporationContact.ts index f186fb9de96..b6ec21f7b41 100644 --- a/shared/src/business/entities/contacts/PetitionerCorporationContact.ts +++ b/shared/src/business/entities/contacts/PetitionerCorporationContact.ts @@ -1,13 +1,8 @@ import { Contact } from './Contact'; export class PetitionerCorporationContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'PetitionerCorporationContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'PetitionerCorporationContact'); } getValidationRules() { diff --git a/shared/src/business/entities/contacts/PetitionerCustodianContact.ts b/shared/src/business/entities/contacts/PetitionerCustodianContact.ts index 6eed12e188f..234ddb48c07 100644 --- a/shared/src/business/entities/contacts/PetitionerCustodianContact.ts +++ b/shared/src/business/entities/contacts/PetitionerCustodianContact.ts @@ -2,13 +2,8 @@ import { Contact } from './Contact'; import { JoiValidationConstants } from '../JoiValidationConstants'; export class PetitionerCustodianContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'PetitionerCustodianContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'PetitionerCustodianContact'); } getValidationRules() { diff --git a/shared/src/business/entities/contacts/PetitionerDeceasedSpouseContact.ts b/shared/src/business/entities/contacts/PetitionerDeceasedSpouseContact.ts index 613a9b3e109..093b2016490 100644 --- a/shared/src/business/entities/contacts/PetitionerDeceasedSpouseContact.ts +++ b/shared/src/business/entities/contacts/PetitionerDeceasedSpouseContact.ts @@ -2,13 +2,8 @@ import { Contact } from './Contact'; import { JoiValidationConstants } from '../JoiValidationConstants'; export class PetitionerDeceasedSpouseContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'PetitionerDeceasedSpouseContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'PetitionerDeceasedSpouseContact'); } getValidationRules() { diff --git a/shared/src/business/entities/contacts/PetitionerEstateWithExecutorPrimaryContact.ts b/shared/src/business/entities/contacts/PetitionerEstateWithExecutorPrimaryContact.ts index 044aa735f65..63c4199065c 100644 --- a/shared/src/business/entities/contacts/PetitionerEstateWithExecutorPrimaryContact.ts +++ b/shared/src/business/entities/contacts/PetitionerEstateWithExecutorPrimaryContact.ts @@ -2,13 +2,8 @@ import { Contact } from './Contact'; import { JoiValidationConstants } from '../JoiValidationConstants'; export class PetitionerEstateWithExecutorPrimaryContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'PetitionerEstateWithExecutorPrimaryContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'PetitionerEstateWithExecutorPrimaryContact'); } getValidationRules() { diff --git a/shared/src/business/entities/contacts/PetitionerGuardianContact.ts b/shared/src/business/entities/contacts/PetitionerGuardianContact.ts index 22974691da4..a4c69731344 100644 --- a/shared/src/business/entities/contacts/PetitionerGuardianContact.ts +++ b/shared/src/business/entities/contacts/PetitionerGuardianContact.ts @@ -2,13 +2,8 @@ import { Contact } from './Contact'; import { JoiValidationConstants } from '../JoiValidationConstants'; export class PetitionerGuardianContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'PetitionerGuardianContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'PetitionerGuardianContact'); } getValidationRules() { diff --git a/shared/src/business/entities/contacts/PetitionerIntermediaryContact.ts b/shared/src/business/entities/contacts/PetitionerIntermediaryContact.ts index 3a0dfadb018..4909a91d62c 100644 --- a/shared/src/business/entities/contacts/PetitionerIntermediaryContact.ts +++ b/shared/src/business/entities/contacts/PetitionerIntermediaryContact.ts @@ -2,13 +2,8 @@ import { Contact } from './Contact'; import { JoiValidationConstants } from '../JoiValidationConstants'; export class PetitionerIntermediaryContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'PetitionerIntermediaryContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'PetitionerIntermediaryContact'); } getValidationRules() { diff --git a/shared/src/business/entities/contacts/PetitionerPrimaryContact.test.ts b/shared/src/business/entities/contacts/PetitionerPrimaryContact.test.ts index 841409237d2..d146945c2ab 100644 --- a/shared/src/business/entities/contacts/PetitionerPrimaryContact.test.ts +++ b/shared/src/business/entities/contacts/PetitionerPrimaryContact.test.ts @@ -1,25 +1,22 @@ import { CONTACT_TYPES, COUNTRY_TYPES } from '../EntityConstants'; import { PetitionerPrimaryContact } from './PetitionerPrimaryContact'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('Petition', () => { describe('for Petitioner Primary contact', () => { it('can validate primary contact name', () => { - const petition = new PetitionerPrimaryContact( - { - address1: '123 Deming Way', - city: 'Los Angeles', - contactType: CONTACT_TYPES.primary, - country: 'USA', - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'petitioner@example.com', - name: 'Eric', - phone: '555-555-1212', - postalCode: '90210', - state: 'TN', - }, - { applicationContext }, - ); + const petition = new PetitionerPrimaryContact({ + address1: '123 Deming Way', + city: 'Los Angeles', + contactType: CONTACT_TYPES.primary, + country: 'USA', + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'petitioner@example.com', + name: 'Eric', + phone: '555-555-1212', + postalCode: '90210', + state: 'TN', + }); + expect(petition.getFormattedValidationErrors()).toEqual(null); }); }); diff --git a/shared/src/business/entities/contacts/PetitionerPrimaryContact.ts b/shared/src/business/entities/contacts/PetitionerPrimaryContact.ts index b93ea725d26..b5d2e2b5e06 100644 --- a/shared/src/business/entities/contacts/PetitionerPrimaryContact.ts +++ b/shared/src/business/entities/contacts/PetitionerPrimaryContact.ts @@ -1,13 +1,8 @@ import { Contact } from './Contact'; export class PetitionerPrimaryContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'PetitionerPrimaryContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'PetitionerPrimaryContact'); } getValidationRules() { diff --git a/shared/src/business/entities/contacts/PetitionerSpouseContact.ts b/shared/src/business/entities/contacts/PetitionerSpouseContact.ts index 152023276cb..ebe17f6c5d8 100644 --- a/shared/src/business/entities/contacts/PetitionerSpouseContact.ts +++ b/shared/src/business/entities/contacts/PetitionerSpouseContact.ts @@ -1,13 +1,8 @@ import { Contact } from './Contact'; export class PetitionerSpouseContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'PetitionerSpouseContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'PetitionerSpouseContact'); } getValidationRules() { diff --git a/shared/src/business/entities/contacts/PetitionerTrustContact.ts b/shared/src/business/entities/contacts/PetitionerTrustContact.ts index abd3c0efa86..082405e7cab 100644 --- a/shared/src/business/entities/contacts/PetitionerTrustContact.ts +++ b/shared/src/business/entities/contacts/PetitionerTrustContact.ts @@ -2,13 +2,8 @@ import { Contact } from './Contact'; import { JoiValidationConstants } from '../JoiValidationConstants'; export class PetitionerTrustContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'PetitionerTrustContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'PetitionerTrustContact'); } getValidationRules() { diff --git a/shared/src/business/entities/contacts/SurvivingSpouseContact.ts b/shared/src/business/entities/contacts/SurvivingSpouseContact.ts index 81527e7edda..62028ae01e2 100644 --- a/shared/src/business/entities/contacts/SurvivingSpouseContact.ts +++ b/shared/src/business/entities/contacts/SurvivingSpouseContact.ts @@ -2,13 +2,8 @@ import { Contact } from './Contact'; import { JoiValidationConstants } from '../JoiValidationConstants'; export class SurvivingSpouseContact extends Contact { - constructor( - rawContact, - { applicationContext }: { applicationContext: IApplicationContext }, - ) { - super(rawContact, 'SurvivingSpouseContact', { - applicationContext, - }); + constructor(rawContact) { + super(rawContact, 'SurvivingSpouseContact'); } getValidationRules() { diff --git a/shared/src/business/entities/trialSessions/NewTrialSession.test.ts b/shared/src/business/entities/trialSessions/NewTrialSession.test.ts index d071207bcab..6e526fc19a0 100644 --- a/shared/src/business/entities/trialSessions/NewTrialSession.test.ts +++ b/shared/src/business/entities/trialSessions/NewTrialSession.test.ts @@ -1,43 +1,28 @@ import { MOCK_NEW_TRIAL_REMOTE } from '../../../test/mockTrial'; import { NewTrialSession } from './NewTrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('NewTrialSession entity', () => { - it('should throw an error when application context is not passed in to the constructor', () => { - expect( - () => new NewTrialSession(MOCK_NEW_TRIAL_REMOTE, {} as any), - ).toThrow(); - }); - describe('isValid', () => { it('should return true when the trial session has all required and valid data', () => { - const trialSession = new NewTrialSession(MOCK_NEW_TRIAL_REMOTE, { - applicationContext, - }); + const trialSession = new NewTrialSession(MOCK_NEW_TRIAL_REMOTE); expect(trialSession.isValid()).toEqual(true); }); it('should be false when the trial session start date is in the past', () => { - const trialSession = new NewTrialSession( - { - ...MOCK_NEW_TRIAL_REMOTE, - startDate: '2000-03-01T00:00:00.000Z', - }, - { applicationContext }, - ); + const trialSession = new NewTrialSession({ + ...MOCK_NEW_TRIAL_REMOTE, + startDate: '2000-03-01T00:00:00.000Z', + }); expect(trialSession.isValid()).toEqual(false); }); it('should be false when the trial session type is not valid', () => { - const trialSession = new NewTrialSession( - { - ...MOCK_NEW_TRIAL_REMOTE, - sessionType: 'Something Else', - }, - { applicationContext }, - ); + const trialSession = new NewTrialSession({ + ...MOCK_NEW_TRIAL_REMOTE, + sessionType: 'Something Else', + }); expect(trialSession.isValid()).toEqual(false); }); @@ -45,26 +30,22 @@ describe('NewTrialSession entity', () => { describe('validate', () => { it('should do nothing when the trial session is valid', () => { - const trialSession = new NewTrialSession(MOCK_NEW_TRIAL_REMOTE, { - applicationContext, - }); + const trialSession = new NewTrialSession(MOCK_NEW_TRIAL_REMOTE); expect(() => trialSession.validate()).not.toThrow(); }); it('should throw an error when the trial session is invalid', () => { - const trialSession = new NewTrialSession({} as any, { - applicationContext, - }); + const trialSession = new NewTrialSession({} as any); expect(() => trialSession.validate()).toThrow(); }); it('should throw an error when a valid alternateTrialClerkName is not provided and only when "Other" is selected', () => { - const trialSession = new NewTrialSession( - { ...MOCK_NEW_TRIAL_REMOTE, trialClerkId: 'Other' }, - { applicationContext }, - ); + const trialSession = new NewTrialSession({ + ...MOCK_NEW_TRIAL_REMOTE, + trialClerkId: 'Other', + }); expect(() => trialSession.validate()).toThrow(); }); diff --git a/shared/src/business/entities/trialSessions/NewTrialSession.ts b/shared/src/business/entities/trialSessions/NewTrialSession.ts index 5617e0211ed..f4a9c0b907e 100644 --- a/shared/src/business/entities/trialSessions/NewTrialSession.ts +++ b/shared/src/business/entities/trialSessions/NewTrialSession.ts @@ -5,8 +5,8 @@ import joi from 'joi'; export class NewTrialSession extends TrialSession { public trialClerkId: string; - constructor(rawSession: RawNewTrialSession, { applicationContext }) { - super(rawSession, { applicationContext }); + constructor(rawSession: RawNewTrialSession) { + super(rawSession); this.trialClerkId = rawSession.trialClerkId; } diff --git a/shared/src/business/entities/trialSessions/TrialSession.IrsCalendarAdministratorInfo.test.ts b/shared/src/business/entities/trialSessions/TrialSession.IrsCalendarAdministratorInfo.test.ts index 2df9e58475b..9e4b6830f18 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.IrsCalendarAdministratorInfo.test.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.IrsCalendarAdministratorInfo.test.ts @@ -1,48 +1,32 @@ import { MOCK_TRIAL_REGULAR } from '@shared/test/mockTrial'; import { TrialSession } from '@shared/business/entities/trialSessions/TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('TrialSession.IrsCalendarAdministratorInfo', () => { it('should not throw any validation error when IrsCalendarAdministratorInfo is undefined', () => { - const entity = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - irsCalendarAdministratorInfo: undefined, - }, - { - applicationContext, - }, - ); + const entity = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + irsCalendarAdministratorInfo: undefined, + }); expect(entity.getFormattedValidationErrors()).toEqual(null); }); it('should not throw any validation error when IrsCalendarAdministratorInfo is an empty object', () => { - const entity = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - irsCalendarAdministratorInfo: {}, - }, - { - applicationContext, - }, - ); + const entity = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + irsCalendarAdministratorInfo: {}, + }); expect(entity.getFormattedValidationErrors()).toEqual(null); }); it('should return a validation error when IrsCalendarAdministratorInfo name exceeds max length', () => { - const entity = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - irsCalendarAdministratorInfo: { - name: '#'.repeat(101), - }, + const entity = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + irsCalendarAdministratorInfo: { + name: '#'.repeat(101), }, - { - applicationContext, - }, - ); + }); const validationErrors = entity.getFormattedValidationErrors(); expect(validationErrors).toEqual({ @@ -51,17 +35,12 @@ describe('TrialSession.IrsCalendarAdministratorInfo', () => { }); it('should return a validation error when IrsCalendarAdministratorInfo email exceeds max length', () => { - const entity = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - irsCalendarAdministratorInfo: { - email: '#'.repeat(101), - }, - }, - { - applicationContext, + const entity = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + irsCalendarAdministratorInfo: { + email: '#'.repeat(101), }, - ); + }); const validationErrors = entity.getFormattedValidationErrors(); expect(validationErrors).toEqual({ @@ -71,17 +50,12 @@ describe('TrialSession.IrsCalendarAdministratorInfo', () => { }); it('should return a validation error when IrsCalendarAdministratorInfo phone exceeds max length', () => { - const entity = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - irsCalendarAdministratorInfo: { - phone: '#'.repeat(101), - }, - }, - { - applicationContext, + const entity = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + irsCalendarAdministratorInfo: { + phone: '#'.repeat(101), }, - ); + }); const validationErrors = entity.getFormattedValidationErrors(); expect(validationErrors).toEqual({ diff --git a/shared/src/business/entities/trialSessions/TrialSession.addCaseToCalendar.test.ts b/shared/src/business/entities/trialSessions/TrialSession.addCaseToCalendar.test.ts index 1fb18585b6d..f50792cbedf 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.addCaseToCalendar.test.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.addCaseToCalendar.test.ts @@ -1,20 +1,14 @@ import { MOCK_TRIAL_INPERSON } from '../../../test/mockTrial'; import { TrialSession } from './TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('TrialSession entity', () => { describe('addCaseToCalendar', () => { it('should add case to calendar of valid trial session when provided a raw case entity with a docketNumber', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - caseOrder: [], - sessionType: 'Hybrid', - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + caseOrder: [], + sessionType: 'Hybrid', + }); trialSession.addCaseToCalendar({ docketNumber: '123-45' }); @@ -22,16 +16,11 @@ describe('TrialSession entity', () => { }); it('should add case to calendar once', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - caseOrder: [], - sessionType: 'Hybrid', - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + caseOrder: [], + sessionType: 'Hybrid', + }); trialSession.addCaseToCalendar({ docketNumber: '123-45' }); trialSession.addCaseToCalendar({ docketNumber: '123-45' }); diff --git a/shared/src/business/entities/trialSessions/TrialSession.addPaperServicePdf.test.ts b/shared/src/business/entities/trialSessions/TrialSession.addPaperServicePdf.test.ts index 1c5e4f640fe..c477835ecb2 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.addPaperServicePdf.test.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.addPaperServicePdf.test.ts @@ -1,6 +1,5 @@ import { MOCK_TRIAL_INPERSON } from '../../../test/mockTrial'; import { TrialSession } from './TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('TrialSession entity', () => { describe('addPaperServicePdf', () => { @@ -9,15 +8,10 @@ describe('TrialSession entity', () => { const mockPaperServicePdfTitle = '30 Day Notice of Trial on 10/12/2023 at Seattle, WA'; - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - paperServicePdfs: [], - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + paperServicePdfs: [], + }); trialSession.addPaperServicePdf(mockFileId, mockPaperServicePdfTitle); diff --git a/shared/src/business/entities/trialSessions/TrialSession.canSetAsCalendared.test.ts b/shared/src/business/entities/trialSessions/TrialSession.canSetAsCalendared.test.ts index dd8ee79a96d..d653ea04013 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.canSetAsCalendared.test.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.canSetAsCalendared.test.ts @@ -3,50 +3,35 @@ import { MOCK_TRIAL_REMOTE, } from '../../../test/mockTrial'; import { TrialSession } from './TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('TrialSession entity', () => { describe('canSetAsCalendared', () => { it('should be able to set a trial session as calendared when all properties are not empty for an in-person session', () => { - const trialSession = new TrialSession(MOCK_TRIAL_INPERSON, { - applicationContext, - }); + const trialSession = new TrialSession(MOCK_TRIAL_INPERSON); expect(trialSession.canSetAsCalendared()).toEqual(true); }); it('should NOT be able to set a trial session as calendared when one or more properties are empty for an in-person session', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - judge: {}, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + judge: {}, + }); expect(trialSession.canSetAsCalendared()).toEqual(false); }); it('should be able to set a trial session as calendared when all properties are not empty for a remote session', () => { - const trialSession = new TrialSession(MOCK_TRIAL_REMOTE, { - applicationContext, - }); + const trialSession = new TrialSession(MOCK_TRIAL_REMOTE); expect(trialSession.canSetAsCalendared()).toEqual(true); }); it('should NOT be able to set a trial session as calendared when one or more properties are empty for a remote session', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REMOTE, - judge: {}, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REMOTE, + judge: {}, + }); expect(trialSession.canSetAsCalendared()).toEqual(false); }); diff --git a/shared/src/business/entities/trialSessions/TrialSession.deleteCaseFromCalendar.test.ts b/shared/src/business/entities/trialSessions/TrialSession.deleteCaseFromCalendar.test.ts index 31ec8355de3..10d208b6874 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.deleteCaseFromCalendar.test.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.deleteCaseFromCalendar.test.ts @@ -1,19 +1,13 @@ import { MOCK_TRIAL_INPERSON } from '../../../test/mockTrial'; import { TrialSession } from './TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('TrialSession entity', () => { describe('deleteCaseFromCalendar', () => { it('should remove the expected case from the order', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - caseOrder: [{ docketNumber: '678-90' }, { docketNumber: '123-45' }], - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + caseOrder: [{ docketNumber: '678-90' }, { docketNumber: '123-45' }], + }); trialSession.deleteCaseFromCalendar({ docketNumber: '123-45', @@ -23,15 +17,10 @@ describe('TrialSession entity', () => { }); it('should remove the expected case from the order when there is only one entry', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - caseOrder: [{ docketNumber: '123-45' }], - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + caseOrder: [{ docketNumber: '123-45' }], + }); trialSession.deleteCaseFromCalendar({ docketNumber: '123-45', diff --git a/shared/src/business/entities/trialSessions/TrialSession.generateSortKeyPrefix.test.ts b/shared/src/business/entities/trialSessions/TrialSession.generateSortKeyPrefix.test.ts index dffea958747..2c8ca6e15bf 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.generateSortKeyPrefix.test.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.generateSortKeyPrefix.test.ts @@ -1,13 +1,10 @@ import { MOCK_TRIAL_REGULAR } from '../../../test/mockTrial'; import { TrialSession } from './TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('TrialSession entity', () => { describe('generateSortKeyPrefix', () => { it('should generate correct sort key prefix for a regular trial session', () => { - const trialSession = new TrialSession(MOCK_TRIAL_REGULAR, { - applicationContext, - }); + const trialSession = new TrialSession(MOCK_TRIAL_REGULAR); expect(trialSession.generateSortKeyPrefix()).toEqual( 'BirminghamAlabama-R', @@ -15,15 +12,10 @@ describe('TrialSession entity', () => { }); it('should generate correct sort key prefix for a small trial session', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - sessionType: 'Small', - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + sessionType: 'Small', + }); expect(trialSession.generateSortKeyPrefix()).toEqual( 'BirminghamAlabama-S', @@ -31,15 +23,10 @@ describe('TrialSession entity', () => { }); it('should generate correct sort key prefix for a hybrid trial session', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - sessionType: 'Hybrid', - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + sessionType: 'Hybrid', + }); expect(trialSession.generateSortKeyPrefix()).toEqual( 'BirminghamAlabama-H', diff --git a/shared/src/business/entities/trialSessions/TrialSession.getEmptyFields.test.ts b/shared/src/business/entities/trialSessions/TrialSession.getEmptyFields.test.ts index fbbc26b1802..9afcbf7ea5f 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.getEmptyFields.test.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.getEmptyFields.test.ts @@ -3,25 +3,19 @@ import { MOCK_TRIAL_REMOTE, } from '../../../test/mockTrial'; import { TrialSession } from './TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('TrialSession entity', () => { describe('getEmptyFields', () => { it('should return all missing fields as a list for an in-person session', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - address1: undefined, - chambersPhoneNumber: undefined, - city: undefined, - judge: undefined, - postalCode: undefined, - state: undefined, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + address1: undefined, + chambersPhoneNumber: undefined, + city: undefined, + judge: undefined, + postalCode: undefined, + state: undefined, + }); const result = trialSession.getEmptyFields(); @@ -36,9 +30,7 @@ describe('TrialSession entity', () => { }); it('should return an empty list when all required fields as set for an in-person session', () => { - const trialSession = new TrialSession(MOCK_TRIAL_INPERSON, { - applicationContext, - }); + const trialSession = new TrialSession(MOCK_TRIAL_INPERSON); const result = trialSession.getEmptyFields(); @@ -46,19 +38,14 @@ describe('TrialSession entity', () => { }); it('should return all missing fields as a list for a remote session', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REMOTE, - chambersPhoneNumber: undefined, - joinPhoneNumber: undefined, - judge: undefined, - meetingId: undefined, - password: undefined, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REMOTE, + chambersPhoneNumber: undefined, + joinPhoneNumber: undefined, + judge: undefined, + meetingId: undefined, + password: undefined, + }); const result = trialSession.getEmptyFields(); @@ -72,9 +59,7 @@ describe('TrialSession entity', () => { }); it('should return an empty list when all required fields as set for a remote session', () => { - const trialSession = new TrialSession(MOCK_TRIAL_REMOTE, { - applicationContext, - }); + const trialSession = new TrialSession(MOCK_TRIAL_REMOTE); const result = trialSession.getEmptyFields(); diff --git a/shared/src/business/entities/trialSessions/TrialSession.isCaseAlreadyCalendared.test.ts b/shared/src/business/entities/trialSessions/TrialSession.isCaseAlreadyCalendared.test.ts index 8bb34e235c6..5f2d238715e 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.isCaseAlreadyCalendared.test.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.isCaseAlreadyCalendared.test.ts @@ -1,19 +1,13 @@ import { MOCK_TRIAL_INPERSON } from '../../../test/mockTrial'; import { TrialSession } from './TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('TrialSession entity', () => { describe('isCaseAlreadyCalendared', () => { it('should return true when a case is already part of the trial session', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - caseOrder: [{ docketNumber: '123-45' }], - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + caseOrder: [{ docketNumber: '123-45' }], + }); expect( trialSession.isCaseAlreadyCalendared({ docketNumber: '123-45' }), @@ -21,15 +15,10 @@ describe('TrialSession entity', () => { }); it('should return false when a case is not already part of the trial session', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - caseOrder: [{ docketNumber: 'abc-de' }], - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + caseOrder: [{ docketNumber: 'abc-de' }], + }); expect( trialSession.isCaseAlreadyCalendared({ docketNumber: '123-45' }), @@ -37,15 +26,10 @@ describe('TrialSession entity', () => { }); it('should return false even for cases that have been manually removed', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - caseOrder: [{ docketNumber: 'abc-de', removedFromTrial: true }], - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + caseOrder: [{ docketNumber: 'abc-de', removedFromTrial: true }], + }); expect( trialSession.isCaseAlreadyCalendared({ docketNumber: '123-45' }), diff --git a/shared/src/business/entities/trialSessions/TrialSession.manuallyAddCaseToCalendar.test.ts b/shared/src/business/entities/trialSessions/TrialSession.manuallyAddCaseToCalendar.test.ts index 61e7368b124..c82f261f2c2 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.manuallyAddCaseToCalendar.test.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.manuallyAddCaseToCalendar.test.ts @@ -2,25 +2,22 @@ import { Case } from '../cases/Case'; import { MOCK_CASE } from '../../../test/mockCase'; import { MOCK_TRIAL_INPERSON } from '../../../test/mockTrial'; import { TrialSession } from './TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('TrialSession entity', () => { describe('manuallyAddCaseToCalendar', () => { - const mockCaseEntity = new Case(MOCK_CASE, { applicationContext }); + const mockCaseEntity = new Case(MOCK_CASE, { + authorizedUser: mockDocketClerkUser, + }); const dateRegex = /^\d*-\d*-\d*T\d*:\d*:\d*.\d*Z$/g; let trialSession: TrialSession; beforeEach(() => { - trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - caseOrder: [], - }, - { - applicationContext, - }, - ); + trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + caseOrder: [], + }); }); it('should add case to calendar of valid trial session when provided a raw case entity with a docketNumber', () => { diff --git a/shared/src/business/entities/trialSessions/TrialSession.noticeOfTrialReminder.test.ts b/shared/src/business/entities/trialSessions/TrialSession.noticeOfTrialReminder.test.ts index ecca18cbfdd..3e0ff04614b 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.noticeOfTrialReminder.test.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.noticeOfTrialReminder.test.ts @@ -1,6 +1,5 @@ import { MOCK_TRIAL_REGULAR } from '../../../test/mockTrial'; import { TrialSession } from './TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; import { prepareDateFromString } from '../../utilities/DateHandler'; describe('TrialSession entity', () => { @@ -22,15 +21,10 @@ describe('TrialSession entity', () => { { daysFromToday: 35, expectedOutput: false }, ]; it('should set isStartDateWithinNOTTReminderRange to false when the trial session is not calendared', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - isCalendared: false, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + isCalendared: false, + }); expect(trialSession.isStartDateWithinNOTTReminderRange).toBe(false); }); @@ -39,16 +33,11 @@ describe('TrialSession entity', () => { it(`should set isStartDateWithinNOTTReminderRange to ${expectedOutput} when the trial session is calendared and the start date is ${daysFromToday} days from today`, () => { const thirtyDaysFromToday = today.plus({ ['days']: daysFromToday }); - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - isCalendared: true, - startDate: thirtyDaysFromToday, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + isCalendared: true, + startDate: thirtyDaysFromToday, + }); expect(trialSession.isStartDateWithinNOTTReminderRange).toBe( expectedOutput, diff --git a/shared/src/business/entities/trialSessions/TrialSession.removeCaseFromCalendar.test.ts b/shared/src/business/entities/trialSessions/TrialSession.removeCaseFromCalendar.test.ts index a09a74f8dd3..a624fcc720e 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.removeCaseFromCalendar.test.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.removeCaseFromCalendar.test.ts @@ -4,20 +4,14 @@ import { } from '../../../test/mockTrial'; import { SESSION_STATUS_GROUPS } from '../EntityConstants'; import { TrialSession } from './TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('TrialSession entity', () => { describe('removeCaseFromCalendar', () => { it('should set case on calendar to removedFromTrial with removedFromTrialDate and disposition', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - caseOrder: [], - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + caseOrder: [], + }); trialSession.addCaseToCalendar({ docketNumber: '123-45' }); trialSession.addCaseToCalendar({ docketNumber: '234-45' }); trialSession.addCaseToCalendar({ docketNumber: '456-45' }); @@ -40,15 +34,10 @@ describe('TrialSession entity', () => { }); it('should not modify case calendar if docketNumber is not in caseOrder', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - caseOrder: [], - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + caseOrder: [], + }); trialSession.addCaseToCalendar({ docketNumber: '123-45' }); trialSession.addCaseToCalendar({ docketNumber: '234-45' }); trialSession.addCaseToCalendar({ docketNumber: '456-45' }); @@ -67,15 +56,10 @@ describe('TrialSession entity', () => { }); it('should set the sessionStatus to closed when all cases on the session are removed', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - caseOrder: [], - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + caseOrder: [], + }); trialSession.addCaseToCalendar({ docketNumber: '123-45' }); expect(trialSession.caseOrder!.length).toEqual(1); @@ -90,15 +74,10 @@ describe('TrialSession entity', () => { }); it('should keep the status as open when the session is standalone remote, even after removing all cases', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_STANDALONE_REMOTE, - caseOrder: [], - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_STANDALONE_REMOTE, + caseOrder: [], + }); trialSession.addCaseToCalendar({ docketNumber: '123-45' }); expect(trialSession.caseOrder!.length).toEqual(1); diff --git a/shared/src/business/entities/trialSessions/TrialSession.setAsCalendared.test.ts b/shared/src/business/entities/trialSessions/TrialSession.setAsCalendared.test.ts index 41dd393f715..226fbca6261 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.setAsCalendared.test.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.setAsCalendared.test.ts @@ -1,19 +1,13 @@ import { MOCK_TRIAL_INPERSON } from '../../../test/mockTrial'; import { TrialSession } from './TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('TrialSession entity', () => { describe('setAsCalendared', () => { it('should set a valid trial session entity as calendared upon request', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - isCalendared: false, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + isCalendared: false, + }); trialSession.setAsCalendared(); diff --git a/shared/src/business/entities/trialSessions/TrialSession.setNoticesIssued.test.ts b/shared/src/business/entities/trialSessions/TrialSession.setNoticesIssued.test.ts index d121223af0a..d7bbcc0f623 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.setNoticesIssued.test.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.setNoticesIssued.test.ts @@ -1,19 +1,13 @@ import { MOCK_TRIAL_INPERSON } from '../../../test/mockTrial'; import { TrialSession } from './TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('TrialSession entity', () => { describe('setNoticesIssued', () => { it('should set the noticeIssuedDate on the trial session', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_INPERSON, - noticeIssuedDate: undefined, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_INPERSON, + noticeIssuedDate: undefined, + }); trialSession.setNoticesIssued(); diff --git a/shared/src/business/entities/trialSessions/TrialSession.test.ts b/shared/src/business/entities/trialSessions/TrialSession.test.ts index 0aae5932ff2..0e347122eb0 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.test.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.test.ts @@ -7,65 +7,43 @@ import { TRIAL_SESSION_SCOPE_TYPES, } from '../EntityConstants'; import { TrialSession } from './TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('TrialSession entity', () => { - it('should throw an error when applicationContext is not passed in', () => { - expect(() => new TrialSession({}, {} as any)).toThrow(); - }); - describe('isValid', () => { it('should be true when a valid trial session is provided', () => { - const trialSession = new TrialSession(MOCK_TRIAL_REGULAR, { - applicationContext, - }); + const trialSession = new TrialSession(MOCK_TRIAL_REGULAR); expect(trialSession.isValid()).toBe(true); }); it('should be true when a valid trial session with startDate in the past is provided', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - startDate: '2000-03-01T00:00:00.000Z', - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + startDate: '2000-03-01T00:00:00.000Z', + }); expect(trialSession.isValid()).toBe(true); }); it('should be false when an invalid sessionType is provided', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - sessionType: 'Something Else', - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + sessionType: 'Something Else', + }); expect(trialSession.isValid()).toBe(false); }); it('should be false when an invalid docketNumber in caseOrder is provided', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - caseOrder: [ - { - docketNumber: 'abc', - }, - ], - sessionType: 'Something Else', - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + caseOrder: [ + { + docketNumber: 'abc', + }, + ], + sessionType: 'Something Else', + }); expect(trialSession.isValid()).toBe(false); }); @@ -73,40 +51,30 @@ describe('TrialSession entity', () => { describe('isCalendared === true', () => { describe('proceedingType === "In Person"', () => { it('should be valid when isCalendared is true, proceedingType is "In Person", and optional address fields are missing', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - address1: undefined, - city: undefined, - isCalendared: true, - postalCode: undefined, - proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.inPerson, - state: undefined, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + address1: undefined, + city: undefined, + isCalendared: true, + postalCode: undefined, + proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.inPerson, + state: undefined, + }); expect(trialSession.isValid()).toBe(true); expect(trialSession.getFormattedValidationErrors()).toEqual(null); }); it('should be valid when isCalendared is true, proceedingType is In Person, and required address fields are defined', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - address1: '123 Flavor Ave', - city: 'Flavortown', - isCalendared: true, - postalCode: '12345', - proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.inPerson, - state: 'TN', - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + address1: '123 Flavor Ave', + city: 'Flavortown', + isCalendared: true, + postalCode: '12345', + proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.inPerson, + state: 'TN', + }); expect(trialSession.isValid()).toBe(true); expect(trialSession.getFormattedValidationErrors()).toEqual(null); @@ -116,21 +84,16 @@ describe('TrialSession entity', () => { describe('proceedingType === "Remote"', () => { describe(`sessionScope === ${TRIAL_SESSION_SCOPE_TYPES.locationBased}`, () => { it('should be invalid when isCalendared is true and required proceeding information fields are missing', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - chambersPhoneNumber: undefined, - isCalendared: true, - joinPhoneNumber: undefined, - meetingId: undefined, - password: undefined, - proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.remote, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + chambersPhoneNumber: undefined, + isCalendared: true, + joinPhoneNumber: undefined, + meetingId: undefined, + password: undefined, + proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.remote, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, + }); expect(trialSession.isValid()).toBe(false); expect(trialSession.getFormattedValidationErrors()).toMatchObject({ @@ -142,65 +105,50 @@ describe('TrialSession entity', () => { }); it('should be valid when isCalendared is true and required proceeding information fields are defined', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - chambersPhoneNumber: '1111', - isCalendared: true, - joinPhoneNumber: '222222', - meetingId: '33333', - password: '44444', - proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.remote, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + chambersPhoneNumber: '1111', + isCalendared: true, + joinPhoneNumber: '222222', + meetingId: '33333', + password: '44444', + proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.remote, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, + }); expect(trialSession.isValid()).toBe(true); expect(trialSession.getFormattedValidationErrors()).toEqual(null); }); it('should be valid when isCalendared is true, sessionType is "Special" and optional proceeding information fields are missing', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - chambersPhoneNumber: undefined, - isCalendared: true, - joinPhoneNumber: undefined, - meetingId: undefined, - password: undefined, - proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.remote, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, - sessionType: SESSION_TYPES.special, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + chambersPhoneNumber: undefined, + isCalendared: true, + joinPhoneNumber: undefined, + meetingId: undefined, + password: undefined, + proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.remote, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, + sessionType: SESSION_TYPES.special, + }); expect(trialSession.isValid()).toBe(true); expect(trialSession.getFormattedValidationErrors()).toEqual(null); }); it('should be valid when isCalendared is true, sessionType is Motion/Hearing and optional proceeding information fields are missing', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - chambersPhoneNumber: undefined, - isCalendared: true, - joinPhoneNumber: undefined, - meetingId: undefined, - password: undefined, - proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.remote, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, - sessionType: SESSION_TYPES.motionHearing, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + chambersPhoneNumber: undefined, + isCalendared: true, + joinPhoneNumber: undefined, + meetingId: undefined, + password: undefined, + proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.remote, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, + sessionType: SESSION_TYPES.motionHearing, + }); expect(trialSession.isValid()).toBe(true); expect(trialSession.getFormattedValidationErrors()).toEqual(null); @@ -209,21 +157,16 @@ describe('TrialSession entity', () => { describe(`sessionScope === ${TRIAL_SESSION_SCOPE_TYPES.standaloneRemote}`, () => { it('should be valid when isCalendared is true and optional proceeding information fields are missing', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - chambersPhoneNumber: undefined, - isCalendared: true, - joinPhoneNumber: undefined, - meetingId: undefined, - password: undefined, - proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.remote, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + chambersPhoneNumber: undefined, + isCalendared: true, + joinPhoneNumber: undefined, + meetingId: undefined, + password: undefined, + proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.remote, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, + }); expect(trialSession.isValid()).toBe(true); expect(trialSession.getFormattedValidationErrors()).toEqual(null); @@ -234,20 +177,15 @@ describe('TrialSession entity', () => { describe('proceedingType', () => { it('should be invalid when proceedingType is invalid', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - address1: '123 Flavor Ave', - city: 'Flavortown', - judge: {}, - postalCode: '12345', - proceedingType: 'NOT A VALID TYPE', - state: 'TN', - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + address1: '123 Flavor Ave', + city: 'Flavortown', + judge: {}, + postalCode: '12345', + proceedingType: 'NOT A VALID TYPE', + state: 'TN', + }); expect(trialSession.isValid()).toBe(false); expect(trialSession.getFormattedValidationErrors()).toMatchObject({ @@ -256,58 +194,43 @@ describe('TrialSession entity', () => { }); it('should be valid when proceedingType is "Remote"', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - address1: '123 Flavor Ave', - city: 'Flavortown', - judge: {}, - postalCode: '12345', - proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.remote, - state: 'TN', - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + address1: '123 Flavor Ave', + city: 'Flavortown', + judge: {}, + postalCode: '12345', + proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.remote, + state: 'TN', + }); expect(trialSession.isValid()).toBe(true); }); it('should be valid when proceedingType is "In Person"', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - address1: '123 Flavor Ave', - city: 'Flavortown', - judge: {}, - postalCode: '12345', - proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.inPerson, - state: 'TN', - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + address1: '123 Flavor Ave', + city: 'Flavortown', + judge: {}, + postalCode: '12345', + proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.inPerson, + state: 'TN', + }); expect(trialSession.isValid()).toBe(true); }); it('should be invalid when proceedingType is undefined', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - address1: '123 Flavor Ave', - city: 'Flavortown', - judge: {}, - postalCode: '12345', - proceedingType: null, - state: 'TN', - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + address1: '123 Flavor Ave', + city: 'Flavortown', + judge: {}, + postalCode: '12345', + proceedingType: null, + state: 'TN', + }); expect(trialSession.isValid()).toBe(false); expect(trialSession.getFormattedValidationErrors()).toMatchObject({ @@ -318,31 +241,21 @@ describe('TrialSession entity', () => { describe('sessionScope', () => { it(`should make maxCases optional when sessionScope is ${TRIAL_SESSION_SCOPE_TYPES.standaloneRemote}`, () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - maxCases: undefined, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + maxCases: undefined, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, + }); expect(trialSession.isValid()).toBe(true); }); it(`should require maxCases when sessionScope is ${TRIAL_SESSION_SCOPE_TYPES.locationBased}`, () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - maxCases: undefined, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + maxCases: undefined, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, + }); expect(trialSession.isValid()).toBe(false); expect(trialSession.getFormattedValidationErrors()).toMatchObject({ @@ -351,31 +264,21 @@ describe('TrialSession entity', () => { }); it(`should make trialLocation optional when sessionScope is ${TRIAL_SESSION_SCOPE_TYPES.standaloneRemote}`, () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, - trialLocation: undefined, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, + trialLocation: undefined, + }); expect(trialSession.isValid()).toBe(true); }); it(`should require trialLocation when sessionScope is ${TRIAL_SESSION_SCOPE_TYPES.locationBased}`, () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, - trialLocation: undefined, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, + trialLocation: undefined, + }); expect(trialSession.isValid()).toBe(false); expect(trialSession.getFormattedValidationErrors()).toMatchObject({ @@ -387,20 +290,13 @@ describe('TrialSession entity', () => { describe('validate', () => { it('should do nothing when the trialSession is valid', () => { - const trialSession = new TrialSession(MOCK_TRIAL_REGULAR, { - applicationContext, - }); + const trialSession = new TrialSession(MOCK_TRIAL_REGULAR); expect(() => trialSession.validate()).not.toThrow(); }); it('should throw an error when the trialSession is invalid', () => { - const trialSession = new TrialSession( - {}, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({}); expect(() => trialSession.validate()).toThrow(); }); @@ -408,29 +304,19 @@ describe('TrialSession entity', () => { describe('isStandaloneRemote', () => { it(`should return false when the sessionScope is ${TRIAL_SESSION_SCOPE_TYPES.locationBased}`, () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, + }); expect(trialSession.isStandaloneRemote()).toEqual(false); }); it(`should return true when the sessionScope is ${TRIAL_SESSION_SCOPE_TYPES.standaloneRemote}`, () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, + }); expect(trialSession.isStandaloneRemote()).toEqual(true); }); @@ -438,21 +324,16 @@ describe('TrialSession entity', () => { describe('proceedingType', () => { it(`should be ${TRIAL_SESSION_PROCEEDING_TYPES.remote} when sessionScope is ${TRIAL_SESSION_SCOPE_TYPES.standaloneRemote}`, () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - address1: '123 Flavor Ave', - city: 'Flavortown', - judge: {}, - postalCode: '12345', - proceedingType: undefined, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, - state: 'TN', - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + address1: '123 Flavor Ave', + city: 'Flavortown', + judge: {}, + postalCode: '12345', + proceedingType: undefined, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, + state: 'TN', + }); expect(trialSession.proceedingType).toBe( TRIAL_SESSION_PROCEEDING_TYPES.remote, @@ -462,12 +343,10 @@ describe('TrialSession entity', () => { describe('sessionScope', () => { it(`should default to ${TRIAL_SESSION_SCOPE_TYPES.locationBased} when sessionScope is undefined`, () => { - const trialSession = new TrialSession( - { ...MOCK_TRIAL_REGULAR, sessionScope: undefined }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + sessionScope: undefined, + }); expect(trialSession.sessionScope).toEqual( TRIAL_SESSION_SCOPE_TYPES.locationBased, @@ -477,16 +356,11 @@ describe('TrialSession entity', () => { describe('startTime', () => { it(`should default to "10:00" when sessionScope is ${TRIAL_SESSION_SCOPE_TYPES.locationBased} and startTime is not provided`, () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, - startTime: undefined, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, + startTime: undefined, + }); expect(trialSession.startTime).toEqual('10:00'); }); @@ -494,16 +368,11 @@ describe('TrialSession entity', () => { it(`should be set to the provided value when sessionScope is ${TRIAL_SESSION_SCOPE_TYPES.locationBased}`, () => { const mockStartTime = '12:00'; - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, - startTime: mockStartTime, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, + startTime: mockStartTime, + }); expect(trialSession.startTime).toEqual(mockStartTime); }); @@ -511,16 +380,11 @@ describe('TrialSession entity', () => { it(`should be set to "13:00" (1:00PM) when sessionScope is ${TRIAL_SESSION_SCOPE_TYPES.standaloneRemote}`, () => { const mockStartTime = '12:00'; - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, - startTime: mockStartTime, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, + startTime: mockStartTime, + }); expect(trialSession.startTime).toEqual('13:00'); }); @@ -528,16 +392,11 @@ describe('TrialSession entity', () => { describe('trialLocation', () => { it(`should be set to ${TRIAL_SESSION_SCOPE_TYPES.standaloneRemote} when sessionScope is ${TRIAL_SESSION_SCOPE_TYPES.standaloneRemote}`, () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, - trialLocation: undefined, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, + trialLocation: undefined, + }); expect(trialSession.trialLocation).toBe( TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, @@ -554,9 +413,6 @@ describe('TrialSession entity', () => { trialLocation: mockTrialLocation, }, // eslint-disable-next-line max-lines - { - applicationContext, - }, ); expect(trialSession.trialLocation).toBe(mockTrialLocation); @@ -572,15 +428,10 @@ describe('TrialSession entity', () => { ['days']: 34, }); - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - estimatedEndDate: incorrectEstimatedEndDate, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + estimatedEndDate: incorrectEstimatedEndDate, + }); expect(() => trialSession.validate()).toThrow(); expect(trialSession.getFormattedValidationErrors()).toMatchObject({ @@ -589,15 +440,10 @@ describe('TrialSession entity', () => { }); it('should be valid when estimatedEndDate is greater than or equal to the startDate', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - estimatedEndDate: MOCK_TRIAL_REGULAR.startDate, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + estimatedEndDate: MOCK_TRIAL_REGULAR.startDate, + }); expect(trialSession.isValid()).toBe(true); }); @@ -605,14 +451,9 @@ describe('TrialSession entity', () => { describe('dismissedAlertForNOTT', () => { it('should have a default value of false', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + }); expect(trialSession.dismissedAlertForNOTT).toBe(false); }); @@ -620,29 +461,19 @@ describe('TrialSession entity', () => { describe('paperServicePdfs', () => { it('should default to an empty array when the trial session does not already have any paper service pdfs', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - paperServicePdfs: undefined, - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + paperServicePdfs: undefined, + }); expect(trialSession.paperServicePdfs).toEqual([]); }); it('should require a fileId and title on each entry to be valid', () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - paperServicePdfs: [{}], - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + paperServicePdfs: [{}], + }); expect(trialSession.getFormattedValidationErrors()).toEqual({ fileId: '"paperServicePdfs[0].fileId" is required', diff --git a/shared/src/business/entities/trialSessions/TrialSession.thirtyDaysBeforeTrialFormatted.test.ts b/shared/src/business/entities/trialSessions/TrialSession.thirtyDaysBeforeTrialFormatted.test.ts index 510d64f3610..4e4c6d00d6e 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.thirtyDaysBeforeTrialFormatted.test.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.thirtyDaysBeforeTrialFormatted.test.ts @@ -1,22 +1,16 @@ import { MOCK_TRIAL_REGULAR } from '../../../test/mockTrial'; import { TrialSession } from './TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; describe('TrialSession entity', () => { describe('thirtyDaysBeforeTrialFormatted', () => { // this is how the court was calculating the duration days between dates // https://www.timeanddate.com/date/durationresult.html?m1=5&d1=17&y1=2023&m2=6&d2=15&y2=2023&ti=on it("should set thirtyDaysBeforeTrialFormatted to 30 days prior to the trial's startDate, inclusive of the startDate, when the trial session is calendared", () => { - const trialSession = new TrialSession( - { - ...MOCK_TRIAL_REGULAR, - isCalendared: true, - startDate: '2023-06-15', - }, - { - applicationContext, - }, - ); + const trialSession = new TrialSession({ + ...MOCK_TRIAL_REGULAR, + isCalendared: true, + startDate: '2023-06-15', + }); expect(trialSession.thirtyDaysBeforeTrialFormatted).toBe('05/17/23'); }); diff --git a/shared/src/business/entities/trialSessions/TrialSession.ts b/shared/src/business/entities/trialSessions/TrialSession.ts index fc3322789e5..570050287da 100644 --- a/shared/src/business/entities/trialSessions/TrialSession.ts +++ b/shared/src/business/entities/trialSessions/TrialSession.ts @@ -26,6 +26,7 @@ import { US_STATES, US_STATES_OTHER, } from '../EntityConstants'; +import { getUniqueId } from '@shared/sharedAppContext'; import { isEmpty, isEqual } from 'lodash'; import joi from 'joi'; @@ -132,13 +133,9 @@ export class TrialSession extends JoiValidationEntity { ], }; - constructor(rawSession, { applicationContext }) { + constructor(rawSession) { super('TrialSession'); - if (!applicationContext) { - throw new TypeError('applicationContext must be defined'); - } - this.address1 = rawSession.address1; this.address2 = rawSession.address2; this.alternateTrialClerkName = rawSession.alternateTrialClerkName; @@ -191,8 +188,7 @@ export class TrialSession extends JoiValidationEntity { this.proceedingType = this.isStandaloneRemote() ? TRIAL_SESSION_PROCEEDING_TYPES.remote : rawSession.proceedingType; - this.trialSessionId = - rawSession.trialSessionId || applicationContext.getUniqueId(); + this.trialSessionId = rawSession.trialSessionId || getUniqueId(); this.paperServicePdfs = rawSession.paperServicePdfs || []; if (rawSession.judge?.name) { diff --git a/shared/src/business/test/createTestApplicationContext.ts b/shared/src/business/test/createTestApplicationContext.ts index 7ec4a857332..f4569758a4c 100644 --- a/shared/src/business/test/createTestApplicationContext.ts +++ b/shared/src/business/test/createTestApplicationContext.ts @@ -1,10 +1,7 @@ /* eslint-disable max-lines */ import * as DateHandler from '@shared/business/utilities/DateHandler'; import * as pdfLib from 'pdf-lib'; -import { - ALLOWLIST_FEATURE_FLAGS, - ROLES, -} from '@shared/business/entities/EntityConstants'; +import { ALLOWLIST_FEATURE_FLAGS } from '@shared/business/entities/EntityConstants'; import { Case, canAllowDocumentServiceForCase, @@ -155,9 +152,7 @@ const appContextProxy = (initial = {}, makeMock = true) => { return makeMock ? jest.fn().mockReturnValue(proxied) : proxied; }; -export const createTestApplicationContext = ({ - user, -}: { user?: User } = {}) => { +export const createTestApplicationContext = () => { const emptyAppContextProxy = appContextProxy(); const mockGetPdfJsReturnValue = { @@ -628,19 +623,6 @@ export const createTestApplicationContext = ({ ERROR_MAP_429, }; }), - getCurrentUser: jest.fn().mockImplementation(() => { - return new User( - user || { - name: 'richard', - role: ROLES.petitioner, - userId: 'a805d1ab-18d0-43ec-bafb-654e83405416', - }, - ); - }), - getCurrentUserPermissions: jest.fn(), - getCurrentUserToken: () => { - return ''; - }, getDispatchers: jest.fn().mockReturnValue({ sendBulkTemplatedEmail: jest.fn(), sendNotificationOfSealing: jest.fn(), @@ -705,7 +687,6 @@ export const createTestApplicationContext = ({ warn: jest.fn(), }, setCurrentUser: jest.fn(), - setCurrentUserToken: jest.fn(), setTimeout: jest.fn().mockImplementation(callback => callback()), }; return applicationContext; diff --git a/shared/src/business/useCases/caseConsolidation/canConsolidateInteractor.test.ts b/shared/src/business/useCases/caseConsolidation/canConsolidateInteractor.test.ts index 6efc884d759..b1f381eaf99 100644 --- a/shared/src/business/useCases/caseConsolidation/canConsolidateInteractor.test.ts +++ b/shared/src/business/useCases/caseConsolidation/canConsolidateInteractor.test.ts @@ -1,7 +1,7 @@ import { CASE_STATUS_TYPES } from '../../entities/EntityConstants'; import { MOCK_CASE } from '../../../test/mockCase'; -import { applicationContext } from '../../test/createTestApplicationContext'; import { canConsolidateInteractor } from './canConsolidateInteractor'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('canConsolidateInteractor', () => { let currentCase; @@ -25,7 +25,7 @@ describe('canConsolidateInteractor', () => { }); it('should return true when cases are consolidatable', () => { - const result = canConsolidateInteractor(applicationContext, { + const result = canConsolidateInteractor(mockDocketClerkUser, { caseToConsolidate, currentCase, }); @@ -36,7 +36,7 @@ describe('canConsolidateInteractor', () => { it('should return false when cases are not consolidatable', () => { caseToConsolidate.status = CASE_STATUS_TYPES.closed; - const result = canConsolidateInteractor(applicationContext, { + const result = canConsolidateInteractor(mockDocketClerkUser, { caseToConsolidate, currentCase, }); diff --git a/shared/src/business/useCases/caseConsolidation/canConsolidateInteractor.ts b/shared/src/business/useCases/caseConsolidation/canConsolidateInteractor.ts index bd35b5211a7..094d69395a0 100644 --- a/shared/src/business/useCases/caseConsolidation/canConsolidateInteractor.ts +++ b/shared/src/business/useCases/caseConsolidation/canConsolidateInteractor.ts @@ -1,3 +1,4 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { Case } from '../../entities/cases/Case'; /** @@ -9,13 +10,15 @@ import { Case } from '../../entities/cases/Case'; * @returns {object} whether or not the cases can be consolidated with the reason */ export const canConsolidateInteractor = ( - applicationContext: IApplicationContext, + authorizedUser: AuthUser, { caseToConsolidate, currentCase, }: { caseToConsolidate: Case; currentCase: Case }, ) => { - const caseEntity = new Case(currentCase, { applicationContext }); + const caseEntity = new Case(currentCase, { + authorizedUser, + }); const results = caseEntity.getConsolidationStatus({ caseEntity: caseToConsolidate, diff --git a/shared/src/business/useCases/correspondence/uploadCorrespondenceDocumentInteractor.test.ts b/shared/src/business/useCases/correspondence/uploadCorrespondenceDocumentInteractor.test.ts index ce10b055a83..7afa739ae33 100644 --- a/shared/src/business/useCases/correspondence/uploadCorrespondenceDocumentInteractor.test.ts +++ b/shared/src/business/useCases/correspondence/uploadCorrespondenceDocumentInteractor.test.ts @@ -1,35 +1,33 @@ -import { ROLES } from '../../entities/EntityConstants'; import { applicationContext } from '../../test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { uploadCorrespondenceDocumentInteractor } from './uploadCorrespondenceDocumentInteractor'; describe('uploadCorrespondenceDocumentInteractor', () => { - let mockUser; const mockKey = 'cf105788-5d34-4451-aa8d-dfd9a851b675'; const mockDocumentFile = 'bananas'; - const mockUserFixture = { - name: 'Docket Clerk', - role: ROLES.docketClerk, - userId: '2474e5c0-f741-4120-befa-b77378ac8bf0', - }; - - beforeEach(() => { - mockUser = mockUserFixture; - applicationContext.getCurrentUser.mockImplementation(() => mockUser); - }); it('should throw an Unauthorized error if the user role does not have the CASE_CORRESPONDENCE permission', async () => { - mockUser = { ...mockUser, role: ROLES.petitioner }; - await expect( - uploadCorrespondenceDocumentInteractor(applicationContext, {} as any), + uploadCorrespondenceDocumentInteractor( + applicationContext, + {} as any, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should upload the document file to the specified correspondence document', async () => { - await uploadCorrespondenceDocumentInteractor(applicationContext, { - documentFile: mockDocumentFile, - keyToOverwrite: mockKey, - }); + await uploadCorrespondenceDocumentInteractor( + applicationContext, + { + documentFile: mockDocumentFile, + keyToOverwrite: mockKey, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().uploadDocumentFromClient.mock diff --git a/shared/src/business/useCases/correspondence/uploadCorrespondenceDocumentInteractor.ts b/shared/src/business/useCases/correspondence/uploadCorrespondenceDocumentInteractor.ts index 9033ed8ac54..9c92f227508 100644 --- a/shared/src/business/useCases/correspondence/uploadCorrespondenceDocumentInteractor.ts +++ b/shared/src/business/useCases/correspondence/uploadCorrespondenceDocumentInteractor.ts @@ -4,6 +4,7 @@ import { isAuthorized, } from '../../../authorization/authorizationClientService'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const uploadCorrespondenceDocumentInteractor = async ( applicationContext: ClientApplicationContext, @@ -11,10 +12,9 @@ export const uploadCorrespondenceDocumentInteractor = async ( documentFile, keyToOverwrite, }: { documentFile: string; keyToOverwrite: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.CASE_CORRESPONDENCE)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CASE_CORRESPONDENCE)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/shared/src/business/useCases/externalDocument/uploadDocumentInteractor.test.ts b/shared/src/business/useCases/externalDocument/uploadDocumentInteractor.test.ts index 93ba5a6fd6d..4a73f9f6b51 100644 --- a/shared/src/business/useCases/externalDocument/uploadDocumentInteractor.test.ts +++ b/shared/src/business/useCases/externalDocument/uploadDocumentInteractor.test.ts @@ -1,79 +1,78 @@ -import { ROLES } from '../../entities/EntityConstants'; import { applicationContext } from '../../test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { uploadDocumentInteractor } from './uploadDocumentInteractor'; describe('uploadDocumentInteractor', () => { it('throws an error when an unauthorized user tries to access the use case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: 'other', - userId: 'other', - }); - await expect( - uploadDocumentInteractor(applicationContext, { - documentFile: { - primary: 'something', + uploadDocumentInteractor( + applicationContext, + { + documentFile: { + primary: 'something', + }, + key: 'abc', + onUploadProgress: () => {}, }, - key: 'abc', - onUploadProgress: () => {}, - }), + undefined, + ), ).rejects.toThrow('Unauthorized'); }); it('runs successfully with no errors with a valid user', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }); - await expect( - uploadDocumentInteractor(applicationContext, { - documentFile: { - primary: 'something', + uploadDocumentInteractor( + applicationContext, + { + documentFile: { + primary: 'something', + }, + key: 'abc', + onUploadProgress: () => {}, }, - key: 'abc', - onUploadProgress: () => {}, - }), + mockPetitionsClerkUser, + ), ).resolves.not.toThrow(); }); it('runs successfully with no errors with all data and valid user', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }); - await expect( - uploadDocumentInteractor(applicationContext, { - documentFile: { - primary: 'something', - primarySupporting0: 'something3', - secondary: 'something2', - secondarySupporting0: 'something4', + uploadDocumentInteractor( + applicationContext, + { + documentFile: { + primary: 'something', + primarySupporting0: 'something3', + secondary: 'something2', + secondarySupporting0: 'something4', + }, + key: 'abc', + onUploadProgress: () => {}, }, - key: 'abc', - onUploadProgress: () => {}, - }), + mockPetitionsClerkUser, + ), ).resolves.not.toThrow(); }); it('runs successfully with no errors with all data and valid user who is a docketclerk', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketclerk', - }); - await expect( - uploadDocumentInteractor(applicationContext, { - documentFile: { - primary: 'something', - primarySupporting0: 'something3', - secondary: 'something2', - secondarySupporting0: 'something4', + uploadDocumentInteractor( + applicationContext, + { + documentFile: { + primary: 'something', + primarySupporting0: 'something3', + secondary: 'something2', + secondarySupporting0: 'something4', + }, + key: 'abc', + onUploadProgress: () => {}, }, - key: 'abc', - onUploadProgress: () => {}, - }), + mockDocketClerkUser, + ), ).resolves.not.toThrow(); }); }); diff --git a/shared/src/business/useCases/externalDocument/uploadDocumentInteractor.ts b/shared/src/business/useCases/externalDocument/uploadDocumentInteractor.ts index 6468935a5e9..dde666f2c15 100644 --- a/shared/src/business/useCases/externalDocument/uploadDocumentInteractor.ts +++ b/shared/src/business/useCases/externalDocument/uploadDocumentInteractor.ts @@ -4,18 +4,18 @@ import { isAuthorized, } from '../../../authorization/authorizationClientService'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const uploadDocumentInteractor = async ( applicationContext: ClientApplicationContext, { documentFile, key, onUploadProgress }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - if ( !( - isAuthorized(user, ROLE_PERMISSIONS.FILE_EXTERNAL_DOCUMENT) || - isAuthorized(user, ROLE_PERMISSIONS.COURT_ISSUED_DOCUMENT) || - isAuthorized(user, ROLE_PERMISSIONS.DOCKET_ENTRY) + isAuthorized(authorizedUser, ROLE_PERMISSIONS.FILE_EXTERNAL_DOCUMENT) || + isAuthorized(authorizedUser, ROLE_PERMISSIONS.COURT_ISSUED_DOCUMENT) || + isAuthorized(authorizedUser, ROLE_PERMISSIONS.DOCKET_ENTRY) ) ) { throw new UnauthorizedError('Unauthorized'); diff --git a/shared/src/business/useCases/externalDocument/uploadExternalDocumentsInteractor.test.ts b/shared/src/business/useCases/externalDocument/uploadExternalDocumentsInteractor.test.ts index 2b52f30889c..09075832c03 100644 --- a/shared/src/business/useCases/externalDocument/uploadExternalDocumentsInteractor.test.ts +++ b/shared/src/business/useCases/externalDocument/uploadExternalDocumentsInteractor.test.ts @@ -1,5 +1,8 @@ -import { ROLES } from '../../entities/EntityConstants'; import { applicationContext } from '../../test/createTestApplicationContext'; +import { + mockIrsPractitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { uploadExternalDocumentsInteractor } from './uploadExternalDocumentsInteractor'; describe('uploadExternalDocumentsInteractor', () => { @@ -10,136 +13,133 @@ describe('uploadExternalDocumentsInteractor', () => { }); it('throws an error when an unauthorized user tries to access the use case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }); - await expect( - uploadExternalDocumentsInteractor(applicationContext, { - documentFiles: { - primary: { - stuff: 'hi', + uploadExternalDocumentsInteractor( + applicationContext, + { + documentFiles: { + primary: { + stuff: 'hi', + }, }, - }, - documentMetadata: {}, - fileUploadProgressMap: { - primary: { - file: undefined, - uploadProgress: () => {}, + documentMetadata: {}, + fileUploadProgressMap: { + primary: { + file: undefined, + uploadProgress: () => {}, + }, }, }, - }), + mockPetitionsClerkUser, + ), ).rejects.toThrow('Unauthorized'); }); it('runs successfully with no errors with minimum data and valid user', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.irsPractitioner, - userId: 'irsPractitioner', - }); - - const result = await uploadExternalDocumentsInteractor(applicationContext, { - documentFiles: { - primary: 'something', - }, - documentMetadata: { - primaryDocumentFile: {}, - }, - fileUploadProgressMap: { - primary: { - file: undefined, - uploadProgress: () => {}, - }, - }, - }); - expect(result).toMatchObject({ - caseDetail: expect.anything(), - docketEntryIdsAdded: expect.any(Array), - }); - }); - - it('runs successfully with no errors with all data and valid user', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.irsPractitioner, - userId: 'irsPractitioner', - }); - - await expect( - uploadExternalDocumentsInteractor(applicationContext, { + const result = await uploadExternalDocumentsInteractor( + applicationContext, + { documentFiles: { primary: 'something', - primarySupporting0: 'something3', - secondary: 'something2', - secondarySupporting0: 'something4', }, documentMetadata: { - hasSecondarySupportingDocuments: true, - hasSupportingDocuments: true, primaryDocumentFile: {}, - secondaryDocument: {}, - secondarySupportingDocuments: [{ supportingDocument: 'something' }], - supportingDocuments: [{ supportingDocument: 'something' }], }, fileUploadProgressMap: { primary: { file: undefined, - uploadProgress: () => 'something', + uploadProgress: () => {}, }, - primarySupporting0: { - file: undefined, - uploadProgress: () => 'something3', + }, + }, + mockIrsPractitionerUser, + ); + expect(result).toMatchObject({ + caseDetail: expect.anything(), + docketEntryIdsAdded: expect.any(Array), + }); + }); + + it('runs successfully with no errors with all data and valid user', async () => { + await expect( + uploadExternalDocumentsInteractor( + applicationContext, + { + documentFiles: { + primary: 'something', + primarySupporting0: 'something3', + secondary: 'something2', + secondarySupporting0: 'something4', }, - secondary: { - file: undefined, - uploadProgress: () => 'something2', + documentMetadata: { + hasSecondarySupportingDocuments: true, + hasSupportingDocuments: true, + primaryDocumentFile: {}, + secondaryDocument: {}, + secondarySupportingDocuments: [{ supportingDocument: 'something' }], + supportingDocuments: [{ supportingDocument: 'something' }], }, - secondarySupporting0: { - file: undefined, - uploadProgress: () => 'something4', + fileUploadProgressMap: { + primary: { + file: undefined, + uploadProgress: () => 'something', + }, + primarySupporting0: { + file: undefined, + uploadProgress: () => 'something3', + }, + secondary: { + file: undefined, + uploadProgress: () => 'something2', + }, + secondarySupporting0: { + file: undefined, + uploadProgress: () => 'something4', + }, }, }, - }), + mockIrsPractitionerUser, + ), ).resolves.not.toThrow(); }); it('runs successfully with no errors with all data and valid user who is a practitioner', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.irsPractitioner, - userId: 'irsPractitioner', - }); - await expect( - uploadExternalDocumentsInteractor(applicationContext, { - documentFiles: { - primary: 'something', - primarySupporting0: 'something3', - secondary: 'something2', - secondarySupporting0: 'something4', - }, - documentMetadata: { - primaryDocumentFile: {}, - secondaryDocument: {}, - }, - fileUploadProgressMap: { - primary: { - file: undefined, - uploadProgress: () => 'something', - }, - primarySupporting0: { - file: undefined, - uploadProgress: () => 'something3', + uploadExternalDocumentsInteractor( + applicationContext, + { + documentFiles: { + primary: 'something', + primarySupporting0: 'something3', + secondary: 'something2', + secondarySupporting0: 'something4', }, - secondary: { - file: undefined, - uploadProgress: () => 'something2', + + documentMetadata: { + primaryDocumentFile: {}, + secondaryDocument: {}, }, - secondarySupporting0: { - file: undefined, - uploadProgress: () => 'something4', + fileUploadProgressMap: { + primary: { + file: undefined, + uploadProgress: () => 'something', + }, + primarySupporting0: { + file: undefined, + uploadProgress: () => 'something3', + }, + secondary: { + file: undefined, + uploadProgress: () => 'something2', + }, + secondarySupporting0: { + file: undefined, + uploadProgress: () => 'something4', + }, }, }, - }), + mockIrsPractitionerUser, + ), ).resolves.not.toThrow(); }); }); diff --git a/shared/src/business/useCases/externalDocument/uploadExternalDocumentsInteractor.ts b/shared/src/business/useCases/externalDocument/uploadExternalDocumentsInteractor.ts index 7e623cd3c9d..8ad5f591b4a 100644 --- a/shared/src/business/useCases/externalDocument/uploadExternalDocumentsInteractor.ts +++ b/shared/src/business/useCases/externalDocument/uploadExternalDocumentsInteractor.ts @@ -5,6 +5,7 @@ import { isAuthorized, } from '../../../authorization/authorizationClientService'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * Uploads external documents and calls the interactor to associate them with one or more cases @@ -27,10 +28,9 @@ export const uploadExternalDocumentsInteractor = async ( documentMetadata: any; fileUploadProgressMap: Record; }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.FILE_EXTERNAL_DOCUMENT)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.FILE_EXTERNAL_DOCUMENT)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/shared/src/business/useCases/externalDocument/uploadOrderDocumentInteractor.test.ts b/shared/src/business/useCases/externalDocument/uploadOrderDocumentInteractor.test.ts index 7b32a0d247c..dedfc93b79d 100644 --- a/shared/src/business/useCases/externalDocument/uploadOrderDocumentInteractor.test.ts +++ b/shared/src/business/useCases/externalDocument/uploadOrderDocumentInteractor.test.ts @@ -1,28 +1,31 @@ -import { ROLES } from '../../entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { uploadOrderDocumentInteractor } from './uploadOrderDocumentInteractor'; describe('uploadOrderDocumentInteractor', () => { it('throws an error when an unauthorized user tries to access the use case', async () => { await expect( - uploadOrderDocumentInteractor(applicationContext, { - documentFile: '', - fileIdToOverwrite: '123', - }), + uploadOrderDocumentInteractor( + applicationContext, + { + documentFile: '', + fileIdToOverwrite: '123', + }, + undefined, + ), ).rejects.toThrow(UnauthorizedError); }); it('uploads documents on behalf of authorized users', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'admin', - }); - - await uploadOrderDocumentInteractor(applicationContext, { - documentFile: 'document file', - fileIdToOverwrite: '123', - }); + await uploadOrderDocumentInteractor( + applicationContext, + { + documentFile: 'document file', + fileIdToOverwrite: '123', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().uploadDocumentFromClient.mock diff --git a/shared/src/business/useCases/externalDocument/uploadOrderDocumentInteractor.ts b/shared/src/business/useCases/externalDocument/uploadOrderDocumentInteractor.ts index 410fe977669..718baa3908b 100644 --- a/shared/src/business/useCases/externalDocument/uploadOrderDocumentInteractor.ts +++ b/shared/src/business/useCases/externalDocument/uploadOrderDocumentInteractor.ts @@ -4,6 +4,7 @@ import { isAuthorized, } from '../../../authorization/authorizationClientService'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * @@ -18,11 +19,10 @@ export const uploadOrderDocumentInteractor = async ( { documentFile, fileIdToOverwrite, - }: { fileIdToOverwrite: string; documentFile: any }, + }: { fileIdToOverwrite?: string; documentFile: any }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.COURT_ISSUED_DOCUMENT)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.COURT_ISSUED_DOCUMENT)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/shared/src/business/useCases/generateDocumentIds.test.ts b/shared/src/business/useCases/generateDocumentIds.test.ts index 9c1a50668d8..2e953f590d7 100644 --- a/shared/src/business/useCases/generateDocumentIds.test.ts +++ b/shared/src/business/useCases/generateDocumentIds.test.ts @@ -1,6 +1,9 @@ -import { ROLES } from '../entities/EntityConstants'; import { applicationContext } from '../test/createTestApplicationContext'; import { generateDocumentIds } from './generateDocumentIds'; +import { + mockIrsPractitionerUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('generateDocumentIds', () => { let petitionMetadata: object; @@ -17,42 +20,34 @@ describe('generateDocumentIds', () => { }); beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: 'petitioner', - }); petitionMetadata = {}; }); - it('throws an error when a null user tries to access the case', async () => { - applicationContext.getCurrentUser.mockReturnValue(null); - - await expect( - generateDocumentIds(applicationContext, {} as any), - ).rejects.toThrow(); - }); it('throws an error when an unauthorized user tries to access the case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.irsPractitioner, - userId: 'irsPractitioner', - }); - await expect( - generateDocumentIds(applicationContext, { - petitionFile: null, - petitionMetadata: null, - } as any), + generateDocumentIds( + applicationContext, + { + petitionFile: null, + petitionMetadata: null, + } as any, + mockIrsPractitionerUser, + ), ).rejects.toThrow(); }); it('calls upload on a Petition file', async () => { - await generateDocumentIds(applicationContext, { - petitionMetadata, - petitionUploadProgress: { - file: mockFile, - uploadProgress: jest.fn(), - }, - } as any); + await generateDocumentIds( + applicationContext, + { + petitionMetadata, + petitionUploadProgress: { + file: mockFile, + uploadProgress: jest.fn(), + }, + } as any, + mockPetitionerUser, + ); expect( applicationContext.getUseCases().uploadDocumentAndMakeSafeInteractor.mock @@ -61,17 +56,21 @@ describe('generateDocumentIds', () => { }); it('uploads a Petition file and a STIN file', async () => { - await generateDocumentIds(applicationContext, { - petitionMetadata, - petitionUploadProgress: { - file: mockFile, - uploadProgress: jest.fn(), - }, - stinUploadProgress: { - file: mockFile, - uploadProgress: jest.fn(), - }, - } as any); + await generateDocumentIds( + applicationContext, + { + petitionMetadata, + petitionUploadProgress: { + file: mockFile, + uploadProgress: jest.fn(), + }, + stinUploadProgress: { + file: mockFile, + uploadProgress: jest.fn(), + }, + } as any, + mockPetitionerUser, + ); expect( applicationContext.getUseCases().uploadDocumentAndMakeSafeInteractor.mock @@ -80,17 +79,21 @@ describe('generateDocumentIds', () => { }); it('uploads a Corporate Disclosure Statement file and a petition', async () => { - await generateDocumentIds(applicationContext, { - corporateDisclosureUploadProgress: { - file: mockFile, - uploadProgress: jest.fn(), - }, - petitionMetadata, - petitionUploadProgress: { - file: mockFile, - uploadProgress: jest.fn(), - }, - } as any); + await generateDocumentIds( + applicationContext, + { + corporateDisclosureUploadProgress: { + file: mockFile, + uploadProgress: jest.fn(), + }, + petitionMetadata, + petitionUploadProgress: { + file: mockFile, + uploadProgress: jest.fn(), + }, + } as any, + mockPetitionerUser, + ); expect( applicationContext.getUseCases().uploadDocumentAndMakeSafeInteractor.mock @@ -99,19 +102,23 @@ describe('generateDocumentIds', () => { }); it('uploads Attachment to Petition file and a Petition file', async () => { - await generateDocumentIds(applicationContext, { - attachmentToPetitionUploadProgress: [ - { + await generateDocumentIds( + applicationContext, + { + attachmentToPetitionUploadProgress: [ + { + file: mockFile, + uploadProgress: jest.fn(), + }, + ], + petitionMetadata, + petitionUploadProgress: { file: mockFile, uploadProgress: jest.fn(), }, - ], - petitionMetadata, - petitionUploadProgress: { - file: mockFile, - uploadProgress: jest.fn(), - }, - } as any); + } as any, + mockPetitionerUser, + ); expect( applicationContext.getUseCases().uploadDocumentAndMakeSafeInteractor.mock .calls[1][1].document, @@ -119,23 +126,27 @@ describe('generateDocumentIds', () => { }); it('uploads multiple Attachment to Petition files and a Petition file', async () => { - await generateDocumentIds(applicationContext, { - attachmentToPetitionUploadProgress: [ - { + await generateDocumentIds( + applicationContext, + { + attachmentToPetitionUploadProgress: [ + { + file: mockFile, + uploadProgress: jest.fn(), + }, + { + file: mockFile2, + uploadProgress: jest.fn(), + }, + ], + petitionMetadata, + petitionUploadProgress: { file: mockFile, uploadProgress: jest.fn(), }, - { - file: mockFile2, - uploadProgress: jest.fn(), - }, - ], - petitionMetadata, - petitionUploadProgress: { - file: mockFile, - uploadProgress: jest.fn(), - }, - } as any); + } as any, + mockPetitionerUser, + ); expect( applicationContext.getUseCases().uploadDocumentAndMakeSafeInteractor.mock @@ -164,13 +175,17 @@ describe('generateDocumentIds', () => { .uploadDocumentAndMakeSafeInteractor.mockRejectedValue('something wrong'); await expect( - generateDocumentIds(applicationContext, { - petitionMetadata, - petitionUploadProgress: { - file: mockFile, - uploadProgress: jest.fn(), - }, - } as any), + generateDocumentIds( + applicationContext, + { + petitionMetadata, + petitionUploadProgress: { + file: mockFile, + uploadProgress: jest.fn(), + }, + } as any, + mockPetitionerUser, + ), ).rejects.toThrow('Error generating document Ids'); }); }); diff --git a/shared/src/business/useCases/generateDocumentIds.ts b/shared/src/business/useCases/generateDocumentIds.ts index 98814307f37..a7a0485d324 100644 --- a/shared/src/business/useCases/generateDocumentIds.ts +++ b/shared/src/business/useCases/generateDocumentIds.ts @@ -1,12 +1,14 @@ +import { ClientApplicationContext } from '@web-client/applicationContext'; import { FileUploadProgressType } from '../entities/EntityConstants'; import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const generateDocumentIds = async ( - applicationContext: any, + applicationContext: ClientApplicationContext, { applicationForWaiverOfFilingFeeUploadProgress, attachmentToPetitionUploadProgress, @@ -22,12 +24,11 @@ export const generateDocumentIds = async ( requestForPlaceOfTrialUploadProgress?: FileUploadProgressType; stinUploadProgress: FileUploadProgressType; }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - const hasPermissions = - isAuthorized(user, ROLE_PERMISSIONS.PETITION) || - isAuthorized(user, ROLE_PERMISSIONS.START_PAPER_CASE); + isAuthorized(authorizedUser, ROLE_PERMISSIONS.PETITION) || + isAuthorized(authorizedUser, ROLE_PERMISSIONS.START_PAPER_CASE); if (!hasPermissions) { throw new UnauthorizedError('Unauthorized'); diff --git a/shared/src/business/useCases/generateDraftStampOrderInteractor.test.ts b/shared/src/business/useCases/generateDraftStampOrderInteractor.test.ts index d8f6baba6f9..b7bcfc54840 100644 --- a/shared/src/business/useCases/generateDraftStampOrderInteractor.test.ts +++ b/shared/src/business/useCases/generateDraftStampOrderInteractor.test.ts @@ -1,9 +1,9 @@ -import { MOTION_DISPOSITIONS, ROLES } from '../entities/EntityConstants'; +import { MOTION_DISPOSITIONS } from '../entities/EntityConstants'; import { applicationContext } from '../test/createTestApplicationContext'; import { generateDraftStampOrderInteractor } from './generateDraftStampOrderInteractor'; +import { mockJudgeUser, mockPetitionerUser } from '@shared/test/mockAuthUsers'; describe('generateDraftStampOrderInteractor', () => { - let mockCurrentUser; const docketNumber = '999-99'; const formattedDraftDocumentTitle = 'Motion GRANTED'; const motionDocketEntryId = '67fb412e-cb00-454c-9739-fa90a09dca1d'; @@ -11,48 +11,41 @@ describe('generateDraftStampOrderInteractor', () => { const stampData = { disposition: MOTION_DISPOSITIONS.GRANTED }; const stampedDocketEntryId = 'e9bdeaa1-8c49-479e-9f21-6f3303307f48'; - beforeEach(() => { - mockCurrentUser = { - role: ROLES.judge, - userId: '8675309b-18d0-43ec-bafb-654e83405411', - }; - - applicationContext.getCurrentUser.mockImplementation(() => mockCurrentUser); + it('throws an Unauthorized error when the user role is not allowed to access the method', async () => { + await expect( + generateDraftStampOrderInteractor( + applicationContext, + { + docketNumber, + formattedDraftDocumentTitle, + motionDocketEntryId, + parentMessageId, + stampData, + stampedDocketEntryId, + }, + mockPetitionerUser, + ), + ).rejects.toThrow('Unauthorized'); }); - it('throws an Unauthorized error if the user role is not allowed to access the method', async () => { - mockCurrentUser = { - role: ROLES.petitioner, - userId: '8675309b-18d0-43ec-bafb-654e83405411', - }; - - await expect( - generateDraftStampOrderInteractor(applicationContext, { + it('should add a docket entry for the draft stamp order', async () => { + await generateDraftStampOrderInteractor( + applicationContext, + { docketNumber, formattedDraftDocumentTitle, motionDocketEntryId, parentMessageId, stampData, stampedDocketEntryId, - }), - ).rejects.toThrow('Unauthorized'); - }); - - it('should add a docket entry for the draft stamp order', async () => { - await generateDraftStampOrderInteractor(applicationContext, { - docketNumber, - formattedDraftDocumentTitle, - motionDocketEntryId, - parentMessageId, - stampData, - stampedDocketEntryId, - }); + }, + mockJudgeUser, + ); expect( applicationContext.getUseCaseHelpers() .addDraftStampOrderDocketEntryInteractor, ).toHaveBeenCalled(); - expect( applicationContext.getUseCaseHelpers() .addDraftStampOrderDocketEntryInteractor.mock.calls[0][1], @@ -67,14 +60,18 @@ describe('generateDraftStampOrderInteractor', () => { }); it('should generate a stamped coversheet for the draft stamp order', async () => { - await generateDraftStampOrderInteractor(applicationContext, { - docketNumber, - formattedDraftDocumentTitle, - motionDocketEntryId, - parentMessageId, - stampData, - stampedDocketEntryId, - }); + await generateDraftStampOrderInteractor( + applicationContext, + { + docketNumber, + formattedDraftDocumentTitle, + motionDocketEntryId, + parentMessageId, + stampData, + stampedDocketEntryId, + }, + mockJudgeUser, + ); expect( applicationContext.getUseCaseHelpers() diff --git a/shared/src/business/useCases/generateDraftStampOrderInteractor.ts b/shared/src/business/useCases/generateDraftStampOrderInteractor.ts index 100d22af91f..9043589a738 100644 --- a/shared/src/business/useCases/generateDraftStampOrderInteractor.ts +++ b/shared/src/business/useCases/generateDraftStampOrderInteractor.ts @@ -3,6 +3,7 @@ import { isAuthorized, } from '../../authorization/authorizationClientService'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * generateDraftStampOrderInteractor @@ -32,30 +33,37 @@ export const generateDraftStampOrderInteractor = async ( stampData: any; stampedDocketEntryId: string; }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.STAMP_MOTION)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.STAMP_MOTION)) { throw new UnauthorizedError('Unauthorized'); } await applicationContext .getUseCaseHelpers() - .addDraftStampOrderDocketEntryInteractor(applicationContext, { - docketNumber, - formattedDraftDocumentTitle, - originalDocketEntryId: motionDocketEntryId, - parentMessageId, - stampData, - stampedDocketEntryId, - }); + .addDraftStampOrderDocketEntryInteractor( + applicationContext, + { + docketNumber, + formattedDraftDocumentTitle, + originalDocketEntryId: motionDocketEntryId, + parentMessageId, + stampData, + stampedDocketEntryId, + }, + authorizedUser, + ); await applicationContext .getUseCaseHelpers() - .generateStampedCoversheetInteractor(applicationContext, { - docketEntryId: motionDocketEntryId, - docketNumber, - stampData, - stampedDocketEntryId, - }); + .generateStampedCoversheetInteractor( + applicationContext, + { + docketEntryId: motionDocketEntryId, + docketNumber, + stampData, + stampedDocketEntryId, + }, + authorizedUser, + ); }; diff --git a/shared/src/business/useCases/generatePetitionPdfInteractor.test.ts b/shared/src/business/useCases/generatePetitionPdfInteractor.test.ts index 67fe2bf2bd2..bffaef8fa8c 100644 --- a/shared/src/business/useCases/generatePetitionPdfInteractor.test.ts +++ b/shared/src/business/useCases/generatePetitionPdfInteractor.test.ts @@ -4,14 +4,12 @@ import { } from '@shared/business/entities/EntityConstants'; import { applicationContext } from '../test/createTestApplicationContext'; import { generatePetitionPdfInteractor } from '@shared/business/useCases/generatePetitionPdfInteractor'; -import { petitionerUser } from '@shared/test/mockUsers'; +import { mockPetitionerUser } from '@shared/test/mockAuthUsers'; describe('generatePetitionPdfInteractor', () => { const mockFileId = '9085265b-e8ad-4bab-9e7c-f82e847b41f9'; beforeEach(() => { - applicationContext.getCurrentUser.mockImplementation(() => petitionerUser); - applicationContext .getDocumentGenerators() .petition.mockImplementation( @@ -31,29 +29,31 @@ describe('generatePetitionPdfInteractor', () => { }); it('should throw an Unauthorized user error when user does not have the correct permissions', async () => { - applicationContext.getCurrentUser.mockImplementation(() => ({})); - await expect( - generatePetitionPdfInteractor(applicationContext, {} as any), + generatePetitionPdfInteractor(applicationContext, {} as any, undefined), ).rejects.toThrow('Unauthorized'); }); it('should generate petition and call save document', async () => { - const results = await generatePetitionPdfInteractor(applicationContext, { - caseCaptionExtension: 'TEST_caseCaptionExtension', - caseTitle: 'TEST_caseTitle', - contactPrimary: 'TEST_contactPrimary' as any, - contactSecondary: 'TEST_contactSecondary' as any, - hasIrsNotice: false, - hasUploadedIrsNotice: true, - irsNotices: [], - originalCaseType: CASE_TYPES_MAP.deficiency, - partyType: 'TEST_partyType', - petitionFacts: ['TEST_petitionFacts'], - petitionReasons: ['TEST_petitionReasons'], - preferredTrialCity: 'TEST_preferredTrialCity', - procedureType: 'TEST_procedureType', - }); + const results = await generatePetitionPdfInteractor( + applicationContext, + { + caseCaptionExtension: 'TEST_caseCaptionExtension', + caseTitle: 'TEST_caseTitle', + contactPrimary: 'TEST_contactPrimary' as any, + contactSecondary: 'TEST_contactSecondary' as any, + hasIrsNotice: false, + hasUploadedIrsNotice: true, + irsNotices: [], + originalCaseType: CASE_TYPES_MAP.deficiency, + partyType: 'TEST_partyType', + petitionFacts: ['TEST_petitionFacts'], + petitionReasons: ['TEST_petitionReasons'], + preferredTrialCity: 'TEST_preferredTrialCity', + procedureType: 'TEST_procedureType', + }, + mockPetitionerUser, + ); const petitionCalls = applicationContext.getDocumentGenerators().petition.mock.calls; @@ -96,21 +96,25 @@ describe('generatePetitionPdfInteractor', () => { }, ]; - const results = await generatePetitionPdfInteractor(applicationContext, { - caseCaptionExtension: 'TEST_caseCaptionExtension', - caseTitle: 'TEST_caseTitle', - contactPrimary: 'TEST_contactPrimary' as any, - contactSecondary: 'TEST_contactSecondary' as any, - hasIrsNotice: true, - hasUploadedIrsNotice: true, - irsNotices, - originalCaseType: CASE_TYPES_MAP.deficiency, - partyType: 'TEST_partyType', - petitionFacts: ['TEST_petitionFacts'], - petitionReasons: ['TEST_petitionReasons'], - preferredTrialCity: 'TEST_preferredTrialCity', - procedureType: 'TEST_procedureType', - }); + const results = await generatePetitionPdfInteractor( + applicationContext, + { + caseCaptionExtension: 'TEST_caseCaptionExtension', + caseTitle: 'TEST_caseTitle', + contactPrimary: 'TEST_contactPrimary' as any, + contactSecondary: 'TEST_contactSecondary' as any, + hasIrsNotice: true, + hasUploadedIrsNotice: true, + irsNotices, + originalCaseType: CASE_TYPES_MAP.deficiency, + partyType: 'TEST_partyType', + petitionFacts: ['TEST_petitionFacts'], + petitionReasons: ['TEST_petitionReasons'], + preferredTrialCity: 'TEST_preferredTrialCity', + procedureType: 'TEST_procedureType', + }, + mockPetitionerUser, + ); const petitionCalls = applicationContext.getDocumentGenerators().petition.mock.calls; @@ -140,21 +144,25 @@ describe('generatePetitionPdfInteractor', () => { }, ]; - const results = await generatePetitionPdfInteractor(applicationContext, { - caseCaptionExtension: 'TEST_caseCaptionExtension', - caseTitle: 'TEST_caseTitle', - contactPrimary: 'TEST_contactPrimary' as any, - contactSecondary: 'TEST_contactSecondary' as any, - hasIrsNotice: true, - hasUploadedIrsNotice: true, - irsNotices, - originalCaseType: 'Disclosure1', - partyType: 'TEST_partyType', - petitionFacts: ['TEST_petitionFacts'], - petitionReasons: ['TEST_petitionReasons'], - preferredTrialCity: 'TEST_preferredTrialCity', - procedureType: 'TEST_procedureType', - }); + const results = await generatePetitionPdfInteractor( + applicationContext, + { + caseCaptionExtension: 'TEST_caseCaptionExtension', + caseTitle: 'TEST_caseTitle', + contactPrimary: 'TEST_contactPrimary' as any, + contactSecondary: 'TEST_contactSecondary' as any, + hasIrsNotice: true, + hasUploadedIrsNotice: true, + irsNotices, + originalCaseType: 'Disclosure1', + partyType: 'TEST_partyType', + petitionFacts: ['TEST_petitionFacts'], + petitionReasons: ['TEST_petitionReasons'], + preferredTrialCity: 'TEST_preferredTrialCity', + procedureType: 'TEST_procedureType', + }, + mockPetitionerUser, + ); const petitionCalls = applicationContext.getDocumentGenerators().petition.mock.calls; diff --git a/shared/src/business/useCases/generatePetitionPdfInteractor.ts b/shared/src/business/useCases/generatePetitionPdfInteractor.ts index 54ab16736eb..e8479f72fb1 100644 --- a/shared/src/business/useCases/generatePetitionPdfInteractor.ts +++ b/shared/src/business/useCases/generatePetitionPdfInteractor.ts @@ -8,6 +8,7 @@ import { isAuthorized, } from '@shared/authorization/authorizationClientService'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export type IrsNotice = CreateCaseIrsForm & { noticeIssuedDateFormatted: string; @@ -77,10 +78,9 @@ export const generatePetitionPdfInteractor = async ( originalCaseType: string; irsNotices: IrsNotice[]; }, + authorizedUser: UnknownAuthUser, ): Promise<{ fileId: string }> => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.PETITION)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.PETITION)) { throw new UnauthorizedError('Unauthorized'); } const caseDescription = getCaseDescription(hasIrsNotice, originalCaseType); diff --git a/shared/src/business/useCases/generatePractitionerCaseListPdfInteractor.test.ts b/shared/src/business/useCases/generatePractitionerCaseListPdfInteractor.test.ts index 0538d54321e..62643396490 100644 --- a/shared/src/business/useCases/generatePractitionerCaseListPdfInteractor.test.ts +++ b/shared/src/business/useCases/generatePractitionerCaseListPdfInteractor.test.ts @@ -1,15 +1,13 @@ -import { CASE_STATUS_TYPES, ROLES } from '../entities/EntityConstants'; +import { CASE_STATUS_TYPES } from '../entities/EntityConstants'; import { MOCK_CASE } from '../../test/mockCase'; import { applicationContext } from '../test/createTestApplicationContext'; import { generatePractitionerCaseListPdfInteractor } from './generatePractitionerCaseListPdfInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('generatePractitionerCaseListPdfInteractor', () => { - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - }); - }); - beforeEach(() => { applicationContext.getPersistenceGateway().getUserById.mockResolvedValue({ barNumber: 'PT1234', @@ -18,14 +16,14 @@ describe('generatePractitionerCaseListPdfInteractor', () => { }); it('returns an unauthorized error on non internal users', async () => { - applicationContext.getCurrentUser.mockReturnValueOnce({ - role: ROLES.petitioner, - }); - await expect( - generatePractitionerCaseListPdfInteractor(applicationContext, { - userId: 'a54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + generatePractitionerCaseListPdfInteractor( + applicationContext, + { + userId: 'a54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -51,9 +49,13 @@ describe('generatePractitionerCaseListPdfInteractor', () => { .fn() .mockResolvedValue('pdf'); - await generatePractitionerCaseListPdfInteractor(applicationContext, { - userId: 'a54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + await generatePractitionerCaseListPdfInteractor( + applicationContext, + { + userId: 'a54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getUserById, @@ -70,9 +72,13 @@ describe('generatePractitionerCaseListPdfInteractor', () => { }); await expect( - generatePractitionerCaseListPdfInteractor(applicationContext, { - userId: 'a54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + generatePractitionerCaseListPdfInteractor( + applicationContext, + { + userId: 'a54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Practitioner not found'); }); @@ -104,9 +110,13 @@ describe('generatePractitionerCaseListPdfInteractor', () => { .fn() .mockResolvedValue('pdf'); - await generatePractitionerCaseListPdfInteractor(applicationContext, { - userId: 'a54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + await generatePractitionerCaseListPdfInteractor( + applicationContext, + { + userId: 'a54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCasesByDocketNumbers, @@ -146,9 +156,13 @@ describe('generatePractitionerCaseListPdfInteractor', () => { .fn() .mockResolvedValue('pdf'); - await generatePractitionerCaseListPdfInteractor(applicationContext, { - userId: 'a54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + await generatePractitionerCaseListPdfInteractor( + applicationContext, + { + userId: 'a54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCasesByDocketNumbers, diff --git a/shared/src/business/useCases/generatePractitionerCaseListPdfInteractor.ts b/shared/src/business/useCases/generatePractitionerCaseListPdfInteractor.ts index 2f836039e23..c264925efe5 100644 --- a/shared/src/business/useCases/generatePractitionerCaseListPdfInteractor.ts +++ b/shared/src/business/useCases/generatePractitionerCaseListPdfInteractor.ts @@ -3,7 +3,9 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { partition } from 'lodash'; /** @@ -15,12 +17,13 @@ import { partition } from 'lodash'; * @returns {Object} returns an object of the PDF's fileId and url */ export const generatePractitionerCaseListPdfInteractor = async ( - applicationContext: IApplicationContext, + applicationContext: ServerApplicationContext, { userId }: { userId: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.VIEW_PRACTITIONER_CASE_LIST)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.VIEW_PRACTITIONER_CASE_LIST) + ) { throw new UnauthorizedError('Unauthorized to view practitioners cases'); } diff --git a/shared/src/business/useCases/getAllUsersByRoleInteractor.test.ts b/shared/src/business/useCases/getAllUsersByRoleInteractor.test.ts index cdaa46972af..803076d25ac 100644 --- a/shared/src/business/useCases/getAllUsersByRoleInteractor.test.ts +++ b/shared/src/business/useCases/getAllUsersByRoleInteractor.test.ts @@ -1,32 +1,40 @@ import { applicationContext } from '../test/createTestApplicationContext'; -import { docketClerkUser } from '@shared/test/mockUsers'; import { getAllUsersByRoleInteractor } from '@shared/business/useCases/getAllUsersByRoleInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getAllUsersByRoleInteractor', () => { const TEST_ROLES = ['SOME', 'ROLES']; const EXPECTED_RESULTS = ['user1', 'user2']; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); applicationContext .getPersistenceGateway() .getAllUsersByRole.mockReturnValue(EXPECTED_RESULTS); }); it('should throw an Unauthorized error when user does not have permission', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - getAllUsersByRoleInteractor(applicationContext, { - roles: TEST_ROLES, - }), + getAllUsersByRoleInteractor( + applicationContext, + { + roles: TEST_ROLES, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should call the persistance method with corred params', async () => { - const results = await getAllUsersByRoleInteractor(applicationContext, { - roles: TEST_ROLES, - }); + const results = await getAllUsersByRoleInteractor( + applicationContext, + { + roles: TEST_ROLES, + }, + mockDocketClerkUser, + ); expect(results).toEqual(EXPECTED_RESULTS); diff --git a/shared/src/business/useCases/getAllUsersByRoleInteractor.ts b/shared/src/business/useCases/getAllUsersByRoleInteractor.ts index 97db48c27bc..9a973212aa9 100644 --- a/shared/src/business/useCases/getAllUsersByRoleInteractor.ts +++ b/shared/src/business/useCases/getAllUsersByRoleInteractor.ts @@ -3,12 +3,13 @@ import { isAuthorized, } from '@shared/authorization/authorizationClientService'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const getAllUsersByRoleInteractor = async ( applicationContext: IApplicationContext, { roles }: { roles: string[] }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/shared/src/business/useCases/getBlockedCasesInteractor.test.ts b/shared/src/business/useCases/getBlockedCasesInteractor.test.ts index b5eda2819b7..b3f8ee91a63 100644 --- a/shared/src/business/useCases/getBlockedCasesInteractor.test.ts +++ b/shared/src/business/useCases/getBlockedCasesInteractor.test.ts @@ -1,14 +1,12 @@ -import { ROLES } from '../entities/EntityConstants'; import { applicationContext } from '../test/createTestApplicationContext'; import { getBlockedCasesInteractor } from './getBlockedCasesInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('getBlockedCasesInteractor', () => { it('calls search function with correct params and returns records', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }); - applicationContext.getPersistenceGateway().getBlockedCases.mockReturnValue([ { docketNumber: '101-20', @@ -18,9 +16,13 @@ describe('getBlockedCasesInteractor', () => { }, ]); - const results = await getBlockedCasesInteractor(applicationContext, { - trialLocation: 'Boise, Idaho', - }); + const results = await getBlockedCasesInteractor( + applicationContext, + { + trialLocation: 'Boise, Idaho', + }, + mockPetitionsClerkUser, + ); expect(results).toEqual([ { @@ -33,16 +35,15 @@ describe('getBlockedCasesInteractor', () => { }); it('should throw an unauthorized error if the user does not have access to blocked cases', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: 'petitioner', - }); - let error; try { - await getBlockedCasesInteractor(applicationContext, { - trialLocation: 'Boise, Idaho', - }); + await getBlockedCasesInteractor( + applicationContext, + { + trialLocation: 'Boise, Idaho', + }, + mockPetitionerUser, + ); } catch (err) { error = err; } diff --git a/shared/src/business/useCases/getBlockedCasesInteractor.ts b/shared/src/business/useCases/getBlockedCasesInteractor.ts index cd92061108e..828f3406b32 100644 --- a/shared/src/business/useCases/getBlockedCasesInteractor.ts +++ b/shared/src/business/useCases/getBlockedCasesInteractor.ts @@ -3,6 +3,7 @@ import { isAuthorized, } from '../../authorization/authorizationClientService'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * getBlockedCasesInteractor @@ -15,9 +16,8 @@ import { UnauthorizedError } from '@web-api/errors/errors'; export const getBlockedCasesInteractor = async ( applicationContext: IApplicationContext, { trialLocation }: { trialLocation: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.BLOCK_CASE)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/shared/src/business/useCases/getCaseDeadlinesInteractor.test.ts b/shared/src/business/useCases/getCaseDeadlinesInteractor.test.ts index 0a6ec2cecf6..793e9a9f31d 100644 --- a/shared/src/business/useCases/getCaseDeadlinesInteractor.test.ts +++ b/shared/src/business/useCases/getCaseDeadlinesInteractor.test.ts @@ -4,12 +4,14 @@ import { COUNTRY_TYPES, DOCKET_NUMBER_SUFFIXES, PARTY_TYPES, - ROLES, } from '../entities/EntityConstants'; import { MOCK_CASE } from '../../test/mockCase'; -import { User } from '../entities/User'; import { applicationContext } from '../test/createTestApplicationContext'; import { getCaseDeadlinesInteractor } from './getCaseDeadlinesInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('getCaseDeadlinesInteractor', () => { const mockDeadlines = [ @@ -79,12 +81,6 @@ describe('getCaseDeadlinesInteractor', () => { }, ]; - const mockPetitionsClerk = new User({ - name: 'Test Petitionsclerk', - role: ROLES.petitionsClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - const START_DATE = '2019-08-25T05:00:00.000Z'; const END_DATE = '2020-08-25T05:00:00.000Z'; @@ -99,14 +95,15 @@ describe('getCaseDeadlinesInteractor', () => { applicationContext .getPersistenceGateway() .getCasesByDocketNumbers.mockReturnValue(mockCases); - applicationContext.getCurrentUser.mockReturnValue(mockPetitionsClerk); }); - it('throws an error if the user is not valid or authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue(new User({})); - + it('throws an error when the user is not valid or authorized', async () => { await expect( - getCaseDeadlinesInteractor(applicationContext, {} as any), + getCaseDeadlinesInteractor( + applicationContext, + {} as any, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -114,6 +111,7 @@ describe('getCaseDeadlinesInteractor', () => { const result = await getCaseDeadlinesInteractor( applicationContext, {} as any, + mockPetitionsClerkUser, ); expect(result).toEqual({ @@ -152,13 +150,17 @@ describe('getCaseDeadlinesInteractor', () => { }); it('passes date and filtering params to getCaseDeadlinesByDateRange persistence call', async () => { - await getCaseDeadlinesInteractor(applicationContext, { - endDate: END_DATE, - from: 20, - judge: 'Buch', - pageSize: 50, - startDate: START_DATE, - }); + await getCaseDeadlinesInteractor( + applicationContext, + { + endDate: END_DATE, + from: 20, + judge: 'Buch', + pageSize: 50, + startDate: START_DATE, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseDeadlinesByDateRange @@ -219,7 +221,6 @@ describe('getCaseDeadlinesInteractor', () => { ], }, ]); - applicationContext .getPersistenceGateway() .getCaseDeadlinesByDateRange.mockReturnValue({ @@ -241,6 +242,7 @@ describe('getCaseDeadlinesInteractor', () => { const result = await getCaseDeadlinesInteractor( applicationContext, {} as any, + mockPetitionsClerkUser, ); expect(result).toEqual({ diff --git a/shared/src/business/useCases/getCaseDeadlinesInteractor.ts b/shared/src/business/useCases/getCaseDeadlinesInteractor.ts index afafe465a69..1b89604aa7d 100644 --- a/shared/src/business/useCases/getCaseDeadlinesInteractor.ts +++ b/shared/src/business/useCases/getCaseDeadlinesInteractor.ts @@ -1,3 +1,7 @@ +import { + AuthUser, + UnknownAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; import { Case } from '../entities/cases/Case'; import { CaseDeadline } from '../entities/CaseDeadline'; import { @@ -22,10 +26,9 @@ export const getCaseDeadlinesInteractor = async ( pageSize: number; startDate; }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.CASE_DEADLINE)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CASE_DEADLINE)) { throw new UnauthorizedError('Unauthorized'); } @@ -49,6 +52,7 @@ export const getCaseDeadlinesInteractor = async ( const caseMap = await getCasesByDocketNumbers({ applicationContext, + authorizedUser, docketNumbers: validatedCaseDeadlines.map(item => item.docketNumber), }); @@ -70,10 +74,12 @@ export const getCaseDeadlinesInteractor = async ( const getCasesByDocketNumbers = async ({ applicationContext, + authorizedUser, docketNumbers, }: { applicationContext: IApplicationContext; docketNumbers: string[]; + authorizedUser: AuthUser; }) => { const caseData = await applicationContext .getPersistenceGateway() @@ -83,7 +89,12 @@ const getCasesByDocketNumbers = async ({ }); return caseData - .map(caseRecord => new Case(caseRecord, { applicationContext })) + .map( + caseRecord => + new Case(caseRecord, { + authorizedUser, + }), + ) .filter(caseEntity => { try { caseEntity.validate(); diff --git a/shared/src/business/useCases/getCaseInteractor.test.ts b/shared/src/business/useCases/getCaseInteractor.test.ts index 7cf9e0612b6..e652316188e 100644 --- a/shared/src/business/useCases/getCaseInteractor.test.ts +++ b/shared/src/business/useCases/getCaseInteractor.test.ts @@ -13,14 +13,17 @@ import { applicationContext } from '../test/createTestApplicationContext'; import { cloneDeep } from 'lodash'; import { decorateForCaseStatus, getCaseInteractor } from './getCaseInteractor'; import { getOtherFilers } from '../entities/cases/Case'; +import { + mockDocketClerkUser, + mockPetitionerUser, + mockPetitionsClerkUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getCaseInteractor', () => { - const petitionsclerkId = '23c4d382-1136-492f-b1f4-45e893c34771'; - const docketClerkId = '44c4d382-1136-492f-b1f4-45e893c34771'; const irsPractitionerId = '6cf19fba-18c6-467a-9ea6-7a14e42add2f'; const practitionerId = '295c3640-7ff9-40bb-b2f1-8117bba084ea'; const practitioner2Id = '42614976-4228-49aa-a4c3-597dae1c7220'; - const petitionerId = '42624376-4228-49aa-a4c3-597dae1c7220'; const irsSuperuserId = '5a5c771d-ab63-4d78-a298-1de657dde621'; let testCase; @@ -36,9 +39,13 @@ describe('getCaseInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(testCase); - await getCaseInteractor(applicationContext, { - docketNumber: '000123-19S', - }); + await getCaseInteractor( + applicationContext, + { + docketNumber: '000123-19S', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber.mock @@ -50,11 +57,6 @@ describe('getCaseInteractor', () => { }); it('should throw an error when a case with the provided docketNumber is not found', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Tasha Yar', - role: ROLES.petitionsClerk, - userId: petitionsclerkId, - }); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue( @@ -70,9 +72,13 @@ describe('getCaseInteractor', () => { ); await expect( - getCaseInteractor(applicationContext, { - docketNumber: '123-19', - }), + getCaseInteractor( + applicationContext, + { + docketNumber: '123-19', + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('Case 123-19 was not found.'); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber.mock @@ -81,29 +87,23 @@ describe('getCaseInteractor', () => { }); it('throws an error when the entity returned from persistence is invalid', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: petitionsclerkId, - }); const mockInvalidCase = { ...testCase, caseCaption: undefined }; applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(mockInvalidCase); await expect( - getCaseInteractor(applicationContext, { - docketNumber: '00101-08', - }), + getCaseInteractor( + applicationContext, + { + docketNumber: '00101-08', + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('The Case entity was invalid'); }); it('should return the case when the currentUser is an unassociated IRS practitioner', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'IRS Practitionerr', - role: ROLES.irsPractitioner, - userId: irsPractitionerId, - }); - applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockResolvedValue({ @@ -118,20 +118,23 @@ describe('getCaseInteractor', () => { userId: '320fce0e-b050-4e04-8720-db25da3ca598', }); - const result = await getCaseInteractor(applicationContext, { - docketNumber: '00101-00', - }); + const result = await getCaseInteractor( + applicationContext, + { + docketNumber: '00101-00', + }, + { + email: 'access@example.com', + name: 'IRS Practitionerr', + role: ROLES.irsPractitioner, + userId: irsPractitionerId, + }, + ); expect(result.docketNumber).toEqual('101-00'); }); it('should return the case when the currentUser is an irs superuser even if the case has sealed documents', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'IRS Superuser', - role: ROLES.irsSuperuser, - userId: irsSuperuserId, - }); - applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockResolvedValue({ @@ -156,9 +159,18 @@ describe('getCaseInteractor', () => { userId: '320fce0e-b050-4e04-8720-db25da3ca598', }); - const result = await getCaseInteractor(applicationContext, { - docketNumber: '00101-00', - }); + const result = await getCaseInteractor( + applicationContext, + { + docketNumber: '00101-00', + }, + { + email: 'superduper@example.com', + name: 'IRS Superuser', + role: ROLES.irsSuperuser, + userId: irsSuperuserId, + }, + ); expect(result.docketEntries[1]).toMatchObject({ docketEntryId: testCase.docketEntries[2].docketEntryId, @@ -168,9 +180,6 @@ describe('getCaseInteractor', () => { }); it('should return the case when the currentUser is the contactPrimary on the case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - userId: 'dc56e26e-f9fd-4165-8997-97676cc0523e', - }); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue( @@ -180,16 +189,20 @@ describe('getCaseInteractor', () => { petitioners: [ { ...mockCaseContactPrimary, - contactId: 'dc56e26e-f9fd-4165-8997-97676cc0523e', + contactId: mockPetitionerUser.userId, }, ], userId: '320fce0e-b050-4e04-8720-db25da3ca598', }), ); - const result = await getCaseInteractor(applicationContext, { - docketNumber: '00101-00', - }); + const result = await getCaseInteractor( + applicationContext, + { + docketNumber: '00101-00', + }, + mockPetitionerUser, + ); expect(result.docketNumber).toEqual('101-00'); expect(result.petitioners[0].address1).toBeDefined(); @@ -197,9 +210,6 @@ describe('getCaseInteractor', () => { }); it('should return the case when the currentUser is the contactSecondary on the case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - userId: '754a3191-884f-42f0-ad2c-e6c706685299', - }); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockResolvedValue({ @@ -213,16 +223,20 @@ describe('getCaseInteractor', () => { }, { ...mockCaseContactPrimary, - contactId: '754a3191-884f-42f0-ad2c-e6c706685299', + contactId: mockPetitionerUser.userId, contactType: CONTACT_TYPES.secondary, }, ], userId: '320fce0e-b050-4e04-8720-db25da3ca598', }); - const result = await getCaseInteractor(applicationContext, { - docketNumber: '00101-00', - }); + const result = await getCaseInteractor( + applicationContext, + { + docketNumber: '00101-00', + }, + mockPetitionerUser, + ); expect(result.docketNumber).toEqual('101-00'); expect(result.petitioners[0].address1).toBeDefined(); @@ -230,11 +244,6 @@ describe('getCaseInteractor', () => { }); it('should return the full case (non public) when the user is part of the consolidated group', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Tasha Yar', - role: ROLES.petitioner, - userId: petitionerId, - }); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue({ @@ -246,7 +255,7 @@ describe('getCaseInteractor', () => { petitioners: [ { ...testCase.petitioners[0], - contactId: petitionerId, + contactId: mockPetitionerUser.userId, }, ], }, @@ -255,9 +264,14 @@ describe('getCaseInteractor', () => { leadDocketNumber: '101-20', }); - const result = await getCaseInteractor(applicationContext, { - docketNumber: '101-18', - }); + const result = await getCaseInteractor( + applicationContext, + { + docketNumber: '101-18', + }, + mockPetitionerUser, + ); + expect(result.entityName).toEqual('Case'); }); @@ -277,15 +291,13 @@ describe('getCaseInteractor', () => { }); it(`allows unfiltered view of sealed contact addresses when role is ${ROLES.docketClerk}`, async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Security Officer Worf', - role: ROLES.docketClerk, - userId: docketClerkId, - }); - - const result = await getCaseInteractor(applicationContext, { - docketNumber: '101-18', - }); + const result = await getCaseInteractor( + applicationContext, + { + docketNumber: '101-18', + }, + mockDocketClerkUser, + ); const contactPrimary = result.petitioners[0]; const contactSecondary = result.petitioners[1]; @@ -300,15 +312,13 @@ describe('getCaseInteractor', () => { }); it('returns limited contact address information when address is sealed and requesting user is not docket clerk', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Reginald Barclay', - role: ROLES.privatePractitioner, - userId: applicationContext.getUniqueId(), - }); - - const result = await getCaseInteractor(applicationContext, { - docketNumber: '101-18', - }); + const result = await getCaseInteractor( + applicationContext, + { + docketNumber: '101-18', + }, + mockPrivatePractitionerUser, + ); expect(result.petitioners[0].city).toBeUndefined(); expect(result.petitioners[1].city).toBeUndefined(); @@ -351,15 +361,13 @@ describe('getCaseInteractor', () => { }); it('should return a PublicCase entity when the current user is NOT authorized to view a sealed case and is NOT associated with the case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Tasha Yar', - role: ROLES.privatePractitioner, - userId: practitioner2Id, - }); - - const result = await getCaseInteractor(applicationContext, { - docketNumber: '101-18', - }); + const result = await getCaseInteractor( + applicationContext, + { + docketNumber: '101-18', + }, + mockPrivatePractitionerUser, + ); expect(result).toEqual({ canAllowDocumentService: undefined, @@ -379,15 +387,13 @@ describe('getCaseInteractor', () => { }); it('should return a Case entity when the current user is authorized to view a sealed case and is NOT associated with the case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Tasha Yar', - role: ROLES.docketClerk, - userId: docketClerkId, - }); - - const result = await getCaseInteractor(applicationContext, { - docketNumber: '101-18', - }); + const result = await getCaseInteractor( + applicationContext, + { + docketNumber: '101-18', + }, + mockDocketClerkUser, + ); const contactPrimary = result.petitioners[0]; expect(contactPrimary.address1).toBeDefined(); @@ -395,15 +401,18 @@ describe('getCaseInteractor', () => { }); it('should return a Case entity when the current user is associated with a sealed case and NOT authorized to view it', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Tasha Yar', - role: ROLES.privatePractitioner, - userId: practitionerId, - }); - - const result = await getCaseInteractor(applicationContext, { - docketNumber: '101-18', - }); + const result = await getCaseInteractor( + applicationContext, + { + docketNumber: '101-18', + }, + { + email: 'noaccess@example.com', + name: 'Katherine Pulaski', + role: ROLES.privatePractitioner, + userId: practitionerId, + }, + ); const contactPrimary = result.petitioners[0]; expect(contactPrimary.address1).toBeDefined(); @@ -431,15 +440,13 @@ describe('getCaseInteractor', () => { }); it('should return a Case entity when the current user is an internal user', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Tasha Yar', - role: ROLES.docketClerk, - userId: docketClerkId, - }); - - const result = await getCaseInteractor(applicationContext, { - docketNumber: '101-18', - }); + const result = await getCaseInteractor( + applicationContext, + { + docketNumber: '101-18', + }, + mockDocketClerkUser, + ); const contactPrimary = result.petitioners[0]; expect(contactPrimary.address1).toBeDefined(); @@ -447,15 +454,13 @@ describe('getCaseInteractor', () => { }); it('should return a PublicCase entity when the current user is an external user who is NOT associated with the case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Tasha Yar', - role: ROLES.privatePractitioner, - userId: practitionerId, - }); - - const result = await getCaseInteractor(applicationContext, { - docketNumber: '101-18', - }); + const result = await getCaseInteractor( + applicationContext, + { + docketNumber: '101-18', + }, + mockPrivatePractitionerUser, + ); const contactPrimary = result.petitioners[0]; expect(contactPrimary.address1).toBeUndefined(); @@ -464,15 +469,18 @@ describe('getCaseInteractor', () => { }); it('should return a Case entity when the current user is associated with the case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Tasha Yar', - role: ROLES.privatePractitioner, - userId: practitioner2Id, - }); - - const result = await getCaseInteractor(applicationContext, { - docketNumber: '101-18', - }); + const result = await getCaseInteractor( + applicationContext, + { + docketNumber: '101-18', + }, + { + email: 'accessgranted@example.com', + name: 'Katherine Pulaski', + role: ROLES.privatePractitioner, + userId: practitioner2Id, + }, + ); const contactPrimary = result.petitioners[0]; expect(contactPrimary.address1).toBeDefined(); diff --git a/shared/src/business/useCases/getCaseInteractor.ts b/shared/src/business/useCases/getCaseInteractor.ts index 7b26b879e41..085a6c54ce2 100644 --- a/shared/src/business/useCases/getCaseInteractor.ts +++ b/shared/src/business/useCases/getCaseInteractor.ts @@ -1,3 +1,8 @@ +import { + AuthUser, + UnknownAuthUser, + isAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; import { Case, canAllowDocumentServiceForCase, @@ -7,7 +12,7 @@ import { isAssociatedUser, isUserPartOfGroup, } from '../entities/cases/Case'; -import { NotFoundError } from '@web-api/errors/errors'; +import { NotFoundError, UnauthorizedError } from '@web-api/errors/errors'; import { PublicCase } from '../entities/cases/PublicCase'; import { ROLE_PERMISSIONS, @@ -20,41 +25,37 @@ import { } from '../utilities/caseFilter'; const getSealedCase = ({ - applicationContext, + authorizedUser, caseRecord, isAssociatedWithCase, }: { - applicationContext: IApplicationContext; caseRecord: RawCase; isAssociatedWithCase: boolean; + authorizedUser: AuthUser; }): RawCase | RawPublicCase => { - const currentUser = applicationContext.getCurrentUser(); - let isAuthorizedToViewSealedCase = isAuthorized( - currentUser, + authorizedUser, ROLE_PERMISSIONS.VIEW_SEALED_CASE, ); if (!isAuthorizedToViewSealedCase) { - const petitioner = getPetitionerById(caseRecord, currentUser.userId); + const petitioner = getPetitionerById(caseRecord, authorizedUser.userId); if (petitioner) { isAuthorizedToViewSealedCase = isAuthorized( - currentUser, + authorizedUser, ROLE_PERMISSIONS.VIEW_SEALED_CASE, - getPetitionerById(caseRecord, currentUser.userId).contactId, + getPetitionerById(caseRecord, authorizedUser.userId).contactId, ); } } if (isAuthorizedToViewSealedCase || isAssociatedWithCase) { - return new Case(caseRecord, { applicationContext }) - .validate() - .toRawObject(); + return new Case(caseRecord, { authorizedUser }).validate().toRawObject(); } else { caseRecord = caseSealedFormatter(caseRecord); return new PublicCase(caseRecord, { - applicationContext, + authorizedUser, }) .validate() .toRawObject(); @@ -62,18 +63,16 @@ const getSealedCase = ({ }; const getCaseForExternalUser = ({ - applicationContext, + authorizedUser, caseRecord, isAssociatedWithCase, isAuthorizedToGetCase, }) => { if (isAuthorizedToGetCase && isAssociatedWithCase) { - return new Case(caseRecord, { applicationContext }) - .validate() - .toRawObject(); + return new Case(caseRecord, { authorizedUser }).validate().toRawObject(); } else { return new PublicCase(caseRecord, { - applicationContext, + authorizedUser, }) .validate() .toRawObject(); @@ -110,7 +109,14 @@ export const decorateForCaseStatus = (caseRecord: RawCase) => { export const getCaseInteractor = async ( applicationContext: IApplicationContext, { docketNumber }: { docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { + if (!isAuthUser(authorizedUser)) { + throw new UnauthorizedError( + `Invalid User attempting to view docket Number: ${docketNumber}`, + ); + } + const caseRecord = decorateForCaseStatus( await applicationContext.getPersistenceGateway().getCaseByDocketNumber({ applicationContext, @@ -125,30 +131,29 @@ export const getCaseInteractor = async ( throw error; } - const currentUser = applicationContext.getCurrentUser(); let isAuthorizedToGetCase = isAuthorized( - currentUser, + authorizedUser, ROLE_PERMISSIONS.GET_CASE, ); if (!isAuthorizedToGetCase) { - const petitioner = getPetitionerById(caseRecord, currentUser.userId); + const petitioner = getPetitionerById(caseRecord, authorizedUser.userId); if (petitioner) { isAuthorizedToGetCase = isAuthorized( - currentUser, + authorizedUser, ROLE_PERMISSIONS.GET_CASE, - getPetitionerById(caseRecord, currentUser.userId).contactId, + getPetitionerById(caseRecord, authorizedUser.userId).contactId, ); } else if (caseRecord.leadDocketNumber) { isAuthorizedToGetCase = isUserPartOfGroup({ consolidatedCases: caseRecord.consolidatedCases, - userId: currentUser.userId, + userId: authorizedUser.userId, }); } } let isAssociatedWithCase = isAssociatedUser({ caseRaw: caseRecord, - user: currentUser, + user: authorizedUser, }); if (caseRecord.leadDocketNumber) { @@ -156,7 +161,7 @@ export const getCaseInteractor = async ( isAssociatedWithCase || isUserPartOfGroup({ consolidatedCases: caseRecord.consolidatedCases, - userId: currentUser.userId, + userId: authorizedUser.userId, }); } @@ -169,21 +174,21 @@ export const getCaseInteractor = async ( if (isSealedCase) { caseDetailRaw = await getSealedCase({ - applicationContext, + authorizedUser, caseRecord, isAssociatedWithCase, }); } else { - const { role: userRole } = currentUser; + const { role: userRole } = authorizedUser; const isInternalUser = User.isInternalUser(userRole); if (isInternalUser) { - caseDetailRaw = new Case(caseRecord, { applicationContext }) + caseDetailRaw = new Case(caseRecord, { authorizedUser }) .validate() .toRawObject(); } else { caseDetailRaw = await getCaseForExternalUser({ - applicationContext, + authorizedUser, caseRecord, isAssociatedWithCase, isAuthorizedToGetCase, @@ -191,6 +196,9 @@ export const getCaseInteractor = async ( } } - caseDetailRaw = caseContactAddressSealedFormatter(caseDetailRaw, currentUser); + caseDetailRaw = caseContactAddressSealedFormatter( + caseDetailRaw, + authorizedUser, + ); return caseDetailRaw; }; diff --git a/shared/src/business/useCases/getCasesForUserInteractor.test.ts b/shared/src/business/useCases/getCasesForUserInteractor.test.ts index 1bb462bd729..ccee1c3ff25 100644 --- a/shared/src/business/useCases/getCasesForUserInteractor.test.ts +++ b/shared/src/business/useCases/getCasesForUserInteractor.test.ts @@ -1,11 +1,16 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { CASE_STATUS_TYPES } from '../entities/EntityConstants'; import { MOCK_CASE } from '../../test/mockCase'; import { applicationContext } from '../test/createTestApplicationContext'; import { cloneDeep } from 'lodash'; import { getCasesForUserInteractor } from './getCasesForUserInteractor'; +import { mockPetitionerUser } from '@shared/test/mockAuthUsers'; describe('getCasesForUserInteractor', () => { - const userId = MOCK_CASE.petitioners[0].contactId; + const mockPetitioner: AuthUser = { + ...mockPetitionerUser, + userId: MOCK_CASE.petitioners[0].contactId, + }; let leadCase; let memberCase1; let memberCase2; @@ -64,10 +69,6 @@ describe('getCasesForUserInteractor', () => { }); consolidatedGroupLeadCase11119 = [leadCase, memberCase1, memberCase2]; - - applicationContext.getCurrentUser.mockResolvedValue({ - userId, - }); }); describe('Consolidated cases', () => { it('should return the expected associated cases combined with the consolidated group cases for 111-19', async () => { @@ -102,7 +103,10 @@ describe('getCasesForUserInteractor', () => { consolidatedGroupLeadCase11119, ); - const userCases = await getCasesForUserInteractor(applicationContext); + const userCases = await getCasesForUserInteractor( + applicationContext, + mockPetitioner, + ); expect(userCases).toMatchObject({ closedCaseList: [ @@ -165,7 +169,10 @@ describe('getCasesForUserInteractor', () => { consolidatedGroup, ); - const userCases = await getCasesForUserInteractor(applicationContext); + const userCases = await getCasesForUserInteractor( + applicationContext, + mockPetitioner, + ); const expectedCaseList = [ expect.objectContaining({ @@ -201,7 +208,10 @@ describe('getCasesForUserInteractor', () => { consolidatedGroup, ); - const userCases = await getCasesForUserInteractor(applicationContext); + const userCases = await getCasesForUserInteractor( + applicationContext, + mockPetitioner, + ); const expectedCaseList = [ expect.objectContaining({ @@ -237,7 +247,10 @@ describe('getCasesForUserInteractor', () => { consolidatedGroup, ); - const userCases = await getCasesForUserInteractor(applicationContext); + const userCases = await getCasesForUserInteractor( + applicationContext, + mockPetitioner, + ); const expectedCaseList = [ expect.objectContaining({ @@ -298,7 +311,10 @@ describe('getCasesForUserInteractor', () => { consolidatedGroup, ); - const userCases = await getCasesForUserInteractor(applicationContext); + const userCases = await getCasesForUserInteractor( + applicationContext, + mockPetitioner, + ); const actualOrder = userCases.closedCaseList.map( aCase => aCase.docketNumber, @@ -341,7 +357,10 @@ describe('getCasesForUserInteractor', () => { consolidatedGroupLeadCase11119, ); - const userCases = await getCasesForUserInteractor(applicationContext); + const userCases = await getCasesForUserInteractor( + applicationContext, + mockPetitioner, + ); expect(unconsolidatedCase1.docketEntries).toBeDefined(); expect(unconsolidatedCase2.docketEntries).toBeDefined(); @@ -379,7 +398,10 @@ describe('getCasesForUserInteractor', () => { unconsolidatedClosedCase1, ]); - const userCases = await getCasesForUserInteractor(applicationContext); + const userCases = await getCasesForUserInteractor( + applicationContext, + mockPetitioner, + ); expect(userCases.closedCaseList).toEqual([ expect.objectContaining({ @@ -426,7 +448,7 @@ describe('getCasesForUserInteractor', () => { //call validate to ensure that, yes, the case fails validation (todo) //call getCasesForUser and expect that no exceptions were thrown await expect( - getCasesForUserInteractor(applicationContext), + getCasesForUserInteractor(applicationContext, mockPetitioner), ).resolves.not.toThrow(); }); }); diff --git a/shared/src/business/useCases/getCasesForUserInteractor.ts b/shared/src/business/useCases/getCasesForUserInteractor.ts index fce9d99b9e9..45abd6ba23d 100644 --- a/shared/src/business/useCases/getCasesForUserInteractor.ts +++ b/shared/src/business/useCases/getCasesForUserInteractor.ts @@ -5,6 +5,11 @@ import { userIsDirectlyAssociated, } from '../entities/cases/Case'; import { PaymentStatusTypes } from '@shared/business/entities/EntityConstants'; +import { UnauthorizedError } from '@web-api/errors/errors'; +import { + UnknownAuthUser, + isAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; import { compareISODateStrings } from '../utilities/sortFunctions'; import { partition, uniqBy } from 'lodash'; @@ -27,11 +32,16 @@ export type TAssociatedCase = { export const getCasesForUserInteractor = async ( applicationContext: IApplicationContext, + authorizedUser: UnknownAuthUser, ): Promise<{ openCaseList: TAssociatedCase[]; closedCaseList: TAssociatedCase[]; }> => { - const { userId } = await applicationContext.getCurrentUser(); + if (!isAuthUser(authorizedUser)) { + throw new UnauthorizedError('Invalid User attempting to get cases'); + } + + const { userId } = authorizedUser; const docketNumbers = ( await applicationContext.getPersistenceGateway().getCasesForUser({ diff --git a/shared/src/business/useCases/getNotificationsInteractor.test.ts b/shared/src/business/useCases/getNotificationsInteractor.test.ts index 790ce2298ce..91c5ae9e320 100644 --- a/shared/src/business/useCases/getNotificationsInteractor.test.ts +++ b/shared/src/business/useCases/getNotificationsInteractor.test.ts @@ -1,5 +1,7 @@ import '@web-api/persistence/postgres/messages/mocks.jest'; import { + ADC_SECTION, + CHAMBERS_SECTION, CHIEF_JUDGE, DOCKET_SECTION, PETITIONS_SECTION, @@ -13,6 +15,11 @@ import { getUserInboxMessages as getUserInboxMessagesMock } from '@web-api/persi const getUserInboxMessages = getUserInboxMessagesMock as jest.Mock; const getSectionInboxMessages = getSectionInboxMessagesMock as jest.Mock; +import { + mockAdcUser, + mockDocketClerkUser, + mockJudgeUser, +} from '@shared/test/mockAuthUsers'; const workItems = [ { @@ -100,50 +107,19 @@ describe('getNotificationsInteractor', () => { ...workItems, { ...workItems[0], isRead: false }, ]); - - applicationContext - .getPersistenceGateway() - .getUserById.mockImplementation(({ userId }) => { - if (userId === 'e8577e31-d6d5-4c4a-adc6-520075f3dde5') { - return { - role: ROLES.docketClerk, - section: DOCKET_SECTION, - userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', - }; - } else if (userId === 'ff377e31-d6d5-4c4a-adc6-520075f3dde5') { - return { - role: ROLES.petitioner, - userId: 'ff377e31-d6d5-4c4a-adc6-520075f3dde5', - }; - } else if (userId === 'ee577e31-d6d5-4c4a-adc6-520075f3dde5') { - return { - name: 'Some Judge', - role: ROLES.judge, - section: 'someChambers', - userId: 'ee577e31-d6d5-4c4a-adc6-520075f3dde5', - }; - } else if (userId === '79f21a87-810c-4440-9189-bb6bfea413fd') { - return { - name: 'ADC', - role: ROLES.adc, - section: 'adc', - userId: '79f21a87-810c-4440-9189-bb6bfea413fd', - }; - } - }); - - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', - }); }); it('returns an unread count for my messages', async () => { + applicationContext.getPersistenceGateway().getUserById.mockResolvedValue({ + role: ROLES.docketClerk, + section: DOCKET_SECTION, + userId: mockDocketClerkUser.userId, + }); applicationContext .getPersistenceGateway() .getDocumentQCInboxForUser.mockReturnValue([ { - assigneeId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + assigneeId: mockDocketClerkUser.userId, caseIsInProgress: false, docketEntry: { isFileAttached: true }, isRead: true, @@ -154,7 +130,9 @@ describe('getNotificationsInteractor', () => { const result = await getNotificationsInteractor( applicationContext, {} as any, + mockDocketClerkUser, ); + expect(result).toEqual({ qcIndividualInProgressCount: 0, qcIndividualInboxCount: 1, @@ -168,38 +146,64 @@ describe('getNotificationsInteractor', () => { }); it('returns the total user inbox count', async () => { + applicationContext.getPersistenceGateway().getUserById.mockResolvedValue({ + role: ROLES.docketClerk, + section: DOCKET_SECTION, + userId: mockDocketClerkUser.userId, + }); + const result = await await getNotificationsInteractor( applicationContext, {} as any, + mockDocketClerkUser, ); expect(result.userInboxCount).toEqual(1); }); it('returns the total section messages count', async () => { + applicationContext.getPersistenceGateway().getUserById.mockResolvedValue({ + role: ROLES.docketClerk, + section: DOCKET_SECTION, + userId: mockDocketClerkUser.userId, + }); + const result = await await getNotificationsInteractor( applicationContext, {} as any, + mockDocketClerkUser, ); expect(result.userSectionCount).toEqual(2); }); it('returns an accurate unread count for legacy items marked complete', async () => { + applicationContext.getPersistenceGateway().getUserById.mockResolvedValue({ + role: ROLES.docketClerk, + section: DOCKET_SECTION, + userId: mockDocketClerkUser.userId, + }); + const result = await getNotificationsInteractor( applicationContext, {} as any, + mockDocketClerkUser, ); expect(result.qcUnreadCount).toEqual(1); }); it('returns the qcIndividualInProgressCount for qc individual items with caseIsInProgress true, isFileAttached true and a judgeUserId supplied', async () => { + applicationContext.getPersistenceGateway().getUserById.mockResolvedValue({ + role: ROLES.docketClerk, + section: DOCKET_SECTION, + userId: mockDocketClerkUser.userId, + }); applicationContext .getPersistenceGateway() .getDocumentQCInboxForUser.mockReturnValue([ { - assigneeId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + assigneeId: mockDocketClerkUser.userId, associatedJudge: 'Judge Barker', caseIsInProgress: true, docketEntry: { @@ -210,7 +214,7 @@ describe('getNotificationsInteractor', () => { section: DOCKET_SECTION, }, { - assigneeId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + assigneeId: mockDocketClerkUser.userId, associatedJudge: 'Some Judge', caseIsInProgress: true, docketEntry: { @@ -221,7 +225,7 @@ describe('getNotificationsInteractor', () => { section: DOCKET_SECTION, }, { - assigneeId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + assigneeId: mockDocketClerkUser.userId, associatedJudge: 'Some Judge', caseIsInProgress: false, docketEntry: { @@ -233,20 +237,29 @@ describe('getNotificationsInteractor', () => { }, ]); - const result = await getNotificationsInteractor(applicationContext, { - caseServicesSupervisorData: undefined, - judgeUserId: 'ee577e31-d6d5-4c4a-adc6-520075f3dde5', - }); + const result = await getNotificationsInteractor( + applicationContext, + { + caseServicesSupervisorData: undefined, + judgeUserId: mockJudgeUser.userId, + }, + mockDocketClerkUser, + ); expect(result.qcIndividualInProgressCount).toEqual(1); }); it('returns the qcIndividualInboxCount for qc individual items with caseIsInProgress false, isFileAttached true and a judgeUserId supplied', async () => { + applicationContext.getPersistenceGateway().getUserById.mockResolvedValue({ + role: ROLES.docketClerk, + section: DOCKET_SECTION, + userId: mockDocketClerkUser.userId, + }); applicationContext .getPersistenceGateway() .getDocumentQCInboxForUser.mockReturnValue([ { - assigneeId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + assigneeId: mockDocketClerkUser.userId, associatedJudge: 'Judge Barker', caseIsInProgress: false, docketEntry: { @@ -257,7 +270,7 @@ describe('getNotificationsInteractor', () => { section: DOCKET_SECTION, }, { - assigneeId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + assigneeId: mockDocketClerkUser.userId, associatedJudge: 'Some Judge', caseIsInProgress: false, docketEntry: { @@ -268,7 +281,7 @@ describe('getNotificationsInteractor', () => { section: DOCKET_SECTION, }, { - assigneeId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + assigneeId: mockDocketClerkUser.userId, associatedJudge: 'Some Judge', caseIsInProgress: true, docketEntry: { @@ -280,15 +293,24 @@ describe('getNotificationsInteractor', () => { }, ]); - const result = await getNotificationsInteractor(applicationContext, { - caseServicesSupervisorData: undefined, - judgeUserId: 'ee577e31-d6d5-4c4a-adc6-520075f3dde5', - }); + const result = await getNotificationsInteractor( + applicationContext, + { + caseServicesSupervisorData: undefined, + judgeUserId: mockJudgeUser.userId, + }, + mockDocketClerkUser, + ); expect(result.qcIndividualInboxCount).toEqual(1); }); it('returns the qcSectionInProgressCount for qc section items with caseIsInProgress true, isFileAttached true and a judgeUserId supplied', async () => { + applicationContext.getPersistenceGateway().getUserById.mockResolvedValue({ + role: ROLES.docketClerk, + section: DOCKET_SECTION, + userId: mockDocketClerkUser.userId, + }); applicationContext .getPersistenceGateway() .getDocumentQCInboxForSection.mockReturnValue([ @@ -323,7 +345,7 @@ describe('getNotificationsInteractor', () => { section: DOCKET_SECTION, }, { - assigneeId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + assigneeId: mockDocketClerkUser.userId, associatedJudge: 'Some Judge', caseIsInProgress: true, docketEntry: { @@ -345,15 +367,24 @@ describe('getNotificationsInteractor', () => { }, ]); - const result = await getNotificationsInteractor(applicationContext, { - caseServicesSupervisorData: undefined, - judgeUserId: 'ee577e31-d6d5-4c4a-adc6-520075f3dde5', - }); + const result = await getNotificationsInteractor( + applicationContext, + { + caseServicesSupervisorData: undefined, + judgeUserId: mockJudgeUser.userId, + }, + mockDocketClerkUser, + ); expect(result.qcSectionInProgressCount).toEqual(2); }); it('returns the qcSectionInboxCount for qc section items with caseIsInProgress true, isFileAttached true and a judgeUserId supplied', async () => { + applicationContext.getPersistenceGateway().getUserById.mockResolvedValue({ + role: ROLES.docketClerk, + section: DOCKET_SECTION, + userId: mockDocketClerkUser.userId, + }); applicationContext .getPersistenceGateway() .getDocumentQCInboxForSection.mockReturnValue([ @@ -379,10 +410,14 @@ describe('getNotificationsInteractor', () => { }, ]); - const result = await getNotificationsInteractor(applicationContext, { - caseServicesSupervisorData: undefined, - judgeUserId: 'ee577e31-d6d5-4c4a-adc6-520075f3dde5', - }); + const result = await getNotificationsInteractor( + applicationContext, + { + caseServicesSupervisorData: undefined, + judgeUserId: mockJudgeUser.userId, + }, + mockDocketClerkUser, + ); expect(result.qcSectionInboxCount).toEqual(1); }); @@ -399,10 +434,14 @@ describe('getNotificationsInteractor', () => { }, ]); - const result = await getNotificationsInteractor(applicationContext, { - caseServicesSupervisorData: undefined, - judgeUserId: 'docketclerk', - }); + const result = await getNotificationsInteractor( + applicationContext, + { + caseServicesSupervisorData: undefined, + judgeUserId: 'docketclerk', + }, + mockDocketClerkUser, + ); expect(result).toMatchObject({ userInboxCount: 2, @@ -410,11 +449,22 @@ describe('getNotificationsInteractor', () => { }); it('should fetch the qc section items for the provided judgeUserId', async () => { - await getNotificationsInteractor(applicationContext, { - caseServicesSupervisorData: undefined, - judgeUserId: 'ee577e31-d6d5-4c4a-adc6-520075f3dde5', + applicationContext.getPersistenceGateway().getUserById.mockResolvedValue({ + name: 'Some Judge', + role: ROLES.judge, + section: CHAMBERS_SECTION, + userId: mockJudgeUser.userId, }); + await getNotificationsInteractor( + applicationContext, + { + caseServicesSupervisorData: undefined, + judgeUserId: mockJudgeUser.userId, + }, + mockDocketClerkUser, + ); + expect( applicationContext.getPersistenceGateway().getDocumentQCInboxForSection .mock.calls[0][0], @@ -424,7 +474,17 @@ describe('getNotificationsInteractor', () => { }); it('should fetch the qc section items without a judgeName when a judgeUserId is not provided', async () => { - await getNotificationsInteractor(applicationContext, {} as any); + applicationContext.getPersistenceGateway().getUserById.mockResolvedValue({ + role: ROLES.docketClerk, + section: DOCKET_SECTION, + userId: mockDocketClerkUser.userId, + }); + + await getNotificationsInteractor( + applicationContext, + {} as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getDocumentQCInboxForSection @@ -435,12 +495,17 @@ describe('getNotificationsInteractor', () => { }); it('should fetch the qc section items with judgeName of CHIEF_JUDGE when a judgeUserId is not provided and the user role is adc', async () => { - applicationContext.getCurrentUser.mockReturnValue({ + applicationContext.getPersistenceGateway().getUserById.mockResolvedValue({ role: ROLES.adc, - userId: '79f21a87-810c-4440-9189-bb6bfea413fd', + section: ADC_SECTION, + userId: mockAdcUser.userId, }); - await getNotificationsInteractor(applicationContext, {} as any); + await getNotificationsInteractor( + applicationContext, + {} as any, + mockAdcUser, + ); expect( applicationContext.getPersistenceGateway().getDocumentQCInboxForSection @@ -451,11 +516,6 @@ describe('getNotificationsInteractor', () => { }); it('should fetch messages for the filtered document QC inbox for the selected section when caseServicesSupervisorData is not empty', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.adc, - userId: '79f21a87-810c-4440-9189-bb6bfea413fd', - }); - const filteredWorkItem = { associatedJudge: 'Judge Barker', caseIsInProgress: false, @@ -466,23 +526,25 @@ describe('getNotificationsInteractor', () => { isRead: true, section: PETITIONS_SECTION, }; - const mockCaseServicesSupervisorData = { section: PETITIONS_SECTION, userId: caseServicesSupervisorUser.userId, }; - applicationContext .getPersistenceGateway() .getDocumentQCInboxForSection.mockReturnValue([filteredWorkItem]); - const result = await getNotificationsInteractor(applicationContext, { - caseServicesSupervisorData: { - section: PETITIONS_SECTION, - userId: caseServicesSupervisorUser.userId, + const result = await getNotificationsInteractor( + applicationContext, + { + caseServicesSupervisorData: { + section: PETITIONS_SECTION, + userId: caseServicesSupervisorUser.userId, + }, + judgeUserId: undefined, }, - judgeUserId: undefined, - }); + mockAdcUser, + ); expect(getUserInboxMessages.mock.calls[0][0].userId).toEqual( caseServicesSupervisorUser.userId, diff --git a/shared/src/business/useCases/getNotificationsInteractor.ts b/shared/src/business/useCases/getNotificationsInteractor.ts index fd1fe1e0630..53c3aab620c 100644 --- a/shared/src/business/useCases/getNotificationsInteractor.ts +++ b/shared/src/business/useCases/getNotificationsInteractor.ts @@ -1,5 +1,10 @@ import { CHIEF_JUDGE, ROLES } from '../entities/EntityConstants'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnauthorizedError } from '@web-api/errors/errors'; +import { + UnknownAuthUser, + isAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; import { getSectionInboxMessages } from '@web-api/persistence/postgres/messages/getSectionInboxMessages'; import { getUserInboxMessages } from '@web-api/persistence/postgres/messages/getUserInboxMessages'; import { isEmpty } from 'lodash'; @@ -30,6 +35,7 @@ export const getNotificationsInteractor = async ( caseServicesSupervisorData, judgeUserId, }: { judgeUserId: string; caseServicesSupervisorData: any }, + authorizedUser: UnknownAuthUser, ): Promise<{ qcIndividualInProgressCount: number; qcIndividualInboxCount: number; @@ -40,17 +46,19 @@ export const getNotificationsInteractor = async ( userInboxCount: number; userSectionCount: number; }> => { - const appContextUser = applicationContext.getCurrentUser(); - applicationContext.logger.info('getNotificationsInteractor start', { - appContextUser, + appContextUser: authorizedUser, }); + if (!isAuthUser(authorizedUser)) { + throw new UnauthorizedError('Invalid User getting notifications'); + } + const [currentUser, judgeUser] = await Promise.all([ applicationContext .getPersistenceGateway() - .getUserById({ applicationContext, userId: appContextUser.userId }), - getJudgeUser(judgeUserId, applicationContext, appContextUser.role), + .getUserById({ applicationContext, userId: authorizedUser.userId }), + getJudgeUser(judgeUserId, applicationContext, authorizedUser.role), ]); applicationContext.logger.info('getNotificationsInteractor getUser', { diff --git a/shared/src/business/useCases/getPaperServicePdfUrlInteractor.test.ts b/shared/src/business/useCases/getPaperServicePdfUrlInteractor.test.ts index 19cc4fdf2d7..1b9bd34bd19 100644 --- a/shared/src/business/useCases/getPaperServicePdfUrlInteractor.test.ts +++ b/shared/src/business/useCases/getPaperServicePdfUrlInteractor.test.ts @@ -1,29 +1,37 @@ import { applicationContext } from '../test/createTestApplicationContext'; import { getPaperServicePdfUrlInteractor } from './getPaperServicePdfUrlInteractor'; -import { petitionerUser, petitionsClerkUser } from '@shared/test/mockUsers'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('getPaperServicePdfUrlInteractor', () => { it('should throw an unauthorized error when the user does not have permission to re-print trial session paper service documents', async () => { - applicationContext.getCurrentUser.mockReturnValueOnce(petitionerUser); // Only trial clerks and petitions clerks can re-print paper service documents - await expect( - getPaperServicePdfUrlInteractor(applicationContext, { - fileId: 'd30ca1a5-6e9c-411d-a292-3e89abf13141', - }), + getPaperServicePdfUrlInteractor( + applicationContext, + { + fileId: 'd30ca1a5-6e9c-411d-a292-3e89abf13141', + }, + mockPetitionerUser, // Only trial clerks and petitions clerks can re-print paper service documents + ), ).rejects.toThrow('Unauthorized'); }); it('should return a url to the document specified when the user has permission to re-print trial session paper service documents', async () => { const mockFileId = 'd30ca1a5-6e9c-411d-a292-3e89abf13141'; const mockDocumentUrl = 'example.com'; - applicationContext.getCurrentUser.mockReturnValueOnce(petitionsClerkUser); applicationContext .getPersistenceGateway() .getDownloadPolicyUrl.mockResolvedValue({ url: mockDocumentUrl }); - const { url } = await getPaperServicePdfUrlInteractor(applicationContext, { - fileId: mockFileId, - }); + const { url } = await getPaperServicePdfUrlInteractor( + applicationContext, + { + fileId: mockFileId, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getDownloadPolicyUrl, diff --git a/shared/src/business/useCases/getPaperServicePdfUrlInteractor.ts b/shared/src/business/useCases/getPaperServicePdfUrlInteractor.ts index a103813b8ff..47b5fc1b6be 100644 --- a/shared/src/business/useCases/getPaperServicePdfUrlInteractor.ts +++ b/shared/src/business/useCases/getPaperServicePdfUrlInteractor.ts @@ -3,14 +3,14 @@ import { isAuthorized, } from '../../authorization/authorizationClientService'; import { UnauthorizedError } from '../../../../web-api/src/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const getPaperServicePdfUrlInteractor = async ( applicationContext: IApplicationContext, { fileId }: { fileId: string }, + authorizedUser: UnknownAuthUser, ): Promise<{ url: string }> => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/shared/src/business/useCases/getReconciliationReportInteractor.test.ts b/shared/src/business/useCases/getReconciliationReportInteractor.test.ts index 5c8c8ef0345..0c072debbc8 100644 --- a/shared/src/business/useCases/getReconciliationReportInteractor.test.ts +++ b/shared/src/business/useCases/getReconciliationReportInteractor.test.ts @@ -4,9 +4,12 @@ import { createStartOfDayISO, formatNow, } from '../utilities/DateHandler'; -import { ROLES } from '../entities/EntityConstants'; import { applicationContext } from '../test/createTestApplicationContext'; import { getReconciliationReportInteractor } from './getReconciliationReportInteractor'; +import { + mockDocketClerkUser, + mockIrsSuperuser, +} from '@shared/test/mockAuthUsers'; describe('getReconciliationReportInteractor', () => { const mockCaseCaption = 'Kaitlin Chaney, Petitioner'; @@ -22,46 +25,56 @@ describe('getReconciliationReportInteractor', () => { sk: 'case|135-20', }, ]); - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.irsSuperuser, - userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', - }); }); it('should throw unauthorized error if user does not have permission', async () => { - applicationContext.getCurrentUser.mockReturnValueOnce({ - role: ROLES.docketClerk, - userId: '33577e31-d6d5-4c4a-adc6-520075f3dde5', - }); await expect( - getReconciliationReportInteractor(applicationContext, { - reconciliationDate: undefined, - }), + getReconciliationReportInteractor( + applicationContext, + { + reconciliationDate: undefined, + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should throw an error if date is not formatted correctly', async () => { await expect( - getReconciliationReportInteractor(applicationContext, { - reconciliationDate: undefined, - }), + getReconciliationReportInteractor( + applicationContext, + { + reconciliationDate: undefined, + }, + mockIrsSuperuser, + ), ).rejects.toThrow('Must be valid reconciliation date'); }); + it('should throw an error if date is in the future', async () => { await expect( - getReconciliationReportInteractor(applicationContext, { - reconciliationDate: '9999-01-01', - }), + getReconciliationReportInteractor( + applicationContext, + { + reconciliationDate: '9999-01-01', + }, + mockIrsSuperuser, + ), ).rejects.toThrow('not later than today'); }); + it('should call the persistence method with current date if "today" is provided as a parameter', async () => { applicationContext .getPersistenceGateway() .getReconciliationReport.mockReturnValue([]); - await getReconciliationReportInteractor(applicationContext, { - reconciliationDate: 'today', - }); + await getReconciliationReportInteractor( + applicationContext, + { + reconciliationDate: 'today', + }, + mockIrsSuperuser, + ); const reconciliationDateNow = formatNow(FORMATS.YYYYMMDD); const [year, month, day] = reconciliationDateNow.split('-'); @@ -83,9 +96,13 @@ describe('getReconciliationReportInteractor', () => { .getReconciliationReport.mockReturnValue([]); const reconciliationDate = '2021-01-01'; - const result = await getReconciliationReportInteractor(applicationContext, { - reconciliationDate, - }); + const result = await getReconciliationReportInteractor( + applicationContext, + { + reconciliationDate, + }, + mockIrsSuperuser, + ); expect(result).toMatchObject({ docketEntries: expect.any(Array), @@ -114,9 +131,13 @@ describe('getReconciliationReportInteractor', () => { .getReconciliationReport.mockReturnValue(docketEntries); const reconciliationDate = '2021-01-01'; - const result = await getReconciliationReportInteractor(applicationContext, { - reconciliationDate, - }); + const result = await getReconciliationReportInteractor( + applicationContext, + { + reconciliationDate, + }, + mockIrsSuperuser, + ); expect(result).toMatchObject({ docketEntries, @@ -154,9 +175,13 @@ describe('getReconciliationReportInteractor', () => { .getReconciliationReport.mockReturnValue(docketEntries); const reconciliationDate = '2021-01-01'; - await getReconciliationReportInteractor(applicationContext, { - reconciliationDate, - }); + await getReconciliationReportInteractor( + applicationContext, + { + reconciliationDate, + }, + mockIrsSuperuser, + ); expect( applicationContext.getPersistenceGateway().getCasesByDocketNumbers.mock @@ -169,10 +194,14 @@ describe('getReconciliationReportInteractor', () => { const startDate = '2020-01-01'; const timeStart = '05:00'; await expect( - getReconciliationReportInteractor(applicationContext, { - reconciliationDate: startDate, - start: timeStart, - }), + getReconciliationReportInteractor( + applicationContext, + { + reconciliationDate: startDate, + start: timeStart, + }, + mockIrsSuperuser, + ), ).resolves.not.toThrow(); }); @@ -197,11 +226,15 @@ describe('getReconciliationReportInteractor', () => { .getPersistenceGateway() .getReconciliationReport.mockReturnValue(docketEntries); - const result = await getReconciliationReportInteractor(applicationContext, { - end: timeEnd, - reconciliationDate: startDate, - start: timeStart, - }); + const result = await getReconciliationReportInteractor( + applicationContext, + { + end: timeEnd, + reconciliationDate: startDate, + start: timeStart, + }, + mockIrsSuperuser, + ); expect(result.reconciliationDate).toBe(startDate); }); }); diff --git a/shared/src/business/useCases/getReconciliationReportInteractor.ts b/shared/src/business/useCases/getReconciliationReportInteractor.ts index 8602e31ec64..84edf5c7582 100644 --- a/shared/src/business/useCases/getReconciliationReportInteractor.ts +++ b/shared/src/business/useCases/getReconciliationReportInteractor.ts @@ -13,6 +13,7 @@ import { } from '../../authorization/authorizationClientService'; import { ReconciliationReportEntry } from '../entities/ReconciliationReportEntry'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; function isValidTime(time: string): boolean { return isValidDateString(time, [FORMATS.TIME_24_HOUR]); @@ -37,8 +38,8 @@ export const getReconciliationReportInteractor = async ( end?: string; start?: string; }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.SERVICE_SUMMARY_REPORT)) { throw new UnauthorizedError('Unauthorized'); } @@ -77,10 +78,8 @@ export const getReconciliationReportInteractor = async ( await assignCaseCaptionFromPersistence(applicationContext, docketEntries); const report = { - docketEntries: ReconciliationReportEntry.validateRawCollection( - docketEntries, - { applicationContext }, - ), + docketEntries: + ReconciliationReportEntry.validateRawCollection(docketEntries), reconciliationDate, reconciliationDateEnd: isoEnd, reportTitle: 'Reconciliation Report', diff --git a/shared/src/business/useCases/getUserInteractor.test.ts b/shared/src/business/useCases/getUserInteractor.test.ts index d1e368996f9..1040c52b37b 100644 --- a/shared/src/business/useCases/getUserInteractor.test.ts +++ b/shared/src/business/useCases/getUserInteractor.test.ts @@ -1,32 +1,31 @@ -import { IrsPractitioner } from '../entities/IrsPractitioner'; +import { IrsPractitioner } from '@shared/business/entities/IrsPractitioner'; import { PETITIONS_SECTION, ROLES } from '../entities/EntityConstants'; import { Practitioner } from '@shared/business/entities/Practitioner'; import { PrivatePractitioner } from '@shared/business/entities/PrivatePractitioner'; -import { User } from '../entities/User'; import { applicationContext } from '../test/createTestApplicationContext'; import { getUserInteractor } from './getUserInteractor'; +import { + mockIrsPractitionerUser, + mockJudgeUser, + mockPetitionsClerkUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getUserInteractor', () => { it('should call the persistence method to get the user', async () => { - const mockPetitionsClerk = { - name: 'Test Petitionsclerk', - role: ROLES.petitionsClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }; - applicationContext.getCurrentUser.mockReturnValue( - new User(mockPetitionsClerk), - ); applicationContext.getPersistenceGateway().getUserById.mockReturnValue({ - ...mockPetitionsClerk, + ...mockPetitionsClerkUser, section: PETITIONS_SECTION, }); - const user = await getUserInteractor(applicationContext); + const user = await getUserInteractor( + applicationContext, + mockPetitionsClerkUser, + ); expect(user).toEqual({ - ...mockPetitionsClerk, + ...mockPetitionsClerkUser, barNumber: undefined, - email: undefined, entityName: 'User', section: PETITIONS_SECTION, token: undefined, @@ -34,20 +33,14 @@ describe('getUserInteractor', () => { }); it('should throw an error if the user is not found', async () => { - const mockPetitionsClerk = { - name: 'Test Petitionsclerk', - role: ROLES.petitionsClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }; - applicationContext.getCurrentUser.mockReturnValue( - new User(mockPetitionsClerk), - ); applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(null); - await expect(getUserInteractor(applicationContext)).rejects.toThrow( - `User id "${mockPetitionsClerk.userId}" not found in persistence.`, + await expect( + getUserInteractor(applicationContext, mockPetitionsClerkUser), + ).rejects.toThrow( + `User id "${mockPetitionsClerkUser.userId}" not found in persistence.`, ); }); @@ -58,15 +51,14 @@ describe('getUserInteractor', () => { judgeTitle: 'Judge', name: 'Test Judge', role: ROLES.judge, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', + userId: mockJudgeUser.userId, }; - applicationContext.getCurrentUser.mockReturnValue(new User(mockJudge)); applicationContext.getPersistenceGateway().getUserById.mockReturnValue({ ...mockJudge, section: 'judge', }); - const user = await getUserInteractor(applicationContext); + const user = await getUserInteractor(applicationContext, mockJudgeUser); expect(user).toEqual({ ...mockJudge, @@ -79,27 +71,20 @@ describe('getUserInteractor', () => { }); it('should return a PrivatePractitioner entity when the entity returned from persistence is a PrivatePractitioner', async () => { - const mockPrivatePractitioner = { - entityName: PrivatePractitioner.ENTITY_NAME, - name: 'Test Private Practitioner', - role: ROLES.privatePractitioner, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }; - - applicationContext.getCurrentUser.mockReturnValue( - new User(mockPrivatePractitioner), - ); applicationContext.getPersistenceGateway().getUserById.mockReturnValue({ - ...mockPrivatePractitioner, + ...mockPrivatePractitionerUser, barNumber: 'PT1234', + entityName: PrivatePractitioner.ENTITY_NAME, }); - const user = await getUserInteractor(applicationContext); + const user = await getUserInteractor( + applicationContext, + mockPrivatePractitionerUser, + ); expect(user).toMatchObject({ - ...mockPrivatePractitioner, + ...mockPrivatePractitionerUser, barNumber: 'PT1234', - email: undefined, isUpdatingInformation: undefined, representing: [], token: undefined, @@ -107,27 +92,20 @@ describe('getUserInteractor', () => { }); it('should return an IrsPractitioner entity when the entity returned from persistence is a IrsPractitioner', async () => { - const mockIrsPractitioner = { - entityName: IrsPractitioner.ENTITY_NAME, - name: 'Test Irs Practitioner', - role: ROLES.irsPractitioner, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }; - - applicationContext.getCurrentUser.mockReturnValue( - new User(mockIrsPractitioner), - ); applicationContext.getPersistenceGateway().getUserById.mockReturnValue({ - ...mockIrsPractitioner, + ...mockIrsPractitionerUser, barNumber: 'PT5678', + entityName: IrsPractitioner.ENTITY_NAME, }); - const user = await getUserInteractor(applicationContext); + const user = await getUserInteractor( + applicationContext, + mockIrsPractitionerUser, + ); expect(user).toMatchObject({ - ...mockIrsPractitioner, + ...mockIrsPractitionerUser, barNumber: 'PT5678', - email: undefined, isUpdatingInformation: undefined, token: undefined, }); @@ -146,18 +124,17 @@ describe('getUserInteractor', () => { practiceType: 'IRS', practitionerType: 'Attorney', role: ROLES.irsPractitioner, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', + userId: mockIrsPractitionerUser.userId, }; - - applicationContext.getCurrentUser.mockReturnValue( - new User(mockPractitioner), - ); applicationContext.getPersistenceGateway().getUserById.mockReturnValue({ ...mockPractitioner, barNumber: 'PT9012', }); - const user = await getUserInteractor(applicationContext); + const user = await getUserInteractor( + applicationContext, + mockIrsPractitionerUser, + ); expect(user).toMatchObject({ ...mockPractitioner, diff --git a/shared/src/business/useCases/getUserInteractor.ts b/shared/src/business/useCases/getUserInteractor.ts index b4cba4c596a..89b061a1838 100644 --- a/shared/src/business/useCases/getUserInteractor.ts +++ b/shared/src/business/useCases/getUserInteractor.ts @@ -2,15 +2,31 @@ import { IrsPractitioner, RawIrsPractitioner, } from '../entities/IrsPractitioner'; -import { NotFoundError } from '../../../../web-api/src/errors/errors'; +import { NotFoundError, UnauthorizedError } from '@web-api/errors/errors'; import { Practitioner, RawPractitioner } from '../entities/Practitioner'; -import { PrivatePractitioner } from '../entities/PrivatePractitioner'; +import { + PrivatePractitioner, + RawPrivatePractitioner, +} from '../entities/PrivatePractitioner'; import { RawUser, User } from '../entities/User'; +import { + UnknownAuthUser, + isAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; + +export type GetUserResponse = + | RawUser + | RawPractitioner + | RawIrsPractitioner + | RawPrivatePractitioner; export const getUserInteractor = async ( applicationContext: IApplicationContext, -): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); + authorizedUser: UnknownAuthUser, +): Promise => { + if (!isAuthUser(authorizedUser)) { + throw new UnauthorizedError('Not authorized to get user'); + } const user = await applicationContext .getPersistenceGateway() diff --git a/shared/src/business/useCases/opinionAdvancedSearchInteractor.test.ts b/shared/src/business/useCases/opinionAdvancedSearchInteractor.test.ts index 3747d981682..07d84a9d42d 100644 --- a/shared/src/business/useCases/opinionAdvancedSearchInteractor.test.ts +++ b/shared/src/business/useCases/opinionAdvancedSearchInteractor.test.ts @@ -4,13 +4,14 @@ import { OPINION_EVENT_CODES_WITH_BENCH_OPINION, } from '../../business/entities/EntityConstants'; import { applicationContext } from '../test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { opinionAdvancedSearchInteractor } from './opinionAdvancedSearchInteractor'; -import { petitionerUser, petitionsClerkUser } from '@shared/test/mockUsers'; describe('opinionAdvancedSearchInteractor', () => { beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - applicationContext .getPersistenceGateway() .advancedDocumentSearch.mockResolvedValue({ @@ -38,19 +39,25 @@ describe('opinionAdvancedSearchInteractor', () => { }); it('should return an unauthorized error when the currentUser is a petitioner', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - await expect( - opinionAdvancedSearchInteractor(applicationContext, {} as any), + opinionAdvancedSearchInteractor( + applicationContext, + {} as any, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should return results when the current user has permission to perform advanced opinion searches (petitionsclerk)', async () => { - const result = await opinionAdvancedSearchInteractor(applicationContext, { - dateRange: DATE_RANGE_SEARCH_OPTIONS.CUSTOM_DATES, - keyword: 'candy', - startDate: '01/01/2001', - } as any); + const result = await opinionAdvancedSearchInteractor( + applicationContext, + { + dateRange: DATE_RANGE_SEARCH_OPTIONS.CUSTOM_DATES, + keyword: 'candy', + startDate: '01/01/2001', + } as any, + mockPetitionsClerkUser, + ); expect(result).toMatchObject([ { @@ -88,10 +95,14 @@ describe('opinionAdvancedSearchInteractor', () => { .getPersistenceGateway() .advancedDocumentSearch.mockResolvedValue({ results: maxPlusOneResults }); - const results = await opinionAdvancedSearchInteractor(applicationContext, { - keyword: 'keyword', - petitionerName: 'test person', - } as any); + const results = await opinionAdvancedSearchInteractor( + applicationContext, + { + keyword: 'keyword', + petitionerName: 'test person', + } as any, + mockPetitionsClerkUser, + ); expect(results.length).toBe(MAX_SEARCH_RESULTS); }); @@ -99,12 +110,16 @@ describe('opinionAdvancedSearchInteractor', () => { it('should search for documents that are of type opinions', async () => { const keyword = 'keyword'; - await opinionAdvancedSearchInteractor(applicationContext, { - dateRange: DATE_RANGE_SEARCH_OPTIONS.CUSTOM_DATES, - keyword, - opinionTypes: OPINION_EVENT_CODES_WITH_BENCH_OPINION, - startDate: '01/01/2001', - } as any); + await opinionAdvancedSearchInteractor( + applicationContext, + { + dateRange: DATE_RANGE_SEARCH_OPTIONS.CUSTOM_DATES, + keyword, + opinionTypes: OPINION_EVENT_CODES_WITH_BENCH_OPINION, + startDate: '01/01/2001', + } as any, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().advancedDocumentSearch.mock @@ -115,7 +130,11 @@ describe('opinionAdvancedSearchInteractor', () => { }); it('should search for opinions with isOpinionSearch set to true', async () => { - await opinionAdvancedSearchInteractor(applicationContext, {} as any); + await opinionAdvancedSearchInteractor( + applicationContext, + {} as any, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().advancedDocumentSearch.mock diff --git a/shared/src/business/useCases/opinionAdvancedSearchInteractor.ts b/shared/src/business/useCases/opinionAdvancedSearchInteractor.ts index 21ef2c5c9ec..fae27ff6a06 100644 --- a/shared/src/business/useCases/opinionAdvancedSearchInteractor.ts +++ b/shared/src/business/useCases/opinionAdvancedSearchInteractor.ts @@ -7,6 +7,7 @@ import { isAuthorized, } from '../../authorization/authorizationClientService'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { omit } from 'lodash'; export const opinionAdvancedSearchInteractor = async ( @@ -30,9 +31,8 @@ export const opinionAdvancedSearchInteractor = async ( opinionTypes: string[]; startDate: string; }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.ADVANCED_SEARCH)) { throw new UnauthorizedError('Unauthorized'); } @@ -69,7 +69,5 @@ export const opinionAdvancedSearchInteractor = async ( const filteredResults = results.slice(0, MAX_SEARCH_RESULTS); - return InternalDocumentSearchResult.validateRawCollection(filteredResults, { - applicationContext, - }); + return InternalDocumentSearchResult.validateRawCollection(filteredResults); }; diff --git a/shared/src/business/useCases/orderAdvancedSearchInteractor.test.ts b/shared/src/business/useCases/orderAdvancedSearchInteractor.test.ts index 5b6d2279822..518bd3cceb3 100644 --- a/shared/src/business/useCases/orderAdvancedSearchInteractor.test.ts +++ b/shared/src/business/useCases/orderAdvancedSearchInteractor.test.ts @@ -5,13 +5,14 @@ import { ROLES, } from '../entities/EntityConstants'; import { applicationContext } from '../test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { orderAdvancedSearchInteractor } from './orderAdvancedSearchInteractor'; -import { petitionerUser, petitionsClerkUser } from '@shared/test/mockUsers'; describe('orderAdvancedSearchInteractor', () => { beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - applicationContext .getPersistenceGateway() .advancedDocumentSearch.mockResolvedValue({ @@ -43,19 +44,25 @@ describe('orderAdvancedSearchInteractor', () => { }); it('returns an unauthorized error on petitioner user role', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - await expect( - orderAdvancedSearchInteractor(applicationContext, {} as any), + orderAdvancedSearchInteractor( + applicationContext, + {} as any, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('logs raw search information and results size', async () => { - const result = await orderAdvancedSearchInteractor(applicationContext, { - dateRange: DATE_RANGE_SEARCH_OPTIONS.CUSTOM_DATES, - keyword: 'candy', - startDate: '01/01/2001', - } as any); + const result = await orderAdvancedSearchInteractor( + applicationContext, + { + dateRange: DATE_RANGE_SEARCH_OPTIONS.CUSTOM_DATES, + keyword: 'candy', + startDate: '01/01/2001', + } as any, + mockPetitionsClerkUser, + ); expect(applicationContext.logger.info.mock.calls[0][1]).toMatchObject({ from: 0, @@ -79,10 +86,14 @@ describe('orderAdvancedSearchInteractor', () => { .getPersistenceGateway() .advancedDocumentSearch.mockResolvedValue({ results: maxPlusOneResults }); - const results = await orderAdvancedSearchInteractor(applicationContext, { - keyword: 'keyword', - petitionerName: 'test person', - } as any); + const results = await orderAdvancedSearchInteractor( + applicationContext, + { + keyword: 'keyword', + petitionerName: 'test person', + } as any, + mockPetitionsClerkUser, + ); expect(results.length).toBe(MAX_SEARCH_RESULTS); }); @@ -90,11 +101,15 @@ describe('orderAdvancedSearchInteractor', () => { it('searches for documents that are of type orders', async () => { const keyword = 'keyword'; - await orderAdvancedSearchInteractor(applicationContext, { - dateRange: DATE_RANGE_SEARCH_OPTIONS.CUSTOM_DATES, - keyword, - startDate: '01/01/2001', - } as any); + await orderAdvancedSearchInteractor( + applicationContext, + { + dateRange: DATE_RANGE_SEARCH_OPTIONS.CUSTOM_DATES, + keyword, + startDate: '01/01/2001', + } as any, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().advancedDocumentSearch.mock diff --git a/shared/src/business/useCases/orderAdvancedSearchInteractor.ts b/shared/src/business/useCases/orderAdvancedSearchInteractor.ts index 3d2320f9b37..d0c5e14b738 100644 --- a/shared/src/business/useCases/orderAdvancedSearchInteractor.ts +++ b/shared/src/business/useCases/orderAdvancedSearchInteractor.ts @@ -10,6 +10,7 @@ import { isAuthorized, } from '../../authorization/authorizationClientService'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { User } from '../entities/User'; import { caseSearchFilter } from '../utilities/caseFilter'; import { omit } from 'lodash'; @@ -35,9 +36,8 @@ export const orderAdvancedSearchInteractor = async ( keyword: string; startDate: string; }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.ADVANCED_SEARCH)) { throw new UnauthorizedError('Unauthorized'); } @@ -80,7 +80,5 @@ export const orderAdvancedSearchInteractor = async ( MAX_SEARCH_RESULTS, ); - return InternalDocumentSearchResult.validateRawCollection(filteredResults, { - applicationContext, - }); + return InternalDocumentSearchResult.validateRawCollection(filteredResults); }; diff --git a/shared/src/business/useCases/prioritizeCaseInteractor.test.ts b/shared/src/business/useCases/prioritizeCaseInteractor.test.ts index 89fa74e6c71..1e68e7e4453 100644 --- a/shared/src/business/useCases/prioritizeCaseInteractor.test.ts +++ b/shared/src/business/useCases/prioritizeCaseInteractor.test.ts @@ -1,8 +1,12 @@ -import { CASE_STATUS_TYPES, ROLES } from '../entities/EntityConstants'; +import { CASE_STATUS_TYPES } from '../entities/EntityConstants'; import { MOCK_CASE } from '../../test/mockCase'; import { MOCK_LOCK } from '../../test/mockLock'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { prioritizeCaseInteractor } from './prioritizeCaseInteractor'; describe('prioritizeCaseInteractor', () => { @@ -16,10 +20,6 @@ describe('prioritizeCaseInteractor', () => { beforeEach(() => { mockLock = undefined; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }); }); it('should update the case with the highPriority flag set as true and attach a reason', async () => { @@ -32,10 +32,14 @@ describe('prioritizeCaseInteractor', () => { }), ); - const result = await prioritizeCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - reason: 'just because', - }); + const result = await prioritizeCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + reason: 'just because', + }, + mockPetitionsClerkUser, + ); expect(result).toMatchObject({ highPriority: true, @@ -61,10 +65,14 @@ describe('prioritizeCaseInteractor', () => { }), ); - await prioritizeCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - reason: 'just because', - }); + await prioritizeCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + reason: 'just because', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -73,12 +81,14 @@ describe('prioritizeCaseInteractor', () => { }); it('should throw an unauthorized error if the user has no access to prioritize cases', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - prioritizeCaseInteractor(applicationContext, { - docketNumber: '123-20', - } as any), + prioritizeCaseInteractor( + applicationContext, + { + docketNumber: '123-20', + } as any, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -93,10 +103,14 @@ describe('prioritizeCaseInteractor', () => { ); await expect( - prioritizeCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - reason: 'just because', - }), + prioritizeCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + reason: 'just because', + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('Cannot set a calendared case as high priority'); }); @@ -113,10 +127,14 @@ describe('prioritizeCaseInteractor', () => { ); await expect( - prioritizeCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - reason: 'just because', - }), + prioritizeCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + reason: 'just because', + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('Cannot set a blocked case as high priority'); }); @@ -130,10 +148,15 @@ describe('prioritizeCaseInteractor', () => { }), ); - await prioritizeCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - reason: 'just because', - }); + await prioritizeCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + reason: 'just because', + }, + mockPetitionsClerkUser, + ); + expect( applicationContext.getPersistenceGateway() .createCaseTrialSortMappingRecords, @@ -153,10 +176,14 @@ describe('prioritizeCaseInteractor', () => { }), ); - await prioritizeCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - reason: 'just because', - }); + await prioritizeCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + reason: 'just because', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -168,10 +195,14 @@ describe('prioritizeCaseInteractor', () => { mockLock = MOCK_LOCK; await expect( - prioritizeCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - reason: 'just because', - }), + prioritizeCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + reason: 'just because', + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -180,10 +211,14 @@ describe('prioritizeCaseInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await prioritizeCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - reason: 'just because', - }); + await prioritizeCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + reason: 'just because', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/shared/src/business/useCases/prioritizeCaseInteractor.ts b/shared/src/business/useCases/prioritizeCaseInteractor.ts index 3dbdcd04c00..4c960a25e5a 100644 --- a/shared/src/business/useCases/prioritizeCaseInteractor.ts +++ b/shared/src/business/useCases/prioritizeCaseInteractor.ts @@ -3,7 +3,9 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -15,11 +17,10 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; * @returns {object} the case data */ export const prioritizeCase = async ( - applicationContext, - { docketNumber, reason }, -) => { - const authorizedUser = applicationContext.getCurrentUser(); - + applicationContext: ServerApplicationContext, + { docketNumber, reason }: { docketNumber: string; reason: string }, + authorizedUser: UnknownAuthUser, +): Promise => { if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.PRIORITIZE_CASE)) { throw new UnauthorizedError('Unauthorized'); } @@ -31,7 +32,7 @@ export const prioritizeCase = async ( docketNumber, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); if (caseEntity.isCalendared()) { throw new Error('Cannot set a calendared case as high priority'); @@ -56,10 +57,11 @@ export const prioritizeCase = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const prioritizeCaseInteractor = withLocking( diff --git a/shared/src/business/useCases/removeCasePendingItemInteractor.test.ts b/shared/src/business/useCases/removeCasePendingItemInteractor.test.ts index eafd746739a..aa8b3f08a6e 100644 --- a/shared/src/business/useCases/removeCasePendingItemInteractor.test.ts +++ b/shared/src/business/useCases/removeCasePendingItemInteractor.test.ts @@ -1,17 +1,15 @@ -import { - AUTOMATIC_BLOCKED_REASONS, - PARTY_TYPES, - ROLES, -} from '../entities/EntityConstants'; +import { AUTOMATIC_BLOCKED_REASONS } from '../entities/EntityConstants'; import { MOCK_CASE } from '../../test/mockCase'; import { MOCK_LOCK } from '../../test/mockLock'; import { ServiceUnavailableError } from '@web-api/errors/errors'; -import { User } from '../entities/User'; import { applicationContext } from '../test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { removeCasePendingItemInteractor } from './removeCasePendingItemInteractor'; describe('removeCasePendingItemInteractor', () => { - let user; let mockLock; beforeAll(() => { @@ -22,13 +20,7 @@ describe('removeCasePendingItemInteractor', () => { beforeEach(() => { mockLock = undefined; - user = new User({ - name: 'Petitions Clerk', - role: ROLES.petitionsClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - applicationContext.getCurrentUser.mockImplementation(() => user); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE); @@ -38,25 +30,27 @@ describe('removeCasePendingItemInteractor', () => { }); it('should throw an unauthorized error if user is unauthorized for updating a case', async () => { - user = new User({ - name: PARTY_TYPES.petitioner, - role: ROLES.petitioner, - userId: '2c464719-646c-463e-9826-16443500ed88', - }); - await expect( - removeCasePendingItemInteractor(applicationContext, { - docketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', // docketEntries[3] from MOCK_CASE - docketNumber: MOCK_CASE.docketNumber, - }), + removeCasePendingItemInteractor( + applicationContext, + { + docketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', // docketEntries[3] from MOCK_CASE + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized for update case'); }); it('should call updateCase with the pending document set to pending=false', async () => { - await removeCasePendingItemInteractor(applicationContext, { - docketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', // docketEntries[3] from MOCK_CASE - docketNumber: MOCK_CASE.docketNumber, - }); + await removeCasePendingItemInteractor( + applicationContext, + { + docketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', // docketEntries[3] from MOCK_CASE + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -69,10 +63,14 @@ describe('removeCasePendingItemInteractor', () => { .getPersistenceGateway() .getCaseDeadlinesByDocketNumber.mockReturnValue([]); - await removeCasePendingItemInteractor(applicationContext, { - docketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', // docketEntries[3] from MOCK_CASE - docketNumber: MOCK_CASE.docketNumber, - }); + await removeCasePendingItemInteractor( + applicationContext, + { + docketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', // docketEntries[3] from MOCK_CASE + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -91,10 +89,14 @@ describe('removeCasePendingItemInteractor', () => { { deadline: 'something' }, ]); - await removeCasePendingItemInteractor(applicationContext, { - docketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', // docketEntries[3] from MOCK_CASE - docketNumber: MOCK_CASE.docketNumber, - }); + await removeCasePendingItemInteractor( + applicationContext, + { + docketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', // docketEntries[3] from MOCK_CASE + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -113,10 +115,14 @@ describe('removeCasePendingItemInteractor', () => { mockLock = MOCK_LOCK; await expect( - removeCasePendingItemInteractor(applicationContext, { - docketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', // docketEntries[3] from MOCK_CASE - docketNumber: MOCK_CASE.docketNumber, - }), + removeCasePendingItemInteractor( + applicationContext, + { + docketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', // docketEntries[3] from MOCK_CASE + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -125,10 +131,14 @@ describe('removeCasePendingItemInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await removeCasePendingItemInteractor(applicationContext, { - docketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', // docketEntries[3] from MOCK_CASE - docketNumber: MOCK_CASE.docketNumber, - }); + await removeCasePendingItemInteractor( + applicationContext, + { + docketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', // docketEntries[3] from MOCK_CASE + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/shared/src/business/useCases/removeCasePendingItemInteractor.ts b/shared/src/business/useCases/removeCasePendingItemInteractor.ts index 716e3104b28..cf7d700416e 100644 --- a/shared/src/business/useCases/removeCasePendingItemInteractor.ts +++ b/shared/src/business/useCases/removeCasePendingItemInteractor.ts @@ -3,7 +3,9 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -15,12 +17,11 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; * @returns {object} the updated case data */ export const removeCasePendingItem = async ( - applicationContext, + applicationContext: ServerApplicationContext, { docketEntryId, docketNumber }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.UPDATE_CASE)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.UPDATE_CASE)) { throw new UnauthorizedError('Unauthorized for update case'); } @@ -34,7 +35,9 @@ export const removeCasePendingItem = async ( } }); - let updatedCaseEntity = new Case(caseToUpdate, { applicationContext }); + let updatedCaseEntity = new Case(caseToUpdate, { + authorizedUser, + }); updatedCaseEntity = await applicationContext .getUseCaseHelpers() @@ -45,6 +48,7 @@ export const removeCasePendingItem = async ( await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: updatedCaseEntity, }); diff --git a/shared/src/business/useCases/removePdfFromDocketEntryInteractor.test.ts b/shared/src/business/useCases/removePdfFromDocketEntryInteractor.test.ts index 36874e5d575..4eefa864eb7 100644 --- a/shared/src/business/useCases/removePdfFromDocketEntryInteractor.test.ts +++ b/shared/src/business/useCases/removePdfFromDocketEntryInteractor.test.ts @@ -10,6 +10,10 @@ import { MOCK_LOCK } from '../../test/mockLock'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { removePdfFromDocketEntryInteractor } from './removePdfFromDocketEntryInteractor'; describe('removePdfFromDocketEntryInteractor', () => { @@ -61,19 +65,15 @@ describe('removePdfFromDocketEntryInteractor', () => { userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', }; - const docketClerkUser = { - name: 'docket clerk', - role: ROLES.docketClerk, - userId: '54cddcd9-d012-4874-b74f-73732c95d42b', - }; let mockLock; beforeAll(() => { applicationContext.getPersistenceGateway().deleteDocumentFile = jest.fn(); - applicationContext - .getPersistenceGateway() - .getUserById.mockReturnValue(docketClerkUser); + applicationContext.getPersistenceGateway().getUserById.mockReturnValue({ + ...mockDocketClerkUser, + name: 'docket clerk', + }); applicationContext .getPersistenceGateway() @@ -88,29 +88,31 @@ describe('removePdfFromDocketEntryInteractor', () => { }); beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); mockLock = undefined; }); it('should throw an error if the user is unauthorized to update a case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: 'nope', - userId: 'nope', - }); - await expect( - removePdfFromDocketEntryInteractor(applicationContext, { - docketEntryId: '7805d1ab-18d0-43ec-bafb-654e83405416', - docketNumber: MOCK_CASE.docketNumber, - }), + removePdfFromDocketEntryInteractor( + applicationContext, + { + docketEntryId: '7805d1ab-18d0-43ec-bafb-654e83405416', + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized for update case'); }); it('should fetch the case by the provided docketNumber', async () => { - await removePdfFromDocketEntryInteractor(applicationContext, { - docketEntryId: '7805d1ab-18d0-43ec-bafb-654e83405416', - docketNumber: MOCK_CASE.docketNumber, - }); + await removePdfFromDocketEntryInteractor( + applicationContext, + { + docketEntryId: '7805d1ab-18d0-43ec-bafb-654e83405416', + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -118,10 +120,14 @@ describe('removePdfFromDocketEntryInteractor', () => { }); it('should delete the pdf from s3 and update the case if the docketEntry has a file attached', async () => { - await removePdfFromDocketEntryInteractor(applicationContext, { - docketEntryId: '7805d1ab-18d0-43ec-bafb-654e83405416', // entry with isFileAttached: true - docketNumber: MOCK_CASE.docketNumber, - }); + await removePdfFromDocketEntryInteractor( + applicationContext, + { + docketEntryId: '7805d1ab-18d0-43ec-bafb-654e83405416', // entry with isFileAttached: true + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().deleteDocumentFile, @@ -133,10 +139,14 @@ describe('removePdfFromDocketEntryInteractor', () => { }); it('should set the docketEntry isFileAttached flag to false', async () => { - await removePdfFromDocketEntryInteractor(applicationContext, { - docketEntryId: '7805d1ab-18d0-43ec-bafb-654e83405416', - docketNumber: MOCK_CASE.docketNumber, - }); + await removePdfFromDocketEntryInteractor( + applicationContext, + { + docketEntryId: '7805d1ab-18d0-43ec-bafb-654e83405416', + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); const docketEntry = applicationContext .getPersistenceGateway() @@ -148,10 +158,14 @@ describe('removePdfFromDocketEntryInteractor', () => { }); it('does not modify the docketEntry or case if the isFileAttachedFlag is false', async () => { - await removePdfFromDocketEntryInteractor(applicationContext, { - docketEntryId: '1905d1ab-18d0-43ec-bafb-654e83405491', // entry with isFileAttached: false - docketNumber: MOCK_CASE.docketNumber, - }); + await removePdfFromDocketEntryInteractor( + applicationContext, + { + docketEntryId: '1905d1ab-18d0-43ec-bafb-654e83405491', // entry with isFileAttached: false + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().deleteDocumentFile, @@ -163,10 +177,14 @@ describe('removePdfFromDocketEntryInteractor', () => { }); it('does not modify the docketEntry or case if the docketEntry can not be found on the case', async () => { - await removePdfFromDocketEntryInteractor(applicationContext, { - docketEntryId: 'nope', - docketNumber: MOCK_CASE.docketNumber, - }); + await removePdfFromDocketEntryInteractor( + applicationContext, + { + docketEntryId: 'nope', + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().deleteDocumentFile, @@ -180,10 +198,14 @@ describe('removePdfFromDocketEntryInteractor', () => { mockLock = MOCK_LOCK; await expect( - removePdfFromDocketEntryInteractor(applicationContext, { - docketEntryId: '7805d1ab-18d0-43ec-bafb-654e83405416', - docketNumber: MOCK_CASE.docketNumber, - }), + removePdfFromDocketEntryInteractor( + applicationContext, + { + docketEntryId: '7805d1ab-18d0-43ec-bafb-654e83405416', + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -192,10 +214,14 @@ describe('removePdfFromDocketEntryInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await removePdfFromDocketEntryInteractor(applicationContext, { - docketEntryId: '7805d1ab-18d0-43ec-bafb-654e83405416', - docketNumber: MOCK_CASE.docketNumber, - }); + await removePdfFromDocketEntryInteractor( + applicationContext, + { + docketEntryId: '7805d1ab-18d0-43ec-bafb-654e83405416', + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/shared/src/business/useCases/removePdfFromDocketEntryInteractor.ts b/shared/src/business/useCases/removePdfFromDocketEntryInteractor.ts index 0d72fce748e..93b6c0b2005 100644 --- a/shared/src/business/useCases/removePdfFromDocketEntryInteractor.ts +++ b/shared/src/business/useCases/removePdfFromDocketEntryInteractor.ts @@ -3,7 +3,9 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -15,11 +17,10 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; * @returns {object} the updated case data */ export const removePdfFromDocketEntry = async ( - applicationContext, + applicationContext: ServerApplicationContext, { docketEntryId, docketNumber }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.UPDATE_CASE)) { throw new UnauthorizedError('Unauthorized for update case'); } @@ -32,7 +33,7 @@ export const removePdfFromDocketEntry = async ( }); const caseEntity = new Case(caseRecord, { - applicationContext, + authorizedUser, }); const docketEntry = caseEntity.getDocketEntryById({ docketEntryId }); @@ -50,10 +51,11 @@ export const removePdfFromDocketEntry = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); - return new Case(updatedCase, { applicationContext }).toRawObject(); + return new Case(updatedCase, { authorizedUser }).toRawObject(); } }; diff --git a/shared/src/business/useCases/removePetitionerAndUpdateCaptionInteractor.test.ts b/shared/src/business/useCases/removePetitionerAndUpdateCaptionInteractor.test.ts index ce7dc2f280a..babbc84bea9 100644 --- a/shared/src/business/useCases/removePetitionerAndUpdateCaptionInteractor.test.ts +++ b/shared/src/business/useCases/removePetitionerAndUpdateCaptionInteractor.test.ts @@ -14,13 +14,19 @@ import { } from '@web-api/errors/errors'; import { applicationContext } from '../test/createTestApplicationContext'; import { getPetitionerById } from '../entities/cases/Case'; +import { + mockDocketClerkUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { removePetitionerAndUpdateCaptionInteractor } from './removePetitionerAndUpdateCaptionInteractor'; describe('removePetitionerAndUpdateCaptionInteractor', () => { let mockCase; let petitionerToRemove; - const SECONDARY_CONTACT_ID = '56387318-0092-49a3-8cc1-921b0432bd16'; let mockLock; + + const SECONDARY_CONTACT_ID = '56387318-0092-49a3-8cc1-921b0432bd16'; + beforeAll(() => { applicationContext .getPersistenceGateway() @@ -47,10 +53,6 @@ describe('removePetitionerAndUpdateCaptionInteractor', () => { petitioners: [MOCK_CASE.petitioners[0], petitionerToRemove], status: CASE_STATUS_TYPES.generalDocket, }; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketClerk', - }); applicationContext .getPersistenceGateway() @@ -62,16 +64,16 @@ describe('removePetitionerAndUpdateCaptionInteractor', () => { }); it('should throw an unauthorized error when the current user does not have permission to edit petitioners', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'petitionsClerk', - }); await expect( - removePetitionerAndUpdateCaptionInteractor(applicationContext, { - caseCaption: MOCK_CASE.caseCaption, - contactId: '7805d1ab-18d0-43ec-bafb-654e83405416', - docketNumber: MOCK_CASE.docketNumber, - }), + removePetitionerAndUpdateCaptionInteractor( + applicationContext, + { + caseCaption: MOCK_CASE.caseCaption, + contactId: '7805d1ab-18d0-43ec-bafb-654e83405416', + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -82,11 +84,15 @@ describe('removePetitionerAndUpdateCaptionInteractor', () => { }; await expect( - removePetitionerAndUpdateCaptionInteractor(applicationContext, { - caseCaption: MOCK_CASE.caseCaption, - contactId: SECONDARY_CONTACT_ID, - docketNumber: MOCK_CASE.docketNumber, - }), + removePetitionerAndUpdateCaptionInteractor( + applicationContext, + { + caseCaption: MOCK_CASE.caseCaption, + contactId: SECONDARY_CONTACT_ID, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow( `Case with docketNumber ${mockCase.docketNumber} has not been served`, ); @@ -100,22 +106,30 @@ describe('removePetitionerAndUpdateCaptionInteractor', () => { }; await expect( - removePetitionerAndUpdateCaptionInteractor(applicationContext, { - caseCaption: MOCK_CASE.caseCaption, - contactId: MOCK_CASE.petitioners[0].contactId, - docketNumber: MOCK_CASE.docketNumber, - }), + removePetitionerAndUpdateCaptionInteractor( + applicationContext, + { + caseCaption: MOCK_CASE.caseCaption, + contactId: MOCK_CASE.petitioners[0].contactId, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow( `Cannot remove petitioner ${MOCK_CASE.petitioners[0].contactId} from case with docketNumber ${MOCK_CASE.docketNumber}`, ); }); it('should remove the specified petitioner form the case petitioners array', async () => { - await removePetitionerAndUpdateCaptionInteractor(applicationContext, { - caseCaption: MOCK_CASE.caseCaption, - contactId: petitionerToRemove.contactId, - docketNumber: MOCK_CASE.docketNumber, - }); + await removePetitionerAndUpdateCaptionInteractor( + applicationContext, + { + caseCaption: MOCK_CASE.caseCaption, + contactId: petitionerToRemove.contactId, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); const { caseToUpdate } = applicationContext.getUseCaseHelpers().updateCaseAndAssociations.mock @@ -143,11 +157,15 @@ describe('removePetitionerAndUpdateCaptionInteractor', () => { privatePractitioners: [mockPrivatePractitioner], }; - await removePetitionerAndUpdateCaptionInteractor(applicationContext, { - caseCaption: mockCase.caseCaption, - contactId: petitionerToRemove.contactId, - docketNumber: mockCase.docketNumber, - }); + await removePetitionerAndUpdateCaptionInteractor( + applicationContext, + { + caseCaption: mockCase.caseCaption, + contactId: petitionerToRemove.contactId, + docketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); const { caseToUpdate } = applicationContext.getUseCaseHelpers().updateCaseAndAssociations.mock @@ -168,11 +186,15 @@ describe('removePetitionerAndUpdateCaptionInteractor', () => { it('should update the case caption', async () => { const mockUpdatedCaption = 'An updated caption'; - await removePetitionerAndUpdateCaptionInteractor(applicationContext, { - caseCaption: mockUpdatedCaption, - contactId: MOCK_CASE.petitioners[0].contactId, - docketNumber: mockCase.docketNumber, - }); + await removePetitionerAndUpdateCaptionInteractor( + applicationContext, + { + caseCaption: mockUpdatedCaption, + contactId: MOCK_CASE.petitioners[0].contactId, + docketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -210,11 +232,15 @@ describe('removePetitionerAndUpdateCaptionInteractor', () => { }, ]; - await removePetitionerAndUpdateCaptionInteractor(applicationContext, { - caseCaption: 'hello world', - contactId: MOCK_CASE.petitioners[0].contactId, - docketNumber: mockCase.docketNumber, - }); + await removePetitionerAndUpdateCaptionInteractor( + applicationContext, + { + caseCaption: 'hello world', + contactId: MOCK_CASE.petitioners[0].contactId, + docketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -225,11 +251,15 @@ describe('removePetitionerAndUpdateCaptionInteractor', () => { mockLock = MOCK_LOCK; await expect( - removePetitionerAndUpdateCaptionInteractor(applicationContext, { - caseCaption: 'some caption', - contactId: MOCK_CASE.petitioners[0].contactId, - docketNumber: mockCase.docketNumber, - }), + removePetitionerAndUpdateCaptionInteractor( + applicationContext, + { + caseCaption: 'some caption', + contactId: MOCK_CASE.petitioners[0].contactId, + docketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -238,11 +268,15 @@ describe('removePetitionerAndUpdateCaptionInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await removePetitionerAndUpdateCaptionInteractor(applicationContext, { - caseCaption: 'some caption', - contactId: MOCK_CASE.petitioners[0].contactId, - docketNumber: mockCase.docketNumber, - }); + await removePetitionerAndUpdateCaptionInteractor( + applicationContext, + { + caseCaption: 'some caption', + contactId: MOCK_CASE.petitioners[0].contactId, + docketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/shared/src/business/useCases/removePetitionerAndUpdateCaptionInteractor.ts b/shared/src/business/useCases/removePetitionerAndUpdateCaptionInteractor.ts index f07b47d90c2..3de8032c5e3 100644 --- a/shared/src/business/useCases/removePetitionerAndUpdateCaptionInteractor.ts +++ b/shared/src/business/useCases/removePetitionerAndUpdateCaptionInteractor.ts @@ -4,7 +4,9 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -17,17 +19,17 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; * @returns {object} the case data */ export const removePetitionerAndUpdateCaption = async ( - applicationContext: IApplicationContext, + applicationContext: ServerApplicationContext, { caseCaption, contactId, docketNumber, }: { caseCaption: string; contactId: string; docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { const petitionerContactId = contactId; - const user = applicationContext.getCurrentUser(); - if (!isAuthorized(user, ROLE_PERMISSIONS.REMOVE_PETITIONER)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.REMOVE_PETITIONER)) { throw new UnauthorizedError( 'Unauthorized for removing petitioner from case', ); @@ -37,7 +39,7 @@ export const removePetitionerAndUpdateCaption = async ( .getPersistenceGateway() .getCaseByDocketNumber({ applicationContext, docketNumber }); - let caseEntity = new Case(caseToUpdate, { applicationContext }); + let caseEntity = new Case(caseToUpdate, { authorizedUser }); if (caseToUpdate.status === CASE_STATUS_TYPES.new) { throw new Error( @@ -55,6 +57,7 @@ export const removePetitionerAndUpdateCaption = async ( .getUseCaseHelpers() .removeCounselFromRemovedPetitioner({ applicationContext, + authorizedUser, caseEntity, petitionerContactId, }); @@ -73,10 +76,11 @@ export const removePetitionerAndUpdateCaption = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const removePetitionerAndUpdateCaptionInteractor = withLocking( diff --git a/shared/src/business/useCases/removeSignatureFromDocumentInteractor.test.ts b/shared/src/business/useCases/removeSignatureFromDocumentInteractor.test.ts index 9f8d7bd6ebe..6613063f340 100644 --- a/shared/src/business/useCases/removeSignatureFromDocumentInteractor.test.ts +++ b/shared/src/business/useCases/removeSignatureFromDocumentInteractor.test.ts @@ -1,6 +1,7 @@ import { MOCK_CASE } from '../../test/mockCase'; import { ROLES } from '../entities/EntityConstants'; import { applicationContext } from '../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { removeSignatureFromDocumentInteractor } from './removeSignatureFromDocumentInteractor'; describe('removeSignatureFromDocumentInteractor', () => { @@ -35,11 +36,30 @@ describe('removeSignatureFromDocumentInteractor', () => { .getCaseByDocketNumber.mockReturnValue(mockCase); }); + it('should throw an error when user is undefined', async () => { + await expect( + removeSignatureFromDocumentInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + docketNumber: mockCase.docketNumber, + }, + undefined, + ), + ).rejects.toThrow( + 'User attempting to remove signature from document is not an auth user', + ); + }); + it('should retrieve the original, unsigned document from S3', async () => { - await removeSignatureFromDocumentInteractor(applicationContext, { - docketEntryId: mockDocketEntryId, - docketNumber: mockCase.docketNumber, - }); + await removeSignatureFromDocumentInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + docketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getDocument.mock.calls[0][0], @@ -50,10 +70,14 @@ describe('removeSignatureFromDocumentInteractor', () => { }); it('should overwrite the current, signed document in S3 with the original, unsigned document', async () => { - await removeSignatureFromDocumentInteractor(applicationContext, { - docketEntryId: mockDocketEntryId, - docketNumber: mockCase.docketNumber, - }); + await removeSignatureFromDocumentInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + docketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveDocumentFromLambda.mock @@ -70,6 +94,7 @@ describe('removeSignatureFromDocumentInteractor', () => { docketEntryId: mockDocketEntryId, docketNumber: mockCase.docketNumber, }, + mockDocketClerkUser, ); const unsignedDocument = updatedCase.docketEntries.find( diff --git a/shared/src/business/useCases/removeSignatureFromDocumentInteractor.ts b/shared/src/business/useCases/removeSignatureFromDocumentInteractor.ts index 6c07f630e34..b714c8d9f3c 100644 --- a/shared/src/business/useCases/removeSignatureFromDocumentInteractor.ts +++ b/shared/src/business/useCases/removeSignatureFromDocumentInteractor.ts @@ -1,4 +1,9 @@ import { Case } from '../entities/cases/Case'; +import { ServerApplicationContext } from '@web-api/applicationContext'; +import { + UnknownAuthUser, + isAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; /** * Removes a signature from a document @@ -10,16 +15,24 @@ import { Case } from '../entities/cases/Case'; * @returns {object} the updated case */ export const removeSignatureFromDocumentInteractor = async ( - applicationContext, + applicationContext: ServerApplicationContext, { docketEntryId, docketNumber }, + authorizedUser: UnknownAuthUser, ) => { + if (!isAuthUser(authorizedUser)) { + throw new Error( + 'User attempting to remove signature from document is not an auth user', + ); + } const caseRecord = await applicationContext .getPersistenceGateway() .getCaseByDocketNumber({ applicationContext, docketNumber, }); - const caseEntity = new Case(caseRecord, { applicationContext }); + const caseEntity = new Case(caseRecord, { + authorizedUser, + }); const docketEntryToUnsign = caseEntity.getDocketEntryById({ docketEntryId, }); @@ -42,6 +55,7 @@ export const removeSignatureFromDocumentInteractor = async ( await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); diff --git a/shared/src/business/useCases/saveCaseDetailInternalEditInteractor.test.ts b/shared/src/business/useCases/saveCaseDetailInternalEditInteractor.test.ts index 4473c6dafb1..9bb5c9add82 100644 --- a/shared/src/business/useCases/saveCaseDetailInternalEditInteractor.test.ts +++ b/shared/src/business/useCases/saveCaseDetailInternalEditInteractor.test.ts @@ -11,6 +11,10 @@ import { MOCK_PRACTITIONER, petitionsClerkUser } from '../../test/mockUsers'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../test/createTestApplicationContext'; import { getContactPrimary, getContactSecondary } from '../entities/cases/Case'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { omit } from 'lodash'; import { saveCaseDetailInternalEditInteractor } from './saveCaseDetailInternalEditInteractor'; @@ -55,10 +59,10 @@ describe('updateCase', () => { beforeEach(() => { mockLock = undefined; - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - applicationContext - .getPersistenceGateway() - .getUserById.mockReturnValue(petitionsClerkUser); + applicationContext.getPersistenceGateway().getUserById.mockReturnValue({ + ...petitionsClerkUser, + userId: mockPetitionsClerkUser.userId, + }); applicationContext .getPersistenceGateway() @@ -67,32 +71,39 @@ describe('updateCase', () => { it('should throw an error if caseToUpdate is not passed in', async () => { await expect( - saveCaseDetailInternalEditInteractor(applicationContext, { - docketNumber: mockCase.docketNumber, - } as any), + saveCaseDetailInternalEditInteractor( + applicationContext, + { + docketNumber: mockCase.docketNumber, + } as any, + mockPetitionsClerkUser, + ), ).rejects.toThrow('cannot process'); }); it('should throw an error if the user is unauthorized to update a case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: 'nope', - userId: 'nope', - }); - await expect( - saveCaseDetailInternalEditInteractor(applicationContext, { - caseToUpdate: mockCase, - docketNumber: mockCase.docketNumber, - }), + saveCaseDetailInternalEditInteractor( + applicationContext, + { + caseToUpdate: mockCase, + docketNumber: mockCase.docketNumber, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized for update case'); }); it('should throw an error if the caseToUpdate passed in is an invalid case', async () => { await expect( - saveCaseDetailInternalEditInteractor(applicationContext, { - caseToUpdate: omit({ ...mockCase }, 'caseCaption'), - docketNumber: mockCase.docketNumber, - }), + saveCaseDetailInternalEditInteractor( + applicationContext, + { + caseToUpdate: omit({ ...mockCase }, 'caseCaption'), + docketNumber: mockCase.docketNumber, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('The Case entity was invalid'); }); @@ -113,6 +124,7 @@ describe('updateCase', () => { }, docketNumber: mockCase.docketNumber, }, + mockPetitionsClerkUser, ); expect(result.petitioners[1].address1).toEqual(mockAddress); @@ -121,14 +133,18 @@ describe('updateCase', () => { it("should move the initialize case work item into the current user's in-progress box if the case is not paper", async () => { const caseToUpdate = Object.assign(mockCase); - await saveCaseDetailInternalEditInteractor(applicationContext, { - caseToUpdate: { - ...caseToUpdate, - caseCaption: 'Iola Snow & Linda Singleton, Petitioners', - contactPrimary: getContactPrimary(mockCase), + await saveCaseDetailInternalEditInteractor( + applicationContext, + { + caseToUpdate: { + ...caseToUpdate, + caseCaption: 'Iola Snow & Linda Singleton, Petitioners', + contactPrimary: getContactPrimary(mockCase), + }, + docketNumber: caseToUpdate.docketNumber, }, - docketNumber: caseToUpdate.docketNumber, - }); + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveWorkItem, @@ -137,7 +153,7 @@ describe('updateCase', () => { applicationContext.getPersistenceGateway().saveWorkItem.mock.calls[0][0] .workItem, ).toMatchObject({ - assigneeId: petitionsClerkUser.userId, + assigneeId: mockPetitionsClerkUser.userId, assigneeName: petitionsClerkUser.name, caseIsInProgress: true, }); @@ -148,14 +164,18 @@ describe('updateCase', () => { caseToUpdate.isPaper = true; caseToUpdate.mailingDate = 'yesterday'; - await saveCaseDetailInternalEditInteractor(applicationContext, { - caseToUpdate: { - ...caseToUpdate, - caseCaption: 'Iola Snow & Linda Singleton, Petitioners', - contactPrimary: getContactPrimary(mockCase), + await saveCaseDetailInternalEditInteractor( + applicationContext, + { + caseToUpdate: { + ...caseToUpdate, + caseCaption: 'Iola Snow & Linda Singleton, Petitioners', + contactPrimary: getContactPrimary(mockCase), + }, + docketNumber: caseToUpdate.docketNumber, }, - docketNumber: caseToUpdate.docketNumber, - }); + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveWorkItem, @@ -166,14 +186,18 @@ describe('updateCase', () => { const caseToUpdate = Object.assign(mockCase); await expect( - saveCaseDetailInternalEditInteractor(applicationContext, { - caseToUpdate: { - ...caseToUpdate, - contactPrimary: null, - contactSecondary: {}, + saveCaseDetailInternalEditInteractor( + applicationContext, + { + caseToUpdate: { + ...caseToUpdate, + contactPrimary: null, + contactSecondary: {}, + }, + docketNumber: caseToUpdate.docketNumber, }, - docketNumber: caseToUpdate.docketNumber, - }), + mockPetitionsClerkUser, + ), ).rejects.toThrow('The Case entity was invalid'); }); @@ -196,16 +220,20 @@ describe('updateCase', () => { isPaper: true, }); - await saveCaseDetailInternalEditInteractor(applicationContext, { - caseToUpdate: { - ...mockCase, - contactPrimary: getContactPrimary(mockCase), - docketEntries: [...mockCase.docketEntries, mockRQT], - isPaper: true, - mailingDate: 'yesterday', + await saveCaseDetailInternalEditInteractor( + applicationContext, + { + caseToUpdate: { + ...mockCase, + contactPrimary: getContactPrimary(mockCase), + docketEntries: [...mockCase.docketEntries, mockRQT], + isPaper: true, + mailingDate: 'yesterday', + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockPetitionsClerkUser, + ); expect( applicationContext.getUseCaseHelpers().updateInitialFilingDocuments, @@ -232,6 +260,7 @@ describe('updateCase', () => { }, docketNumber: caseToUpdate.docketNumber, }, + mockPetitionsClerkUser, ); expect(result.orderDesignatingPlaceOfTrial).toBeTruthy(); @@ -256,6 +285,7 @@ describe('updateCase', () => { }, docketNumber: mockCase.docketNumber, }, + mockPetitionsClerkUser, ); expect(result.petitioners[0].contactId).toEqual( @@ -278,6 +308,7 @@ describe('updateCase', () => { }, docketNumber: mockCase.docketNumber, }, + mockPetitionsClerkUser, ); expect(result.petitioners.length).toEqual(1); @@ -318,6 +349,7 @@ describe('updateCase', () => { }, docketNumber: mockCase.docketNumber, }, + mockPetitionsClerkUser, ); expect(result.privatePractitioners).toBeDefined(); @@ -349,6 +381,7 @@ describe('updateCase', () => { }, docketNumber: mockCase.docketNumber, }, + mockPetitionsClerkUser, ); expect(result.receivedAt).toEqual(currentCaseDetail.receivedAt); @@ -357,16 +390,20 @@ describe('updateCase', () => { mockLock = MOCK_LOCK; await expect( - saveCaseDetailInternalEditInteractor(applicationContext, { - caseToUpdate: { - ...mockCase, - contactPrimary: { - ...getContactPrimary(mockCase), + saveCaseDetailInternalEditInteractor( + applicationContext, + { + caseToUpdate: { + ...mockCase, + contactPrimary: { + ...getContactPrimary(mockCase), + }, + petitioners: undefined, }, - petitioners: undefined, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }), + mockPetitionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -375,16 +412,20 @@ describe('updateCase', () => { }); it('should acquire and remove the lock on the case', async () => { - await saveCaseDetailInternalEditInteractor(applicationContext, { - caseToUpdate: { - ...mockCase, - contactPrimary: { - ...getContactPrimary(mockCase), + await saveCaseDetailInternalEditInteractor( + applicationContext, + { + caseToUpdate: { + ...mockCase, + contactPrimary: { + ...getContactPrimary(mockCase), + }, + petitioners: undefined, }, - petitioners: undefined, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/shared/src/business/useCases/saveCaseDetailInternalEditInteractor.ts b/shared/src/business/useCases/saveCaseDetailInternalEditInteractor.ts index cf1d8d4b197..432593943d4 100644 --- a/shared/src/business/useCases/saveCaseDetailInternalEditInteractor.ts +++ b/shared/src/business/useCases/saveCaseDetailInternalEditInteractor.ts @@ -4,10 +4,12 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError, UnprocessableEntityError, } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { WorkItem } from '../entities/WorkItem'; import { isEmpty } from 'lodash'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; @@ -21,11 +23,10 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; * @returns {object} the updated case data */ export const saveCaseDetailInternalEdit = async ( - applicationContext, + applicationContext: ServerApplicationContext, { caseToUpdate, docketNumber }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.UPDATE_CASE)) { throw new UnauthorizedError('Unauthorized for update case'); } @@ -45,7 +46,7 @@ export const saveCaseDetailInternalEdit = async ( docketNumber, }); - const originalCaseEntity = new Case(caseRecord, { applicationContext }); + const originalCaseEntity = new Case(caseRecord, { authorizedUser }); const editableFields = { caseCaption: caseToUpdate.caseCaption, @@ -89,7 +90,7 @@ export const saveCaseDetailInternalEdit = async ( }; const caseEntityWithFormEdits = new Case(caseWithFormEdits, { - applicationContext, + authorizedUser, }); if (!isEmpty(caseToUpdate.contactPrimary)) { @@ -119,13 +120,14 @@ export const saveCaseDetailInternalEdit = async ( .getUseCaseHelpers() .removeCounselFromRemovedPetitioner({ applicationContext, + authorizedUser, caseEntity: caseEntityWithFormEdits, petitionerContactId: originalSecondaryContactId, }); } const caseEntity = new Case(caseEntityWithFormEdits, { - applicationContext, + authorizedUser, }); if (caseEntity.isPaper) { @@ -149,8 +151,7 @@ export const saveCaseDetailInternalEdit = async ( trialDate: caseEntity.trialDate, trialLocation: caseEntity.trialLocation, }, - { applicationContext }, - caseEntity, + { caseEntity }, ); await applicationContext.getPersistenceGateway().saveWorkItem({ @@ -163,10 +164,11 @@ export const saveCaseDetailInternalEdit = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); - return new Case(updatedCase, { applicationContext }).toRawObject(); + return new Case(updatedCase, { authorizedUser }).toRawObject(); }; export const saveCaseDetailInternalEditInteractor = withLocking( diff --git a/shared/src/business/useCases/saveSignedDocumentInteractor.test.ts b/shared/src/business/useCases/saveSignedDocumentInteractor.test.ts index aa531cde628..4fa80f4f4e5 100644 --- a/shared/src/business/useCases/saveSignedDocumentInteractor.test.ts +++ b/shared/src/business/useCases/saveSignedDocumentInteractor.test.ts @@ -8,6 +8,7 @@ import { MOCK_CASE } from '../../test/mockCase'; import { MOCK_DOCUMENTS } from '../../test/mockDocketEntry'; import { applicationContext } from '../test/createTestApplicationContext'; import { getMessageThreadByParentId as getMessageThreadByParentIdMock } from '@web-api/persistence/postgres/messages/getMessageThreadByParentId'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { saveSignedDocumentInteractor } from './saveSignedDocumentInteractor'; import { updateMessage as updateMessageMock } from '@web-api/persistence/postgres/messages/updateMessage'; @@ -57,13 +58,34 @@ describe('saveSignedDocumentInteractor', () => { ]); }); + it('should throw an error when an unknown user attempts to save a signed document', async () => { + await expect( + saveSignedDocumentInteractor( + applicationContext, + { + docketNumber: mockCase.docketNumber, + nameForSigning: mockSigningName, + originalDocketEntryId: mockOriginalDocketEntryId, + signedDocketEntryId: mockSignedDocketEntryId, + } as any, + undefined, + ), + ).rejects.toThrow( + 'User attempting to save signed document is not an auth user', + ); + }); + it('should save the original, unsigned document to S3 with a new id', async () => { - await saveSignedDocumentInteractor(applicationContext, { - docketNumber: mockCase.docketNumber, - nameForSigning: mockSigningName, - originalDocketEntryId: mockOriginalDocketEntryId, - signedDocketEntryId: mockSignedDocketEntryId, - } as any); + await saveSignedDocumentInteractor( + applicationContext, + { + docketNumber: mockCase.docketNumber, + nameForSigning: mockSigningName, + originalDocketEntryId: mockOriginalDocketEntryId, + signedDocketEntryId: mockSignedDocketEntryId, + } as any, + mockDocketClerkUser, + ); expect(applicationContext.getUniqueId).toHaveBeenCalled(); expect( @@ -75,12 +97,16 @@ describe('saveSignedDocumentInteractor', () => { }); it('should replace the original, unsigned document with the signed document', async () => { - await saveSignedDocumentInteractor(applicationContext, { - docketNumber: mockCase.docketNumber, - nameForSigning: mockSigningName, - originalDocketEntryId: mockOriginalDocketEntryId, - signedDocketEntryId: mockSignedDocketEntryId, - } as any); + await saveSignedDocumentInteractor( + applicationContext, + { + docketNumber: mockCase.docketNumber, + nameForSigning: mockSigningName, + originalDocketEntryId: mockOriginalDocketEntryId, + signedDocketEntryId: mockSignedDocketEntryId, + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveDocumentFromLambda.mock @@ -99,6 +125,7 @@ describe('saveSignedDocumentInteractor', () => { originalDocketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', signedDocketEntryId: mockSignedDocketEntryId, } as any, + mockDocketClerkUser, ); expect(caseEntity.docketEntries.length).toEqual(MOCK_DOCUMENTS.length + 1); @@ -133,6 +160,7 @@ describe('saveSignedDocumentInteractor', () => { originalDocketEntryId: mockOriginalDocketEntryId, signedDocketEntryId: mockSignedDocketEntryId, } as any, + mockDocketClerkUser, ); const signedDocument = caseEntity.docketEntries.find( @@ -152,6 +180,7 @@ describe('saveSignedDocumentInteractor', () => { originalDocketEntryId: mockOriginalDocketEntryId, signedDocketEntryId: mockSignedDocketEntryId, } as any, + mockDocketClerkUser, ); const signedDocument = caseEntity.docketEntries.find( @@ -164,13 +193,17 @@ describe('saveSignedDocumentInteractor', () => { it('should add the signed document to the latest message in the message thread if parentMessageId is included and the original document is a Proposed Stipulated Decision', async () => { const updateMessage = updateMessageMock as jest.Mock; - await saveSignedDocumentInteractor(applicationContext, { - docketNumber: mockCase.docketNumber, - nameForSigning: mockSigningName, - originalDocketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', - parentMessageId: mockParentMessageId, - signedDocketEntryId: mockSignedDocketEntryId, - }); + await saveSignedDocumentInteractor( + applicationContext, + { + docketNumber: mockCase.docketNumber, + nameForSigning: mockSigningName, + originalDocketEntryId: 'def81f4d-1e47-423a-8caf-6d2fdc3d3859', + parentMessageId: mockParentMessageId, + signedDocketEntryId: mockSignedDocketEntryId, + }, + mockDocketClerkUser, + ); expect(updateMessage).toHaveBeenCalled(); expect(updateMessage.mock.calls[0][0].message).toMatchObject({ diff --git a/shared/src/business/useCases/saveSignedDocumentInteractor.ts b/shared/src/business/useCases/saveSignedDocumentInteractor.ts index 0348062ef9e..8770e798674 100644 --- a/shared/src/business/useCases/saveSignedDocumentInteractor.ts +++ b/shared/src/business/useCases/saveSignedDocumentInteractor.ts @@ -5,6 +5,11 @@ import { } from '../entities/EntityConstants'; import { DocketEntry } from '../entities/DocketEntry'; import { Message } from '../entities/Message'; +import { ServerApplicationContext } from '@web-api/applicationContext'; +import { + UnknownAuthUser, + isAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; import { getMessageThreadByParentId } from '@web-api/persistence/postgres/messages/getMessageThreadByParentId'; import { orderBy } from 'lodash'; import { updateMessage } from '@web-api/persistence/postgres/messages/updateMessage'; @@ -64,7 +69,7 @@ const replaceOriginalWithSignedDocument = async ({ * @returns {object} an object containing the updated caseEntity and the signed document ID */ export const saveSignedDocumentInteractor = async ( - applicationContext, + applicationContext: ServerApplicationContext, { docketNumber, nameForSigning, @@ -72,15 +77,20 @@ export const saveSignedDocumentInteractor = async ( parentMessageId, signedDocketEntryId, }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); + if (!isAuthUser(authorizedUser)) { + throw new Error( + 'User attempting to save signed document is not an auth user', + ); + } const caseRecord = await applicationContext .getPersistenceGateway() .getCaseByDocketNumber({ applicationContext, docketNumber, }); - const caseEntity = new Case(caseRecord, { applicationContext }); + const caseEntity = new Case(caseRecord, { authorizedUser }); const originalDocketEntryEntity = caseEntity.docketEntries.find( docketEntry => docketEntry.docketEntryId === originalDocketEntryId, ); @@ -105,12 +115,12 @@ export const saveSignedDocumentInteractor = async ( isPaper: false, processingStatus: DOCUMENT_PROCESSING_STATUS_OPTIONS.COMPLETE, }, - { applicationContext }, + { authorizedUser }, ); - signedDocketEntryEntity.setFiledBy(user); + signedDocketEntryEntity.setFiledBy(authorizedUser); - signedDocketEntryEntity.setSigned(user.userId, nameForSigning); + signedDocketEntryEntity.setSigned(authorizedUser?.userId, nameForSigning); caseEntity.addDocketEntry(signedDocketEntryEntity); @@ -151,18 +161,19 @@ export const saveSignedDocumentInteractor = async ( isFileAttached: true, processingStatus: DOCUMENT_PROCESSING_STATUS_OPTIONS.COMPLETE, }, - { applicationContext }, + { authorizedUser }, ); - signedDocketEntryEntity.setFiledBy(user); + signedDocketEntryEntity.setFiledBy(authorizedUser); - signedDocketEntryEntity.setSigned(user.userId, nameForSigning); + signedDocketEntryEntity.setSigned(authorizedUser?.userId, nameForSigning); caseEntity.updateDocketEntry(signedDocketEntryEntity); } await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); diff --git a/shared/src/business/useCases/sealCaseContactAddressInteractor.test.ts b/shared/src/business/useCases/sealCaseContactAddressInteractor.test.ts index c00f55758f2..138186f94c5 100644 --- a/shared/src/business/useCases/sealCaseContactAddressInteractor.test.ts +++ b/shared/src/business/useCases/sealCaseContactAddressInteractor.test.ts @@ -3,10 +3,13 @@ import { MOCK_CASE_WITH_SECONDARY_OTHERS, } from '../../test/mockCase'; import { MOCK_LOCK } from '../../test/mockLock'; -import { ROLES } from '../entities/EntityConstants'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../test/createTestApplicationContext'; import { getOtherFilers } from '../entities/cases/Case'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { sealCaseContactAddressInteractor } from './sealCaseContactAddressInteractor'; describe('sealCaseContactAddressInteractor', () => { @@ -22,31 +25,31 @@ describe('sealCaseContactAddressInteractor', () => { applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE); - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketClerk', - }); }); it('should throw an error if the user is unauthorized to seal a case contact address', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: 'docketClerk', - }); await expect( - sealCaseContactAddressInteractor(applicationContext, { - contactId: '10aa100f-0330-442b-8423-b01690c76e3f', - docketNumber: MOCK_CASE.docketNumber, - }), + sealCaseContactAddressInteractor( + applicationContext, + { + contactId: '10aa100f-0330-442b-8423-b01690c76e3f', + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized for sealing case contact addresses'); }); it('should throw an error if the contactId is not found on the case', async () => { await expect( - sealCaseContactAddressInteractor(applicationContext, { - contactId: '23-skidoo', - docketNumber: MOCK_CASE.docketNumber, - }), + sealCaseContactAddressInteractor( + applicationContext, + { + contactId: '23-skidoo', + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Cannot seal contact'); }); @@ -61,24 +64,27 @@ describe('sealCaseContactAddressInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(caseWithoutOthers); - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketClerk', - }); - await expect( - sealCaseContactAddressInteractor(applicationContext, { - contactId: '23-skidoo', - docketNumber: MOCK_CASE.docketNumber, - }), + sealCaseContactAddressInteractor( + applicationContext, + { + contactId: '23-skidoo', + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Cannot seal contact'); }); it('should call updateCase with `isSealedAddress` on contactPrimary and return the updated case', async () => { - const result = await sealCaseContactAddressInteractor(applicationContext, { - contactId: '7805d1ab-18d0-43ec-bafb-654e83405416', // contactPrimary - docketNumber: MOCK_CASE.docketNumber, - }); + const result = await sealCaseContactAddressInteractor( + applicationContext, + { + contactId: '7805d1ab-18d0-43ec-bafb-654e83405416', // contactPrimary + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -91,15 +97,14 @@ describe('sealCaseContactAddressInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE_WITH_SECONDARY_OTHERS); - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketClerk', - }); - - const result = await sealCaseContactAddressInteractor(applicationContext, { - contactId: '2226050f-a423-47bb-943b-a5661fe08a6b', // contactSecondary - docketNumber: MOCK_CASE.docketNumber, - }); + const result = await sealCaseContactAddressInteractor( + applicationContext, + { + contactId: '2226050f-a423-47bb-943b-a5661fe08a6b', // contactSecondary + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -112,15 +117,14 @@ describe('sealCaseContactAddressInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE_WITH_SECONDARY_OTHERS); - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketClerk', - }); - - const result = await sealCaseContactAddressInteractor(applicationContext, { - contactId: '4446050f-a423-47bb-943b-a5661fe08a6b', // otherFilers[1] - docketNumber: MOCK_CASE.docketNumber, - }); + const result = await sealCaseContactAddressInteractor( + applicationContext, + { + contactId: '4446050f-a423-47bb-943b-a5661fe08a6b', // otherFilers[1] + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -132,10 +136,14 @@ describe('sealCaseContactAddressInteractor', () => { mockLock = MOCK_LOCK; await expect( - sealCaseContactAddressInteractor(applicationContext, { - contactId: '7805d1ab-18d0-43ec-bafb-654e83405416', // contactPrimary - docketNumber: MOCK_CASE.docketNumber, - }), + sealCaseContactAddressInteractor( + applicationContext, + { + contactId: '7805d1ab-18d0-43ec-bafb-654e83405416', // contactPrimary + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -144,10 +152,14 @@ describe('sealCaseContactAddressInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await sealCaseContactAddressInteractor(applicationContext, { - contactId: '7805d1ab-18d0-43ec-bafb-654e83405416', // contactPrimary - docketNumber: MOCK_CASE.docketNumber, - }); + await sealCaseContactAddressInteractor( + applicationContext, + { + contactId: '7805d1ab-18d0-43ec-bafb-654e83405416', // contactPrimary + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/shared/src/business/useCases/sealCaseContactAddressInteractor.ts b/shared/src/business/useCases/sealCaseContactAddressInteractor.ts index 32107234165..4e65c13a64c 100644 --- a/shared/src/business/useCases/sealCaseContactAddressInteractor.ts +++ b/shared/src/business/useCases/sealCaseContactAddressInteractor.ts @@ -3,10 +3,12 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError, UnprocessableEntityError, } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -18,11 +20,10 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; * @returns {object} the updated case data */ export const sealCaseContactAddress = async ( - applicationContext, + applicationContext: ServerApplicationContext, { contactId, docketNumber }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.UPDATE_CASE)) { throw new UnauthorizedError( 'Unauthorized for sealing case contact addresses', @@ -37,7 +38,7 @@ export const sealCaseContactAddress = async ( }); const caseEntity = new Case(caseRecord, { - applicationContext, + authorizedUser, }); const contactToSeal = caseEntity.getPetitionerById(contactId); @@ -53,10 +54,11 @@ export const sealCaseContactAddress = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); - return new Case(updatedCase, { applicationContext }).toRawObject(); + return new Case(updatedCase, { authorizedUser }).toRawObject(); }; export const sealCaseContactAddressInteractor = withLocking( diff --git a/shared/src/business/useCases/sealCaseInteractor.test.ts b/shared/src/business/useCases/sealCaseInteractor.test.ts index 9e88ab6eec2..0c358e926a3 100644 --- a/shared/src/business/useCases/sealCaseInteractor.test.ts +++ b/shared/src/business/useCases/sealCaseInteractor.test.ts @@ -1,12 +1,16 @@ import { MOCK_CASE } from '../../test/mockCase'; import { MOCK_LOCK } from '../../test/mockLock'; -import { ROLES } from '../entities/EntityConstants'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; import { sealCaseInteractor } from './sealCaseInteractor'; describe('sealCaseInteractor', () => { let mockLock; + beforeAll(() => { applicationContext .getPersistenceGateway() @@ -18,35 +22,39 @@ describe('sealCaseInteractor', () => { applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE); - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketClerk', - }); }); it('should throw an error if the user is unauthorized to seal a case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.privatePractitioner, - userId: 'docketClerk', - }); await expect( - sealCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }), + sealCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockPrivatePractitionerUser, + ), ).rejects.toThrow('Unauthorized for sealing cases'); }); it('should call updateCase with the sealedDate set on the case and return the updated case', async () => { - const result = await sealCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }); + const result = await sealCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect(result.sealedDate).toBeTruthy(); }); it('should send a notification that a case has been sealed', async () => { - await sealCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }); + await sealCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getDispatchers().sendNotificationOfSealing, ).toHaveBeenCalled(); @@ -56,9 +64,13 @@ describe('sealCaseInteractor', () => { mockLock = MOCK_LOCK; await expect( - sealCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }), + sealCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -67,9 +79,13 @@ describe('sealCaseInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await sealCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }); + await sealCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/shared/src/business/useCases/sealCaseInteractor.ts b/shared/src/business/useCases/sealCaseInteractor.ts index 9a77ecc20a3..350c2ea3154 100644 --- a/shared/src/business/useCases/sealCaseInteractor.ts +++ b/shared/src/business/useCases/sealCaseInteractor.ts @@ -3,7 +3,9 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -14,12 +16,11 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; * @returns {Promise} the updated case data */ export const sealCase = async ( - applicationContext: IApplicationContext, + applicationContext: ServerApplicationContext, { docketNumber }: { docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.SEAL_CASE)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.SEAL_CASE)) { throw new UnauthorizedError('Unauthorized for sealing cases'); } @@ -27,7 +28,7 @@ export const sealCase = async ( .getPersistenceGateway() .getCaseByDocketNumber({ applicationContext, docketNumber }); - const newCase = new Case(oldCase, { applicationContext }); + const newCase = new Case(oldCase, { authorizedUser }); newCase.setAsSealed(); @@ -35,6 +36,7 @@ export const sealCase = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: newCase, }); @@ -42,7 +44,7 @@ export const sealCase = async ( .getDispatchers() .sendNotificationOfSealing(applicationContext, { docketNumber }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const sealCaseInteractor = withLocking( diff --git a/shared/src/business/useCases/startCase/validateStartCaseWizardInteractor.ts b/shared/src/business/useCases/startCase/validateStartCaseWizardInteractor.ts index 0abb5ec5608..307cca41d50 100644 --- a/shared/src/business/useCases/startCase/validateStartCaseWizardInteractor.ts +++ b/shared/src/business/useCases/startCase/validateStartCaseWizardInteractor.ts @@ -12,8 +12,8 @@ export const validateStartCaseWizardInteractor = ( applicationContext: IApplicationContext, { petition }: { petition: any }, ) => { - const errors = new ElectronicPetitionInformationFactory(petition, { - applicationContext, - }).getFormattedValidationErrors(); + const errors = new ElectronicPetitionInformationFactory( + petition, + ).getFormattedValidationErrors(); return errors || null; }; diff --git a/shared/src/business/useCases/trialSessions/canSetTrialSessionAsCalendaredInteractor.test.ts b/shared/src/business/useCases/trialSessions/canSetTrialSessionAsCalendaredInteractor.test.ts index 879269c36bf..07954476820 100644 --- a/shared/src/business/useCases/trialSessions/canSetTrialSessionAsCalendaredInteractor.test.ts +++ b/shared/src/business/useCases/trialSessions/canSetTrialSessionAsCalendaredInteractor.test.ts @@ -1,10 +1,7 @@ -import { - ROLES, - TRIAL_SESSION_PROCEEDING_TYPES, -} from '../../entities/EntityConstants'; import { RawTrialSession } from '../../entities/trialSessions/TrialSession'; -import { applicationContext } from '../../test/createTestApplicationContext'; +import { TRIAL_SESSION_PROCEEDING_TYPES } from '../../entities/EntityConstants'; import { canSetTrialSessionAsCalendaredInteractor } from './canSetTrialSessionAsCalendaredInteractor'; +import { mockPetitionsClerkUser } from '@shared/test/mockAuthUsers'; const MOCK_TRIAL = { maxCases: 100, @@ -16,36 +13,18 @@ const MOCK_TRIAL = { trialLocation: 'Birmingham, Alabama', }; -let user; - describe('canSetTrialSessionAsCalendaredInteractor', () => { - beforeEach(() => { - applicationContext.getCurrentUser.mockImplementation(() => user); - }); - it('throws an error if a user is unauthorized', () => { - user = { - role: 'unauthorizedRole', - userId: 'unauthorizedUser', - }; - expect(() => - canSetTrialSessionAsCalendaredInteractor(applicationContext, { + canSetTrialSessionAsCalendaredInteractor(undefined, { trialSession: MOCK_TRIAL as RawTrialSession, }), ).toThrow('Unauthorized'); }); it('gets the result back from the interactor with empty fields and an in-person trial proceeding', () => { - user = { - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }; - - applicationContext.getUniqueId.mockReturnValue('easy-as-abc-123'); - const result = canSetTrialSessionAsCalendaredInteractor( - applicationContext, + mockPetitionsClerkUser, { trialSession: MOCK_TRIAL as RawTrialSession, }, @@ -66,15 +45,8 @@ describe('canSetTrialSessionAsCalendaredInteractor', () => { }); it('gets the result back from the interactor with no empty fields and a remote trial proceeding', () => { - user = { - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }; - - applicationContext.getUniqueId.mockReturnValue('easy-as-abc-123'); - const result = canSetTrialSessionAsCalendaredInteractor( - applicationContext, + mockPetitionsClerkUser, { trialSession: { ...MOCK_TRIAL, diff --git a/shared/src/business/useCases/trialSessions/canSetTrialSessionAsCalendaredInteractor.ts b/shared/src/business/useCases/trialSessions/canSetTrialSessionAsCalendaredInteractor.ts index 523b8265841..069d5f304fb 100644 --- a/shared/src/business/useCases/trialSessions/canSetTrialSessionAsCalendaredInteractor.ts +++ b/shared/src/business/useCases/trialSessions/canSetTrialSessionAsCalendaredInteractor.ts @@ -7,6 +7,7 @@ import { TrialSession, } from '../../entities/trialSessions/TrialSession'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * canSetTrialSessionAsCalendaredInteractor @@ -17,18 +18,14 @@ import { UnauthorizedError } from '@web-api/errors/errors'; * @returns {boolean} result of the entity method call depicting trial session calendaring eligibility */ export const canSetTrialSessionAsCalendaredInteractor = ( - applicationContext: IApplicationContext, + authorizedUser: UnknownAuthUser, { trialSession }: { trialSession: RawTrialSession }, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } - const trialSessionEntity = new TrialSession(trialSession, { - applicationContext, - }); + const trialSessionEntity = new TrialSession(trialSession); const canSetAsCalendared = trialSessionEntity.canSetAsCalendared(); const emptyFields = trialSessionEntity.getEmptyFields(); diff --git a/shared/src/business/useCases/trialSessions/validateTrialSessionInteractor.ts b/shared/src/business/useCases/trialSessions/validateTrialSessionInteractor.ts index 9ae70aa72d9..8325bff3305 100644 --- a/shared/src/business/useCases/trialSessions/validateTrialSessionInteractor.ts +++ b/shared/src/business/useCases/trialSessions/validateTrialSessionInteractor.ts @@ -15,8 +15,8 @@ export const validateTrialSessionInteractor = ( applicationContext: IApplicationContext, { trialSession }: { trialSession: RawNewTrialSession }, ) => { - const errors = new NewTrialSession(trialSession, { - applicationContext, - }).getFormattedValidationErrors(); + const errors = new NewTrialSession( + trialSession, + ).getFormattedValidationErrors(); return errors || null; }; diff --git a/shared/src/business/useCases/unblockCaseFromTrialInteractor.test.ts b/shared/src/business/useCases/unblockCaseFromTrialInteractor.test.ts index 71f8c7d5fe6..338b71e5fbb 100644 --- a/shared/src/business/useCases/unblockCaseFromTrialInteractor.test.ts +++ b/shared/src/business/useCases/unblockCaseFromTrialInteractor.test.ts @@ -1,8 +1,12 @@ -import { CASE_STATUS_TYPES, ROLES } from '../entities/EntityConstants'; +import { CASE_STATUS_TYPES } from '../entities/EntityConstants'; import { MOCK_CASE } from '../../test/mockCase'; import { MOCK_LOCK } from '../../test/mockLock'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { unblockCaseFromTrialInteractor } from './unblockCaseFromTrialInteractor'; describe('unblockCaseFromTrialInteractor', () => { @@ -15,10 +19,6 @@ describe('unblockCaseFromTrialInteractor', () => { beforeEach(() => { mockLock = undefined; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: '7ad8dcbc-5978-4a29-8c41-02422b66f410', - }); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue( @@ -29,9 +29,13 @@ describe('unblockCaseFromTrialInteractor', () => { ); }); it('should set the blocked flag to false and remove the blockedReason', async () => { - const result = await unblockCaseFromTrialInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }); + const result = await unblockCaseFromTrialInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ); expect(result).toMatchObject({ blocked: false, @@ -48,12 +52,14 @@ describe('unblockCaseFromTrialInteractor', () => { }); it('should throw an unauthorized error if the user has no access to unblock the case', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - unblockCaseFromTrialInteractor(applicationContext, { - docketNumber: '123-45', - }), + unblockCaseFromTrialInteractor( + applicationContext, + { + docketNumber: '123-45', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -68,9 +74,13 @@ describe('unblockCaseFromTrialInteractor', () => { }), ); - await unblockCaseFromTrialInteractor(applicationContext, { - docketNumber: '123-45', - }); + await unblockCaseFromTrialInteractor( + applicationContext, + { + docketNumber: '123-45', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -82,9 +92,13 @@ describe('unblockCaseFromTrialInteractor', () => { mockLock = MOCK_LOCK; await expect( - unblockCaseFromTrialInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }), + unblockCaseFromTrialInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -93,9 +107,13 @@ describe('unblockCaseFromTrialInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await unblockCaseFromTrialInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }); + await unblockCaseFromTrialInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/shared/src/business/useCases/unblockCaseFromTrialInteractor.ts b/shared/src/business/useCases/unblockCaseFromTrialInteractor.ts index 834f5a9aa02..6a0a088f0af 100644 --- a/shared/src/business/useCases/unblockCaseFromTrialInteractor.ts +++ b/shared/src/business/useCases/unblockCaseFromTrialInteractor.ts @@ -3,7 +3,9 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -14,11 +16,10 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; * @returns {object} the case data */ export const unblockCaseFromTrial = async ( - applicationContext: IApplicationContext, + applicationContext: ServerApplicationContext, { docketNumber }: { docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.BLOCK_CASE)) { throw new UnauthorizedError('Unauthorized'); } @@ -30,7 +31,7 @@ export const unblockCaseFromTrial = async ( docketNumber, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); caseEntity.unsetAsBlocked(); @@ -48,10 +49,11 @@ export const unblockCaseFromTrial = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const unblockCaseFromTrialInteractor = withLocking( diff --git a/shared/src/business/useCases/unprioritizeCaseInteractor.test.ts b/shared/src/business/useCases/unprioritizeCaseInteractor.test.ts index 38d86ae78b2..a3888f0370f 100644 --- a/shared/src/business/useCases/unprioritizeCaseInteractor.test.ts +++ b/shared/src/business/useCases/unprioritizeCaseInteractor.test.ts @@ -1,18 +1,20 @@ -import { CASE_STATUS_TYPES, ROLES } from '../entities/EntityConstants'; +import { CASE_STATUS_TYPES } from '../entities/EntityConstants'; import { MOCK_CASE } from '../../test/mockCase'; import { MOCK_LOCK } from '../../test/mockLock'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { unprioritizeCaseInteractor } from './unprioritizeCaseInteractor'; describe('unprioritizeCaseInteractor', () => { - let mockUser; let mockLock; beforeAll(() => { applicationContext .getPersistenceGateway() .getLock.mockImplementation(() => mockLock); - applicationContext.getCurrentUser.mockImplementation(() => mockUser); applicationContext .getUseCaseHelpers() @@ -23,19 +25,17 @@ describe('unprioritizeCaseInteractor', () => { beforeEach(() => { mockLock = undefined; - mockUser = { - role: ROLES.petitionsClerk, - userId: '7ad8dcbc-5978-4a29-8c41-02422b66f410', - }; }); it('should throw an unauthorized error if the user has no access to unprioritize the case', async () => { - mockUser = {}; - await expect( - unprioritizeCaseInteractor(applicationContext, { - docketNumber: '123-20', - }), + unprioritizeCaseInteractor( + applicationContext, + { + docketNumber: '123-20', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -44,9 +44,13 @@ describe('unprioritizeCaseInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(Promise.resolve(MOCK_CASE)); - await unprioritizeCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }); + await unprioritizeCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getUseCaseHelpers().updateCaseAutomaticBlock, @@ -65,9 +69,13 @@ describe('unprioritizeCaseInteractor', () => { }), ); - const result = await unprioritizeCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }); + const result = await unprioritizeCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ); expect(result).toMatchObject({ highPriority: false, @@ -99,9 +107,13 @@ describe('unprioritizeCaseInteractor', () => { }), ); - const result = await unprioritizeCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }); + const result = await unprioritizeCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ); expect(result).toMatchObject({ highPriority: false, @@ -125,9 +137,13 @@ describe('unprioritizeCaseInteractor', () => { mockLock = MOCK_LOCK; await expect( - unprioritizeCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }), + unprioritizeCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -138,9 +154,13 @@ describe('unprioritizeCaseInteractor', () => { it('should acquire and remove the lock on the case', async () => { mockLock = undefined; - await unprioritizeCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }); + await unprioritizeCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/shared/src/business/useCases/unprioritizeCaseInteractor.ts b/shared/src/business/useCases/unprioritizeCaseInteractor.ts index 2f80d601470..302cba9bd43 100644 --- a/shared/src/business/useCases/unprioritizeCaseInteractor.ts +++ b/shared/src/business/useCases/unprioritizeCaseInteractor.ts @@ -3,7 +3,9 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -14,11 +16,10 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; * @returns {object} the case data */ export const unprioritizeCase = async ( - applicationContext: IApplicationContext, + applicationContext: ServerApplicationContext, { docketNumber }: { docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.PRIORITIZE_CASE)) { throw new UnauthorizedError('Unauthorized'); } @@ -30,7 +31,7 @@ export const unprioritizeCase = async ( docketNumber, }); - let caseEntity = new Case(caseToUpdate, { applicationContext }); + let caseEntity = new Case(caseToUpdate, { authorizedUser }); caseEntity.unsetAsHighPriority(); @@ -59,10 +60,11 @@ export const unprioritizeCase = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const unprioritizeCaseInteractor = withLocking( diff --git a/shared/src/business/useCases/unsealCaseInteractor.test.ts b/shared/src/business/useCases/unsealCaseInteractor.test.ts index b540ed77390..1a1d94a4b1d 100644 --- a/shared/src/business/useCases/unsealCaseInteractor.test.ts +++ b/shared/src/business/useCases/unsealCaseInteractor.test.ts @@ -1,12 +1,16 @@ import { MOCK_CASE } from '../../test/mockCase'; import { MOCK_LOCK } from '../../test/mockLock'; -import { ROLES } from '../entities/EntityConstants'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { unsealCaseInteractor } from './unsealCaseInteractor'; describe('unsealCaseInteractor', () => { let mockLock; + beforeAll(() => { applicationContext .getPersistenceGateway() @@ -18,28 +22,29 @@ describe('unsealCaseInteractor', () => { applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE); - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketClerk', - }); }); it('should throw an error if the user is unauthorized to unseal a case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - }); - await expect( - unsealCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }), + unsealCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('Unauthorized for unsealing cases'); }); it('should call updateCase with isSealed set to false and return the updated case', async () => { - const result = await unsealCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }); + const result = await unsealCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); + expect(result.isSealed).toBe(false); expect(result.sealedDate).toBe(undefined); }); @@ -48,9 +53,13 @@ describe('unsealCaseInteractor', () => { mockLock = MOCK_LOCK; await expect( - unsealCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }), + unsealCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -59,9 +68,13 @@ describe('unsealCaseInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await unsealCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }); + await unsealCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/shared/src/business/useCases/unsealCaseInteractor.ts b/shared/src/business/useCases/unsealCaseInteractor.ts index c03d0971598..12b0878765f 100644 --- a/shared/src/business/useCases/unsealCaseInteractor.ts +++ b/shared/src/business/useCases/unsealCaseInteractor.ts @@ -3,7 +3,9 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -14,12 +16,11 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; * @returns {Promise} the updated case data */ export const unsealCase = async ( - applicationContext: IApplicationContext, + applicationContext: ServerApplicationContext, { docketNumber }: { docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.UNSEAL_CASE)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.UNSEAL_CASE)) { throw new UnauthorizedError('Unauthorized for unsealing cases'); } @@ -27,7 +28,7 @@ export const unsealCase = async ( .getPersistenceGateway() .getCaseByDocketNumber({ applicationContext, docketNumber }); - const newCase = new Case(oldCase, { applicationContext }); + const newCase = new Case(oldCase, { authorizedUser }); newCase.setAsUnsealed(); @@ -35,10 +36,11 @@ export const unsealCase = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: newCase, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const unsealCaseInteractor = withLocking( diff --git a/shared/src/business/useCases/updateCaseContextInteractor.test.ts b/shared/src/business/useCases/updateCaseContextInteractor.test.ts index 24df901d739..8418fbbe98f 100644 --- a/shared/src/business/useCases/updateCaseContextInteractor.test.ts +++ b/shared/src/business/useCases/updateCaseContextInteractor.test.ts @@ -1,22 +1,15 @@ import '@web-api/persistence/postgres/messages/mocks.jest'; -import { - CASE_STATUS_TYPES, - CHIEF_JUDGE, - ROLES, -} from '../entities/EntityConstants'; +import { CASE_STATUS_TYPES, CHIEF_JUDGE } from '../entities/EntityConstants'; import { MOCK_CASE, MOCK_CASE_WITH_TRIAL_SESSION } from '../../test/mockCase'; import { MOCK_TRIAL_REMOTE } from '../../test/mockTrial'; import { applicationContext } from '../test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { updateCaseContextInteractor } from './updateCaseContextInteractor'; describe('updateCaseContextInteractor', () => { - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: '7ad8dcbc-5978-4a29-8c41-02422b66f410', - }); - }); - beforeEach(() => { applicationContext .getPersistenceGateway() @@ -24,42 +17,48 @@ describe('updateCaseContextInteractor', () => { }); it('should throw an error if the user is unauthorized to update a case', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - updateCaseContextInteractor(applicationContext, { - caseStatus: CASE_STATUS_TYPES.cav, - docketNumber: MOCK_CASE.docketNumber, - }), + updateCaseContextInteractor( + applicationContext, + { + caseStatus: CASE_STATUS_TYPES.cav, + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized for update case'); }); it('should call updateCase with the updated case status and return the updated case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: '7ad8dcbc-5978-4a29-8c41-02422b66f410', - }); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(Promise.resolve(MOCK_CASE)); - const result = await updateCaseContextInteractor(applicationContext, { - caseStatus: CASE_STATUS_TYPES.cav, - docketNumber: MOCK_CASE.docketNumber, - }); + const result = await updateCaseContextInteractor( + applicationContext, + { + caseStatus: CASE_STATUS_TYPES.cav, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect(result.status).toEqual(CASE_STATUS_TYPES.cav); }); it('should not remove the case from trial if the old and new case status match', async () => { const rachaelId = 'dabbad00-18d0-43ec-bafb-654e83405416'; - const result = await updateCaseContextInteractor(applicationContext, { - caseStatus: CASE_STATUS_TYPES.new, - docketNumber: MOCK_CASE.docketNumber, - judgeData: { - associatedJudge: 'Judge Rachael', - associatedJudgeId: rachaelId, + const result = await updateCaseContextInteractor( + applicationContext, + { + caseStatus: CASE_STATUS_TYPES.new, + docketNumber: MOCK_CASE.docketNumber, + judgeData: { + associatedJudge: 'Judge Rachael', + associatedJudgeId: rachaelId, + }, }, - }); + mockDocketClerkUser, + ); expect(result.status).toEqual(CASE_STATUS_TYPES.new); expect( @@ -80,14 +79,18 @@ describe('updateCaseContextInteractor', () => { .getPersistenceGateway() .getTrialSessionById.mockReturnValue(MOCK_TRIAL_REMOTE); - const result = await updateCaseContextInteractor(applicationContext, { - caseStatus: CASE_STATUS_TYPES.cav, - docketNumber: MOCK_CASE_WITH_TRIAL_SESSION.docketNumber, - judgeData: { - associatedJudge: 'Judge Rachael', - associatedJudgeId: rachaelId, + const result = await updateCaseContextInteractor( + applicationContext, + { + caseStatus: CASE_STATUS_TYPES.cav, + docketNumber: MOCK_CASE_WITH_TRIAL_SESSION.docketNumber, + judgeData: { + associatedJudge: 'Judge Rachael', + associatedJudgeId: rachaelId, + }, }, - }); + mockDocketClerkUser, + ); expect(result.status).toEqual(CASE_STATUS_TYPES.cav); expect(result.associatedJudge).toEqual('Judge Rachael'); @@ -96,10 +99,14 @@ describe('updateCaseContextInteractor', () => { }); it('should call updateCase and remove the case from trial if the old case status was calendared and the new case status is General Docket - Not At Issue', async () => { - const result = await updateCaseContextInteractor(applicationContext, { - caseStatus: CASE_STATUS_TYPES.generalDocket, - docketNumber: MOCK_CASE.docketNumber, - }); + const result = await updateCaseContextInteractor( + applicationContext, + { + caseStatus: CASE_STATUS_TYPES.generalDocket, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect(result.status).toEqual(CASE_STATUS_TYPES.generalDocket); expect(result.associatedJudge).toEqual(CHIEF_JUDGE); @@ -115,10 +122,14 @@ describe('updateCaseContextInteractor', () => { status: CASE_STATUS_TYPES.generalDocketReadyForTrial, }); - const result = await updateCaseContextInteractor(applicationContext, { - caseStatus: CASE_STATUS_TYPES.generalDocket, - docketNumber: MOCK_CASE.docketNumber, - }); + const result = await updateCaseContextInteractor( + applicationContext, + { + caseStatus: CASE_STATUS_TYPES.generalDocket, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect(result.status).toEqual(CASE_STATUS_TYPES.generalDocket); expect( @@ -128,10 +139,14 @@ describe('updateCaseContextInteractor', () => { }); it('should call updateCase and createCaseTrialSortMappingRecords if the case status is being updated to Ready for Trial and is not assigned to a trial session', async () => { - const result = await updateCaseContextInteractor(applicationContext, { - caseStatus: CASE_STATUS_TYPES.generalDocketReadyForTrial, - docketNumber: MOCK_CASE.docketNumber, - }); + const result = await updateCaseContextInteractor( + applicationContext, + { + caseStatus: CASE_STATUS_TYPES.generalDocketReadyForTrial, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect(result.status).toEqual(CASE_STATUS_TYPES.generalDocketReadyForTrial); expect( @@ -157,10 +172,14 @@ describe('updateCaseContextInteractor', () => { return caseToUpdate; }); - const result = await updateCaseContextInteractor(applicationContext, { - caseStatus: CASE_STATUS_TYPES.generalDocketReadyForTrial, - docketNumber: MOCK_CASE.docketNumber, - }); + const result = await updateCaseContextInteractor( + applicationContext, + { + caseStatus: CASE_STATUS_TYPES.generalDocketReadyForTrial, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect(result.status).toEqual(CASE_STATUS_TYPES.generalDocketReadyForTrial); expect( @@ -173,10 +192,6 @@ describe('updateCaseContextInteractor', () => { }); it('should only update the associated judge without changing the status if only the associated judge is passed in', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: '7ad8dcbc-5978-4a29-8c41-02422b66f410', - }); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue({ @@ -186,27 +201,36 @@ describe('updateCaseContextInteractor', () => { status: CASE_STATUS_TYPES.submitted, }); - const result = await updateCaseContextInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - judgeData: { - associatedJudge: 'Judge Carluzzo', - associatedJudgeId: 'carluzzo-id', + const result = await updateCaseContextInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + judgeData: { + associatedJudge: 'Judge Carluzzo', + associatedJudgeId: 'carluzzo-id', + }, }, - }); + mockDocketClerkUser, + ); + expect(result.status).toEqual(CASE_STATUS_TYPES.submitted); expect(result.associatedJudge).toEqual('Judge Carluzzo'); expect(result.associatedJudgeId).toEqual('carluzzo-id'); }); it('should only update the associated judge without changing the status if the associated judge and the same case status are passed in', async () => { - const result = await updateCaseContextInteractor(applicationContext, { - caseStatus: CASE_STATUS_TYPES.submitted, - docketNumber: MOCK_CASE.docketNumber, - judgeData: { - associatedJudge: 'Judge Carluzzo', - associatedJudgeId: 'carluzzo-id', + const result = await updateCaseContextInteractor( + applicationContext, + { + caseStatus: CASE_STATUS_TYPES.submitted, + docketNumber: MOCK_CASE.docketNumber, + judgeData: { + associatedJudge: 'Judge Carluzzo', + associatedJudgeId: 'carluzzo-id', + }, }, - }); + mockDocketClerkUser, + ); expect(result.status).toEqual(CASE_STATUS_TYPES.submitted); expect(result.associatedJudge).toEqual('Judge Carluzzo'); @@ -214,10 +238,14 @@ describe('updateCaseContextInteractor', () => { }); it('should call updateCase with the updated case caption and return the updated case', async () => { - const result = await updateCaseContextInteractor(applicationContext, { - caseCaption: 'The new case caption', - docketNumber: MOCK_CASE.docketNumber, - }); + const result = await updateCaseContextInteractor( + applicationContext, + { + caseCaption: 'The new case caption', + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect(result.caseCaption).toEqual('The new case caption'); }); @@ -232,10 +260,14 @@ describe('updateCaseContextInteractor', () => { }), ); - await updateCaseContextInteractor(applicationContext, { - caseCaption: 'The new case caption', - docketNumber: MOCK_CASE.docketNumber, - }); + await updateCaseContextInteractor( + applicationContext, + { + caseCaption: 'The new case caption', + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway() diff --git a/shared/src/business/useCases/updateCaseContextInteractor.ts b/shared/src/business/useCases/updateCaseContextInteractor.ts index 479f435ec51..774adf4ee2b 100644 --- a/shared/src/business/useCases/updateCaseContextInteractor.ts +++ b/shared/src/business/useCases/updateCaseContextInteractor.ts @@ -5,12 +5,14 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialSession } from '../entities/trialSessions/TrialSession'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; export const updateCaseContext = async ( - applicationContext: IApplicationContext, + applicationContext: ServerApplicationContext, { caseCaption, caseStatus, @@ -25,10 +27,9 @@ export const updateCaseContext = async ( caseStatus?: string; docketNumber: string; }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.UPDATE_CASE_CONTEXT)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.UPDATE_CASE_CONTEXT)) { throw new UnauthorizedError('Unauthorized for update case'); } @@ -36,7 +37,7 @@ export const updateCaseContext = async ( .getPersistenceGateway() .getCaseByDocketNumber({ applicationContext, docketNumber }); - const newCase = new Case(oldCase, { applicationContext }); + const newCase = new Case(oldCase, { authorizedUser }); if (caseCaption) { newCase.setCaseCaption(caseCaption); @@ -53,7 +54,7 @@ export const updateCaseContext = async ( if (caseStatus && caseStatus !== oldCase.status) { const date = applicationContext.getUtilities().createISODateString(); newCase.setCaseStatus({ - changedBy: user.name, + changedBy: authorizedUser.name, date, updatedCaseStatus: caseStatus, }); @@ -74,9 +75,7 @@ export const updateCaseContext = async ( ); } - const trialSessionEntity = new TrialSession(trialSession, { - applicationContext, - }); + const trialSessionEntity = new TrialSession(trialSession); trialSessionEntity.removeCaseFromCalendar({ disposition, @@ -115,10 +114,13 @@ export const updateCaseContext = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: newCase, }); - return new Case(updatedCase, { applicationContext }).toRawObject(); + return new Case(updatedCase, { + authorizedUser, + }).toRawObject(); }; export const updateCaseContextInteractor = withLocking( diff --git a/shared/src/business/useCases/updateCaseDetailsInteractor.test.ts b/shared/src/business/useCases/updateCaseDetailsInteractor.test.ts index 8c95a4fa949..6b1b1c05213 100644 --- a/shared/src/business/useCases/updateCaseDetailsInteractor.test.ts +++ b/shared/src/business/useCases/updateCaseDetailsInteractor.test.ts @@ -13,7 +13,10 @@ import { } from '@web-api/errors/errors'; import { applicationContext } from '../test/createTestApplicationContext'; import { cloneDeep } from 'lodash'; -import { docketClerkUser } from '@shared/test/mockUsers'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { updateCaseDetailsInteractor } from './updateCaseDetailsInteractor'; describe('updateCaseDetailsInteractor', () => { @@ -34,71 +37,87 @@ describe('updateCaseDetailsInteractor', () => { status: CASE_STATUS_TYPES.generalDocketReadyForTrial, }); - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(mockCase); }); it('should throw an error when the user is unauthorized to update a case', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - updateCaseDetailsInteractor(applicationContext, { - caseDetails: {}, - docketNumber: mockCase.docketNumber, - }), + updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: {}, + docketNumber: mockCase.docketNumber, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); it('should throw a validation error when the updates to the case make it invalid', async () => { await expect( - updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - caseType: undefined, + updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + caseType: undefined, + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }), + mockDocketClerkUser, + ), ).rejects.toThrow('The Case entity was invalid'); }); it('should set irsNoticeDate when the updated case has a verified IRS notice', async () => { - const result = await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...mockCase, - hasVerifiedIrsNotice: true, - irsNoticeDate: '2020-08-28T01:49:58.117Z', + const result = await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...mockCase, + hasVerifiedIrsNotice: true, + irsNoticeDate: '2020-08-28T01:49:58.117Z', + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockDocketClerkUser, + ); expect(result.hasVerifiedIrsNotice).toBe(true); expect(result.irsNoticeDate).toBe('2020-08-28T01:49:58.117Z'); }); it('should set irsNoticeDate to undefined when the updated case does not have a verified IRS notice', async () => { - const result = await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...mockCase, - hasVerifiedIrsNotice: false, - irsNoticeDate: '2020-08-28T01:49:58.117Z', + const result = await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...mockCase, + hasVerifiedIrsNotice: false, + irsNoticeDate: '2020-08-28T01:49:58.117Z', + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockDocketClerkUser, + ); expect(result.hasVerifiedIrsNotice).toBe(false); expect(result.irsNoticeDate).toBe(undefined); }); it('should call updateCase with the updated case payment information (when unpaid) and return the updated case', async () => { - const result = await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...mockCase, - petitionPaymentStatus: PAYMENT_STATUS.UNPAID, + const result = await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...mockCase, + petitionPaymentStatus: PAYMENT_STATUS.UNPAID, + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -110,15 +129,19 @@ describe('updateCaseDetailsInteractor', () => { }); it('should call updateCase with the updated case payment information (when paid) and return the updated case', async () => { - const result = await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...mockCase, - petitionPaymentDate: '2019-11-30T09:10:11.000Z', - petitionPaymentMethod: 'check', - petitionPaymentStatus: PAYMENT_STATUS.PAID, + const result = await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...mockCase, + petitionPaymentDate: '2019-11-30T09:10:11.000Z', + petitionPaymentMethod: 'check', + petitionPaymentStatus: PAYMENT_STATUS.PAID, + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -130,14 +153,18 @@ describe('updateCaseDetailsInteractor', () => { }); it('should call updateCase with the updated case payment information (when waived) and return the updated case', async () => { - const result = await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...mockCase, - petitionPaymentStatus: PAYMENT_STATUS.WAIVED, - petitionPaymentWaivedDate: '2019-11-30T09:10:11.000Z', + const result = await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...mockCase, + petitionPaymentStatus: PAYMENT_STATUS.WAIVED, + petitionPaymentWaivedDate: '2019-11-30T09:10:11.000Z', + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -158,14 +185,18 @@ describe('updateCaseDetailsInteractor', () => { petitionPaymentStatus: PAYMENT_STATUS.UNPAID, }); - const result = await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...mockCase, - petitionPaymentStatus: PAYMENT_STATUS.WAIVED, - petitionPaymentWaivedDate: '2019-11-30T09:10:11.000Z', + const result = await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...mockCase, + petitionPaymentStatus: PAYMENT_STATUS.WAIVED, + petitionPaymentWaivedDate: '2019-11-30T09:10:11.000Z', + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockDocketClerkUser, + ); const waivedDocument = result.docketEntries.find( entry => @@ -183,15 +214,19 @@ describe('updateCaseDetailsInteractor', () => { petitionPaymentStatus: PAYMENT_STATUS.UNPAID, }); - const result = await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...mockCase, - petitionPaymentDate: '2019-11-30T09:10:11.000Z', - petitionPaymentMethod: 'check', - petitionPaymentStatus: PAYMENT_STATUS.PAID, + const result = await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...mockCase, + petitionPaymentDate: '2019-11-30T09:10:11.000Z', + petitionPaymentMethod: 'check', + petitionPaymentStatus: PAYMENT_STATUS.PAID, + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockDocketClerkUser, + ); const paidDocument = result.docketEntries.find( entry => @@ -209,13 +244,17 @@ describe('updateCaseDetailsInteractor', () => { petitionPaymentStatus: PAYMENT_STATUS.UNPAID, }); - const result = await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...mockCase, - petitionPaymentStatus: PAYMENT_STATUS.UNPAID, + const result = await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...mockCase, + petitionPaymentStatus: PAYMENT_STATUS.UNPAID, + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockDocketClerkUser, + ); expect(result).toMatchObject({ docketEntries: MOCK_CASE.docketEntries, @@ -227,13 +266,17 @@ describe('updateCaseDetailsInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(generalDocketReadyForTrialCase); - const result = await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...generalDocketReadyForTrialCase, - preferredTrialCity: 'Cheyenne, Wyoming', + const result = await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...generalDocketReadyForTrialCase, + preferredTrialCity: 'Cheyenne, Wyoming', + }, + docketNumber: generalDocketReadyForTrialCase.docketNumber, }, - docketNumber: generalDocketReadyForTrialCase.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -254,14 +297,18 @@ describe('updateCaseDetailsInteractor', () => { highPriorityReason: 'roll out', }); - const result = await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...generalDocketReadyForTrialCase, - preferredTrialCity: 'Cheyenne, Wyoming', - status: CASE_STATUS_TYPES.rule155, + const result = await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...generalDocketReadyForTrialCase, + preferredTrialCity: 'Cheyenne, Wyoming', + status: CASE_STATUS_TYPES.rule155, + }, + docketNumber: generalDocketReadyForTrialCase.docketNumber, }, - docketNumber: generalDocketReadyForTrialCase.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -285,15 +332,19 @@ describe('updateCaseDetailsInteractor', () => { highPriorityReason: 'roll out', }); - await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...generalDocketReadyForTrialCase, - highPriority: true, - preferredTrialCity: 'Cheyenne, Wyoming', - status: CASE_STATUS_TYPES.rule155, + await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...generalDocketReadyForTrialCase, + highPriority: true, + preferredTrialCity: 'Cheyenne, Wyoming', + status: CASE_STATUS_TYPES.rule155, + }, + docketNumber: generalDocketReadyForTrialCase.docketNumber, }, - docketNumber: generalDocketReadyForTrialCase.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -309,13 +360,17 @@ describe('updateCaseDetailsInteractor', () => { caseType: CASE_TYPES_MAP.cdp, }); - await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...generalDocketReadyForTrialCase, - caseType: CASE_TYPES_MAP.deficiency, + await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...generalDocketReadyForTrialCase, + caseType: CASE_TYPES_MAP.deficiency, + }, + docketNumber: generalDocketReadyForTrialCase.docketNumber, }, - docketNumber: generalDocketReadyForTrialCase.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -331,13 +386,17 @@ describe('updateCaseDetailsInteractor', () => { procedureType: 'Regular', }); - await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...generalDocketReadyForTrialCase, - procedureType: 'Small', + await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...generalDocketReadyForTrialCase, + procedureType: 'Small', + }, + docketNumber: generalDocketReadyForTrialCase.docketNumber, }, - docketNumber: generalDocketReadyForTrialCase.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -354,13 +413,17 @@ describe('updateCaseDetailsInteractor', () => { procedureType: 'Regular', }); - await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...generalDocketReadyForTrialCase, - procedureType: 'Small', + await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...generalDocketReadyForTrialCase, + procedureType: 'Small', + }, + docketNumber: generalDocketReadyForTrialCase.docketNumber, }, - docketNumber: generalDocketReadyForTrialCase.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -376,12 +439,16 @@ describe('updateCaseDetailsInteractor', () => { procedureType: 'Regular', }); - await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...generalDocketReadyForTrialCase, + await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...generalDocketReadyForTrialCase, + }, + docketNumber: generalDocketReadyForTrialCase.docketNumber, }, - docketNumber: generalDocketReadyForTrialCase.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -397,16 +464,20 @@ describe('updateCaseDetailsInteractor', () => { highPriorityReason: 'roll out', }); - await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...generalDocketReadyForTrialCase, - mailingDate: 'SOME NEW MAILING DATE', // attempting to change a field that does not exist in editableFields - partyType: 'SOME NEW PARTY TYPE', // attempting to change a field that does not exist in editableFields - preferredTrialCity: 'Cheyenne, Wyoming', - status: CASE_STATUS_TYPES.rule155, + await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...generalDocketReadyForTrialCase, + mailingDate: 'SOME NEW MAILING DATE', // attempting to change a field that does not exist in editableFields + partyType: 'SOME NEW PARTY TYPE', // attempting to change a field that does not exist in editableFields + preferredTrialCity: 'Cheyenne, Wyoming', + status: CASE_STATUS_TYPES.rule155, + }, + docketNumber: generalDocketReadyForTrialCase.docketNumber, }, - docketNumber: generalDocketReadyForTrialCase.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().updateCaseAndAssociations.mock @@ -423,13 +494,17 @@ describe('updateCaseDetailsInteractor', () => { mockLock = MOCK_LOCK; await expect( - updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...mockCase, - petitionPaymentStatus: PAYMENT_STATUS.UNPAID, + updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...mockCase, + petitionPaymentStatus: PAYMENT_STATUS.UNPAID, + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }), + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -438,13 +513,17 @@ describe('updateCaseDetailsInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await updateCaseDetailsInteractor(applicationContext, { - caseDetails: { - ...mockCase, - petitionPaymentStatus: PAYMENT_STATUS.UNPAID, + await updateCaseDetailsInteractor( + applicationContext, + { + caseDetails: { + ...mockCase, + petitionPaymentStatus: PAYMENT_STATUS.UNPAID, + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/shared/src/business/useCases/updateCaseDetailsInteractor.ts b/shared/src/business/useCases/updateCaseDetailsInteractor.ts index 2a869e9b915..e2652d190b1 100644 --- a/shared/src/business/useCases/updateCaseDetailsInteractor.ts +++ b/shared/src/business/useCases/updateCaseDetailsInteractor.ts @@ -8,7 +8,9 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -21,12 +23,11 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; * @returns {object} the updated case data */ export const updateCaseDetails = async ( - applicationContext: IApplicationContext, + applicationContext: ServerApplicationContext, { caseDetails, docketNumber }: { caseDetails: any; docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.EDIT_CASE_DETAILS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.EDIT_CASE_DETAILS)) { throw new UnauthorizedError('Unauthorized for editing case details'); } @@ -66,7 +67,7 @@ export const updateCaseDetails = async ( ? editableFields.petitionPaymentWaivedDate : null, }, - { applicationContext }, + { authorizedUser }, ); if (oldCase.petitionPaymentStatus === PAYMENT_STATUS.UNPAID) { @@ -81,10 +82,10 @@ export const updateCaseDetails = async ( isOnDocketRecord: true, processingStatus: 'complete', }, - { applicationContext }, + { authorizedUser }, ); - filingFeePaidEntry.setFiledBy(user); + filingFeePaidEntry.setFiledBy(authorizedUser); newCaseEntity.addDocketEntry(filingFeePaidEntry); } else if (isWaived) { @@ -98,17 +99,17 @@ export const updateCaseDetails = async ( isOnDocketRecord: true, processingStatus: 'complete', }, - { applicationContext }, + { authorizedUser }, ); - filingFeeWaivedEntry.setFiledBy(user); + filingFeeWaivedEntry.setFiledBy(authorizedUser); newCaseEntity.addDocketEntry(filingFeeWaivedEntry); } } if (newCaseEntity.getShouldHaveTrialSortMappingRecords()) { - const oldCaseEntity = new Case(oldCase, { applicationContext }); + const oldCaseEntity = new Case(oldCase, { authorizedUser }); const oldTrialSortTag = oldCaseEntity.getShouldHaveTrialSortMappingRecords() ? oldCaseEntity.generateTrialSortTags() : { nonHybrid: undefined }; @@ -132,10 +133,11 @@ export const updateCaseDetails = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: newCaseEntity, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const updateCaseDetailsInteractor = withLocking( diff --git a/shared/src/business/useCases/updateCaseTrialSortTagsInteractor.test.ts b/shared/src/business/useCases/updateCaseTrialSortTagsInteractor.test.ts index 62a2b6dcdbc..7d926f81a7c 100644 --- a/shared/src/business/useCases/updateCaseTrialSortTagsInteractor.test.ts +++ b/shared/src/business/useCases/updateCaseTrialSortTagsInteractor.test.ts @@ -1,8 +1,12 @@ -import { CASE_STATUS_TYPES, ROLES } from '../entities/EntityConstants'; +import { CASE_STATUS_TYPES } from '../entities/EntityConstants'; import { Case } from '../entities/cases/Case'; import { MOCK_CASE } from '../../test/mockCase'; -import { User } from '../entities/User'; import { applicationContext } from '../test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { omit } from 'lodash'; import { updateCaseTrialSortTagsInteractor } from './updateCaseTrialSortTagsInteractor'; @@ -12,23 +16,19 @@ describe('Update case trial sort tags', () => { beforeEach(() => { mockCase = MOCK_CASE; - applicationContext.getCurrentUser.mockReturnValue( - new User({ - name: 'bob', - role: ROLES.petitionsClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }), - ); - applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(Promise.resolve(mockCase)); }); it('does not call persistence if case status is not ready for trial', async () => { - await updateCaseTrialSortTagsInteractor(applicationContext, { - docketNumber: mockCase.docketNumber, - }); + await updateCaseTrialSortTagsInteractor( + applicationContext, + { + docketNumber: mockCase.docketNumber, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -39,9 +39,13 @@ describe('Update case trial sort tags', () => { it('calls persistence if case status is ready for trial', async () => { mockCase.status = CASE_STATUS_TYPES.generalDocketReadyForTrial; - await updateCaseTrialSortTagsInteractor(applicationContext, { - docketNumber: mockCase.docketNumber, - }); + await updateCaseTrialSortTagsInteractor( + applicationContext, + { + docketNumber: mockCase.docketNumber, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -50,12 +54,14 @@ describe('Update case trial sort tags', () => { }); it('throws unauthorized error if user is unauthorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - updateCaseTrialSortTagsInteractor(applicationContext, { - docketNumber: mockCase.docketNumber, - }), + updateCaseTrialSortTagsInteractor( + applicationContext, + { + docketNumber: mockCase.docketNumber, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized for update case'); }); @@ -65,9 +71,13 @@ describe('Update case trial sort tags', () => { .getCaseByDocketNumber.mockReturnValue(null); await expect( - updateCaseTrialSortTagsInteractor(applicationContext, { - docketNumber: '123-45', - }), + updateCaseTrialSortTagsInteractor( + applicationContext, + { + docketNumber: '123-45', + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('Case 123-45'); }); @@ -79,13 +89,18 @@ describe('Update case trial sort tags', () => { applicationContext .getPersistenceGateway() .updateCase.mockImplementation( - ({ caseToUpdate }) => new Case(caseToUpdate, { applicationContext }), + ({ caseToUpdate }) => + new Case(caseToUpdate, { authorizedUser: mockDocketClerkUser }), ); await expect( - updateCaseTrialSortTagsInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }), + updateCaseTrialSortTagsInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('The Case entity was invalid'); }); }); diff --git a/shared/src/business/useCases/updateCaseTrialSortTagsInteractor.ts b/shared/src/business/useCases/updateCaseTrialSortTagsInteractor.ts index 9ca331456d5..23b0c1d04cb 100644 --- a/shared/src/business/useCases/updateCaseTrialSortTagsInteractor.ts +++ b/shared/src/business/useCases/updateCaseTrialSortTagsInteractor.ts @@ -4,6 +4,7 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * updates the case trial sort tags @@ -15,9 +16,8 @@ import { export const updateCaseTrialSortTagsInteractor = async ( applicationContext: IApplicationContext, { docketNumber }: { docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - const caseToUpdate = await applicationContext .getPersistenceGateway() .getCaseByDocketNumber({ @@ -29,9 +29,9 @@ export const updateCaseTrialSortTagsInteractor = async ( throw new NotFoundError(`Case ${docketNumber} was not found.`); } - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); - if (!isAuthorized(user, ROLE_PERMISSIONS.UPDATE_CASE)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.UPDATE_CASE)) { throw new UnauthorizedError('Unauthorized for update case'); } diff --git a/shared/src/business/useCases/updateContactInteractor.test.ts b/shared/src/business/useCases/updateContactInteractor.test.ts index 8b23b9ebeee..8991b36f082 100644 --- a/shared/src/business/useCases/updateContactInteractor.test.ts +++ b/shared/src/business/useCases/updateContactInteractor.test.ts @@ -10,15 +10,14 @@ import { } from '../../test/mockCase'; import { MOCK_LOCK } from '../../test/mockLock'; import { ServiceUnavailableError } from '@web-api/errors/errors'; -import { User } from '../entities/User'; import { applicationContext } from '../test/createTestApplicationContext'; import { fakeData } from '../test/getFakeFile'; import { getContactPrimary } from '../entities/cases/Case'; +import { mockPetitionerUser } from '@shared/test/mockAuthUsers'; import { updateContactInteractor } from './updateContactInteractor'; describe('updates the contact on a case', () => { let mockCase; - let mockUser; let mockCaseContactPrimary; let mockLock; beforeAll(() => { @@ -35,12 +34,7 @@ describe('updates the contact on a case', () => { }; mockCaseContactPrimary = mockCase.petitioners[0]; mockCaseContactPrimary.contactType = 'petitioner'; - - mockUser = new User({ - name: 'bob', - role: ROLES.petitioner, - userId: mockCaseContactPrimary.contactId, - }); + mockCaseContactPrimary.contactId = mockPetitionerUser.userId; applicationContext .getPersistenceGateway() @@ -54,8 +48,6 @@ describe('updates the contact on a case', () => { .getDocumentGenerators() .changeOfAddress.mockReturnValue(fakeData); - applicationContext.getCurrentUser.mockImplementation(() => mockUser); - applicationContext .getChromiumBrowser() .newPage() @@ -82,19 +74,23 @@ describe('updates the contact on a case', () => { .getUseCaseHelpers() .countPagesInDocument.mockReturnValue(mockNumberOfPages); - const caseDetail = await updateContactInteractor(applicationContext, { - contactInfo: { - ...mockCaseContactPrimary, - address1: '453 Electric Ave', - city: 'Philadelphia', - email: 'petitioner', - name: 'Bill Burr', - phone: '1234567890', - postalCode: '99999', - state: 'PA', + const caseDetail = await updateContactInteractor( + applicationContext, + { + contactInfo: { + ...mockCaseContactPrimary, + address1: '453 Electric Ave', + city: 'Philadelphia', + email: 'petitioner', + name: 'Bill Burr', + phone: '1234567890', + postalCode: '99999', + state: 'PA', + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockPetitionerUser, + ); const updatedCase = applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -153,13 +149,17 @@ describe('updates the contact on a case', () => { ], }); - await updateContactInteractor(applicationContext, { - contactInfo: { - ...mockCaseContactPrimary, - address1: '453 Electric Ave', + await updateContactInteractor( + applicationContext, + { + contactInfo: { + ...mockCaseContactPrimary, + address1: '453 Electric Ave', + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockPetitionerUser, + ); expect( applicationContext.getPersistenceGateway().saveWorkItem, @@ -189,13 +189,17 @@ describe('updates the contact on a case', () => { ], }); - await updateContactInteractor(applicationContext, { - contactInfo: { - ...mockCaseContactPrimary, - address1: '453 Electric Ave', + await updateContactInteractor( + applicationContext, + { + contactInfo: { + ...mockCaseContactPrimary, + address1: '453 Electric Ave', + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockPetitionerUser, + ); expect( applicationContext.getPersistenceGateway().saveWorkItem, @@ -225,13 +229,17 @@ describe('updates the contact on a case', () => { ], }); - await updateContactInteractor(applicationContext, { - contactInfo: { - ...mockCaseContactPrimary, - address1: '453 Electric Ave', + await updateContactInteractor( + applicationContext, + { + contactInfo: { + ...mockCaseContactPrimary, + address1: '453 Electric Ave', + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockPetitionerUser, + ); expect( applicationContext.getPersistenceGateway().saveWorkItem, @@ -244,24 +252,30 @@ describe('updates the contact on a case', () => { .getCaseByDocketNumber.mockResolvedValue(null); await expect( - updateContactInteractor(applicationContext, { - contactInfo: {}, - docketNumber: mockCase.docketNumber, - }), + updateContactInteractor( + applicationContext, + { + contactInfo: {}, + docketNumber: mockCase.docketNumber, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Case 101-18 was not found.'); }); it('throws an error if the user making the request is not associated with the case', async () => { - mockUser = { - ...mockUser, - userId: 'de300c01-f6ff-4843-a72f-ee7cd2521237', - }; - await expect( - updateContactInteractor(applicationContext, { - contactInfo: mockCaseContactPrimary, - docketNumber: mockCase.docketNumber, - }), + updateContactInteractor( + applicationContext, + { + contactInfo: mockCaseContactPrimary, + docketNumber: mockCase.docketNumber, + }, + { + ...mockPetitionerUser, + userId: '4885d93e-ab94-48b9-be87-4cda005568d4', + }, + ), ).rejects.toThrow('Unauthorized for update case contact'); }); @@ -269,10 +283,14 @@ describe('updates the contact on a case', () => { mockCase = { ...MOCK_CASE_WITH_SECONDARY_OTHERS, petitioners: [] }; await expect( - updateContactInteractor(applicationContext, { - contactInfo: mockCaseContactPrimary, - docketNumber: mockCase.docketNumber, - }), + updateContactInteractor( + applicationContext, + { + contactInfo: mockCaseContactPrimary, + docketNumber: mockCase.docketNumber, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Error: Petitioner was not found on case 109-19.'); }); @@ -281,10 +299,14 @@ describe('updates the contact on a case', () => { .getUtilities() .getDocumentTypeForAddressChange.mockReturnValue(undefined); - await updateContactInteractor(applicationContext, { - contactInfo: mockCaseContactPrimary, - docketNumber: mockCase.docketNumber, - }); + await updateContactInteractor( + applicationContext, + { + contactInfo: mockCaseContactPrimary, + docketNumber: mockCase.docketNumber, + }, + mockPetitionerUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -302,16 +324,20 @@ describe('updates the contact on a case', () => { .getUtilities() .getDocumentTypeForAddressChange.mockReturnValue(undefined); - const caseDetail = await updateContactInteractor(applicationContext, { - contactInfo: { - ...mockCaseContactPrimary, - address1: 'nothing', - city: 'Somewhere', - email: 'hello123@example.com', - name: 'Secondary Party Name Changed', + const caseDetail = await updateContactInteractor( + applicationContext, + { + contactInfo: { + ...mockCaseContactPrimary, + address1: 'nothing', + city: 'Somewhere', + email: 'hello123@example.com', + name: 'Secondary Party Name Changed', + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockPetitionerUser, + ); const contactPrimary = getContactPrimary(caseDetail); @@ -338,13 +364,17 @@ describe('updates the contact on a case', () => { () => mockCaseWithSealedAddress, ); - await updateContactInteractor(applicationContext, { - contactInfo: { - ...mockCaseContactPrimary, - address1: 'nothing 1', + await updateContactInteractor( + applicationContext, + { + contactInfo: { + ...mockCaseContactPrimary, + address1: 'nothing 1', + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockPetitionerUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -361,13 +391,17 @@ describe('updates the contact on a case', () => { }); it('should use original case caption to create case title when creating work item', async () => { - await updateContactInteractor(applicationContext, { - contactInfo: { - ...mockCaseContactPrimary, - address1: '453 Electric Ave', + await updateContactInteractor( + applicationContext, + { + contactInfo: { + ...mockCaseContactPrimary, + address1: '453 Electric Ave', + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockPetitionerUser, + ); expect( applicationContext.getPersistenceGateway().saveWorkItem.mock.calls[0][0] @@ -388,13 +422,17 @@ describe('updates the contact on a case', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockImplementation(() => mockClosedCase); - await updateContactInteractor(applicationContext, { - contactInfo: { - ...mockCaseContactPrimary, - address1: '453 Electric Ave', + await updateContactInteractor( + applicationContext, + { + contactInfo: { + ...mockCaseContactPrimary, + address1: '453 Electric Ave', + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockPetitionerUser, + ); expect( applicationContext.getPersistenceGateway().saveDocumentFromLambda, @@ -408,12 +446,16 @@ describe('updates the contact on a case', () => { .getUtilities() .getDocumentTypeForAddressChange.mockReturnValue(null); - await updateContactInteractor(applicationContext, { - contactInfo: { - ...mockCaseContactPrimary, + await updateContactInteractor( + applicationContext, + { + contactInfo: { + ...mockCaseContactPrimary, + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockPetitionerUser, + ); expect( applicationContext.getUseCaseHelpers().updateCaseAndAssociations, @@ -424,13 +466,17 @@ describe('updates the contact on a case', () => { mockLock = MOCK_LOCK; await expect( - updateContactInteractor(applicationContext, { - contactInfo: { - ...mockCaseContactPrimary, - address1: '453 Electric Ave', + updateContactInteractor( + applicationContext, + { + contactInfo: { + ...mockCaseContactPrimary, + address1: '453 Electric Ave', + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }), + mockPetitionerUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -439,13 +485,17 @@ describe('updates the contact on a case', () => { }); it('should acquire and remove the lock on the case', async () => { - await updateContactInteractor(applicationContext, { - contactInfo: { - ...mockCaseContactPrimary, - address1: '453 Electric Ave', + await updateContactInteractor( + applicationContext, + { + contactInfo: { + ...mockCaseContactPrimary, + address1: '453 Electric Ave', + }, + docketNumber: mockCase.docketNumber, }, - docketNumber: mockCase.docketNumber, - }); + mockPetitionerUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/shared/src/business/useCases/updateContactInteractor.ts b/shared/src/business/useCases/updateContactInteractor.ts index 5f6e384ce88..0eef844e7e3 100644 --- a/shared/src/business/useCases/updateContactInteractor.ts +++ b/shared/src/business/useCases/updateContactInteractor.ts @@ -5,7 +5,16 @@ import { SERVICE_INDICATOR_TYPES, } from '../entities/EntityConstants'; import { DocketEntry } from '../entities/DocketEntry'; -import { NotFoundError, UnauthorizedError } from '@web-api/errors/errors'; +import { + NotFoundError, + UnauthorizedError, + UnidentifiedUserError, +} from '@web-api/errors/errors'; +import { ServerApplicationContext } from '@web-api/applicationContext'; +import { + UnknownAuthUser, + isAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; import { WorkItem } from '../entities/WorkItem'; import { addCoverToPdf } from '../../../../web-api/src/business/useCases/addCoverToPdf'; import { aggregatePartiesForService } from '../utilities/aggregatePartiesForService'; @@ -24,10 +33,15 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; * @returns {object} the updated case */ export const updateContact = async ( - applicationContext, + applicationContext: ServerApplicationContext, { contactInfo, docketNumber }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); + if (!isAuthUser(authorizedUser)) { + throw new UnidentifiedUserError( + 'Unable to confirm user is an authenticated user', + ); + } const editableFields = { address1: contactInfo.address1, @@ -56,7 +70,7 @@ export const updateContact = async ( { ...caseToUpdate, }, - { applicationContext }, + { authorizedUser }, ); const oldCaseContact = cloneDeep( @@ -75,12 +89,12 @@ export const updateContact = async ( } const rawUpdatedCase = caseEntity.validate().toRawObject(); - caseEntity = new Case(rawUpdatedCase, { applicationContext }); + caseEntity = new Case(rawUpdatedCase, { authorizedUser }); const updatedPetitioner = caseEntity.getPetitionerById(contactInfo.contactId); const userIsAssociated = caseEntity.isAssociatedUser({ - user, + user: authorizedUser, }); if (!userIsAssociated) { @@ -136,10 +150,10 @@ export const updateContact = async ( partyPrimary: true, processingStatus: DOCUMENT_PROCESSING_STATUS_OPTIONS.COMPLETE, }, - { applicationContext, petitioners: caseEntity.petitioners }, + { authorizedUser, petitioners: caseEntity.petitioners }, ); - changeOfAddressDocketEntry.setFiledBy(user); + changeOfAddressDocketEntry.setFiledBy(authorizedUser); const servedParties = aggregatePartiesForService(caseEntity); @@ -170,13 +184,12 @@ export const updateContact = async ( docketNumber: caseEntity.docketNumber, docketNumberWithSuffix: caseEntity.docketNumberWithSuffix, section: DOCKET_SECTION, - sentBy: user.name, - sentByUserId: user.userId, + sentBy: authorizedUser.name, + sentByUserId: authorizedUser.userId, trialDate: caseEntity.trialDate, trialLocation: caseEntity.trialLocation, }, - { applicationContext }, - caseEntity, + { caseEntity }, ); changeOfAddressDocketEntry.setWorkItem(workItem); @@ -227,6 +240,7 @@ export const updateContact = async ( if (shouldUpdateCase) { await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); } diff --git a/shared/src/business/useCases/updateQcCompleteForTrialInteractor.test.ts b/shared/src/business/useCases/updateQcCompleteForTrialInteractor.test.ts index 13fd7ea518b..3c796b93246 100644 --- a/shared/src/business/useCases/updateQcCompleteForTrialInteractor.test.ts +++ b/shared/src/business/useCases/updateQcCompleteForTrialInteractor.test.ts @@ -1,18 +1,19 @@ import { MOCK_CASE } from '../../test/mockCase'; import { MOCK_LOCK } from '../../test/mockLock'; -import { ROLES } from '../entities/EntityConstants'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { updateQcCompleteForTrialInteractor } from './updateQcCompleteForTrialInteractor'; describe('updateQcCompleteForTrialInteractor', () => { - let user; let mockLock; beforeAll(() => { applicationContext .getPersistenceGateway() .getLock.mockImplementation(() => mockLock); - applicationContext.getCurrentUser.mockImplementation(() => user); applicationContext .getPersistenceGateway() .updateCase.mockImplementation(({ caseToUpdate }) => @@ -28,26 +29,20 @@ describe('updateQcCompleteForTrialInteractor', () => { }); it('should throw an error if the user is unauthorized to update a trial session', async () => { - user = { - role: ROLES.petitioner, - userId: 'petitioner', - }; - await expect( - updateQcCompleteForTrialInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - qcCompleteForTrial: true, - trialSessionId: '10aa100f-0330-442b-8423-b01690c76e3f', - }), + updateQcCompleteForTrialInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + qcCompleteForTrial: true, + trialSessionId: '10aa100f-0330-442b-8423-b01690c76e3f', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized for trial session QC complete'); }); it('should call updateCase with the updated qcCompleteForTrial value and return the updated case', async () => { - user = { - role: ROLES.petitionsClerk, - userId: 'petitionsClerk', - }; - const result = await updateQcCompleteForTrialInteractor( applicationContext, { @@ -55,6 +50,7 @@ describe('updateQcCompleteForTrialInteractor', () => { qcCompleteForTrial: true, trialSessionId: '10aa100f-0330-442b-8423-b01690c76e3f', }, + mockPetitionsClerkUser, ); expect(result.qcCompleteForTrial).toEqual({ '10aa100f-0330-442b-8423-b01690c76e3f': true, @@ -65,11 +61,15 @@ describe('updateQcCompleteForTrialInteractor', () => { mockLock = MOCK_LOCK; await expect( - updateQcCompleteForTrialInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - qcCompleteForTrial: true, - trialSessionId: '10aa100f-0330-442b-8423-b01690c76e3f', - }), + updateQcCompleteForTrialInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + qcCompleteForTrial: true, + trialSessionId: '10aa100f-0330-442b-8423-b01690c76e3f', + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -78,11 +78,15 @@ describe('updateQcCompleteForTrialInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await updateQcCompleteForTrialInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - qcCompleteForTrial: true, - trialSessionId: '10aa100f-0330-442b-8423-b01690c76e3f', - }); + await updateQcCompleteForTrialInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + qcCompleteForTrial: true, + trialSessionId: '10aa100f-0330-442b-8423-b01690c76e3f', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/shared/src/business/useCases/updateQcCompleteForTrialInteractor.ts b/shared/src/business/useCases/updateQcCompleteForTrialInteractor.ts index b42aaeccde1..4d2cf2f9160 100644 --- a/shared/src/business/useCases/updateQcCompleteForTrialInteractor.ts +++ b/shared/src/business/useCases/updateQcCompleteForTrialInteractor.ts @@ -3,7 +3,9 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -18,7 +20,7 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; */ export const updateQcCompleteForTrial = async ( - applicationContext: IApplicationContext, + applicationContext: ServerApplicationContext, { docketNumber, qcCompleteForTrial, @@ -28,10 +30,11 @@ export const updateQcCompleteForTrial = async ( qcCompleteForTrial: boolean; trialSessionId: string; }, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSION_QC_COMPLETE)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSION_QC_COMPLETE) + ) { throw new UnauthorizedError('Unauthorized for trial session QC complete'); } @@ -39,7 +42,7 @@ export const updateQcCompleteForTrial = async ( .getPersistenceGateway() .getCaseByDocketNumber({ applicationContext, docketNumber }); - const newCase = new Case(oldCase, { applicationContext }); + const newCase = new Case(oldCase, { authorizedUser }); newCase.setQcCompleteForTrial({ qcCompleteForTrial, trialSessionId }); @@ -47,10 +50,11 @@ export const updateQcCompleteForTrial = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: newCase, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const updateQcCompleteForTrialInteractor = withLocking( diff --git a/shared/src/business/useCases/validateAddDeficiencyStatisticsInteractor.ts b/shared/src/business/useCases/validateAddDeficiencyStatisticsInteractor.ts index a4275f6a899..f8e6607dca1 100644 --- a/shared/src/business/useCases/validateAddDeficiencyStatisticsInteractor.ts +++ b/shared/src/business/useCases/validateAddDeficiencyStatisticsInteractor.ts @@ -4,7 +4,5 @@ export const validateAddDeficiencyStatisticsInteractor = ( applicationContext: IApplicationContext, { statistic }: { statistic: any }, ) => { - return new Statistic(statistic, { - applicationContext, - }).getFormattedValidationErrors(); + return new Statistic(statistic).getFormattedValidationErrors(); }; diff --git a/shared/src/business/useCases/validateAddPetitionerInteractor.ts b/shared/src/business/useCases/validateAddPetitionerInteractor.ts index 0cb57b37030..12467a74e49 100644 --- a/shared/src/business/useCases/validateAddPetitionerInteractor.ts +++ b/shared/src/business/useCases/validateAddPetitionerInteractor.ts @@ -17,9 +17,9 @@ export const validateAddPetitionerInteractor = ( existingPetitioners, }: { contact: any; existingPetitioners?: any[] }, ) => { - const petitionerErrors = new Petitioner(contact, { - applicationContext, - }).getFormattedValidationErrors(); + const petitionerErrors = new Petitioner( + contact, + ).getFormattedValidationErrors(); let caseCaptionError; if (!contact.caseCaption) { diff --git a/shared/src/business/useCases/validateCaseDetailInteractor.test.ts b/shared/src/business/useCases/validateCaseDetailInteractor.test.ts index 73ce12d6753..a32252835d3 100644 --- a/shared/src/business/useCases/validateCaseDetailInteractor.test.ts +++ b/shared/src/business/useCases/validateCaseDetailInteractor.test.ts @@ -5,8 +5,8 @@ import { PARTY_TYPES, ROLES, } from '../entities/EntityConstants'; -import { MOCK_USERS } from '../../test/mockUsers'; import { applicationContext } from '../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { validateCaseDetailInteractor } from './validateCaseDetailInteractor'; describe('validate case detail', () => { @@ -23,16 +23,13 @@ describe('validate case detail', () => { }, ]; - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue( - MOCK_USERS['a7d90c05-f6cd-442c-a168-202db587f16f'], - ); - }); - it('returns the expected errors object on an empty case', () => { - const errors = validateCaseDetailInteractor(applicationContext, { - caseDetail: {}, - }); + const errors = validateCaseDetailInteractor( + { + caseDetail: {}, + }, + mockDocketClerkUser, + ); expect(errors).toBeTruthy(); expect(errors).toMatchObject({ @@ -41,11 +38,14 @@ describe('validate case detail', () => { }); it('does not return an error if that field is valid', () => { - const errors = validateCaseDetailInteractor(applicationContext, { - caseDetail: { - caseCaption: 'A case caption', + const errors = validateCaseDetailInteractor( + { + caseDetail: { + caseCaption: 'A case caption', + }, }, - }); + mockDocketClerkUser, + ); expect(errors).toBeTruthy(); expect(errors).toMatchObject({ @@ -54,186 +54,207 @@ describe('validate case detail', () => { }); it('returns no errors if the case validates', () => { - const errors = validateCaseDetailInteractor(applicationContext, { - caseDetail: { - caseCaption: 'Caption', - caseType: CASE_TYPES_MAP.other, - docketEntries: [ - { - createdAt: '2018-11-21T20:49:28.192Z', - docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', - docketNumber: '101-18', - documentType: 'Petition', - eventCode: 'P', - filedBy: 'Test Petitioner', - filedByRole: ROLES.petitioner, - role: ROLES.petitioner, - userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', - }, - { - createdAt: '2018-11-21T20:49:28.192Z', - docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', - docketNumber: '101-18', - documentType: 'Petition', - eventCode: 'P', - filedBy: 'Test Petitioner', - filedByRole: ROLES.petitioner, - userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', - }, - ], - docketNumber: '101-18', - filingType: 'Myself', - hasVerifiedIrsNotice: true, - irsNoticeDate: applicationContext.getUtilities().createISODateString(), - partyType: PARTY_TYPES.petitioner, - petitioners, - preferredTrialCity: 'Fresno, California', - procedureType: 'Regular', - signature: true, - userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + const errors = validateCaseDetailInteractor( + { + caseDetail: { + caseCaption: 'Caption', + caseType: CASE_TYPES_MAP.other, + docketEntries: [ + { + createdAt: '2018-11-21T20:49:28.192Z', + docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', + docketNumber: '101-18', + documentType: 'Petition', + eventCode: 'P', + filedBy: 'Test Petitioner', + filedByRole: ROLES.petitioner, + role: ROLES.petitioner, + userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', + }, + { + createdAt: '2018-11-21T20:49:28.192Z', + docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', + docketNumber: '101-18', + documentType: 'Petition', + eventCode: 'P', + filedBy: 'Test Petitioner', + filedByRole: ROLES.petitioner, + userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', + }, + ], + docketNumber: '101-18', + filingType: 'Myself', + hasVerifiedIrsNotice: true, + irsNoticeDate: applicationContext + .getUtilities() + .createISODateString(), + partyType: PARTY_TYPES.petitioner, + petitioners, + preferredTrialCity: 'Fresno, California', + procedureType: 'Regular', + signature: true, + userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + }, }, - }); + mockDocketClerkUser, + ); expect(errors).toEqual(null); }); it('returns the expected errors when passed bad date objects', () => { - const errors: any = validateCaseDetailInteractor(applicationContext, { - caseDetail: { - hasVerifiedIrsNotice: true, - irsNoticeDate: 'aa', + const errors: any = validateCaseDetailInteractor( + { + caseDetail: { + hasVerifiedIrsNotice: true, + irsNoticeDate: 'aa', + }, }, - }); + mockDocketClerkUser, + ); expect(errors).toBeTruthy(); expect(errors.irsNoticeDate).toBeTruthy(); }); it('returns no errors on valid amounts and years', () => { - const errors = validateCaseDetailInteractor(applicationContext, { - caseDetail: { - caseCaption: 'Caption', - caseType: CASE_TYPES_MAP.other, - docketEntries: [ - { - createdAt: '2018-11-21T20:49:28.192Z', - docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', - docketNumber: '101-18', - documentType: 'Petition', - eventCode: 'P', - filedBy: 'Test Petitioner', - filedByRole: ROLES.petitioner, - userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', - }, - { - createdAt: '2018-11-21T20:49:28.192Z', - docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', - docketNumber: '101-18', - documentType: 'Petition', - eventCode: 'P', - filedBy: 'Test Petitioner', - filedByRole: ROLES.petitioner, - userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', - }, - ], - docketNumber: '101-18', - filingType: CASE_TYPES_MAP.other, - hasVerifiedIrsNotice: true, - irsNoticeDate: applicationContext.getUtilities().createISODateString(), - partyType: PARTY_TYPES.petitioner, - petitioners, - preferredTrialCity: 'Fresno, California', - procedureType: 'Regular', - signature: true, - userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + const errors = validateCaseDetailInteractor( + { + caseDetail: { + caseCaption: 'Caption', + caseType: CASE_TYPES_MAP.other, + docketEntries: [ + { + createdAt: '2018-11-21T20:49:28.192Z', + docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', + docketNumber: '101-18', + documentType: 'Petition', + eventCode: 'P', + filedBy: 'Test Petitioner', + filedByRole: ROLES.petitioner, + userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', + }, + { + createdAt: '2018-11-21T20:49:28.192Z', + docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', + docketNumber: '101-18', + documentType: 'Petition', + eventCode: 'P', + filedBy: 'Test Petitioner', + filedByRole: ROLES.petitioner, + userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', + }, + ], + docketNumber: '101-18', + filingType: CASE_TYPES_MAP.other, + hasVerifiedIrsNotice: true, + irsNoticeDate: applicationContext + .getUtilities() + .createISODateString(), + partyType: PARTY_TYPES.petitioner, + petitioners, + preferredTrialCity: 'Fresno, California', + procedureType: 'Regular', + signature: true, + userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + }, }, - }); + mockDocketClerkUser, + ); expect(errors).toEqual(null); }); it('returns no errors on null irsNoticeDate', () => { - const errors = validateCaseDetailInteractor(applicationContext, { - caseDetail: { - caseCaption: 'Caption', - caseType: CASE_TYPES_MAP.other, - docketEntries: [ - { - createdAt: '2018-11-21T20:49:28.192Z', - docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', - docketNumber: '101-18', - documentType: 'Petition', - eventCode: 'P', - filedBy: 'Test Petitioner', - filedByRole: ROLES.petitioner, - userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', - }, - { - createdAt: '2018-11-21T20:49:28.192Z', - docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', - docketNumber: '101-18', - documentType: 'Petition', - eventCode: 'P', - filedBy: 'Test Petitioner', - filedByRole: ROLES.petitioner, - userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', - }, - ], - docketNumber: '101-18', - filingType: CASE_TYPES_MAP.other, - hasVerifiedIrsNotice: false, - irsNoticeDate: null, - partyType: PARTY_TYPES.petitioner, - petitioners, - preferredTrialCity: 'Fresno, California', - procedureType: 'Regular', - signature: true, - userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + const errors = validateCaseDetailInteractor( + { + caseDetail: { + caseCaption: 'Caption', + caseType: CASE_TYPES_MAP.other, + docketEntries: [ + { + createdAt: '2018-11-21T20:49:28.192Z', + docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', + docketNumber: '101-18', + documentType: 'Petition', + eventCode: 'P', + filedBy: 'Test Petitioner', + filedByRole: ROLES.petitioner, + userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', + }, + { + createdAt: '2018-11-21T20:49:28.192Z', + docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', + docketNumber: '101-18', + documentType: 'Petition', + eventCode: 'P', + filedBy: 'Test Petitioner', + filedByRole: ROLES.petitioner, + userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', + }, + ], + docketNumber: '101-18', + filingType: CASE_TYPES_MAP.other, + hasVerifiedIrsNotice: false, + irsNoticeDate: null, + partyType: PARTY_TYPES.petitioner, + petitioners, + preferredTrialCity: 'Fresno, California', + procedureType: 'Regular', + signature: true, + userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + }, }, - }); + mockDocketClerkUser, + ); expect(errors).toEqual(null); }); it('should validate a new Case entity when useCaseEntity is true', () => { - const errors = validateCaseDetailInteractor(applicationContext, { - caseDetail: { - caseCaption: 'Caption', - caseType: CASE_TYPES_MAP.other, - docketEntries: [ - { - createdAt: '2018-11-21T20:49:28.192Z', - docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', - docketNumber: '101-18', - documentType: 'Petition', - eventCode: 'P', - filedBy: 'Test Petitioner', - filedByRole: ROLES.petitioner, - userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', - }, - { - createdAt: '2018-11-21T20:49:28.192Z', - docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', - docketNumber: '101-18', - documentType: 'Petition', - eventCode: 'P', - filedBy: 'Test Petitioner', - filedByRole: ROLES.petitioner, - userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', - }, - ], - docketNumber: '101-18', - filingType: CASE_TYPES_MAP.other, - irsNoticeDate: applicationContext.getUtilities().createISODateString(), - partyType: PARTY_TYPES.petitioner, - petitioners, - preferredTrialCity: 'Fresno, California', - procedureType: 'Regular', - signature: true, - userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + const errors = validateCaseDetailInteractor( + { + caseDetail: { + caseCaption: 'Caption', + caseType: CASE_TYPES_MAP.other, + docketEntries: [ + { + createdAt: '2018-11-21T20:49:28.192Z', + docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', + docketNumber: '101-18', + documentType: 'Petition', + eventCode: 'P', + filedBy: 'Test Petitioner', + filedByRole: ROLES.petitioner, + userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', + }, + { + createdAt: '2018-11-21T20:49:28.192Z', + docketEntryId: '9de27a7d-7c6b-434b-803b-7655f82d5e07', + docketNumber: '101-18', + documentType: 'Petition', + eventCode: 'P', + filedBy: 'Test Petitioner', + filedByRole: ROLES.petitioner, + userId: '9271f5ca-e7c9-40e8-b465-e970e22934e8', + }, + ], + docketNumber: '101-18', + filingType: CASE_TYPES_MAP.other, + irsNoticeDate: applicationContext + .getUtilities() + .createISODateString(), + partyType: PARTY_TYPES.petitioner, + petitioners, + preferredTrialCity: 'Fresno, California', + procedureType: 'Regular', + signature: true, + userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + }, + useCaseEntity: true, }, - useCaseEntity: true, - }); + mockDocketClerkUser, + ); expect(errors).toEqual(null); }); diff --git a/shared/src/business/useCases/validateCaseDetailInteractor.ts b/shared/src/business/useCases/validateCaseDetailInteractor.ts index c31bd1ad51a..8ab83f2a2f5 100644 --- a/shared/src/business/useCases/validateCaseDetailInteractor.ts +++ b/shared/src/business/useCases/validateCaseDetailInteractor.ts @@ -1,5 +1,6 @@ import { Case } from '../entities/cases/Case'; import { CaseQC } from '../entities/cases/CaseQC'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * validateCaseDetailInteractor @@ -10,18 +11,18 @@ import { CaseQC } from '../entities/cases/CaseQC'; * @returns {object} errors (null if no errors) */ export const validateCaseDetailInteractor = ( - applicationContext: IApplicationContext, { caseDetail, useCaseEntity = false, }: { caseDetail: any; useCaseEntity?: boolean }, + authorizedUser: UnknownAuthUser, ): Record | null => { if (useCaseEntity) { return new Case(caseDetail, { - applicationContext, + authorizedUser, }).getFormattedValidationErrors(); } return new CaseQC(caseDetail, { - applicationContext, + authorizedUser, }).getFormattedValidationErrors(); }; diff --git a/shared/src/business/useCases/validateDocumentInteractor.test.ts b/shared/src/business/useCases/validateDocumentInteractor.test.ts index e83d5927889..c002f02ec57 100644 --- a/shared/src/business/useCases/validateDocumentInteractor.test.ts +++ b/shared/src/business/useCases/validateDocumentInteractor.test.ts @@ -1,30 +1,36 @@ import { ROLES } from '../entities/EntityConstants'; -import { applicationContext } from '../test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { validateDocumentInteractor } from './validateDocumentInteractor'; describe('validateDocumentInteractor', () => { it('returns the expected errors object on an empty docket record', () => { - const errors = validateDocumentInteractor(applicationContext, { - document: {}, - }); + const errors = validateDocumentInteractor( + { + document: {}, + }, + mockDocketClerkUser, + ); expect(Object.keys(errors!).length).toBeGreaterThan(0); }); it('returns null when there are no errors', () => { - const result = validateDocumentInteractor(applicationContext, { - document: { - docketNumber: '101-21', - documentTitle: 'Administrative Record', - documentType: 'Administrative Record', - eventCode: 'ADMR', - filedBy: 'Test User', - filedByRole: ROLES.docketClerk, - filingDate: '2020-01-01T02:04:06.007Z', - index: '1', - userId: '3ab77c88-1dd0-4adb-a03c-c466ad72d417', + const result = validateDocumentInteractor( + { + document: { + docketNumber: '101-21', + documentTitle: 'Administrative Record', + documentType: 'Administrative Record', + eventCode: 'ADMR', + filedBy: 'Test User', + filedByRole: ROLES.docketClerk, + filingDate: '2020-01-01T02:04:06.007Z', + index: '1', + userId: '3ab77c88-1dd0-4adb-a03c-c466ad72d417', + }, }, - }); + mockDocketClerkUser, + ); expect(result).toEqual(null); }); diff --git a/shared/src/business/useCases/validateDocumentInteractor.ts b/shared/src/business/useCases/validateDocumentInteractor.ts index 38140753c2a..7b3d7ca12f1 100644 --- a/shared/src/business/useCases/validateDocumentInteractor.ts +++ b/shared/src/business/useCases/validateDocumentInteractor.ts @@ -1,4 +1,5 @@ import { DocketEntry } from '../entities/DocketEntry'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * validateDocumentInteractor @@ -9,11 +10,11 @@ import { DocketEntry } from '../entities/DocketEntry'; * @returns {object} the validation errors or null */ export const validateDocumentInteractor = ( - applicationContext: IApplicationContext, { document }: { document: any }, + authorizedUser: UnknownAuthUser, ) => { const errors = new DocketEntry(document, { - applicationContext, + authorizedUser, }).getFormattedValidationErrors(); return errors || null; diff --git a/shared/src/business/useCases/validatePenaltiesInteractor.ts b/shared/src/business/useCases/validatePenaltiesInteractor.ts index bdc7d7eb25b..f266fc92681 100644 --- a/shared/src/business/useCases/validatePenaltiesInteractor.ts +++ b/shared/src/business/useCases/validatePenaltiesInteractor.ts @@ -4,7 +4,5 @@ export const validatePenaltiesInteractor = ( applicationContext: IApplicationContext, { rawPenalty }: { rawPenalty: object }, ): Record | null => { - return new Penalty(rawPenalty, { - applicationContext, - }).getFormattedValidationErrors(); + return new Penalty(rawPenalty).getFormattedValidationErrors(); }; diff --git a/shared/src/business/useCases/validatePetitionFromPaperInteractor.test.ts b/shared/src/business/useCases/validatePetitionFromPaperInteractor.test.ts index 34fe0518615..c765e742cae 100644 --- a/shared/src/business/useCases/validatePetitionFromPaperInteractor.test.ts +++ b/shared/src/business/useCases/validatePetitionFromPaperInteractor.test.ts @@ -5,12 +5,13 @@ import { PARTY_TYPES, PAYMENT_STATUS, } from '../entities/EntityConstants'; -import { applicationContext } from '../test/createTestApplicationContext'; +import { createISODateString } from '@shared/business/utilities/DateHandler'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { validatePetitionFromPaperInteractor } from './validatePetitionFromPaperInteractor'; describe('validate petition from paper', () => { it('returns the expected errors object on an empty petition', () => { - const errors = validatePetitionFromPaperInteractor(applicationContext, { + const errors = validatePetitionFromPaperInteractor(mockDocketClerkUser, { petition: {}, }); @@ -28,7 +29,7 @@ describe('validate petition from paper', () => { }); it('returns null if no errors exist', () => { - const errors = validatePetitionFromPaperInteractor(applicationContext, { + const errors = validatePetitionFromPaperInteractor(mockDocketClerkUser, { petition: { archivedDocketEntries: [], caseCaption: 'testing', @@ -54,7 +55,7 @@ describe('validate petition from paper', () => { }, ], procedureType: 'Regular', - receivedAt: applicationContext.getUtilities().createISODateString(), + receivedAt: createISODateString(), }, }); diff --git a/shared/src/business/useCases/validatePetitionFromPaperInteractor.ts b/shared/src/business/useCases/validatePetitionFromPaperInteractor.ts index 26a18d48276..b58e106123b 100644 --- a/shared/src/business/useCases/validatePetitionFromPaperInteractor.ts +++ b/shared/src/business/useCases/validatePetitionFromPaperInteractor.ts @@ -1,3 +1,4 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { PaperPetition } from '../entities/cases/PaperPetition'; /** @@ -9,11 +10,11 @@ import { PaperPetition } from '../entities/cases/PaperPetition'; * @returns {object} errors (null if no errors) */ export const validatePetitionFromPaperInteractor = ( - applicationContext: IApplicationContext, + authorizedUser: AuthUser, { petition }: { petition: any }, ) => { const errors = new PaperPetition(petition, { - applicationContext, + authorizedUser, }).getFormattedValidationErrors(); return errors || null; }; diff --git a/shared/src/business/useCases/validatePetitionInteractor.ts b/shared/src/business/useCases/validatePetitionInteractor.ts index adf58817577..72f4730b5f7 100644 --- a/shared/src/business/useCases/validatePetitionInteractor.ts +++ b/shared/src/business/useCases/validatePetitionInteractor.ts @@ -4,7 +4,5 @@ export const validatePetitionInteractor = ( applicationContext: IApplicationContext, { petition }: { petition: any }, ) => { - return new ElectronicPetition(petition, { - applicationContext, - }).getFormattedValidationErrors(); + return new ElectronicPetition(petition).getFormattedValidationErrors(); }; diff --git a/shared/src/business/useCases/validatePetitionerInformationFormInteractor.ts b/shared/src/business/useCases/validatePetitionerInformationFormInteractor.ts index e4a399befcf..9478de1b40c 100644 --- a/shared/src/business/useCases/validatePetitionerInformationFormInteractor.ts +++ b/shared/src/business/useCases/validatePetitionerInformationFormInteractor.ts @@ -25,7 +25,6 @@ export const validatePetitionerInformationFormInteractor = ( }, ) => { const contacts = ContactFactory({ - applicationContext, contactInfo: { primary: contactPrimary, secondary: contactSecondary }, partyType, }); diff --git a/shared/src/business/useCases/validatePetitionerInteractor.ts b/shared/src/business/useCases/validatePetitionerInteractor.ts index f73daf322c5..250f6d0c6ce 100644 --- a/shared/src/business/useCases/validatePetitionerInteractor.ts +++ b/shared/src/business/useCases/validatePetitionerInteractor.ts @@ -23,9 +23,9 @@ export const validatePetitionerInteractor = ( existingPetitioners: TPetitioner[]; }, ) => { - const contactErrors = new Petitioner(contactInfo, { - applicationContext, - }).getFormattedValidationErrors(); + const contactErrors = new Petitioner( + contactInfo, + ).getFormattedValidationErrors(); let updateUserEmailErrors; if (contactInfo.updatedEmail || contactInfo.confirmEmail) { diff --git a/shared/src/business/utilities/caseFilter.test.ts b/shared/src/business/utilities/caseFilter.test.ts index d8ebbda39e5..2649e92791f 100644 --- a/shared/src/business/utilities/caseFilter.test.ts +++ b/shared/src/business/utilities/caseFilter.test.ts @@ -8,6 +8,12 @@ import { caseSealedFormatter, caseSearchFilter, } from './caseFilter'; +import { + mockIrsPractitionerUser, + mockIrsSuperuser, + mockPetitionsClerkUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; describe('caseFilter', () => { it('should format sealed cases to preserve ONLY attributes appearing in a whitelist', () => { @@ -167,10 +173,10 @@ describe('caseFilter', () => { ]; it('should remove sealed cases from a set of advanced search results', () => { - const result = caseSearchFilter(caseSearchResults, { - role: ROLES.irsPractitioner, - userId: '0e69052d-b59d-496e-ba2a-39af3a9535dc', - }); + const result = caseSearchFilter( + caseSearchResults, + mockIrsPractitionerUser, + ); expect(result).toMatchObject([ { @@ -184,10 +190,7 @@ describe('caseFilter', () => { }); it('should format sealed addresses in search results if user does not have permission to see sealed contact addresses', () => { - let result = caseSearchFilter(caseSearchResults, { - role: ROLES.petitionsClerk, - userId: 'petitionsClerk', - }); + let result = caseSearchFilter(caseSearchResults, mockPetitionsClerkUser); expect(result.length).toEqual(4); expect(result[2].petitioners[0]).toMatchObject({ @@ -198,31 +201,27 @@ describe('caseFilter', () => { }); it('should keep sealed cases in search results if user is an internal user with permission to see sealed cases', () => { - let result = caseSearchFilter(caseSearchResults, { - role: ROLES.petitionsClerk, - userId: 'petitionsClerk', - }); + let result = caseSearchFilter(caseSearchResults, mockPetitionsClerkUser); expect(result.length).toEqual(4); }); it('should keep sealed cases in search results if user is an IRS superuser with permission to see sealed cases', () => { - let result = caseSearchFilter(caseSearchResults, { - role: ROLES.irsSuperuser, - userId: 'irsSuperuser', - }); + let result = caseSearchFilter(caseSearchResults, mockIrsSuperuser); expect(result.length).toEqual(4); }); it('should keep sealed cases in search results if user is associated as practitioner or respondent', () => { let result = caseSearchFilter(caseSearchResults, { + ...mockPrivatePractitionerUser, userId: 'authPractitioner', }); expect(result.length).toEqual(4); result = caseSearchFilter(caseSearchResults, { + ...mockPrivatePractitionerUser, userId: 'authRespondent', }); @@ -230,9 +229,10 @@ describe('caseFilter', () => { }); it('should filter out sealed documents in search results when the user is not associated with the case', () => { - const result = caseSearchFilter(documentSearchResults, { - userId: 'unassociatedPractitioner', - }); + const result = caseSearchFilter( + documentSearchResults, + mockPrivatePractitionerUser, + ); expect(result.length).toEqual(1); expect(result[0].docketEntryId).toEqual(unsealedDocketEntryId); @@ -240,6 +240,7 @@ describe('caseFilter', () => { it('should NOT filter out sealed documents in search results when the user is associated with the case', () => { const result = caseSearchFilter(documentSearchResults, { + ...mockPrivatePractitionerUser, userId: 'associatedPractitioner', }); diff --git a/shared/src/business/utilities/caseFilter.ts b/shared/src/business/utilities/caseFilter.ts index 7772f2bdb19..7037669d23f 100644 --- a/shared/src/business/utilities/caseFilter.ts +++ b/shared/src/business/utilities/caseFilter.ts @@ -1,3 +1,4 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { ROLE_PERMISSIONS, isAuthorized, @@ -75,7 +76,7 @@ export const caseContactAddressSealedFormatter = (caseRaw, currentUser) => { return formattedCase; }; -export const caseSearchFilter = (searchResults, currentUser) => { +export const caseSearchFilter = (searchResults, currentUser: AuthUser) => { return searchResults .filter( searchResult => diff --git a/shared/src/business/utilities/documentGenerators/caseInventoryReport.ts b/shared/src/business/utilities/documentGenerators/caseInventoryReport.ts index 71b15c0d458..824436773f0 100644 --- a/shared/src/business/utilities/documentGenerators/caseInventoryReport.ts +++ b/shared/src/business/utilities/documentGenerators/caseInventoryReport.ts @@ -1,6 +1,7 @@ import { CaseInventoryReport } from '@shared/business/utilities/pdfGenerator/documentTemplates/CaseInventoryReport'; import { DatePrintedFooter } from '@shared/business/utilities/pdfGenerator/components/DatePrintedFooter'; import { ReportsMetaHeader } from '@shared/business/utilities/pdfGenerator/components/ReportsMetaHeader'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { generateHTMLTemplateForPDF } from '../generateHTMLTemplateForPDF/generateHTMLTemplateForPDF'; import React from 'react'; import ReactDOM from 'react-dom/server'; @@ -9,7 +10,7 @@ export const caseInventoryReport = async ({ applicationContext, data, }: { - applicationContext: IApplicationContext; + applicationContext: ServerApplicationContext; data: { formattedCases: { isLeadCase: boolean; diff --git a/shared/src/business/utilities/documentGenerators/noticeOfChangeOfTrialJudge.ts b/shared/src/business/utilities/documentGenerators/noticeOfChangeOfTrialJudge.ts index de45ad090e0..b204a9e39f2 100644 --- a/shared/src/business/utilities/documentGenerators/noticeOfChangeOfTrialJudge.ts +++ b/shared/src/business/utilities/documentGenerators/noticeOfChangeOfTrialJudge.ts @@ -1,6 +1,7 @@ import { DateServedFooter } from '@shared/business/utilities/pdfGenerator/components/DateServedFooter'; import { FormattedTrialInfoType } from '@web-api/business/useCases/trialSessions/generateNoticeOfTrialIssuedInteractor'; import { NoticeOfChangeOfTrialJudge } from '@shared/business/utilities/pdfGenerator/documentTemplates/NoticeOfChangeOfTrialJudge'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { generateHTMLTemplateForPDF } from '../generateHTMLTemplateForPDF/generateHTMLTemplateForPDF'; import React from 'react'; import ReactDOM from 'react-dom/server'; @@ -9,7 +10,7 @@ export const noticeOfChangeOfTrialJudge = async ({ applicationContext, data, }: { - applicationContext: IApplicationContext; + applicationContext: ServerApplicationContext; data: { caseCaptionExtension: string; caseTitle: string; @@ -18,7 +19,7 @@ export const noticeOfChangeOfTrialJudge = async ({ titleOfClerk: string; trialInfo: FormattedTrialInfoType; }; -}): Promise => { +}): Promise => { const { docketNumberWithSuffix } = data; const noticeOfChangeOfTrialJudgeTemplate = ReactDOM.renderToString( diff --git a/shared/src/business/utilities/documentGenerators/noticeOfChangeToInPersonProceeding.ts b/shared/src/business/utilities/documentGenerators/noticeOfChangeToInPersonProceeding.ts index 265fbc3c2b4..e0f8e94b72c 100644 --- a/shared/src/business/utilities/documentGenerators/noticeOfChangeToInPersonProceeding.ts +++ b/shared/src/business/utilities/documentGenerators/noticeOfChangeToInPersonProceeding.ts @@ -1,6 +1,7 @@ import { DateServedFooter } from '@shared/business/utilities/pdfGenerator/components/DateServedFooter'; -import { FormattedTrialInfo } from '@web-api/business/useCases/trialSessions/generateNoticeOfChangeOfTrialJudgeInteractor'; +import { FormattedTrialInfoType } from '@web-api/business/useCases/trialSessions/generateNoticeOfTrialIssuedInteractor'; import { NoticeOfChangeToInPersonProceeding } from '@shared/business/utilities/pdfGenerator/documentTemplates/NoticeOfChangeToInPersonProceeding'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { generateHTMLTemplateForPDF } from '../generateHTMLTemplateForPDF/generateHTMLTemplateForPDF'; import React from 'react'; import ReactDOM from 'react-dom/server'; @@ -9,16 +10,16 @@ export const noticeOfChangeToInPersonProceeding = async ({ applicationContext, data, }: { - applicationContext: IApplicationContext; + applicationContext: ServerApplicationContext; data: { caseCaptionExtension: string; caseTitle: string; docketNumberWithSuffix: string; nameOfClerk: string; titleOfClerk: string; - trialInfo: FormattedTrialInfo; + trialInfo: FormattedTrialInfoType; }; -}): Promise => { +}): Promise => { const noticeOfChangeToInPersonProceedingTemplate = ReactDOM.renderToString( React.createElement(NoticeOfChangeToInPersonProceeding, data), ); diff --git a/shared/src/business/utilities/documentGenerators/noticeOfChangeToRemoteProceeding.ts b/shared/src/business/utilities/documentGenerators/noticeOfChangeToRemoteProceeding.ts index 192fd9452ca..eb11e92a5ed 100644 --- a/shared/src/business/utilities/documentGenerators/noticeOfChangeToRemoteProceeding.ts +++ b/shared/src/business/utilities/documentGenerators/noticeOfChangeToRemoteProceeding.ts @@ -1,5 +1,6 @@ import { DateServedFooter } from '@shared/business/utilities/pdfGenerator/components/DateServedFooter'; import { NoticeOfChangeToRemoteProceeding } from '@shared/business/utilities/pdfGenerator/documentTemplates/NoticeOfChangeToRemoteProceeding'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialInfoType } from '@web-api/business/useCases/trialSessions/generateNoticeOfChangeToRemoteProceedingInteractor'; import { generateHTMLTemplateForPDF } from '../generateHTMLTemplateForPDF/generateHTMLTemplateForPDF'; import React from 'react'; @@ -9,7 +10,7 @@ export const noticeOfChangeToRemoteProceeding = async ({ applicationContext, data, }: { - applicationContext: IApplicationContext; + applicationContext: ServerApplicationContext; data: { nameOfClerk: string; titleOfClerk: string; @@ -18,7 +19,7 @@ export const noticeOfChangeToRemoteProceeding = async ({ docketNumberWithSuffix: string; trialInfo: TrialInfoType; }; -}): Promise => { +}): Promise => { const { docketNumberWithSuffix } = data; const noticeOfChangeToRemoteProceedingTemplate = ReactDOM.renderToString( diff --git a/shared/src/business/utilities/documentGenerators/noticeOfDocketChange.ts b/shared/src/business/utilities/documentGenerators/noticeOfDocketChange.ts index d07cd7002ed..033bd5c3eb2 100644 --- a/shared/src/business/utilities/documentGenerators/noticeOfDocketChange.ts +++ b/shared/src/business/utilities/documentGenerators/noticeOfDocketChange.ts @@ -1,4 +1,5 @@ import { NoticeOfDocketChange } from '@shared/business/utilities/pdfGenerator/documentTemplates/NoticeOfDocketChange'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { generateHTMLTemplateForPDF } from '../generateHTMLTemplateForPDF/generateHTMLTemplateForPDF'; import React from 'react'; import ReactDOM from 'react-dom/server'; @@ -7,7 +8,7 @@ export const noticeOfDocketChange = async ({ applicationContext, data, }: { - applicationContext: IApplicationContext; + applicationContext: ServerApplicationContext; data: { nameOfClerk: string; titleOfClerk: string; diff --git a/shared/src/business/utilities/documentGenerators/noticeOfReceiptOfPetition.ts b/shared/src/business/utilities/documentGenerators/noticeOfReceiptOfPetition.ts index 16787e548e5..88e00ed25b0 100644 --- a/shared/src/business/utilities/documentGenerators/noticeOfReceiptOfPetition.ts +++ b/shared/src/business/utilities/documentGenerators/noticeOfReceiptOfPetition.ts @@ -1,5 +1,6 @@ import { NoticeOfReceiptOfPetition } from '@shared/business/utilities/pdfGenerator/documentTemplates/NoticeOfReceiptOfPetition'; import { RawContact } from '@shared/business/entities/contacts/Contact'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { generateHTMLTemplateForPDF } from '../generateHTMLTemplateForPDF/generateHTMLTemplateForPDF'; import React from 'react'; import ReactDOM from 'react-dom/server'; @@ -8,7 +9,7 @@ export const noticeOfReceiptOfPetition = async ({ applicationContext, data, }: { - applicationContext: IApplicationContext; + applicationContext: ServerApplicationContext; data: { accessCode?: string; caseCaptionExtension: string; diff --git a/shared/src/business/utilities/documentGenerators/noticeOfTrialIssued.ts b/shared/src/business/utilities/documentGenerators/noticeOfTrialIssued.ts index cc89bb1f468..eac8c66cb02 100644 --- a/shared/src/business/utilities/documentGenerators/noticeOfTrialIssued.ts +++ b/shared/src/business/utilities/documentGenerators/noticeOfTrialIssued.ts @@ -1,5 +1,6 @@ import { DateServedFooter } from '@shared/business/utilities/pdfGenerator/components/DateServedFooter'; import { NoticeOfTrialIssued } from '@shared/business/utilities/pdfGenerator/documentTemplates/NoticeOfTrialIssued'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialInfoType } from '@web-api/business/useCases/trialSessions/generateNoticeOfChangeToRemoteProceedingInteractor'; import { generateHTMLTemplateForPDF } from '../generateHTMLTemplateForPDF/generateHTMLTemplateForPDF'; import React from 'react'; @@ -9,7 +10,7 @@ export const noticeOfTrialIssued = async ({ applicationContext, data, }: { - applicationContext: IApplicationContext; + applicationContext: ServerApplicationContext; data: { nameOfClerk: string; titleOfClerk: string; diff --git a/shared/src/business/utilities/documentGenerators/noticeOfTrialIssuedInPerson.ts b/shared/src/business/utilities/documentGenerators/noticeOfTrialIssuedInPerson.ts index 478cca32570..23f9c7ac146 100644 --- a/shared/src/business/utilities/documentGenerators/noticeOfTrialIssuedInPerson.ts +++ b/shared/src/business/utilities/documentGenerators/noticeOfTrialIssuedInPerson.ts @@ -1,6 +1,7 @@ import { DateServedFooter } from '@shared/business/utilities/pdfGenerator/components/DateServedFooter'; import { FormattedTrialInfoType } from '@web-api/business/useCases/trialSessions/generateNoticeOfTrialIssuedInteractor'; import { NoticeOfTrialIssuedInPerson } from '@shared/business/utilities/pdfGenerator/documentTemplates/NoticeOfTrialIssuedInPerson'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { generateHTMLTemplateForPDF } from '../generateHTMLTemplateForPDF/generateHTMLTemplateForPDF'; import React from 'react'; import ReactDOM from 'react-dom/server'; @@ -9,7 +10,7 @@ export const noticeOfTrialIssuedInPerson = async ({ applicationContext, data, }: { - applicationContext: IApplicationContext; + applicationContext: ServerApplicationContext; data: { nameOfClerk: string; titleOfClerk: string; diff --git a/shared/src/business/utilities/documentGenerators/order.ts b/shared/src/business/utilities/documentGenerators/order.ts index 80d006ea99c..c74db18c9d0 100644 --- a/shared/src/business/utilities/documentGenerators/order.ts +++ b/shared/src/business/utilities/documentGenerators/order.ts @@ -1,5 +1,6 @@ import { Order } from '@shared/business/utilities/pdfGenerator/documentTemplates/Order'; import { PageMetaHeaderDocket } from '@shared/business/utilities/pdfGenerator/components/PageMetaHeaderDocket'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { generateHTMLTemplateForPDF } from '../generateHTMLTemplateForPDF/generateHTMLTemplateForPDF'; import React from 'react'; import ReactDOM from 'react-dom/server'; @@ -8,7 +9,7 @@ export const order = async ({ applicationContext, data, }: { - applicationContext: IApplicationContext; + applicationContext: ServerApplicationContext; data: { caseCaptionExtension: string; caseTitle: string; diff --git a/shared/src/business/utilities/documentGenerators/pendingReport.ts b/shared/src/business/utilities/documentGenerators/pendingReport.ts index 633874a2ce8..637d30f4b83 100644 --- a/shared/src/business/utilities/documentGenerators/pendingReport.ts +++ b/shared/src/business/utilities/documentGenerators/pendingReport.ts @@ -2,6 +2,7 @@ import { DatePrintedFooter } from '@shared/business/utilities/pdfGenerator/compo import { PendingItemFormatted } from '@shared/business/utilities/formatPendingItem'; import { PendingReport } from '@shared/business/utilities/pdfGenerator/documentTemplates/PendingReport'; import { ReportsMetaHeader } from '@shared/business/utilities/pdfGenerator/components/ReportsMetaHeader'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { generateHTMLTemplateForPDF } from '../generateHTMLTemplateForPDF/generateHTMLTemplateForPDF'; import React from 'react'; import ReactDOM from 'react-dom/server'; @@ -10,12 +11,12 @@ export const pendingReport = async ({ applicationContext, data, }: { - applicationContext: IApplicationContext; + applicationContext: ServerApplicationContext; data: { pendingItems: PendingItemFormatted[]; subtitle: string; }; -}): Promise => { +}): Promise => { const { pendingItems, subtitle } = data; const pendingReportTemplate = ReactDOM.renderToString( diff --git a/shared/src/business/utilities/documentGenerators/petition.ts b/shared/src/business/utilities/documentGenerators/petition.ts index 4554341da9b..49f76330ae3 100644 --- a/shared/src/business/utilities/documentGenerators/petition.ts +++ b/shared/src/business/utilities/documentGenerators/petition.ts @@ -3,6 +3,7 @@ import { PetitionPdfBase, } from '@shared/business/useCases/generatePetitionPdfInteractor'; import { Petition } from '@shared/business/utilities/pdfGenerator/documentTemplates/Petition'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { generateHTMLTemplateForPDF } from '../generateHTMLTemplateForPDF/generateHTMLTemplateForPDF'; import React from 'react'; import ReactDOM from 'react-dom/server'; @@ -11,7 +12,7 @@ export const petition = async ({ applicationContext, data, }: { - applicationContext: IApplicationContext; + applicationContext: ServerApplicationContext; data: PetitionPdfBase & { caseDescription: string; irsNotices: IrsNoticesWithCaseDescription[]; diff --git a/shared/src/business/utilities/documentGenerators/thirtyDayNoticeOfTrial.ts b/shared/src/business/utilities/documentGenerators/thirtyDayNoticeOfTrial.ts index 74f23697629..2b585b75913 100644 --- a/shared/src/business/utilities/documentGenerators/thirtyDayNoticeOfTrial.ts +++ b/shared/src/business/utilities/documentGenerators/thirtyDayNoticeOfTrial.ts @@ -1,4 +1,5 @@ import { DateServedFooter } from '@shared/business/utilities/pdfGenerator/components/DateServedFooter'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { ThirtyDayNoticeOfTrial, ThirtyDayNoticeOfTrialRequiredInfo, @@ -11,9 +12,9 @@ export const thirtyDayNoticeOfTrial = async ({ applicationContext, data, }: { - applicationContext: IApplicationContext; + applicationContext: ServerApplicationContext; data: ThirtyDayNoticeOfTrialRequiredInfo; -}): Promise => { +}): Promise => { const thirtyDayNoticeOfTrialTemplate = ReactDOM.renderToString( React.createElement(ThirtyDayNoticeOfTrial, data), ); diff --git a/shared/src/business/utilities/documentGenerators/trialCalendar.ts b/shared/src/business/utilities/documentGenerators/trialCalendar.ts index f38c6e89bfa..f3ccfb608b5 100644 --- a/shared/src/business/utilities/documentGenerators/trialCalendar.ts +++ b/shared/src/business/utilities/documentGenerators/trialCalendar.ts @@ -1,6 +1,7 @@ import { DatePrintedFooter } from '@shared/business/utilities/pdfGenerator/components/DatePrintedFooter'; import { RawIrsCalendarAdministratorInfo } from '@shared/business/entities/trialSessions/IrsCalendarAdministratorInfo'; import { ReportsMetaHeader } from '@shared/business/utilities/pdfGenerator/components/ReportsMetaHeader'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialCalendar } from '@shared/business/utilities/pdfGenerator/documentTemplates/TrialCalendar'; import { TrialSessionProceedingType } from '@shared/business/entities/EntityConstants'; import { generateHTMLTemplateForPDF } from '../generateHTMLTemplateForPDF/generateHTMLTemplateForPDF'; @@ -46,9 +47,9 @@ export const trialCalendar = async ({ applicationContext, data, }: { - applicationContext: IApplicationContext; + applicationContext: ServerApplicationContext; data: TrialCalendarType; -}): Promise => { +}): Promise => { const { cases, sessionDetail } = data; const trialCalendarTemplate = ReactDOM.renderToString( diff --git a/shared/src/business/utilities/documentGenerators/trialSessionPlanningReport.ts b/shared/src/business/utilities/documentGenerators/trialSessionPlanningReport.ts index f3e70c7be87..57192b348ca 100644 --- a/shared/src/business/utilities/documentGenerators/trialSessionPlanningReport.ts +++ b/shared/src/business/utilities/documentGenerators/trialSessionPlanningReport.ts @@ -4,6 +4,7 @@ import { TrialLocationData, } from '@web-api/business/useCases/trialSessions/runTrialSessionPlanningReportInteractor'; import { ReportsMetaHeader } from '@shared/business/utilities/pdfGenerator/components/ReportsMetaHeader'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialSessionPlanningReport } from '@shared/business/utilities/pdfGenerator/documentTemplates/TrialSessionPlanningReport'; import { generateHTMLTemplateForPDF } from '../generateHTMLTemplateForPDF/generateHTMLTemplateForPDF'; import React from 'react'; @@ -13,13 +14,13 @@ export const trialSessionPlanningReport = async ({ applicationContext, data, }: { - applicationContext: IApplicationContext; + applicationContext: ServerApplicationContext; data: { locationData: TrialLocationData[]; previousTerms: PreviousTerm[]; term: string; }; -}): Promise => { +}): Promise => { const { locationData, previousTerms, term } = data; const trialSessionPlanningReportTemplate = ReactDOM.renderToString( diff --git a/shared/src/business/utilities/generateChangeOfAddressTemplate.ts b/shared/src/business/utilities/generateChangeOfAddressTemplate.ts index 11853d7421a..c87919cbc24 100644 --- a/shared/src/business/utilities/generateChangeOfAddressTemplate.ts +++ b/shared/src/business/utilities/generateChangeOfAddressTemplate.ts @@ -34,7 +34,15 @@ export const getAddressPhoneDiff = ({ newData, oldData }) => { * @param {object} providers.oldData the old contact information * @returns {string} documentType for the address / phone change scenario */ -export const getDocumentTypeForAddressChange = ({ diff, newData, oldData }) => { +export const getDocumentTypeForAddressChange = ({ + diff, + newData, + oldData, +}: { + diff?: any; + newData: any; + oldData: any; +}) => { let documentType; const initialDiff = diff || getAddressPhoneDiff({ newData, oldData }); diff --git a/shared/src/business/utilities/getFormattedCaseDetail.test.ts b/shared/src/business/utilities/getFormattedCaseDetail.test.ts index 9bc7b1cb9d6..e4aa9c014b3 100644 --- a/shared/src/business/utilities/getFormattedCaseDetail.test.ts +++ b/shared/src/business/utilities/getFormattedCaseDetail.test.ts @@ -1,42 +1,47 @@ import { CASE_STATUS_TYPES, PAYMENT_STATUS } from '../entities/EntityConstants'; import { MOCK_CASE } from '../../test/mockCase'; -import { MOCK_USERS } from '../../test/mockUsers'; -import { applicationContext } from '../../../../web-client/src/applicationContext'; +import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { formatCase, getFormattedCaseDetail } from './getFormattedCaseDetail'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('getFormattedCaseDetail', () => { - applicationContext.getCurrentUser = () => - MOCK_USERS['a7d90c05-f6cd-442c-a168-202db587f16f']; - const getDateISO = () => applicationContext.getUtilities().createISODateString(); describe('formatCase', () => { it('should set showPrintConfirmationLink to true for served cases without legacy docket entries', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - docketEntries: [ - { - ...MOCK_CASE.docketEntries[0], - servedAt: getDateISO(), - }, - ], - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + docketEntries: [ + { + ...MOCK_CASE.docketEntries[0], + servedAt: getDateISO(), + }, + ], + }, + mockDocketClerkUser, + ); expect(result.showPrintConfirmationLink).toBeTruthy(); }); it('should set showPrintConfirmationLink to false for served cases with legacy docket entries', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - docketEntries: [ - { - ...MOCK_CASE.docketEntries[0], - isLegacy: true, - servedAt: getDateISO(), - }, - ], - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + docketEntries: [ + { + ...MOCK_CASE.docketEntries[0], + isLegacy: true, + servedAt: getDateISO(), + }, + ], + }, + mockDocketClerkUser, + ); expect(result.showPrintConfirmationLink).toBeFalsy(); }); @@ -44,59 +49,71 @@ describe('getFormattedCaseDetail', () => { it('should return an empty object if caseDetail is empty', () => { const mockApplicationContext = {}; const caseDetail = {}; - const result = formatCase(mockApplicationContext, caseDetail); + const result = formatCase( + mockApplicationContext, + caseDetail, + mockDocketClerkUser, + ); expect(result).toMatchObject({}); }); it('should format the filing date of all correspondence documents', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - correspondence: [ - { - documentTitle: 'Test Correspondence', - filedBy: 'Test Docket Clerk', - filingDate: '2020-05-21T18:21:59.818Z', - }, - ], - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + correspondence: [ + { + documentTitle: 'Test Correspondence', + filedBy: 'Test Docket Clerk', + filingDate: '2020-05-21T18:21:59.818Z', + }, + ], + }, + mockDocketClerkUser, + ); expect(result.correspondence[0].formattedFilingDate).toEqual('05/21/20'); }); it('should return docket entries with pending and served documents for pendingItemsDocketEntries', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - docketEntries: [ - { - createdAt: getDateISO(), - docketEntryId: '47d9735b-ac41-4adf-8a3c-74d73d3622fb', - documentType: 'Administrative Record', - filingDate: getDateISO(), - index: '1', - isOnDocketRecord: true, - pending: true, - servedAt: '2019-08-25T05:00:00.000Z', - }, - { - createdAt: getDateISO(), - docketEntryId: 'dabe913f-5310-48df-b63d-44cfccb83326', - documentType: 'Administrative Record', - filingDate: getDateISO(), - index: '2', - isOnDocketRecord: true, - pending: true, - }, - { - createdAt: getDateISO(), - docketEntryId: '6936570f-04ad-40bf-b8a2-a7ac648c30c4', - documentType: 'Administrative Record', - filingDate: getDateISO(), - index: '3', - isOnDocketRecord: true, - }, - ], - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + docketEntries: [ + { + createdAt: getDateISO(), + docketEntryId: '47d9735b-ac41-4adf-8a3c-74d73d3622fb', + documentType: 'Administrative Record', + filingDate: getDateISO(), + index: '1', + isOnDocketRecord: true, + pending: true, + servedAt: '2019-08-25T05:00:00.000Z', + }, + { + createdAt: getDateISO(), + docketEntryId: 'dabe913f-5310-48df-b63d-44cfccb83326', + documentType: 'Administrative Record', + filingDate: getDateISO(), + index: '2', + isOnDocketRecord: true, + pending: true, + }, + { + createdAt: getDateISO(), + docketEntryId: '6936570f-04ad-40bf-b8a2-a7ac648c30c4', + documentType: 'Administrative Record', + filingDate: getDateISO(), + index: '3', + isOnDocketRecord: true, + }, + ], + }, + mockDocketClerkUser, + ); expect(result.pendingItemsDocketEntries).toMatchObject([ { @@ -106,16 +123,20 @@ describe('getFormattedCaseDetail', () => { }); it('should return docket entries with pending and isLegacyServed for pendingItemsDocketEntries', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - docketEntries: [ - { - ...MOCK_CASE.docketEntries[0], - isLegacyServed: true, - pending: true, - }, - ], - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + docketEntries: [ + { + ...MOCK_CASE.docketEntries[0], + isLegacyServed: true, + pending: true, + }, + ], + }, + mockDocketClerkUser, + ); expect(result.pendingItemsDocketEntries).toMatchObject([ { @@ -125,24 +146,32 @@ describe('getFormattedCaseDetail', () => { }); it('should return an empty array for formattedDocketEntries and pendingItemsDocketEntries if docketRecord does not exist', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - docketEntries: [], - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + docketEntries: [], + }, + mockDocketClerkUser, + ); expect(result.formattedDocketEntries).toEqual([]); expect(result.pendingItemsDocketEntries).toEqual([]); }); it('should format irsPractitioners if the irsPractitioners array is set', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - irsPractitioners: [ - { - name: 'Test Respondent', - }, - ], - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + irsPractitioners: [ + { + name: 'Test Respondent', + }, + ], + }, + mockDocketClerkUser, + ); expect(result.irsPractitioners[0].formattedName).toEqual( 'Test Respondent', @@ -150,16 +179,20 @@ describe('getFormattedCaseDetail', () => { }); it('should format privatePractitioners if the privatePractitioners array is set', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - privatePractitioners: [ - { - barNumber: 'b1234', - name: 'Test Practitioner', - representing: [MOCK_CASE.petitioners[0].contactId], - }, - ], - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + privatePractitioners: [ + { + barNumber: 'b1234', + name: 'Test Practitioner', + representing: [MOCK_CASE.petitioners[0].contactId], + }, + ], + }, + mockDocketClerkUser, + ); expect(result.privatePractitioners[0].formattedName).toEqual( 'Test Practitioner (b1234)', @@ -174,14 +207,18 @@ describe('getFormattedCaseDetail', () => { }); it('should format the general properties of case details', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - caseCaption: 'Johnny Joe Jacobson, Petitioner', - hasVerifiedIrsNotice: true, - irsNoticeDate: undefined, - preferredTrialCity: undefined, - trialTime: 11, - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + caseCaption: 'Johnny Joe Jacobson, Petitioner', + hasVerifiedIrsNotice: true, + irsNoticeDate: undefined, + preferredTrialCity: undefined, + trialTime: 11, + }, + mockDocketClerkUser, + ); expect(result).toHaveProperty('createdAtFormatted'); expect(result).toHaveProperty('receivedAtFormatted'); @@ -194,10 +231,14 @@ describe('getFormattedCaseDetail', () => { }); it('should format irs notice date', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - irsNoticeDate: getDateISO(), - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + irsNoticeDate: getDateISO(), + }, + mockDocketClerkUser, + ); expect(result.irsNoticeDateFormatted).toEqual( applicationContext @@ -207,22 +248,30 @@ describe('getFormattedCaseDetail', () => { }); it("should return 'No notice provided' when there is no irs notice date", () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - irsNoticeDate: undefined, - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + irsNoticeDate: undefined, + }, + mockDocketClerkUser, + ); expect(result.irsNoticeDateFormatted).toEqual('No notice provided'); }); describe('should indicate blocked status', () => { it('should format blockedDate and when blocked is true', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - blocked: true, - blockedDate: getDateISO(), - blockedReason: 'for reasons', - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + blocked: true, + blockedDate: getDateISO(), + blockedReason: 'for reasons', + }, + mockDocketClerkUser, + ); expect(result).toMatchObject({ blockedDateFormatted: applicationContext @@ -234,13 +283,17 @@ describe('getFormattedCaseDetail', () => { }); it('should format trial details if case status is calendared', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - status: CASE_STATUS_TYPES.calendared, - trialDate: '2011-11-11T05:00:00.000Z', - trialLocation: 'Boise, Idaho', - trialSessionId: '1f1aa3f7-e2e3-43e6-885d-4ce341588c76', - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + status: CASE_STATUS_TYPES.calendared, + trialDate: '2011-11-11T05:00:00.000Z', + trialLocation: 'Boise, Idaho', + trialSessionId: '1f1aa3f7-e2e3-43e6-885d-4ce341588c76', + }, + mockDocketClerkUser, + ); expect(result).toMatchObject({ formattedAssociatedJudge: 'Not assigned', @@ -254,13 +307,17 @@ describe('getFormattedCaseDetail', () => { }); it('should format trial details if case status is not calendared but the case has a trialSessionId', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - trialDate: '2011-11-11T05:00:00.000Z', - trialLocation: 'Boise, Idaho', - trialSessionId: '1f1aa3f7-e2e3-43e6-885d-4ce341588c76', - trialTime: '2:00', - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + trialDate: '2011-11-11T05:00:00.000Z', + trialLocation: 'Boise, Idaho', + trialSessionId: '1f1aa3f7-e2e3-43e6-885d-4ce341588c76', + trialTime: '2:00', + }, + mockDocketClerkUser, + ); expect(result).toMatchObject({ formattedAssociatedJudge: 'Not assigned', @@ -274,23 +331,27 @@ describe('getFormattedCaseDetail', () => { }); it('should format hearing details if the case has associated hearings', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - hearings: [ - { - judge: { - name: 'Judge Dredd', + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + hearings: [ + { + judge: { + name: 'Judge Dredd', + }, + startDate: '2011-11-11T05:00:00.000Z', + startTime: '10:00', + trialLocation: 'Megacity One', }, - startDate: '2011-11-11T05:00:00.000Z', - startTime: '10:00', - trialLocation: 'Megacity One', - }, - ], - status: CASE_STATUS_TYPES.calendared, - trialDate: '2011-11-11T05:00:00.000Z', - trialLocation: 'Boise, Idaho', - trialSessionId: '1f1aa3f7-e2e3-43e6-885d-4ce341588c76', - }); + ], + status: CASE_STATUS_TYPES.calendared, + trialDate: '2011-11-11T05:00:00.000Z', + trialLocation: 'Boise, Idaho', + trialSessionId: '1f1aa3f7-e2e3-43e6-885d-4ce341588c76', + }, + mockDocketClerkUser, + ); expect(result).toMatchObject({ formattedAssociatedJudge: 'Not assigned', @@ -317,13 +378,17 @@ describe('getFormattedCaseDetail', () => { }); it('should format trial details with incomplete trial information', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - status: CASE_STATUS_TYPES.calendared, - trialDate: undefined, - trialLocation: undefined, - trialSessionId: '1f1aa3f7-e2e3-43e6-885d-4ce341588c76', - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + status: CASE_STATUS_TYPES.calendared, + trialDate: undefined, + trialLocation: undefined, + trialSessionId: '1f1aa3f7-e2e3-43e6-885d-4ce341588c76', + }, + mockDocketClerkUser, + ); expect(result).toMatchObject({ formattedTrialCity: 'Not assigned', @@ -332,7 +397,11 @@ describe('getFormattedCaseDetail', () => { }); it('should show not scheduled section if case status is not calendared and case is not blocked', () => { - const result = formatCase(applicationContext, MOCK_CASE); + const result = formatCase( + applicationContext, + MOCK_CASE, + mockDocketClerkUser, + ); expect(result).toMatchObject({ showNotScheduled: true, @@ -340,39 +409,55 @@ describe('getFormattedCaseDetail', () => { }); it('should return showNotScheduled as true when the case has not been added to a trial session', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - status: CASE_STATUS_TYPES.closed, - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + status: CASE_STATUS_TYPES.closed, + }, + mockDocketClerkUser, + ); expect(result.showNotScheduled).toBeTruthy(); }); it('should return showNotScheduled as false when the case status is closed and has been added to a trial session', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - status: CASE_STATUS_TYPES.closed, - trialSessionId: '4f8bd637-fc3b-4073-85b4-388f22731854', - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + status: CASE_STATUS_TYPES.closed, + trialSessionId: '4f8bd637-fc3b-4073-85b4-388f22731854', + }, + mockDocketClerkUser, + ); expect(result.showNotScheduled).toBeFalsy(); }); it('should return showScheduled as true when case status is closed and has been added to a trial session', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - status: CASE_STATUS_TYPES.closed, - trialSessionId: '4f8bd637-fc3b-4073-85b4-388f22731854', - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + status: CASE_STATUS_TYPES.closed, + trialSessionId: '4f8bd637-fc3b-4073-85b4-388f22731854', + }, + mockDocketClerkUser, + ); expect(result.showScheduled).toBeTruthy(); }); it('should set defaults for formattedTrialDate and formattedAssociatedJudge and show the prioritized section if case is high priority', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - highPriority: true, - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + highPriority: true, + }, + mockDocketClerkUser, + ); expect(result).toMatchObject({ formattedAssociatedJudge: 'Not assigned', @@ -382,10 +467,14 @@ describe('getFormattedCaseDetail', () => { }); it("should set lead case attributes when the leadDocketNumber matches the current case's docketNumber", () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - leadDocketNumber: MOCK_CASE.docketNumber, - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + leadDocketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect(result).toMatchObject({ consolidatedIconTooltipText: 'Lead case', @@ -394,10 +483,14 @@ describe('getFormattedCaseDetail', () => { }); it("should not set lead case attributes when the leadDocketNumber does not match the current case's docket number", () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - leadDocketNumber: 'notthedocketNumber', - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + leadDocketNumber: 'notthedocketNumber', + }, + mockDocketClerkUser, + ); expect(result).toMatchObject({ consolidatedIconTooltipText: 'Consolidated case', @@ -406,10 +499,14 @@ describe('getFormattedCaseDetail', () => { }); it('should set consolidated cases if there are any', () => { - const result = formatCase(applicationContext, { - ...MOCK_CASE, - consolidatedCases: [MOCK_CASE], - }); + const result = formatCase( + applicationContext, + { + ...MOCK_CASE, + consolidatedCases: [MOCK_CASE], + }, + mockDocketClerkUser, + ); expect(result).toHaveProperty('consolidatedCases'); expect(result.consolidatedCases).toMatchObject([MOCK_CASE]); @@ -420,6 +517,7 @@ describe('getFormattedCaseDetail', () => { it('should call formatCase and add additional details on the given case', () => { const result = getFormattedCaseDetail({ applicationContext, + authorizedUser: undefined, caseDetail: { ...MOCK_CASE }, docketRecordSort: 'byDate', }); @@ -432,6 +530,7 @@ describe('getFormattedCaseDetail', () => { it('should format draft documents', () => { const result = getFormattedCaseDetail({ applicationContext, + authorizedUser: undefined, caseDetail: { ...MOCK_CASE, docketEntries: [ @@ -483,6 +582,7 @@ describe('getFormattedCaseDetail', () => { it('should sort draft documents by their receivedAt', () => { const result = getFormattedCaseDetail({ applicationContext, + authorizedUser: undefined, caseDetail: { ...MOCK_CASE, docketEntries: [ @@ -519,6 +619,7 @@ describe('getFormattedCaseDetail', () => { it('should format filing fee string for a paid petition fee', () => { const result = getFormattedCaseDetail({ applicationContext, + authorizedUser: undefined, caseDetail: { ...MOCK_CASE, petitionPaymentDate: '2019-03-01T21:40:46.415Z', @@ -533,6 +634,7 @@ describe('getFormattedCaseDetail', () => { it('should format filing fee string for a waived petition fee', () => { const result = getFormattedCaseDetail({ applicationContext, + authorizedUser: undefined, caseDetail: { ...MOCK_CASE, petitionPaymentStatus: PAYMENT_STATUS.WAIVED, @@ -546,6 +648,7 @@ describe('getFormattedCaseDetail', () => { it('should format filing fee string for an unpaid petition fee', () => { const result = getFormattedCaseDetail({ applicationContext, + authorizedUser: undefined, caseDetail: { ...MOCK_CASE, petitionPaymentStatus: PAYMENT_STATUS.UNPAID, diff --git a/shared/src/business/utilities/getFormattedCaseDetail.ts b/shared/src/business/utilities/getFormattedCaseDetail.ts index 0b7fb461e04..5751e7d0c4e 100644 --- a/shared/src/business/utilities/getFormattedCaseDetail.ts +++ b/shared/src/business/utilities/getFormattedCaseDetail.ts @@ -7,7 +7,6 @@ import { TRANSCRIPT_EVENT_CODE, } from '../entities/EntityConstants'; import { Case } from '../entities/cases/Case'; -import { ClientApplicationContext } from '@web-client/applicationContext'; import { DocketEntry } from '../entities/DocketEntry'; import { FORMATS, @@ -15,6 +14,7 @@ import { combineISOandEasternTime, formatDateString, } from './DateHandler'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { cloneDeep, isEmpty, sortBy } from 'lodash'; const computeIsInProgress = ({ formattedEntry }) => { @@ -262,7 +262,11 @@ const getEditUrl = ({ : `/case-detail/${docketNumber}/edit-order/${docketEntryId}`; }; -export const formatCase = (applicationContext, caseDetail) => { +export const formatCase = ( + applicationContext, + caseDetail, + authorizedUser: UnknownAuthUser, +) => { if (isEmpty(caseDetail)) { return {}; } @@ -375,7 +379,9 @@ export const formatCase = (applicationContext, caseDetail) => { } result.filingFee = `${caseDetail.petitionPaymentStatus} ${paymentDate} ${paymentMethod}`; - const caseEntity = new Case(caseDetail, { applicationContext }); + const caseEntity = new Case(caseDetail, { + authorizedUser, + }); result.canConsolidate = caseEntity.canConsolidate(); result.canUnconsolidate = !!caseEntity.leadDocketNumber; result.irsSendDate = caseEntity.getIrsSendDate(); @@ -385,7 +391,7 @@ export const formatCase = (applicationContext, caseDetail) => { if (result.consolidatedCases) { result.consolidatedCases = result.consolidatedCases.map( consolidatedCase => { - return formatCase(applicationContext, consolidatedCase); + return formatCase(applicationContext, consolidatedCase, authorizedUser); }, ); } @@ -479,20 +485,23 @@ export const sortDocketEntries = ( return docketEntries.sort(sortUndefined); }; +// Used by both front and backend export const getFormattedCaseDetail = ({ applicationContext, + authorizedUser, caseDetail, docketRecordSort, }: { - applicationContext: ClientApplicationContext; + applicationContext: IApplicationContext; caseDetail: RawCase; docketRecordSort?: string; + authorizedUser: UnknownAuthUser; }) => { const result = { ...applicationContext .getUtilities() .setServiceIndicatorsForCase(caseDetail), - ...formatCase(applicationContext, caseDetail), + ...formatCase(applicationContext, caseDetail, authorizedUser), }; result.formattedDocketEntries = sortDocketEntries( result.formattedDocketEntries, diff --git a/shared/src/business/utilities/serveCaseDocument.test.ts b/shared/src/business/utilities/serveCaseDocument.test.ts index d2fd959e31e..1fda5965c51 100644 --- a/shared/src/business/utilities/serveCaseDocument.test.ts +++ b/shared/src/business/utilities/serveCaseDocument.test.ts @@ -2,13 +2,14 @@ import { ATP_DOCKET_ENTRY } from '@shared/test/mockDocketEntry'; import { Case } from '../entities/cases/Case'; import { MOCK_CASE } from '../../test/mockCase'; import { applicationContext } from '../test/createTestApplicationContext'; +import { mockPetitionerUser } from '@shared/test/mockAuthUsers'; import { serveCaseDocument } from './serveCaseDocument'; describe('serveCaseDocument', () => { let mockCase; beforeEach(() => { - mockCase = new Case(MOCK_CASE, { applicationContext }); + mockCase = new Case(MOCK_CASE, { authorizedUser: mockPetitionerUser }); }); it('should not set as served or send service email for RQT when a file is not attached', async () => { @@ -30,7 +31,7 @@ describe('serveCaseDocument', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockPetitionerUser }, ); await serveCaseDocument({ @@ -64,7 +65,7 @@ describe('serveCaseDocument', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockPetitionerUser }, ); await serveCaseDocument({ @@ -94,7 +95,7 @@ describe('serveCaseDocument', () => { ...MOCK_CASE, docketEntries: [MOCK_CASE.docketEntries[1]], }, - { applicationContext }, + { authorizedUser: mockPetitionerUser }, ); await serveCaseDocument({ @@ -152,7 +153,7 @@ describe('serveCaseDocument', () => { }, ], }, - { applicationContext }, + { authorizedUser: undefined }, ); await serveCaseDocument({ diff --git a/shared/src/business/utilities/shouldAppendClinicLetter.test.ts b/shared/src/business/utilities/shouldAppendClinicLetter.test.ts index b5d749c9a06..1744e794e81 100644 --- a/shared/src/business/utilities/shouldAppendClinicLetter.test.ts +++ b/shared/src/business/utilities/shouldAppendClinicLetter.test.ts @@ -3,6 +3,7 @@ import { MOCK_CASE } from '../../test/mockCase'; import { MOCK_TRIAL_INPERSON } from '../../test/mockTrial'; import { applicationContext } from '../test/createTestApplicationContext'; import { getClinicLetterKey } from './getClinicLetterKey'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { shouldAppendClinicLetter } from './shouldAppendClinicLetter'; jest.mock('./getClinicLetterKey'); @@ -15,7 +16,7 @@ describe('shouldAppendClinicLetter', () => { ...MOCK_CASE, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -67,7 +68,7 @@ describe('shouldAppendClinicLetter', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/shared/src/proxies/documents/submitCaseAssociationRequestProxy.ts b/shared/src/proxies/documents/submitCaseAssociationRequestProxy.ts index 167dc7c3d20..9f9fc90c785 100644 --- a/shared/src/proxies/documents/submitCaseAssociationRequestProxy.ts +++ b/shared/src/proxies/documents/submitCaseAssociationRequestProxy.ts @@ -14,18 +14,19 @@ export const submitCaseAssociationRequestInteractor = ( { docketNumber, filers, + userId, }: { docketNumber: string; + userId: string; filers?: string[]; }, ) => { - const user = applicationContext.getCurrentUser(); return put({ applicationContext, body: { docketNumber, filers, }, - endpoint: `/users/${user.userId}/case/${docketNumber}`, + endpoint: `/users/${userId}/case/${docketNumber}`, }); }; diff --git a/shared/src/proxies/documents/submitPendingCaseAssociationRequestProxy.ts b/shared/src/proxies/documents/submitPendingCaseAssociationRequestProxy.ts index 14746b266eb..20727497a39 100644 --- a/shared/src/proxies/documents/submitPendingCaseAssociationRequestProxy.ts +++ b/shared/src/proxies/documents/submitPendingCaseAssociationRequestProxy.ts @@ -10,11 +10,10 @@ import { put } from '../requests'; */ export const submitPendingCaseAssociationRequestInteractor = ( applicationContext, - { docketNumber }, + { docketNumber, userId }: { docketNumber: string; userId: string }, ) => { - const user = applicationContext.getCurrentUser(); return put({ applicationContext, - endpoint: `/users/${user.userId}/case/${docketNumber}/pending`, + endpoint: `/users/${userId}/case/${docketNumber}/pending`, }); }; diff --git a/shared/src/proxies/requests.ts b/shared/src/proxies/requests.ts index 026422bec76..d2236b2549a 100644 --- a/shared/src/proxies/requests.ts +++ b/shared/src/proxies/requests.ts @@ -3,6 +3,14 @@ import moize from 'moize'; const MAX_RETRIES = 10; +let token: string = ''; +export const getCurrentUserToken = (): string => { + return token; +}; +export const setCurrentUserToken = (newToken: string) => { + token = newToken; +}; + /** * *head @@ -16,7 +24,7 @@ export const head = async ({ applicationContext, endpoint, params }) => { return await applicationContext .getHttpClient() .head(`${applicationContext.getBaseUrl()}${endpoint}`, { - headers: getDefaultHeaders(applicationContext.getCurrentUserToken()), + headers: getDefaultHeaders(getCurrentUserToken()), params, }) .then(response => response.data); @@ -61,7 +69,7 @@ export const getResponse = ({ applicationContext, endpoint, params }) => { return applicationContext .getHttpClient() .get(`${applicationContext.getBaseUrl()}${endpoint}`, { - headers: getDefaultHeaders(applicationContext.getCurrentUserToken()), + headers: getDefaultHeaders(getCurrentUserToken()), params, }); }; @@ -102,7 +110,7 @@ export const post = async ({ .getHttpClient() .post(`${applicationContext.getBaseUrl()}${endpoint}`, body, { headers: { - ...getDefaultHeaders(applicationContext.getCurrentUserToken()), + ...getDefaultHeaders(getCurrentUserToken()), ...headers, Asyncsyncid: asyncSyncId, }, @@ -179,7 +187,7 @@ export const put = async ({ .getHttpClient() .put(`${applicationContext.getBaseUrl()}${endpoint}`, body, { headers: { - ...getDefaultHeaders(applicationContext.getCurrentUserToken()), + ...getDefaultHeaders(getCurrentUserToken()), Asyncsyncid: asyncSyncId, }, }) @@ -230,7 +238,7 @@ export const remove = async ({ return await applicationContext .getHttpClient() .delete(`${applicationContext.getBaseUrl()}${endpoint}`, { - headers: getDefaultHeaders(applicationContext.getCurrentUserToken()), + headers: getDefaultHeaders(getCurrentUserToken()), params, ...options, }) diff --git a/shared/src/proxies/users/getUserProxy.ts b/shared/src/proxies/users/getUserProxy.ts index c84743368f4..33bb46f4ede 100644 --- a/shared/src/proxies/users/getUserProxy.ts +++ b/shared/src/proxies/users/getUserProxy.ts @@ -1,3 +1,4 @@ +import { GetUserResponse } from '@shared/business/useCases/getUserInteractor'; import { get } from '../requests'; /** @@ -7,7 +8,9 @@ import { get } from '../requests'; * @param {object} providers the providers object * @returns {Promise<*>} the promise of the api call */ -export const getUserInteractor = applicationContext => { +export const getUserInteractor = ( + applicationContext, +): Promise => { return get({ applicationContext, endpoint: '/users', diff --git a/shared/src/proxies/verifyPendingCaseForUserProxy.ts b/shared/src/proxies/verifyPendingCaseForUserProxy.ts index bd42dd42bec..245a7a5b110 100644 --- a/shared/src/proxies/verifyPendingCaseForUserProxy.ts +++ b/shared/src/proxies/verifyPendingCaseForUserProxy.ts @@ -10,11 +10,10 @@ import { get } from './requests'; */ export const verifyPendingCaseForUserInteractor = ( applicationContext, - { docketNumber }, + { docketNumber, userId }: { docketNumber: string; userId: string }, ) => { - const user = applicationContext.getCurrentUser(); return get({ applicationContext, - endpoint: `/users/${user.userId}/case/${docketNumber}/pending`, + endpoint: `/users/${userId}/case/${docketNumber}/pending`, }); }; diff --git a/shared/src/test/mockUsers.ts b/shared/src/test/mockUsers.ts index 1df9c4170e1..8c7871e854b 100644 --- a/shared/src/test/mockUsers.ts +++ b/shared/src/test/mockUsers.ts @@ -19,6 +19,7 @@ import { } from '../../../web-client/src/business/chambers/getJudgesChambers'; export const adminUser: RawUser = { + email: 'admin@example.com', entityName: 'User', name: 'Test admin', role: ROLES.admin, @@ -26,13 +27,15 @@ export const adminUser: RawUser = { }; export const adcUser = { + email: 'adc@example.com', name: 'ADC', role: ROLES.adc, section: ADC_SECTION, - userId: 'g7d90c05-f6cd-442c-a168-202db587f16f', + userId: '9f357f78-a8fa-40bf-83db-8144ddf14047', }; export const colvinsChambersUser = { + email: 'chambers@e.mail', name: 'Chandler Chambers', role: ROLES.chambers, section: getJudgesChambers().COLVINS_CHAMBERS_SECTION.section, @@ -40,6 +43,8 @@ export const colvinsChambersUser = { }; export const clerkOfCourtUser = { + email: 'theClerkUser@example.com', + name: 'Caster Clerk', role: ROLES.clerkOfCourt, userId: 'b6e4a5ac-c006-4b47-a5f0-67028372cd63', }; @@ -139,6 +144,7 @@ export const judgeColvin: RawUser = { }; export const petitionerUser = { + email: 'petitioner@example.com', name: 'Tax Payer', role: ROLES.petitioner, section: 'petitioner', @@ -147,6 +153,7 @@ export const petitionerUser = { export const privatePractitionerUser = { barNumber: 'BN1234', + email: 'privatePractitioner@example.com', name: 'Private Practitioner', role: ROLES.privatePractitioner, section: 'privatePractitioner', @@ -163,6 +170,7 @@ export const trialClerkUser: RawUser = { }; export const caseServicesSupervisorUser = { + email: 'caseservicessupervisor@example.com', name: 'Test Case Services Supervisor', role: ROLES.caseServicesSupervisor, section: CASE_SERVICES_SUPERVISOR_SECTION, @@ -170,6 +178,7 @@ export const caseServicesSupervisorUser = { }; export const docketClerkUser = { + email: 'theDocketMocket@example.com', name: 'Docketclerk', role: ROLES.docketClerk, section: DOCKET_SECTION, @@ -195,6 +204,7 @@ export const petitionsClerkUser: RawUser = { }; export const admissionsClerkUser = { + email: 'admissionsClerk@example.com', name: 'AdmissionsClerk', role: ROLES.admissionsClerk, section: ADMISSIONS_SECTION, diff --git a/web-api/hostedEnvironmentTests/irsSuperUser.test.ts b/web-api/hostedEnvironmentTests/irsSuperUser.test.ts index 38530bb653c..dd12d73f3d3 100644 --- a/web-api/hostedEnvironmentTests/irsSuperUser.test.ts +++ b/web-api/hostedEnvironmentTests/irsSuperUser.test.ts @@ -139,10 +139,22 @@ async function createUserInIrsPool({ await cognito.adminCreateUser({ TemporaryPassword: password, UserAttributes: [ + { + Name: 'name', + Value: 'irsSuperUser CI/CD', + }, + { + Name: 'custom:userId', + Value: '37808c8c-e658-4ff9-a57e-bbb64f0e6065', + }, { Name: 'custom:role', Value: ROLES.irsSuperuser, }, + { + Name: 'custom:userId', + Value: '14de78aa-b148-4a55-a2a1-875253e414f3', + }, { Name: 'email', Value: userName, @@ -155,6 +167,7 @@ async function createUserInIrsPool({ UserPoolId: irsUserPoolId, Username: userName, }); + await cognito.adminSetUserPassword({ Password: password, Permanent: true, diff --git a/web-api/runtimes/puppeteer/web-api/runtimes/puppeteer/package-lock.json b/web-api/runtimes/puppeteer/web-api/runtimes/puppeteer/package-lock.json deleted file mode 100644 index 2f902f11643..00000000000 --- a/web-api/runtimes/puppeteer/web-api/runtimes/puppeteer/package-lock.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "puppeteer", - "lockfileVersion": 3, - "requires": true, - "packages": {} -} diff --git a/web-api/src/applicationContext.ts b/web-api/src/applicationContext.ts index 1f2026bbd9c..92b9a3d4ef1 100644 --- a/web-api/src/applicationContext.ts +++ b/web-api/src/applicationContext.ts @@ -12,7 +12,6 @@ import { MAX_SEARCH_CLIENT_RESULTS, MAX_SEARCH_RESULTS, ORDER_TYPES, - Role, SESSION_STATUS_GROUPS, TRIAL_SESSION_SCOPE_TYPES, } from '../../shared/src/business/entities/EntityConstants'; @@ -102,20 +101,7 @@ export const createApplicationContext = ( appContextUser = {}, logger = createLogger(), ) => { - let user; - - if (appContextUser) { - user = new User(appContextUser); - } - - const getCurrentUser = (): { - role: Role; - userId: string; - email: string; - name: string; - } => { - return user; - }; + const user = new User(appContextUser); if (process.env.NODE_ENV === 'production') { const authenticated = user && Object.keys(user).length; @@ -170,7 +156,6 @@ export const createApplicationContext = ( STATUS_TYPES: CASE_STATUS_TYPES, TRIAL_SESSION_SCOPE_TYPES, }), - getCurrentUser, getDispatchers: () => ({ sendBulkTemplatedEmail, sendNotificationOfSealing: diff --git a/web-api/src/business/useCaseHelper/acquireLock.test.ts b/web-api/src/business/useCaseHelper/acquireLock.test.ts index 953754dc73a..008d306ddb4 100644 --- a/web-api/src/business/useCaseHelper/acquireLock.test.ts +++ b/web-api/src/business/useCaseHelper/acquireLock.test.ts @@ -3,6 +3,7 @@ import { MOCK_LOCK } from '../../../../shared/src/test/mockLock'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { acquireLock, checkLock, removeLock, withLocking } from './acquireLock'; import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; const onLockError = new ServiceUnavailableError('The case is currently locked'); @@ -26,6 +27,7 @@ describe('acquireLock', () => { beforeEach(() => { mockCall = { applicationContext, + authorizedUser: mockDocketClerkUser, identifiers: ['case|123-45'], onLockError, retries: 0, @@ -147,6 +149,7 @@ describe('acquireLock', () => { expect(mockCallbackFunction).toHaveBeenCalledWith( applicationContext, mockCall.options, + mockDocketClerkUser, ); }); @@ -241,12 +244,20 @@ describe('withLocking', () => { it('does not throw a ServiceUnavailableError if the feature flag is false and we could not acquire the lock on the specified identifier', async () => { await expect( - func(applicationContext, { docketNumber: '123-45' }), + func( + applicationContext, + { docketNumber: '123-45' }, + mockDocketClerkUser, + ), ).resolves.not.toThrow(); expect(mockInteractor).toHaveBeenCalledTimes(1); - expect(mockInteractor).toHaveBeenCalledWith(applicationContext, { - docketNumber: '123-45', - }); + expect(mockInteractor).toHaveBeenCalledWith( + applicationContext, + { + docketNumber: '123-45', + }, + mockDocketClerkUser, + ); }); it('creates a lock for the specified entity', async () => { @@ -292,11 +303,19 @@ describe('withLocking', () => { const onLockErrorFunction = jest.fn(); func = withLocking(mockInteractor, getLockInfo, onLockErrorFunction); await expect( - func(applicationContext, { docketNumber: '123-45' }), + func( + applicationContext, + { docketNumber: '123-45' }, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); - expect(onLockErrorFunction).toHaveBeenCalledWith(applicationContext, { - docketNumber: '123-45', - }); + expect(onLockErrorFunction).toHaveBeenCalledWith( + applicationContext, + { + docketNumber: '123-45', + }, + mockDocketClerkUser, + ); }); it('throws a ServiceUnavailableError if an onLockError function is provided', async () => { @@ -328,11 +347,19 @@ describe('withLocking', () => { }); it('calls the specified callback function', async () => { - await func(applicationContext, { docketNumber: '123-45' }); + await func( + applicationContext, + { docketNumber: '123-45' }, + mockDocketClerkUser, + ); expect(mockInteractor).toHaveBeenCalledTimes(1); - expect(mockInteractor).toHaveBeenCalledWith(applicationContext, { - docketNumber: '123-45', - }); + expect(mockInteractor).toHaveBeenCalledWith( + applicationContext, + { + docketNumber: '123-45', + }, + mockDocketClerkUser, + ); }); it('removes the lock for the specified identifier', async () => { @@ -406,6 +433,7 @@ describe('checkLock', () => { mockFeatureFlagValue = true; // enabled mockCall = { applicationContext, + authorizedUser: mockDocketClerkUser, identifier: 'case|123-45', }; }); @@ -475,6 +503,7 @@ describe('checkLock', () => { expect(mockCallbackFunction).toHaveBeenCalledWith( applicationContext, mockCall.options, + mockDocketClerkUser, ); }); }); diff --git a/web-api/src/business/useCaseHelper/acquireLock.ts b/web-api/src/business/useCaseHelper/acquireLock.ts index c98ce029079..394a1fef98a 100644 --- a/web-api/src/business/useCaseHelper/acquireLock.ts +++ b/web-api/src/business/useCaseHelper/acquireLock.ts @@ -1,16 +1,19 @@ import { ALLOWLIST_FEATURE_FLAGS } from '../../../../shared/src/business/entities/EntityConstants'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { ServiceUnavailableError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const checkLock = async ({ applicationContext, + authorizedUser, identifier, onLockError, options = {}, }: { + authorizedUser: UnknownAuthUser; applicationContext: ServerApplicationContext; identifier: string; - onLockError?: Error | Function; + onLockError?: TOnLockError; options?: any; }): Promise => { const featureFlags = await applicationContext @@ -42,7 +45,7 @@ export const checkLock = async ({ if (onLockError instanceof Error) { throw onLockError; } else if (typeof onLockError === 'function') { - await onLockError(applicationContext, options); + await onLockError(applicationContext, options, authorizedUser); } throw new ServiceUnavailableError( 'One of the items you are trying to update is being updated by someone else', @@ -51,6 +54,7 @@ export const checkLock = async ({ export const acquireLock = async ({ applicationContext, + authorizedUser, identifiers = [], onLockError, options = {}, @@ -60,11 +64,12 @@ export const acquireLock = async ({ }: { applicationContext: ServerApplicationContext; identifiers?: string[]; - onLockError?: Error | Function; + onLockError?: TOnLockError; options?: any; retries?: number; ttl?: number; waitTime?: number; + authorizedUser: UnknownAuthUser; }): Promise => { if (!identifiers) { return; @@ -80,6 +85,7 @@ export const acquireLock = async ({ identifiers.map(entityIdentifier => checkLock({ applicationContext, + authorizedUser, identifier: entityIdentifier, onLockError, options, @@ -129,28 +135,32 @@ export const removeLock = ({ */ export function withLocking( interactor: ( - applicationContext: ServerApplicationContext, + applicationContext: any, options: InteractorInput, + authorizedUser: UnknownAuthUser, ) => Promise, getLockInfo: ( - applicationContext: ServerApplicationContext, + applicationContext: any, options: any, ) => | Promise<{ identifiers: string[]; ttl?: number }> | { identifiers: string[]; ttl?: number }, - onLockError?: Error | Function, + onLockError?: TOnLockError, ): ( - applicationContext: ServerApplicationContext, + applicationContext: any, options: InteractorInput, + authorizedUser: UnknownAuthUser, ) => Promise { return async function ( - applicationContext: ServerApplicationContext, + applicationContext: any, options: InteractorInput, + authorizedUser: UnknownAuthUser, ) { const { identifiers, ttl } = await getLockInfo(applicationContext, options); await acquireLock({ applicationContext, + authorizedUser, identifiers, onLockError, options, @@ -160,7 +170,7 @@ export function withLocking( let caughtError; let results: InteractorOutput; try { - results = await interactor(applicationContext, options); + results = await interactor(applicationContext, options, authorizedUser); } catch (err) { caughtError = err; } @@ -176,3 +186,11 @@ export function withLocking( return results!; }; } + +export type TOnLockError = + | Error + | (( + applicationContext: any, + originalRequest: any, + authorizedUser: UnknownAuthUser, + ) => void); diff --git a/web-api/src/business/useCaseHelper/addDocketEntryForSystemGeneratedOrder.test.ts b/web-api/src/business/useCaseHelper/addDocketEntryForSystemGeneratedOrder.test.ts index d7aca9e4ea4..7f8e4323a5f 100644 --- a/web-api/src/business/useCaseHelper/addDocketEntryForSystemGeneratedOrder.test.ts +++ b/web-api/src/business/useCaseHelper/addDocketEntryForSystemGeneratedOrder.test.ts @@ -6,10 +6,11 @@ import { Case } from '../../../../shared/src/business/entities/cases/Case'; import { MOCK_CASE } from '../../../../shared/src/test/mockCase'; import { addDocketEntryForSystemGeneratedOrder } from './addDocketEntryForSystemGeneratedOrder'; import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { testPdfDoc } from '@shared/business/test/getFakeFile'; describe('addDocketEntryForSystemGeneratedOrder', () => { - const caseEntity = new Case(MOCK_CASE, { applicationContext }); + const caseEntity = new Case(MOCK_CASE, { authorizedUser: undefined }); const { noticeOfAttachmentsInNatureOfEvidence, @@ -33,6 +34,7 @@ describe('addDocketEntryForSystemGeneratedOrder', () => { await addDocketEntryForSystemGeneratedOrder({ applicationContext, + authorizedUser: mockDocketClerkUser, caseEntity, systemGeneratedDocument: noticeOfAttachmentsInNatureOfEvidence, }); @@ -56,6 +58,7 @@ describe('addDocketEntryForSystemGeneratedOrder', () => { it('should only add freeText to notices', async () => { await addDocketEntryForSystemGeneratedOrder({ applicationContext, + authorizedUser: mockDocketClerkUser, caseEntity, systemGeneratedDocument: noticeOfAttachmentsInNatureOfEvidence, }); @@ -70,6 +73,7 @@ describe('addDocketEntryForSystemGeneratedOrder', () => { it('should set the title and the name of clerk for notices', async () => { await addDocketEntryForSystemGeneratedOrder({ applicationContext, + authorizedUser: mockDocketClerkUser, caseEntity, systemGeneratedDocument: noticeOfAttachmentsInNatureOfEvidence, }); @@ -85,6 +89,7 @@ describe('addDocketEntryForSystemGeneratedOrder', () => { it('should not set a title or the name of clerk for orders', async () => { await addDocketEntryForSystemGeneratedOrder({ applicationContext, + authorizedUser: mockDocketClerkUser, caseEntity, systemGeneratedDocument: orderForFilingFee, }); @@ -100,6 +105,7 @@ describe('addDocketEntryForSystemGeneratedOrder', () => { it('should upload a generated pdf for the provided document', async () => { await addDocketEntryForSystemGeneratedOrder({ applicationContext, + authorizedUser: mockDocketClerkUser, caseEntity, systemGeneratedDocument: noticeOfAttachmentsInNatureOfEvidence, }); @@ -122,6 +128,7 @@ describe('addDocketEntryForSystemGeneratedOrder', () => { await addDocketEntryForSystemGeneratedOrder({ applicationContext, + authorizedUser: mockDocketClerkUser, caseEntity, systemGeneratedDocument: mockClonedSystemDocument, }); @@ -144,6 +151,7 @@ describe('addDocketEntryForSystemGeneratedOrder', () => { await addDocketEntryForSystemGeneratedOrder({ applicationContext, + authorizedUser: mockDocketClerkUser, caseEntity, systemGeneratedDocument: orderForAmendedPetition, }); @@ -166,6 +174,7 @@ describe('addDocketEntryForSystemGeneratedOrder', () => { await addDocketEntryForSystemGeneratedOrder({ applicationContext, + authorizedUser: mockDocketClerkUser, caseEntity, systemGeneratedDocument: orderForAmendedPetitionAndFilingFee, }); diff --git a/web-api/src/business/useCaseHelper/addDocketEntryForSystemGeneratedOrder.ts b/web-api/src/business/useCaseHelper/addDocketEntryForSystemGeneratedOrder.ts index 147d3de1fc7..c898f848118 100644 --- a/web-api/src/business/useCaseHelper/addDocketEntryForSystemGeneratedOrder.ts +++ b/web-api/src/business/useCaseHelper/addDocketEntryForSystemGeneratedOrder.ts @@ -2,6 +2,7 @@ import { AMENDED_PETITION_FORM_NAME, SYSTEM_GENERATED_DOCUMENT_TYPES, } from '../../../../shared/src/business/entities/EntityConstants'; +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { Case } from '@shared/business/entities/cases/Case'; import { DocketEntry } from '../../../../shared/src/business/entities/DocketEntry'; import { ServerApplicationContext } from '@web-api/applicationContext'; @@ -9,14 +10,15 @@ import { getCaseCaptionMeta } from '../../../../shared/src/business/utilities/ge export const addDocketEntryForSystemGeneratedOrder = async ({ applicationContext, + authorizedUser, caseEntity, systemGeneratedDocument, }: { applicationContext: ServerApplicationContext; caseEntity: Case; systemGeneratedDocument: any; + authorizedUser: AuthUser; }): Promise => { - const user = applicationContext.getCurrentUser(); const isNotice = systemGeneratedDocument.eventCode === 'NOT'; const newDocketEntry = new DocketEntry( @@ -35,10 +37,10 @@ export const addDocketEntryForSystemGeneratedOrder = async ({ isDraft: true, isFileAttached: true, }, - { applicationContext }, + { authorizedUser }, ); - newDocketEntry.setFiledBy(user); + newDocketEntry.setFiledBy(authorizedUser); caseEntity.addDocketEntry(newDocketEntry); const { caseCaptionExtension, caseTitle } = getCaseCaptionMeta(caseEntity); diff --git a/web-api/src/business/useCaseHelper/automaticBlock/updateCaseAutomaticBlock.test.ts b/web-api/src/business/useCaseHelper/automaticBlock/updateCaseAutomaticBlock.test.ts index 2fc129c07db..a7eb1d261b0 100644 --- a/web-api/src/business/useCaseHelper/automaticBlock/updateCaseAutomaticBlock.test.ts +++ b/web-api/src/business/useCaseHelper/automaticBlock/updateCaseAutomaticBlock.test.ts @@ -7,19 +7,17 @@ import { MOCK_CASE, MOCK_CASE_WITHOUT_PENDING, } from '../../../../../shared/src/test/mockCase'; -import { MOCK_USERS } from '../../../../../shared/src/test/mockUsers'; import { PENDING_DOCKET_ENTRY } from '../../../../../shared/src/test/mockDocketEntry'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { cloneDeep } from 'lodash'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { updateCaseAutomaticBlock } from './updateCaseAutomaticBlock'; describe('updateCaseAutomaticBlock', () => { let mockCase; + beforeEach(() => { mockCase = cloneDeep(MOCK_CASE); - applicationContext.getCurrentUser.mockReturnValue( - MOCK_USERS['a7d90c05-f6cd-442c-a168-202db587f16f'], - ); applicationContext.getUniqueId.mockReturnValue('unique-id-1'); }); @@ -29,7 +27,9 @@ describe('updateCaseAutomaticBlock', () => { .getCaseDeadlinesByDocketNumber.mockReturnValue([]); mockCase.docketEntries = [PENDING_DOCKET_ENTRY]; - const caseEntity = new Case(mockCase, { applicationContext }); + const caseEntity = new Case(mockCase, { + authorizedUser: mockDocketClerkUser, + }); const updatedCase = await updateCaseAutomaticBlock({ applicationContext, caseEntity, @@ -54,7 +54,7 @@ describe('updateCaseAutomaticBlock', () => { ]); const caseEntity = new Case(MOCK_CASE_WITHOUT_PENDING, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); const updatedCase = await updateCaseAutomaticBlock({ applicationContext, @@ -86,7 +86,7 @@ describe('updateCaseAutomaticBlock', () => { trialDate: '2021-03-01T21:40:46.415Z', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); const updatedCase = await updateCaseAutomaticBlock({ @@ -114,7 +114,7 @@ describe('updateCaseAutomaticBlock', () => { trialDate: undefined, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); const updatedCase = await updateCaseAutomaticBlock({ @@ -135,7 +135,7 @@ describe('updateCaseAutomaticBlock', () => { .getCaseDeadlinesByDocketNumber.mockReturnValue([]); const caseEntity = new Case(MOCK_CASE_WITHOUT_PENDING, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); const updatedCase = await updateCaseAutomaticBlock({ applicationContext, @@ -164,7 +164,7 @@ describe('updateCaseAutomaticBlock', () => { status: CASE_STATUS_TYPES.generalDocketReadyForTrial, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); const updatedCase = await updateCaseAutomaticBlock({ @@ -195,7 +195,7 @@ describe('updateCaseAutomaticBlock', () => { status: CASE_STATUS_TYPES.generalDocketReadyForTrial, }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/web-api/src/business/useCaseHelper/caseAssociation/addExistingUserToCase.test.ts b/web-api/src/business/useCaseHelper/caseAssociation/addExistingUserToCase.test.ts index 190f57ae46a..6cd3ecfeb05 100644 --- a/web-api/src/business/useCaseHelper/caseAssociation/addExistingUserToCase.test.ts +++ b/web-api/src/business/useCaseHelper/caseAssociation/addExistingUserToCase.test.ts @@ -8,8 +8,12 @@ import { } from '../../../../../shared/src/business/entities/cases/Case'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { addExistingUserToCase } from './addExistingUserToCase'; -import { admissionsClerkUser, petitionerUser } from '@shared/test/mockUsers'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockAdmissionsClerkUser, + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('addExistingUserToCase', () => { const mockUserId = '674fdded-1d17-4081-b9fa-950abc677cee'; @@ -27,12 +31,13 @@ describe('addExistingUserToCase', () => { }); it('should throw an unauthorized error when the user is not authorized to add a user to a case', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - await expect( addExistingUserToCase({ applicationContext, - caseEntity: new Case(MOCK_CASE, { applicationContext }), + authorizedUser: mockPetitionerUser, + caseEntity: new Case(MOCK_CASE, { + authorizedUser: mockDocketClerkUser, + }), contactId: mockContactId, email: 'testing@example.com', name: 'Bob Ross', @@ -41,13 +46,15 @@ describe('addExistingUserToCase', () => { }); it('should throw an error when a user is NOT found with the provided email', async () => { - applicationContext.getCurrentUser.mockReturnValue(admissionsClerkUser); applicationContext.getUserGateway().getUserByEmail.mockReturnValue(null); await expect( addExistingUserToCase({ applicationContext, - caseEntity: new Case(MOCK_CASE, { applicationContext }), + authorizedUser: mockAdmissionsClerkUser, + caseEntity: new Case(MOCK_CASE, { + authorizedUser: mockDocketClerkUser, + }), contactId: mockContactId, email: 'testing@example.com', name: 'Bob Ross', @@ -60,15 +67,15 @@ describe('addExistingUserToCase', () => { contactId: '60dd21b3-5abb-447f-b036-9794962252a0', contactType: CONTACT_TYPES.primary, }; - applicationContext.getCurrentUser.mockReturnValue(admissionsClerkUser); const caseEntity = new Case( { ...MOCK_CASE, petitioners: [mockExistingUser] }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); await expect( addExistingUserToCase({ applicationContext, + authorizedUser: mockAdmissionsClerkUser, caseEntity, contactId: mockExistingUser.contactId, email: 'testing@example.com', @@ -78,7 +85,6 @@ describe('addExistingUserToCase', () => { }); it('should call associateUserWithCase and return the updated case with contact primary email', async () => { - applicationContext.getCurrentUser.mockReturnValue(admissionsClerkUser); const caseEntity = new Case( { ...MOCK_CASE, @@ -92,11 +98,12 @@ describe('addExistingUserToCase', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); await addExistingUserToCase({ applicationContext, + authorizedUser: mockAdmissionsClerkUser, caseEntity, contactId: mockContactId, email: mockUpdatedEmail, @@ -118,7 +125,6 @@ describe('addExistingUserToCase', () => { }); it('should call associateUserWithCase and update the representing arrays entries with the expect contactId', async () => { - applicationContext.getCurrentUser.mockReturnValue(admissionsClerkUser); const caseEntity = new Case( { ...MOCK_CASE, @@ -155,11 +161,12 @@ describe('addExistingUserToCase', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); await addExistingUserToCase({ applicationContext, + authorizedUser: mockAdmissionsClerkUser, caseEntity, contactId: mockContactId, email: mockUpdatedEmail, @@ -172,7 +179,6 @@ describe('addExistingUserToCase', () => { }); it("should not update the practitioner's representing array when the cognito user's ID already exists", async () => { - applicationContext.getCurrentUser.mockReturnValue(admissionsClerkUser); const caseEntity = new Case( { ...MOCK_CASE, @@ -209,11 +215,12 @@ describe('addExistingUserToCase', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); await addExistingUserToCase({ applicationContext, + authorizedUser: mockAdmissionsClerkUser, caseEntity, contactId: mockContactId, email: mockUpdatedEmail, @@ -226,7 +233,6 @@ describe('addExistingUserToCase', () => { }); it('should not change the service indicator to electronic when the user has a pendingEmail', async () => { - applicationContext.getCurrentUser.mockReturnValue(admissionsClerkUser); applicationContext.getPersistenceGateway().getUserById.mockReturnValue({ pendingEmail: 'testing@example.com', userId: mockUserId, @@ -245,11 +251,12 @@ describe('addExistingUserToCase', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); await addExistingUserToCase({ applicationContext, + authorizedUser: mockAdmissionsClerkUser, caseEntity, contactId: mockContactId, email: mockUpdatedEmail, diff --git a/web-api/src/business/useCaseHelper/caseAssociation/addExistingUserToCase.ts b/web-api/src/business/useCaseHelper/caseAssociation/addExistingUserToCase.ts index da3b2f6b7e6..bb8ae0105f5 100644 --- a/web-api/src/business/useCaseHelper/caseAssociation/addExistingUserToCase.ts +++ b/web-api/src/business/useCaseHelper/caseAssociation/addExistingUserToCase.ts @@ -1,3 +1,4 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { Case } from '@shared/business/entities/cases/Case'; import { ROLE_PERMISSIONS, @@ -10,6 +11,7 @@ import { UserCase } from '../../../../../shared/src/business/entities/UserCase'; export const addExistingUserToCase = async ({ applicationContext, + authorizedUser, caseEntity, contactId, email, @@ -20,9 +22,8 @@ export const addExistingUserToCase = async ({ contactId: string; email: string; name: string; + authorizedUser: AuthUser; }): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.ADD_USER_TO_CASE)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCaseHelper/caseAssociation/associateIrsPractitionerToCase.test.ts b/web-api/src/business/useCaseHelper/caseAssociation/associateIrsPractitionerToCase.test.ts index 96ef770b795..c9f8628ddcf 100644 --- a/web-api/src/business/useCaseHelper/caseAssociation/associateIrsPractitionerToCase.test.ts +++ b/web-api/src/business/useCaseHelper/caseAssociation/associateIrsPractitionerToCase.test.ts @@ -9,10 +9,8 @@ import { import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { associateIrsPractitionerToCase } from './associateIrsPractitionerToCase'; -import { - docketClerkUser, - irsPractitionerUser, -} from '../../../../../shared/src/test/mockUsers'; +import { irsPractitionerUser } from '../../../../../shared/src/test/mockUsers'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('associateIrsPractitionerToCase', () => { let caseRecord1 = { @@ -42,8 +40,6 @@ describe('associateIrsPractitionerToCase', () => { }; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockResolvedValue(caseRecord1); @@ -56,6 +52,7 @@ describe('associateIrsPractitionerToCase', () => { await associateIrsPractitionerToCase({ applicationContext, + authorizedUser: mockDocketClerkUser, docketNumber: caseRecord1.docketNumber, serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, user: irsPractitionerUser, @@ -76,6 +73,7 @@ describe('associateIrsPractitionerToCase', () => { await associateIrsPractitionerToCase({ applicationContext, + authorizedUser: mockDocketClerkUser, docketNumber: caseRecord1.docketNumber, serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, user: irsPractitionerUser, diff --git a/web-api/src/business/useCaseHelper/caseAssociation/associateIrsPractitionerToCase.ts b/web-api/src/business/useCaseHelper/caseAssociation/associateIrsPractitionerToCase.ts index 642a5c51368..c3c81d2deea 100644 --- a/web-api/src/business/useCaseHelper/caseAssociation/associateIrsPractitionerToCase.ts +++ b/web-api/src/business/useCaseHelper/caseAssociation/associateIrsPractitionerToCase.ts @@ -1,29 +1,23 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { Case } from '../../../../../shared/src/business/entities/cases/Case'; import { IrsPractitioner } from '../../../../../shared/src/business/entities/IrsPractitioner'; import { RawUser } from '@shared/business/entities/User'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UserCase } from '../../../../../shared/src/business/entities/UserCase'; -/** - * associateIrsPractitionerToCase - * @param {object} providers the providers object - * @param {object} providers.applicationContext the application context - * @param {string} providers.docketNumber the docket number of the case - * @param {string} providers.serviceIndicator the type of service the irsPractitioner should receive - * @param {object} providers.user the user object for the logged in user - * @returns {Promise<*>} the updated case entity - */ export const associateIrsPractitionerToCase = async ({ applicationContext, + authorizedUser, docketNumber, serviceIndicator, user, }: { applicationContext: ServerApplicationContext; + authorizedUser: AuthUser; docketNumber: string; serviceIndicator?: string; user: RawUser; -}) => { +}): Promise => { const isAssociated = await applicationContext .getPersistenceGateway() .verifyCaseForUser({ @@ -49,7 +43,9 @@ export const associateIrsPractitionerToCase = async ({ userId: user.userId, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { + authorizedUser, + }); caseEntity.attachIrsPractitioner( new IrsPractitioner({ ...user, serviceIndicator }), @@ -57,6 +53,7 @@ export const associateIrsPractitionerToCase = async ({ await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); } diff --git a/web-api/src/business/useCaseHelper/caseAssociation/associatePrivatePractitionerToCase.test.ts b/web-api/src/business/useCaseHelper/caseAssociation/associatePrivatePractitionerToCase.test.ts index 0c9ae6b1b68..0d336d5ddee 100644 --- a/web-api/src/business/useCaseHelper/caseAssociation/associatePrivatePractitionerToCase.test.ts +++ b/web-api/src/business/useCaseHelper/caseAssociation/associatePrivatePractitionerToCase.test.ts @@ -6,27 +6,18 @@ import { ROLES, SERVICE_INDICATOR_TYPES, } from '../../../../../shared/src/business/entities/EntityConstants'; -import { MOCK_USERS } from '../../../../../shared/src/test/mockUsers'; -import { RawUser } from '@shared/business/entities/User'; +import { MOCK_PRACTITIONER } from '@shared/test/mockUsers'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { associatePrivatePractitionerToCase } from './associatePrivatePractitionerToCase'; import { getContactPrimary, getContactSecondary, } from '../../../../../shared/src/business/entities/cases/Case'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('associatePrivatePractitionerToCase', () => { let caseRecord; - const practitionerUser: RawUser = { - barNumber: 'PT1234', - email: 'emmett@example.com', - entityName: 'User', - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.privatePractitioner, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; - beforeEach(() => { caseRecord = { caseCaption: 'Case Caption', @@ -92,10 +83,6 @@ describe('associatePrivatePractitionerToCase', () => { userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', }; - applicationContext.getCurrentUser.mockReturnValue( - MOCK_USERS['a7d90c05-f6cd-442c-a168-202db587f16f'], - ); - applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockResolvedValue(caseRecord); @@ -108,9 +95,10 @@ describe('associatePrivatePractitionerToCase', () => { await associatePrivatePractitionerToCase({ applicationContext, + authorizedUser: mockDocketClerkUser, docketNumber: caseRecord.docketNumber, representing: [caseRecord.petitioners[0].contactId], - user: practitionerUser, + user: MOCK_PRACTITIONER, }); expect( @@ -128,9 +116,10 @@ describe('associatePrivatePractitionerToCase', () => { await associatePrivatePractitionerToCase({ applicationContext, + authorizedUser: mockDocketClerkUser, docketNumber: caseRecord.docketNumber, representing: [caseRecord.petitioners[0].contactId], - user: practitionerUser, + user: MOCK_PRACTITIONER, }); expect( @@ -148,13 +137,14 @@ describe('associatePrivatePractitionerToCase', () => { await associatePrivatePractitionerToCase({ applicationContext, + authorizedUser: mockDocketClerkUser, docketNumber: caseRecord.docketNumber, representing: [ caseRecord.petitioners[0].contactId, caseRecord.petitioners[1].contactId, caseRecord.petitioners[2].contactId, ], - user: practitionerUser, + user: MOCK_PRACTITIONER, }); const updatedCase = @@ -180,9 +170,10 @@ describe('associatePrivatePractitionerToCase', () => { await associatePrivatePractitionerToCase({ applicationContext, + authorizedUser: mockDocketClerkUser, docketNumber: caseRecord.docketNumber, representing: [caseRecord.petitioners[1].contactId], - user: practitionerUser, + user: MOCK_PRACTITIONER, }); const updatedCase = @@ -216,9 +207,10 @@ describe('associatePrivatePractitionerToCase', () => { await associatePrivatePractitionerToCase({ applicationContext, + authorizedUser: mockDocketClerkUser, docketNumber: caseRecord.docketNumber, representing: [], - user: practitionerUser, + user: MOCK_PRACTITIONER, }); expect( @@ -227,7 +219,7 @@ describe('associatePrivatePractitionerToCase', () => { expect(applicationContext.logger.error).toHaveBeenCalled(); expect(applicationContext.logger.error.mock.calls[0][0]).toEqual( - `BUG 9323: Private Practitioner with userId: ${practitionerUser.userId} was already associated with case ${caseRecord.docketNumber} but did not appear in the privatePractitioners array.`, + `BUG 9323: Private Practitioner with userId: ${MOCK_PRACTITIONER.userId} was already associated with case ${caseRecord.docketNumber} but did not appear in the privatePractitioners array.`, ); }); @@ -240,20 +232,20 @@ describe('associatePrivatePractitionerToCase', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockResolvedValueOnce({ ...caseRecord, - privatePractitioners: [{ userId: practitionerUser.userId }], + privatePractitioners: [{ userId: MOCK_PRACTITIONER.userId }], }); await associatePrivatePractitionerToCase({ applicationContext, + authorizedUser: mockDocketClerkUser, docketNumber: caseRecord.docketNumber, representing: [caseRecord.petitioners[0].contactId], - user: practitionerUser, + user: MOCK_PRACTITIONER, }); expect( applicationContext.getPersistenceGateway().associateUserWithCase, ).not.toHaveBeenCalled(); - expect(applicationContext.logger.error).not.toHaveBeenCalled(); }); }); diff --git a/web-api/src/business/useCaseHelper/caseAssociation/associatePrivatePractitionerToCase.ts b/web-api/src/business/useCaseHelper/caseAssociation/associatePrivatePractitionerToCase.ts index b03e501d036..9bc71cdb93e 100644 --- a/web-api/src/business/useCaseHelper/caseAssociation/associatePrivatePractitionerToCase.ts +++ b/web-api/src/business/useCaseHelper/caseAssociation/associatePrivatePractitionerToCase.ts @@ -1,6 +1,7 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { Case } from '../../../../../shared/src/business/entities/cases/Case'; import { PrivatePractitioner } from '../../../../../shared/src/business/entities/PrivatePractitioner'; -import { RawUser } from '@shared/business/entities/User'; +import { RawPractitioner } from '@shared/business/entities/Practitioner'; import { SERVICE_INDICATOR_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UserCase } from '../../../../../shared/src/business/entities/UserCase'; @@ -17,15 +18,17 @@ import { UserCase } from '../../../../../shared/src/business/entities/UserCase'; */ export const associatePrivatePractitionerToCase = async ({ applicationContext, + authorizedUser, docketNumber, representing = [], serviceIndicator, user, }: { applicationContext: ServerApplicationContext; + authorizedUser: AuthUser; docketNumber: string; serviceIndicator?: string; - user: RawUser; + user: RawPractitioner; representing: string[]; }) => { const isAssociated = await applicationContext @@ -57,7 +60,9 @@ export const associatePrivatePractitionerToCase = async ({ userId: user.userId, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { + authorizedUser, + }); const { petitioners } = caseEntity; @@ -77,6 +82,7 @@ export const associatePrivatePractitionerToCase = async ({ await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); diff --git a/web-api/src/business/useCaseHelper/caseAssociation/createCaseAndAssociations.test.ts b/web-api/src/business/useCaseHelper/caseAssociation/createCaseAndAssociations.test.ts index 07315e03ff3..c8f281dd1ac 100644 --- a/web-api/src/business/useCaseHelper/caseAssociation/createCaseAndAssociations.test.ts +++ b/web-api/src/business/useCaseHelper/caseAssociation/createCaseAndAssociations.test.ts @@ -3,6 +3,7 @@ import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_DOCUMENTS } from '../../../../../shared/src/test/mockDocketEntry'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { createCaseAndAssociations } from './createCaseAndAssociations'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('createCaseAndAssociations', () => { let createCaseMock = jest.fn(); @@ -27,7 +28,7 @@ describe('createCaseAndAssociations', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ) .validate() .toRawObject(); @@ -40,6 +41,7 @@ describe('createCaseAndAssociations', () => { it('always sends valid entities to the createCase persistence method', async () => { await createCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToCreate: validMockCase, }); expect(createCaseMock).toHaveBeenCalled(); @@ -55,7 +57,11 @@ describe('createCaseAndAssociations', () => { docketEntries: [{ docketNumber: 'peaches' }], }; await expect( - createCaseAndAssociations({ applicationContext, caseToCreate }), + createCaseAndAssociations({ + applicationContext, + authorizedUser: mockDocketClerkUser, + caseToCreate, + }), ).rejects.toThrow('entity was invalid'); }); @@ -68,6 +74,7 @@ describe('createCaseAndAssociations', () => { await createCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToCreate, }); @@ -104,7 +111,7 @@ describe('createCaseAndAssociations', () => { ...MOCK_CASE, irsPractitioners: [practitioner], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); it('throws an error if IRS practitioners are invalid', async () => { @@ -113,13 +120,18 @@ describe('createCaseAndAssociations', () => { irsPractitioners: [{ barNumber: 0, role: 'spring', userId: 'yoohoo' }], }; await expect( - createCaseAndAssociations({ applicationContext, caseToCreate }), + createCaseAndAssociations({ + applicationContext, + authorizedUser: mockDocketClerkUser, + caseToCreate, + }), ).rejects.toThrow('entity was invalid'); }); it('calls updateIrsPractitionerOnCase once for each IRS practitioner on the case', async () => { await createCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToCreate: mockCaseWithIrsPractitioners, }); @@ -151,7 +163,7 @@ describe('createCaseAndAssociations', () => { ...MOCK_CASE, privatePractitioners: [practitioner], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); it('throws an error if IRS practitioners are invalid', async () => { @@ -162,13 +174,18 @@ describe('createCaseAndAssociations', () => { ], }; await expect( - createCaseAndAssociations({ applicationContext, caseToCreate }), + createCaseAndAssociations({ + applicationContext, + authorizedUser: mockDocketClerkUser, + caseToCreate, + }), ).rejects.toThrow('entity was invalid'); }); it('calls updateprivatePractitionerOnCase once for each private practitioner on the case', async () => { await createCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToCreate: mockCaseWithPrivatePractitioners, }); diff --git a/web-api/src/business/useCaseHelper/caseAssociation/createCaseAndAssociations.ts b/web-api/src/business/useCaseHelper/caseAssociation/createCaseAndAssociations.ts index e2698ba8048..4751c3e104a 100644 --- a/web-api/src/business/useCaseHelper/caseAssociation/createCaseAndAssociations.ts +++ b/web-api/src/business/useCaseHelper/caseAssociation/createCaseAndAssociations.ts @@ -1,3 +1,4 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { Case } from '../../../../../shared/src/business/entities/cases/Case'; import { DocketEntry } from '../../../../../shared/src/business/entities/DocketEntry'; import { IrsPractitioner } from '../../../../../shared/src/business/entities/IrsPractitioner'; @@ -14,12 +15,19 @@ import { ServerApplicationContext } from '@web-api/applicationContext'; */ const createCaseDocketEntries = ({ applicationContext, + authorizedUser, docketEntries, docketNumber, petitioners, +}: { + applicationContext: ServerApplicationContext; + authorizedUser: AuthUser; + docketEntries: any; + docketNumber: any; + petitioners: any; }) => { const validDocketEntries = DocketEntry.validateRawCollection(docketEntries, { - applicationContext, + authorizedUser, petitioners, }); @@ -46,10 +54,8 @@ const connectIrsPractitioners = ({ docketNumber, irsPractitioners, }) => { - const validIrsPractitioners = IrsPractitioner.validateRawCollection( - irsPractitioners, - { applicationContext }, - ); + const validIrsPractitioners = + IrsPractitioner.validateRawCollection(irsPractitioners); return validIrsPractitioners.map(practitioner => applicationContext.getPersistenceGateway().updateIrsPractitionerOnCase({ @@ -74,10 +80,8 @@ const connectPrivatePractitioners = ({ docketNumber, privatePractitioners, }) => { - const validPrivatePractitioners = PrivatePractitioner.validateRawCollection( - privatePractitioners, - { applicationContext }, - ); + const validPrivatePractitioners = + PrivatePractitioner.validateRawCollection(privatePractitioners); return validPrivatePractitioners.map(practitioner => applicationContext.getPersistenceGateway().updatePrivatePractitionerOnCase({ @@ -99,14 +103,18 @@ const connectPrivatePractitioners = ({ */ export const createCaseAndAssociations = async ({ applicationContext, + authorizedUser, caseToCreate, }: { applicationContext: ServerApplicationContext; + authorizedUser: AuthUser; caseToCreate: any; }) => { const caseEntity = caseToCreate.validate ? caseToCreate - : new Case(caseToCreate, { applicationContext }); + : new Case(caseToCreate, { + authorizedUser, + }); const validRawCaseEntity = caseEntity.validate().toRawObject(); @@ -124,6 +132,7 @@ export const createCaseAndAssociations = async ({ }), ...createCaseDocketEntries({ applicationContext, + authorizedUser, docketEntries, docketNumber, petitioners: caseToCreate.petitioners, diff --git a/web-api/src/business/useCaseHelper/caseAssociation/createUserForContact.test.ts b/web-api/src/business/useCaseHelper/caseAssociation/createUserForContact.test.ts index f6957cbe799..f82e6095ba0 100644 --- a/web-api/src/business/useCaseHelper/caseAssociation/createUserForContact.test.ts +++ b/web-api/src/business/useCaseHelper/caseAssociation/createUserForContact.test.ts @@ -10,6 +10,11 @@ import { import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { createUserForContact } from './createUserForContact'; +import { + mockAdmissionsClerkUser, + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('createUserForContact', () => { const USER_ID = '674fdded-1d17-4081-b9fa-950abc677cee'; @@ -19,12 +24,13 @@ describe('createUserForContact', () => { }); it('should throw an unauthorized error for non admissionsclerk users', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( createUserForContact({ applicationContext, - caseEntity: new Case(MOCK_CASE, { applicationContext }), + authorizedUser: mockPetitionerUser, + caseEntity: new Case(MOCK_CASE, { + authorizedUser: mockDocketClerkUser, + }), contactId: USER_ID, email: 'testing@example.com', name: 'Bob Ross', @@ -34,11 +40,6 @@ describe('createUserForContact', () => { it('should call createNewPetitionerUser with the new user entity', async () => { const UPDATED_EMAIL = 'testing@example.com'; - - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.admissionsClerk, - }); - const caseEntity = new Case( { ...MOCK_CASE, @@ -53,11 +54,12 @@ describe('createUserForContact', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockAdmissionsClerkUser }, ); await createUserForContact({ applicationContext, + authorizedUser: mockAdmissionsClerkUser, caseEntity, contactId: USER_ID, email: UPDATED_EMAIL, @@ -78,11 +80,6 @@ describe('createUserForContact', () => { it('should return the caseEntity', async () => { const UPDATED_EMAIL = 'testing@example.com'; - - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.admissionsClerk, - }); - const caseEntity = new Case( { ...MOCK_CASE, @@ -96,11 +93,12 @@ describe('createUserForContact', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockAdmissionsClerkUser }, ); const updatedCase = await createUserForContact({ applicationContext, + authorizedUser: mockAdmissionsClerkUser, caseEntity, contactId: USER_ID, email: UPDATED_EMAIL, @@ -112,11 +110,6 @@ describe('createUserForContact', () => { it('should call associateUserWithCase', async () => { const UPDATED_EMAIL = 'testing@example.com'; - - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.admissionsClerk, - }); - const caseEntity = new Case( { ...MOCK_CASE, @@ -130,11 +123,12 @@ describe('createUserForContact', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockAdmissionsClerkUser }, ); await createUserForContact({ applicationContext, + authorizedUser: mockAdmissionsClerkUser, caseEntity, contactId: USER_ID, email: UPDATED_EMAIL, diff --git a/web-api/src/business/useCaseHelper/caseAssociation/createUserForContact.ts b/web-api/src/business/useCaseHelper/caseAssociation/createUserForContact.ts index 06533c737be..e9f14d0a933 100644 --- a/web-api/src/business/useCaseHelper/caseAssociation/createUserForContact.ts +++ b/web-api/src/business/useCaseHelper/caseAssociation/createUserForContact.ts @@ -1,30 +1,30 @@ +import { Case } from '@shared/business/entities/cases/Case'; import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { ROLE_PERMISSIONS, isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { User } from '../../../../../shared/src/business/entities/User'; import { UserCase } from '../../../../../shared/src/business/entities/UserCase'; -/** - * createUserForContact - * - * @param {object} options.contactId the id of the contact to create user for - * @param {object} options.caseEntity the case entity to modify and return - * @param {string} options.email the email address for the user we are attaching to the case - * @param {string} options.name the name of the user to update the case with - * @returns {Case} the updated case entity - */ export const createUserForContact = async ({ applicationContext, + authorizedUser, caseEntity, contactId, email, name, -}) => { - const authorizedUser = applicationContext.getCurrentUser(); - +}: { + applicationContext: ServerApplicationContext; + authorizedUser: UnknownAuthUser; + caseEntity: Case; + contactId: string; + email: string; + name: string; +}): Promise => { if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.ADD_USER_TO_CASE)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCaseHelper/caseAssociation/removeCounselFromRemovedPetitioner.test.ts b/web-api/src/business/useCaseHelper/caseAssociation/removeCounselFromRemovedPetitioner.test.ts index ba664c89f33..87355e41d0b 100644 --- a/web-api/src/business/useCaseHelper/caseAssociation/removeCounselFromRemovedPetitioner.test.ts +++ b/web-api/src/business/useCaseHelper/caseAssociation/removeCounselFromRemovedPetitioner.test.ts @@ -1,15 +1,15 @@ import { CONTACT_TYPES, PARTY_TYPES, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { Case } from '../../../../../shared/src/business/entities/cases/Case'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; -import { - MOCK_PRACTITIONER, - petitionsClerkUser, -} from '../../../../../shared/src/test/mockUsers'; +import { MOCK_PRACTITIONER } from '../../../../../shared/src/test/mockUsers'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { removeCounselFromRemovedPetitioner } from './removeCounselFromRemovedPetitioner'; describe('removeCounselFromRemovedPetitioner', () => { @@ -18,19 +18,14 @@ describe('removeCounselFromRemovedPetitioner', () => { const mockSecondPractitionerUserId = '5dde0389-6e09-4e2f-a7f4-34e4f2a534a8'; const mockThirdPractitionerUserId = '0bd63272-781f-4cbd-8b7d-7cb649ca255d'; - beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - }); - it('throws an unauthorized error if user does not have correct permissions', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - }); - await expect( removeCounselFromRemovedPetitioner({ applicationContext, - caseEntity: new Case(MOCK_CASE, { applicationContext }), + authorizedUser: mockPetitionerUser, + caseEntity: new Case(MOCK_CASE, { + authorizedUser: mockPetitionerUser, + }), petitionerContactId: mockContactPrimaryId, }), ).rejects.toThrow('Unauthorized'); @@ -56,11 +51,12 @@ describe('removeCounselFromRemovedPetitioner', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); const updatedCase = await removeCounselFromRemovedPetitioner({ applicationContext, + authorizedUser: mockPetitionsClerkUser, caseEntity, petitionerContactId: mockContactSecondaryId, }); @@ -99,11 +95,12 @@ describe('removeCounselFromRemovedPetitioner', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); const updatedCase = await removeCounselFromRemovedPetitioner({ applicationContext, + authorizedUser: mockPetitionsClerkUser, caseEntity, petitionerContactId: mockContactSecondaryId, }); @@ -144,11 +141,12 @@ describe('removeCounselFromRemovedPetitioner', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); const updatedCase = await removeCounselFromRemovedPetitioner({ applicationContext, + authorizedUser: mockPetitionsClerkUser, caseEntity, petitionerContactId: mockContactSecondaryId, }); diff --git a/web-api/src/business/useCaseHelper/caseAssociation/removeCounselFromRemovedPetitioner.ts b/web-api/src/business/useCaseHelper/caseAssociation/removeCounselFromRemovedPetitioner.ts index e45dd6cb201..a2861744447 100644 --- a/web-api/src/business/useCaseHelper/caseAssociation/removeCounselFromRemovedPetitioner.ts +++ b/web-api/src/business/useCaseHelper/caseAssociation/removeCounselFromRemovedPetitioner.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * removeCounselFromRemovedPetitioner * @@ -16,15 +17,15 @@ import { UnauthorizedError } from '@web-api/errors/errors'; */ export const removeCounselFromRemovedPetitioner = async ({ applicationContext, + authorizedUser, caseEntity, petitionerContactId, }: { applicationContext: ServerApplicationContext; caseEntity: Case; petitionerContactId: string; + authorizedUser: UnknownAuthUser; }) => { - const authorizedUser = applicationContext.getCurrentUser(); - if ( !isAuthorized(authorizedUser, ROLE_PERMISSIONS.QC_PETITION) && !isAuthorized(authorizedUser, ROLE_PERMISSIONS.REMOVE_PETITIONER) diff --git a/web-api/src/business/useCaseHelper/caseAssociation/updateCaseAndAssociations.test.ts b/web-api/src/business/useCaseHelper/caseAssociation/updateCaseAndAssociations.test.ts index 63f7bfe77d4..aa24ee6965a 100644 --- a/web-api/src/business/useCaseHelper/caseAssociation/updateCaseAndAssociations.test.ts +++ b/web-api/src/business/useCaseHelper/caseAssociation/updateCaseAndAssociations.test.ts @@ -19,6 +19,7 @@ import { applicationContext } from '../../../../../shared/src/business/test/crea import { cloneDeep } from 'lodash'; import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; import { getMessagesByDocketNumber as getMessagesByDocketNumberMock } from '@web-api/persistence/postgres/messages/getMessagesByDocketNumber'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { updateCaseAndAssociations } from './updateCaseAndAssociations'; import { updateMessage as updateMessageMock } from '@web-api/persistence/postgres/messages/updateMessage'; import { v4 as uuidv4 } from 'uuid'; @@ -51,7 +52,7 @@ describe('updateCaseAndAssociations', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ) .validate() .toRawObject(); @@ -85,6 +86,7 @@ describe('updateCaseAndAssociations', () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: undefined, caseToUpdate, }); @@ -103,6 +105,7 @@ describe('updateCaseAndAssociations', () => { it('always sends valid entities to the updateCase persistence method', async () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: validMockCase, }); expect( @@ -124,6 +127,7 @@ describe('updateCaseAndAssociations', () => { await expect( updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: { ...validMockCase, associatedJudge: 'Judge Arnold', @@ -220,6 +224,7 @@ describe('updateCaseAndAssociations', () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate, }); @@ -257,6 +262,7 @@ describe('updateCaseAndAssociations', () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate, }); @@ -293,6 +299,7 @@ describe('updateCaseAndAssociations', () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate, }); @@ -332,6 +339,7 @@ describe('updateCaseAndAssociations', () => { updatedCase.mailingDate = '2025-01-05T05:22:16.001Z'; await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: updatedCase, }); expect( @@ -344,6 +352,7 @@ describe('updateCaseAndAssociations', () => { updatedCase.associatedJudgeId = '2f46a889-901c-4e8b-b2bb-c3994e2c75c1'; await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: updatedCase, }); const { workItem } = @@ -357,9 +366,10 @@ describe('updateCaseAndAssociations', () => { it('the docket docketNumberWithSuffix is updated because the case type has changed', async () => { updatedCase.caseType = CASE_TYPES_MAP.whistleblower; - // updatedCase.docketNumberSuffix = DOCKET_NUMBER_SUFFIXES.WHISTLEBLOWER; + await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: updatedCase, }); @@ -375,6 +385,7 @@ describe('updateCaseAndAssociations', () => { updatedCase.caseCaption = 'Some caption changed'; await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: updatedCase, }); @@ -388,6 +399,7 @@ describe('updateCaseAndAssociations', () => { updatedCase.status = CASE_STATUS_TYPES.generalDocket; await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: updatedCase, }); @@ -403,6 +415,7 @@ describe('updateCaseAndAssociations', () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: updatedCase, }); @@ -425,6 +438,7 @@ describe('updateCaseAndAssociations', () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: { ...validMockCase, trialDate: undefined, @@ -440,6 +454,7 @@ describe('updateCaseAndAssociations', () => { it('the trial location has been updated', async () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: { ...validMockCase, trialDate: '2021-01-02T05:22:16.001Z', @@ -468,6 +483,7 @@ describe('updateCaseAndAssociations', () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: { ...validMockCase, trialLocation: undefined, @@ -497,6 +513,7 @@ describe('updateCaseAndAssociations', () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: { ...validMockCase, leadDocketNumber: undefined, @@ -521,6 +538,7 @@ describe('updateCaseAndAssociations', () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: { ...validMockCase, leadDocketNumber: '202-20', @@ -541,6 +559,7 @@ describe('updateCaseAndAssociations', () => { .getCaseByDocketNumber.mockReturnValue(validMockCase); await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: validMockCase, }); expect( @@ -577,6 +596,7 @@ describe('updateCaseAndAssociations', () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate, }); @@ -600,7 +620,7 @@ describe('updateCaseAndAssociations', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); beforeAll(() => { @@ -612,6 +632,7 @@ describe('updateCaseAndAssociations', () => { it('does not call updateIrsPractitionerOnCase or removeIrsPractitionerOnCase if all IRS practitioners are unchanged', async () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: mockCaseWithIrsPractitioners, }); expect( @@ -631,6 +652,7 @@ describe('updateCaseAndAssociations', () => { }; await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: { ...mockCaseWithIrsPractitioners, irsPractitioners: [updatedPractitioner], @@ -656,6 +678,7 @@ describe('updateCaseAndAssociations', () => { it('removes an irsPractitioner from a case with existing irsPractitioners', async () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: { ...mockCaseWithIrsPractitioners, irsPractitioners: [], @@ -680,6 +703,7 @@ describe('updateCaseAndAssociations', () => { it('calls updateIrsPractitionerOnCase to update gsi1pk for unchanged irsPractitioners when the case is part of a consolidated group', async () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: { ...mockCaseWithIrsPractitioners, leadDocketNumber: '101-23', @@ -718,7 +742,7 @@ describe('updateCaseAndAssociations', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); beforeAll(() => { @@ -732,6 +756,7 @@ describe('updateCaseAndAssociations', () => { it('does not call updatePrivatePractitionerOnCase or removePrivatePractitionerOnCase if all private practitioners are unchanged', async () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: mockCaseWithIrsAndPrivatePractitioners, }); expect( @@ -753,6 +778,7 @@ describe('updateCaseAndAssociations', () => { }; await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: { ...mockCaseWithIrsAndPrivatePractitioners, privatePractitioners: [updatedPractitioner], @@ -780,6 +806,7 @@ describe('updateCaseAndAssociations', () => { it('calls updatePrivatePractitionerOnCase to update gsi1pk for unchanged privatePractitioners when the case is part of a consolidated group', async () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: { ...mockCaseWithIrsAndPrivatePractitioners, leadDocketNumber: '101-23', @@ -808,6 +835,7 @@ describe('updateCaseAndAssociations', () => { it('removes an privatePractitioner from a case with existing privatePractitioners', async () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: { ...mockCaseWithIrsAndPrivatePractitioners, privatePractitioners: [], @@ -841,6 +869,7 @@ describe('updateCaseAndAssociations', () => { it('completes without altering message records if no message updates are necessary', async () => { await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: validMockCase, }); expect(getMessagesByDocketNumber).not.toHaveBeenCalled(); @@ -857,6 +886,7 @@ describe('updateCaseAndAssociations', () => { await expect( updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: { ...validMockCase, caseCaption: 'Some other caption', @@ -873,6 +903,7 @@ describe('updateCaseAndAssociations', () => { await expect( updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: { ...validMockCase, caseCaption: 'Some other caption', @@ -910,6 +941,7 @@ describe('updateCaseAndAssociations', () => { }; await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: updatedCase, }); expect( @@ -929,6 +961,7 @@ describe('updateCaseAndAssociations', () => { }; await updateCaseAndAssociations({ applicationContext, + authorizedUser: mockDocketClerkUser, caseToUpdate: updatedCase, }); expect( diff --git a/web-api/src/business/useCaseHelper/caseAssociation/updateCaseAndAssociations.ts b/web-api/src/business/useCaseHelper/caseAssociation/updateCaseAndAssociations.ts index 7f4d5836a92..870a376066d 100644 --- a/web-api/src/business/useCaseHelper/caseAssociation/updateCaseAndAssociations.ts +++ b/web-api/src/business/useCaseHelper/caseAssociation/updateCaseAndAssociations.ts @@ -6,6 +6,7 @@ import { IrsPractitioner } from '../../../../../shared/src/business/entities/Irs import { Message } from '../../../../../shared/src/business/entities/Message'; import { PrivatePractitioner } from '../../../../../shared/src/business/entities/PrivatePractitioner'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { WorkItem } from '../../../../../shared/src/business/entities/WorkItem'; import { getMessagesByDocketNumber } from '@web-api/persistence/postgres/messages/getMessagesByDocketNumber'; import { updateMessage } from '@web-api/persistence/postgres/messages/updateMessage'; @@ -21,8 +22,14 @@ import diff from 'diff-arrays-of-objects'; */ const updateCaseDocketEntries = ({ applicationContext, + authorizedUser, caseToUpdate, oldCase, +}: { + applicationContext: ServerApplicationContext; + authorizedUser: UnknownAuthUser; + caseToUpdate: any; + oldCase: any; }) => { const { added: addedDocketEntries, updated: updatedDocketEntries } = diff( oldCase.docketEntries, @@ -46,7 +53,7 @@ const updateCaseDocketEntries = ({ ...addedArchivedDocketEntries, ...updatedArchivedDocketEntries, ], - { applicationContext, petitioners: caseToUpdate.petitioners }, + { authorizedUser, petitioners: caseToUpdate.petitioners }, ); return validDocketEntries.map( @@ -141,15 +148,12 @@ const updateCorrespondence = ({ 'correspondenceId', ); - const validCorrespondence = Correspondence.validateRawCollection( - [ - ...addedCorrespondences, - ...updatedCorrespondences, - ...addedArchivedCorrespondences, - ...updatedArchivedCorrespondences, - ], - { applicationContext }, - ); + const validCorrespondence = Correspondence.validateRawCollection([ + ...addedCorrespondences, + ...updatedCorrespondences, + ...addedArchivedCorrespondences, + ...updatedArchivedCorrespondences, + ]); return validCorrespondence.map( correspondence => @@ -227,7 +231,6 @@ const updateIrsPractitioners = ({ const validIrsPractitioners = IrsPractitioner.validateRawCollection( currentIrsPractitioners, - { applicationContext }, ); const deletePractitionerFunctions = deletedIrsPractitioners.map( @@ -297,7 +300,6 @@ const updatePrivatePractitioners = ({ const validPrivatePractitioners = PrivatePractitioner.validateRawCollection( currentPrivatePractitioners, - { applicationContext }, ); const deletePractitionerFunctions = deletedPrivatePractitioners.map( @@ -376,9 +378,7 @@ const updateCaseWorkItems = async ({ trialLocation: caseToUpdate.trialLocation || null, })); - const validWorkItems = WorkItem.validateRawCollection(updatedWorkItems, { - applicationContext, - }); + const validWorkItems = WorkItem.validateRawCollection(updatedWorkItems); return validWorkItems.map( validWorkItem => @@ -443,14 +443,18 @@ const updateCaseDeadlines = async ({ */ export const updateCaseAndAssociations = async ({ applicationContext, + authorizedUser, caseToUpdate, }: { applicationContext: ServerApplicationContext; + authorizedUser: UnknownAuthUser; caseToUpdate: any; }): Promise => { const caseEntity: Case = caseToUpdate.validate ? caseToUpdate - : new Case(caseToUpdate, { applicationContext }); + : new Case(caseToUpdate, { + authorizedUser, + }); const oldCaseEntity = await applicationContext .getPersistenceGateway() @@ -461,7 +465,9 @@ export const updateCaseAndAssociations = async ({ const validRawCaseEntity = caseEntity.validate().toRawObject(); - const validRawOldCaseEntity = new Case(oldCaseEntity, { applicationContext }) + const validRawOldCaseEntity = new Case(oldCaseEntity, { + authorizedUser, + }) .validate() .toRawObject(); @@ -479,6 +485,7 @@ export const updateCaseAndAssociations = async ({ const validationRequests = RELATED_CASE_OPERATIONS.map(fn => fn({ applicationContext, + authorizedUser, caseToUpdate: validRawCaseEntity, oldCase: validRawOldCaseEntity, }), diff --git a/web-api/src/business/useCaseHelper/caseInventoryReport/generateCaseInventoryReportPdf.test.ts b/web-api/src/business/useCaseHelper/caseInventoryReport/generateCaseInventoryReportPdf.test.ts index a0fb5895714..7fe32024156 100644 --- a/web-api/src/business/useCaseHelper/caseInventoryReport/generateCaseInventoryReportPdf.test.ts +++ b/web-api/src/business/useCaseHelper/caseInventoryReport/generateCaseInventoryReportPdf.test.ts @@ -1,32 +1,65 @@ import { CASE_STATUS_TYPES, + CASE_TYPES_MAP, CHIEF_JUDGE, - ROLES, + PARTY_TYPES, + PAYMENT_STATUS, + PROCEDURE_TYPES_MAP, } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { generateCaseInventoryReportPdf } from './generateCaseInventoryReportPdf'; - -const mockCases = [ - { - associatedJudge: CHIEF_JUDGE, - docketNumber: '101-19', - status: CASE_STATUS_TYPES.new, - }, - { - associatedJudge: CHIEF_JUDGE, - docketNumber: '101-20', - status: CASE_STATUS_TYPES.new, - }, -]; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('generateCaseInventoryReportPdf', () => { - let user; + const mockCases: RawCase[] = [ + { + associatedJudge: CHIEF_JUDGE, + canAllowPrintableDocketRecord: false, + caseCaption: 'Test Caption, Petitioner', + caseStatusHistory: [], + caseType: CASE_TYPES_MAP.disclosure, + consolidatedCases: [], + correspondence: [], + createdAt: '2018-11-21T20:49:28.192Z', + docketEntries: [], + docketNumber: '101-19', + entityName: 'Case', + hearings: [], + partyType: PARTY_TYPES.donor, + petitionPaymentStatus: PAYMENT_STATUS.PAID, + petitioners: [], + procedureType: PROCEDURE_TYPES_MAP.regular, + receivedAt: '2018-11-20T20:49:28.192Z', + sortableDocketNumber: 2001000101, + status: CASE_STATUS_TYPES.new, + }, + { + associatedJudge: CHIEF_JUDGE, + canAllowPrintableDocketRecord: true, + caseCaption: 'Test Caption Again, Petitioner', + caseStatusHistory: [], + caseType: CASE_TYPES_MAP.other, + consolidatedCases: [], + correspondence: [], + createdAt: '2020-07-21T20:49:28.192Z', + docketEntries: [], + docketNumber: '101-20', + entityName: 'Case', + hearings: [], + partyType: PARTY_TYPES.petitioner, + petitionPaymentStatus: PAYMENT_STATUS.PAID, + petitioners: [], + procedureType: PROCEDURE_TYPES_MAP.regular, + receivedAt: '2020-06-29T20:49:28.192Z', + sortableDocketNumber: 2001000111, + status: CASE_STATUS_TYPES.new, + }, + ]; beforeEach(() => { - user = { role: ROLES.petitionsClerk, userId: 'petitionsClerk' }; - - applicationContext.getCurrentUser.mockReturnValue(user); - applicationContext .getUseCaseHelpers() .saveFileAndGenerateUrl.mockReturnValue({ @@ -39,12 +72,10 @@ describe('generateCaseInventoryReportPdf', () => { }); it('throws an error if the user is unauthorized', async () => { - user = { role: ROLES.petitioner, userId: 'petitioner' }; - - applicationContext.getCurrentUser.mockReturnValue(user); await expect( generateCaseInventoryReportPdf({ applicationContext, + authorizedUser: mockPetitionerUser, cases: mockCases, filters: { associatedJudge: CHIEF_JUDGE }, }), @@ -54,6 +85,7 @@ describe('generateCaseInventoryReportPdf', () => { it('calls the pdf report generator', async () => { await generateCaseInventoryReportPdf({ applicationContext, + authorizedUser: mockPetitionsClerkUser, cases: mockCases, filters: { associatedJudge: CHIEF_JUDGE }, }); @@ -72,6 +104,7 @@ describe('generateCaseInventoryReportPdf', () => { it('returns the pre-signed url to the document', async () => { const result = await generateCaseInventoryReportPdf({ applicationContext, + authorizedUser: mockPetitionsClerkUser, cases: mockCases, filters: { associatedJudge: CHIEF_JUDGE }, }); @@ -87,6 +120,7 @@ describe('generateCaseInventoryReportPdf', () => { await expect( generateCaseInventoryReportPdf({ applicationContext, + authorizedUser: mockPetitionsClerkUser, cases: mockCases, filters: { associatedJudge: CHIEF_JUDGE }, }), @@ -100,6 +134,7 @@ describe('generateCaseInventoryReportPdf', () => { await generateCaseInventoryReportPdf({ applicationContext, + authorizedUser: mockPetitionsClerkUser, cases: mockCases, filters: { status: CASE_STATUS_TYPES.new }, }); @@ -118,6 +153,7 @@ describe('generateCaseInventoryReportPdf', () => { await generateCaseInventoryReportPdf({ applicationContext, + authorizedUser: mockPetitionsClerkUser, cases: mockCases, filters: { associatedJudge: CHIEF_JUDGE }, }); @@ -136,6 +172,7 @@ describe('generateCaseInventoryReportPdf', () => { await generateCaseInventoryReportPdf({ applicationContext, + authorizedUser: mockPetitionsClerkUser, cases: mockCases, filters: { associatedJudge: CHIEF_JUDGE, diff --git a/web-api/src/business/useCaseHelper/caseInventoryReport/generateCaseInventoryReportPdf.ts b/web-api/src/business/useCaseHelper/caseInventoryReport/generateCaseInventoryReportPdf.ts index d77257d23cf..8abd58223fb 100644 --- a/web-api/src/business/useCaseHelper/caseInventoryReport/generateCaseInventoryReportPdf.ts +++ b/web-api/src/business/useCaseHelper/caseInventoryReport/generateCaseInventoryReportPdf.ts @@ -4,17 +4,11 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; -/** - * Generate Case Inventory Report PDF - * - * @param {object} providers the providers object - * @param {object} providers.applicationContext the application context - * @param {string} providers.caseEntity a case entity with its documents - * @returns {Promise<*>} the promise of the document having been uploaded - */ export const generateCaseInventoryReportPdf = async ({ applicationContext, + authorizedUser, cases, filters, }: { @@ -24,10 +18,9 @@ export const generateCaseInventoryReportPdf = async ({ associatedJudge?: string; status?: string; }; + authorizedUser: UnknownAuthUser; }): Promise<{ fileId: string; url: string }> => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.CASE_INVENTORY_REPORT)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CASE_INVENTORY_REPORT)) { throw new UnauthorizedError('Unauthorized for case inventory report'); } diff --git a/web-api/src/business/useCaseHelper/consolidatedCases/formatPublicCase.test.ts b/web-api/src/business/useCaseHelper/consolidatedCases/formatPublicCase.test.ts index bb470ee371c..c9cf4ea9ef7 100644 --- a/web-api/src/business/useCaseHelper/consolidatedCases/formatPublicCase.test.ts +++ b/web-api/src/business/useCaseHelper/consolidatedCases/formatPublicCase.test.ts @@ -1,6 +1,5 @@ import { DOCKET_ENTRY_SEALED_TO_TYPES } from '@shared/business/entities/EntityConstants'; import { MOCK_CASE } from '@shared/test/mockCase'; -import { applicationContext } from '@shared/business/test/createTestApplicationContext'; import { cloneDeep } from 'lodash'; import { formatPublicCase } from '@web-api/business/useCaseHelper/consolidatedCases/formatPublicCase'; import { getContactPrimary } from '@shared/business/entities/cases/Case'; @@ -36,7 +35,6 @@ describe('getPublicCaseInteractor', () => { }; let result = await formatPublicCase({ - applicationContext, rawCaseRecord: sealedCase, }); @@ -46,7 +44,6 @@ describe('getPublicCaseInteractor', () => { delete sealedCase.isSealed; result = await formatPublicCase({ - applicationContext, rawCaseRecord: sealedCase, }); @@ -61,7 +58,6 @@ describe('getPublicCaseInteractor', () => { }; let result = await formatPublicCase({ - applicationContext, rawCaseRecord: { ...mockCase, docketEntries: sealedDocketEntries, @@ -87,7 +83,6 @@ describe('getPublicCaseInteractor', () => { }; let result = await formatPublicCase({ - applicationContext, rawCaseRecord: { ...mockCase, petitioners: [sealedContactPrimary] }, }); @@ -110,7 +105,6 @@ describe('getPublicCaseInteractor', () => { }; let result = await formatPublicCase({ - applicationContext, rawCaseRecord: mockCase, }); diff --git a/web-api/src/business/useCaseHelper/consolidatedCases/formatPublicCase.ts b/web-api/src/business/useCaseHelper/consolidatedCases/formatPublicCase.ts index 84989a29451..4a58fea6990 100644 --- a/web-api/src/business/useCaseHelper/consolidatedCases/formatPublicCase.ts +++ b/web-api/src/business/useCaseHelper/consolidatedCases/formatPublicCase.ts @@ -1,6 +1,5 @@ import { Case, isSealedCase } from '@shared/business/entities/cases/Case'; import { PublicCase } from '@shared/business/entities/cases/PublicCase'; -import { ServerApplicationContext } from '@web-api/applicationContext'; import { caseContactAddressSealedFormatter, caseSealedFormatter, @@ -15,12 +14,9 @@ import { decorateForCaseStatus } from '@shared/business/useCases/getCaseInteract * @param {object} providers.rawCaseRecord the rawCaseRecord * @returns {object} the validated public case data */ - export const formatPublicCase = ({ - applicationContext, rawCaseRecord, }: { - applicationContext: ServerApplicationContext; rawCaseRecord?: Case; }) => { if (isSealedCase(rawCaseRecord)) { @@ -34,7 +30,7 @@ export const formatPublicCase = ({ rawCaseRecord = decorateForCaseStatus(rawCaseRecord); const publicCaseDetail = new PublicCase(rawCaseRecord, { - applicationContext, + authorizedUser: undefined, }); return publicCaseDetail.validate().toRawObject(); diff --git a/web-api/src/business/useCaseHelper/docketEntry/closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments.test.ts b/web-api/src/business/useCaseHelper/docketEntry/closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments.test.ts index 43f566b96a1..dc334ad67b4 100644 --- a/web-api/src/business/useCaseHelper/docketEntry/closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments.test.ts +++ b/web-api/src/business/useCaseHelper/docketEntry/closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments.test.ts @@ -9,6 +9,7 @@ import { MOCK_TRIAL_REGULAR } from '../../../../../shared/src/test/mockTrial'; import { TrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments } from './closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments', () => { let mockCaseEntity; @@ -21,7 +22,7 @@ describe('closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments', () => { beforeEach(() => { mockCaseEntity = new Case(MOCK_CASE, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); }); @@ -73,7 +74,7 @@ describe('closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments', () => { applicationContext, caseEntity: new Case( { ...MOCK_CASE, trialSessionId: undefined }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ), eventCode, }); @@ -98,7 +99,7 @@ describe('closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments', () => { applicationContext, caseEntity: new Case( { ...MOCK_CASE, trialSessionId: MOCK_TRIAL_REGULAR.trialSessionId }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ), eventCode, }); @@ -121,7 +122,7 @@ describe('closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments', () => { applicationContext, caseEntity: new Case( { ...MOCK_CASE, trialSessionId: MOCK_TRIAL_REGULAR.trialSessionId }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ), eventCode, }); @@ -144,7 +145,7 @@ describe('closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments', () => { applicationContext, caseEntity: new Case( { ...MOCK_CASE, trialSessionId: MOCK_TRIAL_REGULAR.trialSessionId }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ), eventCode, }), @@ -167,7 +168,7 @@ describe('closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments', () => { applicationContext, caseEntity: new Case( { ...MOCK_CASE, trialSessionId: MOCK_TRIAL_REGULAR.trialSessionId }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ), eventCode, }); diff --git a/web-api/src/business/useCaseHelper/docketEntry/closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments.ts b/web-api/src/business/useCaseHelper/docketEntry/closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments.ts index d021decba21..55c444af926 100644 --- a/web-api/src/business/useCaseHelper/docketEntry/closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments.ts +++ b/web-api/src/business/useCaseHelper/docketEntry/closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments.ts @@ -39,9 +39,7 @@ export const closeCaseAndUpdateTrialSessionForEnteredAndServedDocuments = ); } - const trialSessionEntity = new TrialSession(trialSession, { - applicationContext, - }); + const trialSessionEntity = new TrialSession(trialSession); if (trialSessionEntity.isCalendared) { trialSessionEntity.removeCaseFromCalendar({ diff --git a/web-api/src/business/useCaseHelper/docketEntry/createAndServeNoticeDocketEntry.test.ts b/web-api/src/business/useCaseHelper/docketEntry/createAndServeNoticeDocketEntry.test.ts index 7bf155796b0..72fef507ea5 100644 --- a/web-api/src/business/useCaseHelper/docketEntry/createAndServeNoticeDocketEntry.test.ts +++ b/web-api/src/business/useCaseHelper/docketEntry/createAndServeNoticeDocketEntry.test.ts @@ -1,5 +1,3 @@ -import { getFakeFile } from '../../../../../shared/src/business/test/getFakeFile'; - import { Case } from '../../../../../shared/src/business/entities/cases/Case'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { @@ -8,7 +6,8 @@ import { } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { createAndServeNoticeDocketEntry } from './createAndServeNoticeDocketEntry'; -import { docketClerk1User } from '../../../../../shared/src/test/mockUsers'; +import { getFakeFile } from '../../../../../shared/src/business/test/getFakeFile'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('createAndServeDocketEntry', () => { const mockDocketEntryId = '85a5b1c81eed44b6932a967af060597a'; @@ -18,7 +17,7 @@ describe('createAndServeDocketEntry', () => { { ...MOCK_CASE, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); beforeEach(() => { @@ -36,13 +35,17 @@ describe('createAndServeDocketEntry', () => { }); it('should save the generated notice to s3', async () => { - await createAndServeNoticeDocketEntry(applicationContext, { - caseEntity: mockCaseEntity, - documentInfo: SYSTEM_GENERATED_DOCUMENT_TYPES.noticeOfChangeOfTrialJudge, - newPdfDoc: getFakeFile, - noticePdf: mockNotice, - user: docketClerk1User, - }); + await createAndServeNoticeDocketEntry( + applicationContext, + { + caseEntity: mockCaseEntity, + documentInfo: + SYSTEM_GENERATED_DOCUMENT_TYPES.noticeOfChangeOfTrialJudge, + newPdfDoc: getFakeFile, + noticePdf: mockNotice, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveDocumentFromLambda.mock @@ -54,13 +57,17 @@ describe('createAndServeDocketEntry', () => { }); it('should create and serve a docket entry and add it to the docket record', async () => { - await createAndServeNoticeDocketEntry(applicationContext, { - caseEntity: mockCaseEntity, - documentInfo: SYSTEM_GENERATED_DOCUMENT_TYPES.noticeOfChangeOfTrialJudge, - newPdfDoc: getFakeFile, - noticePdf: mockNotice, - user: docketClerk1User, - }); + await createAndServeNoticeDocketEntry( + applicationContext, + { + caseEntity: mockCaseEntity, + documentInfo: + SYSTEM_GENERATED_DOCUMENT_TYPES.noticeOfChangeOfTrialJudge, + newPdfDoc: getFakeFile, + noticePdf: mockNotice, + }, + mockDocketClerkUser, + ); const expectedNotice = mockCaseEntity.docketEntries.find( doc => @@ -92,16 +99,20 @@ describe('createAndServeDocketEntry', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); - await createAndServeNoticeDocketEntry(applicationContext, { - caseEntity: mockCaseWithPaperService, - documentInfo: SYSTEM_GENERATED_DOCUMENT_TYPES.noticeOfChangeOfTrialJudge, - newPdfDoc: getFakeFile, - noticePdf: mockNotice, - user: docketClerk1User, - }); + await createAndServeNoticeDocketEntry( + applicationContext, + { + caseEntity: mockCaseWithPaperService, + documentInfo: + SYSTEM_GENERATED_DOCUMENT_TYPES.noticeOfChangeOfTrialJudge, + newPdfDoc: getFakeFile, + noticePdf: mockNotice, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().serveGeneratedNoticesOnCase, diff --git a/web-api/src/business/useCaseHelper/docketEntry/createAndServeNoticeDocketEntry.ts b/web-api/src/business/useCaseHelper/docketEntry/createAndServeNoticeDocketEntry.ts index 95772a2790b..abadb1a5098 100644 --- a/web-api/src/business/useCaseHelper/docketEntry/createAndServeNoticeDocketEntry.ts +++ b/web-api/src/business/useCaseHelper/docketEntry/createAndServeNoticeDocketEntry.ts @@ -1,3 +1,4 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { Case } from '../../../../../shared/src/business/entities/cases/Case'; import { DOCUMENT_PROCESSING_STATUS_OPTIONS, @@ -7,7 +8,6 @@ import { DocketEntry, getServedPartiesCode, } from '../../../../../shared/src/business/entities/DocketEntry'; -import { RawUser } from '@shared/business/entities/User'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { aggregatePartiesForService } from '../../../../../shared/src/business/utilities/aggregatePartiesForService'; import { createISODateString } from '../../../../../shared/src/business/utilities/DateHandler'; @@ -21,7 +21,6 @@ export const createAndServeNoticeDocketEntry = async ( newPdfDoc, noticePdf, onlyProSePetitioners, - user, }: { additionalDocketEntryInfo?: any; caseEntity: Case; @@ -31,10 +30,10 @@ export const createAndServeNoticeDocketEntry = async ( eventCode: string; }; newPdfDoc: any; - noticePdf: Buffer; - user: RawUser; + noticePdf: Uint8Array; onlyProSePetitioners?: boolean; }, + authorizedUser: AuthUser, ) => { const docketEntryId = applicationContext.getUniqueId(); @@ -73,10 +72,10 @@ export const createAndServeNoticeDocketEntry = async ( : getServedPartiesCode(servedParties.all), ...additionalDocketEntryInfo, }, - { applicationContext }, + { authorizedUser }, ); - noticeDocketEntry.setFiledBy(user); + noticeDocketEntry.setFiledBy(authorizedUser); caseEntity.addDocketEntry(noticeDocketEntry); diff --git a/web-api/src/business/useCaseHelper/docketEntry/fileAndServeDocumentOnOneCase.test.ts b/web-api/src/business/useCaseHelper/docketEntry/fileAndServeDocumentOnOneCase.test.ts index 49a04474f36..bac981e91e4 100644 --- a/web-api/src/business/useCaseHelper/docketEntry/fileAndServeDocumentOnOneCase.test.ts +++ b/web-api/src/business/useCaseHelper/docketEntry/fileAndServeDocumentOnOneCase.test.ts @@ -21,6 +21,7 @@ import { judgeUser, } from '../../../../../shared/src/test/mockUsers'; import { fileAndServeDocumentOnOneCase } from './fileAndServeDocumentOnOneCase'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('fileAndServeDocumentOnOneCase', () => { let mockCaseEntity; @@ -54,7 +55,7 @@ describe('fileAndServeDocumentOnOneCase', () => { workItemId: 'b4c7337f-9ca0-45d9-9396-75e003f81e32', }, }, - { applicationContext }, + { authorizedUser: undefined }, ); }); @@ -67,7 +68,7 @@ describe('fileAndServeDocumentOnOneCase', () => { beforeEach(() => { mockCaseEntity = new Case(MOCK_CASE, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); applicationContext @@ -97,7 +98,7 @@ describe('fileAndServeDocumentOnOneCase', () => { signedJudgeName: judgeUser.name, workItem: mockWorkItem, }, - { applicationContext }, + { authorizedUser: undefined }, ); }); @@ -116,7 +117,7 @@ describe('fileAndServeDocumentOnOneCase', () => { signedJudgeName: judgeUser.name, workItem: undefined, }, - { applicationContext }, + { authorizedUser: undefined }, ); await fileAndServeDocumentOnOneCase({ @@ -132,7 +133,7 @@ describe('fileAndServeDocumentOnOneCase', () => { it('should not add a new docket entry when it already exists on the case', async () => { const docketEntryOnCase = new DocketEntry(mockCaseEntity.docketEntries[0], { - applicationContext, + authorizedUser: undefined, }); await fileAndServeDocumentOnOneCase({ @@ -161,7 +162,7 @@ describe('fileAndServeDocumentOnOneCase', () => { signedJudgeName: judgeUser.name, workItem: undefined, }, - { applicationContext }, + { authorizedUser: undefined }, ); await fileAndServeDocumentOnOneCase({ @@ -202,7 +203,7 @@ describe('fileAndServeDocumentOnOneCase', () => { signedJudgeName: judgeUser.name, workItem: mockWorkItem, }, - { applicationContext }, + { authorizedUser: undefined }, ); await fileAndServeDocumentOnOneCase({ @@ -230,7 +231,7 @@ describe('fileAndServeDocumentOnOneCase', () => { caseEntity: new Case( { ...MOCK_CASE, leadDocketNumber: MOCK_CASE.docketNumber }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ), docketEntryEntity: mockDocketEntry, @@ -250,7 +251,7 @@ describe('fileAndServeDocumentOnOneCase', () => { caseEntity: new Case( { ...MOCK_CASE, leadDocketNumber: MOCK_CASE.docketNumber }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ), docketEntryEntity: mockDocketEntry, @@ -274,7 +275,7 @@ describe('fileAndServeDocumentOnOneCase', () => { caseEntity: new Case( { ...MOCK_CASE, leadDocketNumber: MOCK_CASE.docketNumber }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ), docketEntryEntity: mockDocketEntry, @@ -310,7 +311,7 @@ describe('fileAndServeDocumentOnOneCase', () => { index: undefined, isOnDocketRecord: true, }, - { applicationContext }, + { authorizedUser: undefined }, ), subjectCaseDocketNumber: mockCaseEntity.docketNumber, user: docketClerkUser, @@ -385,7 +386,7 @@ describe('fileAndServeDocumentOnOneCase', () => { trialLocation: 'Lubbock, Texas', }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -403,7 +404,7 @@ describe('fileAndServeDocumentOnOneCase', () => { signedJudgeName: judgeUser.name, workItem: undefined, }, - { applicationContext }, + { authorizedUser: undefined }, ); await fileAndServeDocumentOnOneCase({ @@ -438,7 +439,7 @@ describe('fileAndServeDocumentOnOneCase', () => { signedByUserId: judgeUser.userId, signedJudgeName: judgeUser.name, }, - { applicationContext }, + { authorizedUser: undefined }, ); await fileAndServeDocumentOnOneCase({ @@ -491,7 +492,7 @@ describe('fileAndServeDocumentOnOneCase', () => { docketEntryId: mockDocketEntryId, pending: true, }, - { applicationContext }, + { authorizedUser: undefined }, ); applicationContext diff --git a/web-api/src/business/useCaseHelper/docketEntry/fileAndServeDocumentOnOneCase.ts b/web-api/src/business/useCaseHelper/docketEntry/fileAndServeDocumentOnOneCase.ts index 7fa756546c4..1f0019ca659 100644 --- a/web-api/src/business/useCaseHelper/docketEntry/fileAndServeDocumentOnOneCase.ts +++ b/web-api/src/business/useCaseHelper/docketEntry/fileAndServeDocumentOnOneCase.ts @@ -1,6 +1,7 @@ import { Case } from '../../../../../shared/src/business/entities/cases/Case'; import { DOCKET_SECTION } from '../../../../../shared/src/business/entities/EntityConstants'; import { ENTERED_AND_SERVED_EVENT_CODES } from '../../../../../shared/src/business/entities/courtIssuedDocument/CourtIssuedDocumentConstants'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { WorkItem } from '../../../../../shared/src/business/entities/WorkItem'; import { aggregatePartiesForService } from '../../../../../shared/src/business/utilities/aggregatePartiesForService'; @@ -10,6 +11,12 @@ export const fileAndServeDocumentOnOneCase = async ({ docketEntryEntity, subjectCaseDocketNumber, user, +}: { + applicationContext: ServerApplicationContext; + caseEntity: any; + docketEntryEntity: any; + subjectCaseDocketNumber: any; + user: any; }) => { const servedParties = aggregatePartiesForService(caseEntity); @@ -40,8 +47,7 @@ export const fileAndServeDocumentOnOneCase = async ({ trialDate: caseEntity.trialDate, trialLocation: caseEntity.trialLocation, }, - { applicationContext }, - caseEntity, + { caseEntity }, ); } @@ -88,10 +94,13 @@ export const fileAndServeDocumentOnOneCase = async ({ .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser: user, caseToUpdate: caseEntity, }); - return new Case(validRawCaseEntity, { applicationContext }); + return new Case(validRawCaseEntity, { + authorizedUser: user, + }); }; const completeWorkItem = async ({ diff --git a/web-api/src/business/useCaseHelper/generateChangeOfAddressHelper.ts b/web-api/src/business/useCaseHelper/generateChangeOfAddressHelper.ts index cb07c97a904..2b40dfd0a37 100644 --- a/web-api/src/business/useCaseHelper/generateChangeOfAddressHelper.ts +++ b/web-api/src/business/useCaseHelper/generateChangeOfAddressHelper.ts @@ -1,5 +1,9 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { Case } from '@shared/business/entities/cases/Case'; -import { Practitioner } from '../../../../shared/src/business/entities/Practitioner'; +import { + Practitioner, + RawPractitioner, +} from '../../../../shared/src/business/entities/Practitioner'; import { ROLES, SERVICE_INDICATOR_TYPES, @@ -20,6 +24,7 @@ import { generateAndServeDocketEntry } from '@web-api/business/useCaseHelper/ser */ export const generateChangeOfAddressHelper = async ({ applicationContext, + authorizedUser, bypassDocketEntry, contactInfo, docketNumber, @@ -32,6 +37,7 @@ export const generateChangeOfAddressHelper = async ({ websocketMessagePrefix, }: { applicationContext: ServerApplicationContext; + authorizedUser: AuthUser; docketNumber: string; bypassDocketEntry: boolean; contactInfo: TUserContact; @@ -52,7 +58,9 @@ export const generateChangeOfAddressHelper = async ({ applicationContext, docketNumber, }); - let caseEntity = new Case(userCase, { applicationContext }); + let caseEntity = new Case(userCase, { + authorizedUser, + }); const practitionerName = updatedName || user.name; const practitionerObject = caseEntity.privatePractitioners @@ -81,6 +89,7 @@ export const generateChangeOfAddressHelper = async ({ if (!bypassDocketEntry && caseEntity.shouldGenerateNoticesForCase()) { await prepareToGenerateAndServeDocketEntry({ applicationContext, + authorizedUser, caseEntity, newData, oldData, @@ -91,6 +100,7 @@ export const generateChangeOfAddressHelper = async ({ await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); } catch (error) { @@ -153,11 +163,20 @@ export const generateChangeOfAddressHelper = async ({ */ const prepareToGenerateAndServeDocketEntry = async ({ applicationContext, + authorizedUser, caseEntity, newData, oldData, practitionerName, user, +}: { + applicationContext: any; + caseEntity: any; + newData: any; + oldData: any; + practitionerName: any; + user: any; + authorizedUser: AuthUser; }) => { const documentType = applicationContext .getUtilities() @@ -184,6 +203,7 @@ const prepareToGenerateAndServeDocketEntry = async ({ newData.name = practitionerName; const { changeOfAddressDocketEntry } = await generateAndServeDocketEntry({ applicationContext, + authorizedUser, barNumber: user.barNumber, caseEntity, docketMeta, diff --git a/web-api/src/business/useCaseHelper/getJudgeForUserHelper.test.ts b/web-api/src/business/useCaseHelper/getJudgeForUserHelper.test.ts index 15fc2c65038..3c14e71bc81 100644 --- a/web-api/src/business/useCaseHelper/getJudgeForUserHelper.test.ts +++ b/web-api/src/business/useCaseHelper/getJudgeForUserHelper.test.ts @@ -1,6 +1,11 @@ import { ROLES } from '@shared/business/entities/EntityConstants'; import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; import { getJudgeForUserHelper } from './getJudgeForUserHelper'; +import { + mockChambersUser, + mockDocketClerkUser, + mockJudgeUser, +} from '@shared/test/mockAuthUsers'; import { validUser } from '@shared/test/mockUsers'; describe('getJudgeForUserHelper', () => { @@ -32,11 +37,11 @@ describe('getJudgeForUserHelper', () => { describe('Judge User', () => { beforeAll(() => { - mockFoundUser = judgeUser; + mockFoundUser = mockJudgeUser; }); it('retrieves the specified user from the database by its userId', async () => { - await getJudgeForUserHelper(applicationContext, { user: judgeUser }); + await getJudgeForUserHelper(applicationContext, { user: mockJudgeUser }); expect( applicationContext.getPersistenceGateway().getUserById, @@ -48,9 +53,9 @@ describe('getJudgeForUserHelper', () => { it('returns the retrieved from the database', async () => { const result = await getJudgeForUserHelper(applicationContext, { - user: judgeUser, + user: mockJudgeUser, }); - expect(result).toMatchObject(judgeUser); + expect(result).toMatchObject(mockJudgeUser); }); }); @@ -64,7 +69,7 @@ describe('getJudgeForUserHelper', () => { it('calls getJudgeInSectionHelper with the retrieved user`s section if they are a chambers user', async () => { await getJudgeForUserHelper(applicationContext, { - user: chambersUser, + user: mockChambersUser, }); expect( @@ -75,12 +80,8 @@ describe('getJudgeForUserHelper', () => { }); it('returns the user that getJudgeInSectionHelper found', async () => { - await getJudgeForUserHelper(applicationContext, { - user: chambersUser, - }); - const result = await getJudgeForUserHelper(applicationContext, { - user: judgeUser, + user: mockJudgeUser, }); expect(result).toMatchObject(judgeUser); }); @@ -92,7 +93,7 @@ describe('getJudgeForUserHelper', () => { await expect( getJudgeForUserHelper(applicationContext, { - user: docketClerkUser, + user: mockDocketClerkUser, }), ).rejects.toThrow( `Could not find Judge for Chambers Section ${chambersUser.section}`, @@ -105,7 +106,7 @@ describe('getJudgeForUserHelper', () => { mockFoundUser = docketClerkUser; await expect( getJudgeForUserHelper(applicationContext, { - user: docketClerkUser, + user: mockDocketClerkUser, }), ).rejects.toThrow( 'Could not get Judge User ID for non Judge or Chambers User', diff --git a/web-api/src/business/useCaseHelper/getJudgeForUserHelper.ts b/web-api/src/business/useCaseHelper/getJudgeForUserHelper.ts index fb3c89d35a7..d728e0f2b91 100644 --- a/web-api/src/business/useCaseHelper/getJudgeForUserHelper.ts +++ b/web-api/src/business/useCaseHelper/getJudgeForUserHelper.ts @@ -1,10 +1,11 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { InvalidRequest } from '@web-api/errors/errors'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { User } from '@shared/business/entities/User'; export const getJudgeForUserHelper = async ( applicationContext: ServerApplicationContext, - { user }: { user: { userId: string } }, + { user }: { user: AuthUser }, ): Promise> => { const rawUser = await applicationContext.getPersistenceGateway().getUserById({ applicationContext, diff --git a/web-api/src/business/useCaseHelper/getJudgeInSectionHelper.test.ts b/web-api/src/business/useCaseHelper/getJudgeInSectionHelper.test.ts index 07c36acce0e..b9f6c9ef011 100644 --- a/web-api/src/business/useCaseHelper/getJudgeInSectionHelper.test.ts +++ b/web-api/src/business/useCaseHelper/getJudgeInSectionHelper.test.ts @@ -2,13 +2,7 @@ import { ROLES } from '../../../../shared/src/business/entities/EntityConstants' import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; import { getJudgeInSectionHelper } from './getJudgeInSectionHelper'; -let currentUser; - describe('getJudgeInSectionHelper', () => { - beforeEach(() => { - applicationContext.getCurrentUser.mockImplementation(() => currentUser); - }); - it('Fetches the judge associated with a given section', async () => { const expectedJudgeUser = { isSeniorJudge: false, diff --git a/web-api/src/business/useCaseHelper/getJudgeInSectionHelper.ts b/web-api/src/business/useCaseHelper/getJudgeInSectionHelper.ts index a46579baf52..4e95096ed07 100644 --- a/web-api/src/business/useCaseHelper/getJudgeInSectionHelper.ts +++ b/web-api/src/business/useCaseHelper/getJudgeInSectionHelper.ts @@ -21,9 +21,7 @@ export const getJudgeInSectionHelper = async ( section, }); - const sectionUsers = User.validateRawCollection(rawUsers, { - applicationContext, - }); + const sectionUsers = User.validateRawCollection(rawUsers); const judgeUser = sectionUsers.find( sectionUser => sectionUser.role === ROLES.judge, diff --git a/web-api/src/business/useCaseHelper/initialFilingDocuments/updateInitialFilingDocuments.test.ts b/web-api/src/business/useCaseHelper/initialFilingDocuments/updateInitialFilingDocuments.test.ts index d277174b033..8edbe0dc25c 100644 --- a/web-api/src/business/useCaseHelper/initialFilingDocuments/updateInitialFilingDocuments.test.ts +++ b/web-api/src/business/useCaseHelper/initialFilingDocuments/updateInitialFilingDocuments.test.ts @@ -2,7 +2,6 @@ import { CONTACT_TYPES, INITIAL_DOCUMENT_TYPES, PARTY_TYPES, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { Case, @@ -11,6 +10,7 @@ import { import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_DOCUMENTS } from '../../../../../shared/src/test/mockDocketEntry'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { mockPetitionsClerkUser } from '@shared/test/mockAuthUsers'; import { updateInitialFilingDocuments } from './updateInitialFilingDocuments'; describe('addNewInitialFilingToCase', () => { @@ -38,16 +38,10 @@ describe('addNewInitialFilingToCase', () => { let mockOriginalCase; let mockCaseToUpdate; - const petitionsClerkUser = { - name: 'petitions clerk', - role: ROLES.petitionsClerk, - userId: '54cddcd9-d012-4874-b74f-73732c95d42b', - }; - it('should add a new initial filing document to the case when the document does not exist on the original case', async () => { mockOriginalCase = new Case( { ...MOCK_CASE, docketEntries: [mockPetition] }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); mockCaseToUpdate = { @@ -57,7 +51,7 @@ describe('addNewInitialFilingToCase', () => { await updateInitialFilingDocuments({ applicationContext, - authorizedUser: petitionsClerkUser, + authorizedUser: mockPetitionsClerkUser, caseEntity: mockOriginalCase, caseToUpdate: mockCaseToUpdate, }); @@ -72,7 +66,7 @@ describe('addNewInitialFilingToCase', () => { it('should add a new STIN to the case when one does not exist on the original case', async () => { mockOriginalCase = new Case( { ...MOCK_CASE, docketEntries: [mockPetition] }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); mockCaseToUpdate = { @@ -82,7 +76,7 @@ describe('addNewInitialFilingToCase', () => { await updateInitialFilingDocuments({ applicationContext, - authorizedUser: petitionsClerkUser, + authorizedUser: mockPetitionsClerkUser, caseEntity: mockOriginalCase, caseToUpdate: mockCaseToUpdate, }); @@ -97,7 +91,7 @@ describe('addNewInitialFilingToCase', () => { it('should set isFileAttached and isPaper to true', async () => { mockOriginalCase = new Case( { ...MOCK_CASE, docketEntries: [mockPetition] }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); mockCaseToUpdate = { @@ -107,7 +101,7 @@ describe('addNewInitialFilingToCase', () => { await updateInitialFilingDocuments({ applicationContext, - authorizedUser: petitionsClerkUser, + authorizedUser: mockPetitionsClerkUser, caseEntity: mockOriginalCase, caseToUpdate: mockCaseToUpdate, }); @@ -135,7 +129,7 @@ describe('addNewInitialFilingToCase', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); mockCaseToUpdate = { @@ -154,7 +148,7 @@ describe('addNewInitialFilingToCase', () => { await updateInitialFilingDocuments({ applicationContext, - authorizedUser: petitionsClerkUser, + authorizedUser: mockPetitionsClerkUser, caseEntity: mockOriginalCase, caseToUpdate: mockCaseToUpdate, }); @@ -175,12 +169,12 @@ describe('addNewInitialFilingToCase', () => { ...MOCK_CASE, docketEntries: [...MOCK_CASE.docketEntries, mockRQT], }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); await updateInitialFilingDocuments({ applicationContext, - authorizedUser: petitionsClerkUser, + authorizedUser: mockPetitionsClerkUser, caseEntity: mockOriginalCase, caseToUpdate: mockCaseToUpdate, }); @@ -194,7 +188,7 @@ describe('addNewInitialFilingToCase', () => { it('should remove the original document and add the new one to the case when the document has been re-added', async () => { mockOriginalCase = new Case( { ...MOCK_CASE, docketEntries: [...MOCK_CASE.docketEntries, mockRQT] }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); const mockNewRQT = { @@ -208,7 +202,7 @@ describe('addNewInitialFilingToCase', () => { await updateInitialFilingDocuments({ applicationContext, - authorizedUser: petitionsClerkUser, + authorizedUser: mockPetitionsClerkUser, caseEntity: mockOriginalCase, caseToUpdate: mockCaseToUpdate, }); diff --git a/web-api/src/business/useCaseHelper/initialFilingDocuments/updateInitialFilingDocuments.ts b/web-api/src/business/useCaseHelper/initialFilingDocuments/updateInitialFilingDocuments.ts index 06bd22f6098..15dfbd15efe 100644 --- a/web-api/src/business/useCaseHelper/initialFilingDocuments/updateInitialFilingDocuments.ts +++ b/web-api/src/business/useCaseHelper/initialFilingDocuments/updateInitialFilingDocuments.ts @@ -6,7 +6,6 @@ import { import { omit } from 'lodash'; const addNewInitialFilingToCase = ({ - applicationContext, authorizedUser, caseEntity, currentCaseDocument, @@ -22,7 +21,7 @@ const addNewInitialFilingToCase = ({ ...currentCaseDocument, }, { - applicationContext, + authorizedUser, petitioners: caseEntity.petitioners, }, ); @@ -52,7 +51,7 @@ const addNewInitialFilingToCase = ({ receivedAt: caseEntity.receivedAt, }, { - applicationContext, + authorizedUser, petitioners: caseEntity.petitioners, }, ); @@ -120,9 +119,10 @@ export const updateInitialFilingDocuments = async ({ originalCaseDocument.docketEntryId !== currentCaseDocument.docketEntryId ) { addNewInitialFilingToCase({ - applicationContext, + authorizedUser, caseEntity, currentCaseDocument, + documentType, originalCaseDocument, }); await deleteInitialFilingFromCase({ @@ -133,11 +133,11 @@ export const updateInitialFilingDocuments = async ({ } } else if (!originalCaseDocument && currentCaseDocument) { addNewInitialFilingToCase({ - applicationContext, authorizedUser, caseEntity, currentCaseDocument, documentType, + originalCaseDocument, }); } else if (originalCaseDocument && !currentCaseDocument) { await deleteInitialFilingFromCase({ diff --git a/web-api/src/business/useCaseHelper/noticeOfDocketChange/generateNoticeOfDocketChangePdf.test.ts b/web-api/src/business/useCaseHelper/noticeOfDocketChange/generateNoticeOfDocketChangePdf.test.ts index 5f6a7ce7ce4..f6abf5a878c 100644 --- a/web-api/src/business/useCaseHelper/noticeOfDocketChange/generateNoticeOfDocketChangePdf.test.ts +++ b/web-api/src/business/useCaseHelper/noticeOfDocketChange/generateNoticeOfDocketChangePdf.test.ts @@ -1,21 +1,18 @@ import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; -import { - docketClerkUser, - irsSuperuserUser, -} from '../../../../../shared/src/test/mockUsers'; import { generateNoticeOfDocketChangePdf } from './generateNoticeOfDocketChangePdf'; +import { + mockDocketClerkUser, + mockIrsSuperuser, +} from '@shared/test/mockAuthUsers'; describe('generateNoticeOfDocketChangePdf', () => { - beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - }); + beforeEach(() => {}); it('should throw an error when the user does not have permission to generate a notice of docket change', async () => { - applicationContext.getCurrentUser.mockReturnValue(irsSuperuserUser); // IRS Superuser does not have this permission - await expect( generateNoticeOfDocketChangePdf({ applicationContext, + authorizedUser: mockIrsSuperuser, docketChangeInfo: { caseCaptionExtension: 'Bert & Ernie, Petitioners v. Commissioner of Internal Revenue, Respondent', @@ -36,6 +33,7 @@ describe('generateNoticeOfDocketChangePdf', () => { const result = await generateNoticeOfDocketChangePdf({ applicationContext, + authorizedUser: mockDocketClerkUser, docketChangeInfo: { caseCaptionExtension: 'Bert & Ernie, Petitioners v. Commissioner of Internal Revenue, Respondent', diff --git a/web-api/src/business/useCaseHelper/noticeOfDocketChange/generateNoticeOfDocketChangePdf.ts b/web-api/src/business/useCaseHelper/noticeOfDocketChange/generateNoticeOfDocketChangePdf.ts index 61d42509ee0..7075722baa3 100644 --- a/web-api/src/business/useCaseHelper/noticeOfDocketChange/generateNoticeOfDocketChangePdf.ts +++ b/web-api/src/business/useCaseHelper/noticeOfDocketChange/generateNoticeOfDocketChangePdf.ts @@ -4,9 +4,11 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const generateNoticeOfDocketChangePdf = async ({ applicationContext, + authorizedUser, docketChangeInfo, }: { applicationContext: ServerApplicationContext; @@ -20,10 +22,9 @@ export const generateNoticeOfDocketChangePdf = async ({ filingParties: { after: string | undefined; before: string | undefined }; filingsAndProceedings: { after: string; before: string }; }; + authorizedUser: UnknownAuthUser; }): Promise => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.UPLOAD_DOCUMENT)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.UPLOAD_DOCUMENT)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCaseHelper/saveFileAndGenerateUrl.ts b/web-api/src/business/useCaseHelper/saveFileAndGenerateUrl.ts index ac145106111..84794b5f14f 100644 --- a/web-api/src/business/useCaseHelper/saveFileAndGenerateUrl.ts +++ b/web-api/src/business/useCaseHelper/saveFileAndGenerateUrl.ts @@ -9,7 +9,7 @@ export const saveFileAndGenerateUrl = async ({ useTempBucket = false, }: { applicationContext: ServerApplicationContext; - file: Buffer; + file: WithImplicitCoercion; fileNamePrefix?: string; contentType?: string; useTempBucket?: boolean; diff --git a/web-api/src/business/useCaseHelper/sealInLowerEnvironment.test.ts b/web-api/src/business/useCaseHelper/sealInLowerEnvironment.test.ts index 3b21076e72c..b6199edd967 100644 --- a/web-api/src/business/useCaseHelper/sealInLowerEnvironment.test.ts +++ b/web-api/src/business/useCaseHelper/sealInLowerEnvironment.test.ts @@ -1,6 +1,6 @@ import { MOCK_CASE } from '../../../../shared/src/test/mockCase'; -import { ROLES } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { sealInLowerEnvironment } from './sealInLowerEnvironment'; describe('sealInLowerEnvironment', () => { @@ -11,17 +11,19 @@ describe('sealInLowerEnvironment', () => { applicationContext.getNotificationGateway().sendNotificationOfSealing = jest.fn(); applicationContext.isCurrentColorActive = jest.fn().mockReturnValue(true); - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - }); }); it('should seal the case with the docketNumber provided and return the updated case', async () => { - const result = await sealInLowerEnvironment(applicationContext, [ - { - docketNumber: MOCK_CASE.docketNumber, - }, - ]); + const result = await sealInLowerEnvironment( + applicationContext, + [ + { + docketNumber: MOCK_CASE.docketNumber, + }, + ], + mockDocketClerkUser, + ); + expect( applicationContext.getUseCases().sealCaseInteractor, ).toHaveBeenCalled(); @@ -29,7 +31,8 @@ describe('sealInLowerEnvironment', () => { }); it('should only log a warning if we do not have a docketNumber', async () => { - await sealInLowerEnvironment(applicationContext, [{}]); + await sealInLowerEnvironment(applicationContext, [{}], mockDocketClerkUser); + expect( applicationContext.getUseCases().sealCaseInteractor, ).not.toHaveBeenCalled(); @@ -38,11 +41,17 @@ describe('sealInLowerEnvironment', () => { it('should not execute if the current color is not active', async () => { applicationContext.isCurrentColorActive = jest.fn().mockReturnValue(false); - await sealInLowerEnvironment(applicationContext, [ - { - docketNumber: '123-21', - }, - ]); + + await sealInLowerEnvironment( + applicationContext, + [ + { + docketNumber: '123-21', + }, + ], + mockDocketClerkUser, + ); + expect( applicationContext.getUseCases().sealCaseInteractor, ).not.toHaveBeenCalled(); diff --git a/web-api/src/business/useCaseHelper/sealInLowerEnvironment.ts b/web-api/src/business/useCaseHelper/sealInLowerEnvironment.ts index d6cb633f5d3..94b827ef3c1 100644 --- a/web-api/src/business/useCaseHelper/sealInLowerEnvironment.ts +++ b/web-api/src/business/useCaseHelper/sealInLowerEnvironment.ts @@ -1,3 +1,6 @@ +import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; + /** * sealInLowerEnvironment * @@ -5,7 +8,11 @@ * @param {array} records an array of docketNumbers and/or docketEntryIds to seal * @returns {Promise} the array of responses from the interactor */ -export const sealInLowerEnvironment = async (applicationContext, records) => { +export const sealInLowerEnvironment = async ( + applicationContext: ServerApplicationContext, + records, + authorizedUser: UnknownAuthUser, +) => { const isCurrentColorActive = await applicationContext.isCurrentColorActive(applicationContext); @@ -25,11 +32,13 @@ export const sealInLowerEnvironment = async (applicationContext, records) => { // docketNumber, // }); } else if (docketNumber) { - return applicationContext - .getUseCases() - .sealCaseInteractor(applicationContext, { + return applicationContext.getUseCases().sealCaseInteractor( + applicationContext, + { docketNumber, - }); + }, + authorizedUser, + ); } applicationContext.logger.warn( diff --git a/web-api/src/business/useCaseHelper/serveDocumentAndGetPaperServicePdf.test.ts b/web-api/src/business/useCaseHelper/serveDocumentAndGetPaperServicePdf.test.ts index 69eacb876a1..dd52de4b925 100644 --- a/web-api/src/business/useCaseHelper/serveDocumentAndGetPaperServicePdf.test.ts +++ b/web-api/src/business/useCaseHelper/serveDocumentAndGetPaperServicePdf.test.ts @@ -8,6 +8,7 @@ import { } from '../../../../shared/src/test/mockCase'; import { SERVICE_INDICATOR_TYPES } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { serveDocumentAndGetPaperServicePdf } from './serveDocumentAndGetPaperServicePdf'; describe('serveDocumentAndGetPaperServicePdf', () => { @@ -17,7 +18,7 @@ describe('serveDocumentAndGetPaperServicePdf', () => { const mockDocketEntryId = 'cf105788-5d34-4451-aa8d-dfd9a851b675'; beforeEach(() => { - caseEntity = new Case(MOCK_CASE, { applicationContext }); + caseEntity = new Case(MOCK_CASE, { authorizedUser: mockDocketClerkUser }); applicationContext .getPersistenceGateway() @@ -79,7 +80,7 @@ describe('serveDocumentAndGetPaperServicePdf', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); const result = await serveDocumentAndGetPaperServicePdf({ @@ -123,11 +124,11 @@ describe('serveDocumentAndGetPaperServicePdf', () => { { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER }, ], }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); const secondCaseEntity = new Case(MOCK_LEAD_CASE_WITH_PAPER_SERVICE, { - applicationContext, + authorizedUser: mockDocketClerkUser, }); const result = await serveDocumentAndGetPaperServicePdf({ @@ -177,7 +178,7 @@ describe('serveDocumentAndGetPaperServicePdf', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); @@ -210,7 +211,7 @@ describe('serveDocumentAndGetPaperServicePdf', () => { ], }, { - applicationContext, + authorizedUser: mockDocketClerkUser, }, ); diff --git a/web-api/src/business/useCaseHelper/service/createChangeItems.test.ts b/web-api/src/business/useCaseHelper/service/createChangeItems.test.ts index 1308ca3b8da..f4f3638fd77 100644 --- a/web-api/src/business/useCaseHelper/service/createChangeItems.test.ts +++ b/web-api/src/business/useCaseHelper/service/createChangeItems.test.ts @@ -6,6 +6,7 @@ import { } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { generateAndServeDocketEntry } from './createChangeItems'; +import { mockAdmissionsClerkUser } from '@shared/test/mockAuthUsers'; describe('generateAndServeDocketEntry', () => { let testCaseEntity; @@ -17,9 +18,12 @@ describe('generateAndServeDocketEntry', () => { name: 'Test Admissionsclerk', role: 'Admissionsclerk', }; - testCaseEntity = new Case(MOCK_CASE, { applicationContext }); + testCaseEntity = new Case(MOCK_CASE, { + authorizedUser: mockAdmissionsClerkUser, + }); testArguments = { applicationContext, + authorizedUser: mockAdmissionsClerkUser, barNumber: 'DD44444', caseEntity: testCaseEntity, contactName: 'Test Petitioner', @@ -104,7 +108,7 @@ describe('generateAndServeDocketEntry', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockAdmissionsClerkUser }, ), privatePractitionersRepresentingContact: true, user: testUser, @@ -127,7 +131,7 @@ describe('generateAndServeDocketEntry', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockAdmissionsClerkUser }, ), privatePractitionersRepresentingContact: true, user: testUser, @@ -150,7 +154,7 @@ describe('generateAndServeDocketEntry', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockAdmissionsClerkUser }, ), user: { ...testUser, @@ -176,7 +180,7 @@ describe('generateAndServeDocketEntry', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockAdmissionsClerkUser }, ), user: { ...testUser, @@ -202,7 +206,7 @@ describe('generateAndServeDocketEntry', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockAdmissionsClerkUser }, ), user: { ...testUser, @@ -236,7 +240,7 @@ describe('generateAndServeDocketEntry', () => { }, ], }, - { applicationContext }, + { authorizedUser: mockAdmissionsClerkUser }, ), docketMeta: undefined, user: { diff --git a/web-api/src/business/useCaseHelper/service/createChangeItems.ts b/web-api/src/business/useCaseHelper/service/createChangeItems.ts index eab0f6551ad..abc5f29b86d 100644 --- a/web-api/src/business/useCaseHelper/service/createChangeItems.ts +++ b/web-api/src/business/useCaseHelper/service/createChangeItems.ts @@ -1,3 +1,4 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { Case } from '../../../../../shared/src/business/entities/cases/Case'; import { DOCKET_SECTION, @@ -6,6 +7,7 @@ import { SERVICE_INDICATOR_TYPES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { DocketEntry } from '../../../../../shared/src/business/entities/DocketEntry'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { WorkItem } from '../../../../../shared/src/business/entities/WorkItem'; import { addCoverToPdf } from '../../useCases/addCoverToPdf'; import { getCaseCaptionMeta } from '../../../../../shared/src/business/utilities/getCaseCaptionMeta'; @@ -24,6 +26,7 @@ import { getCaseCaptionMeta } from '../../../../../shared/src/business/utilities */ const createDocketEntryForChange = async ({ applicationContext, + authorizedUser, caseEntity, docketMeta = {}, documentType, @@ -31,6 +34,16 @@ const createDocketEntryForChange = async ({ oldData, servedParties, user, +}: { + applicationContext: any; + caseEntity: any; + docketMeta: any; + documentType: any; + newData: any; + oldData: any; + servedParties: any; + user: any; + authorizedUser: AuthUser; }) => { const caseDetail = caseEntity.validate().toRawObject(); const { caseCaptionExtension, caseTitle } = getCaseCaptionMeta(caseDetail); @@ -79,7 +92,7 @@ const createDocketEntryForChange = async ({ processingStatus: DOCUMENT_PROCESSING_STATUS_OPTIONS.COMPLETE, ...docketMeta, }, - { applicationContext }, + { authorizedUser }, ); changeOfAddressDocketEntry.setFiledBy(user); @@ -147,8 +160,7 @@ const createWorkItemForChange = async ({ trialDate: caseEntity.trialDate, trialLocation: caseEntity.trialLocation, }, - { applicationContext }, - caseEntity, + { caseEntity }, ); changeOfAddressDocketEntry.setWorkItem(workItem); @@ -161,6 +173,7 @@ const createWorkItemForChange = async ({ export const generateAndServeDocketEntry = async ({ applicationContext, + authorizedUser, barNumber, caseEntity, contactName, @@ -171,6 +184,19 @@ export const generateAndServeDocketEntry = async ({ privatePractitionersRepresentingContact, servedParties, user, +}: { + applicationContext: ServerApplicationContext; + barNumber: any; + caseEntity: any; + contactName: any; + docketMeta: any; + documentType: any; + newData: any; + oldData: any; + privatePractitionersRepresentingContact: any; + servedParties: any; + user: any; + authorizedUser: AuthUser; }) => { const partyWithPaperService = caseEntity.hasPartyWithServiceType( SERVICE_INDICATOR_TYPES.SI_PAPER, @@ -197,6 +223,7 @@ export const generateAndServeDocketEntry = async ({ let url; ({ changeOfAddressDocketEntry, url } = await createDocketEntryForChange({ applicationContext, + authorizedUser, barNumber, caseEntity, contactName, diff --git a/web-api/src/business/useCaseHelper/service/sendIrsSuperuserPetitionEmail.test.ts b/web-api/src/business/useCaseHelper/service/sendIrsSuperuserPetitionEmail.test.ts index 7cc888f1e6b..cefe2fbb1ff 100644 --- a/web-api/src/business/useCaseHelper/service/sendIrsSuperuserPetitionEmail.test.ts +++ b/web-api/src/business/useCaseHelper/service/sendIrsSuperuserPetitionEmail.test.ts @@ -44,7 +44,7 @@ describe('sendIrsSuperuserPetitionEmail', () => { preferredTrialCity: 'Somecity, ST', privatePractitioners: [], }, - { applicationContext }, + { authorizedUser: undefined }, ); await sendIrsSuperuserPetitionEmail({ @@ -103,7 +103,7 @@ describe('sendIrsSuperuserPetitionEmail', () => { ], procedureType: 'Regular', }, - { applicationContext }, + { authorizedUser: undefined }, ); await sendIrsSuperuserPetitionEmail({ @@ -155,7 +155,7 @@ describe('sendIrsSuperuserPetitionEmail', () => { }, ], }, - { applicationContext }, + { authorizedUser: undefined }, ); await sendIrsSuperuserPetitionEmail({ @@ -197,7 +197,7 @@ describe('sendIrsSuperuserPetitionEmail', () => { ], privatePractitioners: [], }, - { applicationContext }, + { authorizedUser: undefined }, ); await sendIrsSuperuserPetitionEmail({ @@ -235,7 +235,7 @@ describe('sendIrsSuperuserPetitionEmail', () => { preferredTrialCity: 'Fake Trial Location, ST', privatePractitioners: [], }, - { applicationContext }, + { authorizedUser: undefined }, ); await sendIrsSuperuserPetitionEmail({ @@ -273,7 +273,7 @@ describe('sendIrsSuperuserPetitionEmail', () => { preferredTrialCity: '', privatePractitioners: [], }, - { applicationContext }, + { authorizedUser: undefined }, ); await sendIrsSuperuserPetitionEmail({ @@ -310,7 +310,7 @@ describe('sendIrsSuperuserPetitionEmail', () => { preferredTrialCity: '', privatePractitioners: [], }, - { applicationContext }, + { authorizedUser: undefined }, ); await expect( diff --git a/web-api/src/business/useCaseHelper/service/sendServedPartiesEmails.test.ts b/web-api/src/business/useCaseHelper/service/sendServedPartiesEmails.test.ts index c10d2837eb7..7150d3b22d7 100644 --- a/web-api/src/business/useCaseHelper/service/sendServedPartiesEmails.test.ts +++ b/web-api/src/business/useCaseHelper/service/sendServedPartiesEmails.test.ts @@ -7,6 +7,7 @@ import { import { Case } from '../../../../../shared/src/business/entities/cases/Case'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { mockPetitionsClerkUser } from '@shared/test/mockAuthUsers'; import { sendServedPartiesEmails } from './sendServedPartiesEmails'; import React from 'react'; import ReactDOM from 'react-dom/server'; @@ -40,7 +41,7 @@ describe('sendServedPartiesEmails', () => { petitioners: MOCK_CASE.petitioners, status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); await sendServedPartiesEmails({ @@ -85,7 +86,7 @@ describe('sendServedPartiesEmails', () => { petitioners: MOCK_CASE.petitioners, status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); await sendServedPartiesEmails({ @@ -126,7 +127,7 @@ describe('sendServedPartiesEmails', () => { docketNumberWithSuffix: '123-20L', status: CASE_STATUS_TYPES.new, }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); await sendServedPartiesEmails({ @@ -166,7 +167,7 @@ describe('sendServedPartiesEmails', () => { docketNumberWithSuffix: '123-20L', status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); await sendServedPartiesEmails({ @@ -204,7 +205,7 @@ describe('sendServedPartiesEmails', () => { procedureType: 'Regular', status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); await sendServedPartiesEmails({ @@ -236,7 +237,7 @@ describe('sendServedPartiesEmails', () => { docketNumberWithSuffix: '123-20L', status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); await expect( @@ -274,7 +275,7 @@ describe('sendServedPartiesEmails', () => { procedureType: 'Regular', status: CASE_STATUS_TYPES.generalDocket, }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); const servedParties = { @@ -328,7 +329,7 @@ describe('sendServedPartiesEmails', () => { docketNumberWithSuffix: '123-20L', status: CASE_STATUS_TYPES.new, }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); await sendServedPartiesEmails({ diff --git a/web-api/src/business/useCaseHelper/stampDisposition/addDraftStampOrderDocketEntryInteractor.test.ts b/web-api/src/business/useCaseHelper/stampDisposition/addDraftStampOrderDocketEntryInteractor.test.ts index c8c9ba2e530..fabf8430364 100644 --- a/web-api/src/business/useCaseHelper/stampDisposition/addDraftStampOrderDocketEntryInteractor.test.ts +++ b/web-api/src/business/useCaseHelper/stampDisposition/addDraftStampOrderDocketEntryInteractor.test.ts @@ -11,13 +11,11 @@ import { ServiceUnavailableError, UnauthorizedError, } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { addDraftStampOrderDocketEntryInteractor } from './addDraftStampOrderDocketEntryInteractor'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; -import { - clerkOfCourtUser, - judgeUser, -} from '../../../../../shared/src/test/mockUsers'; import { getMessageThreadByParentId } from '@web-api/persistence/postgres/messages/getMessageThreadByParentId'; +import { mockJudgeUser } from '@shared/test/mockAuthUsers'; import { updateMessage } from '@web-api/persistence/postgres/messages/updateMessage'; describe('addDraftStampOrderDocketEntryInteractor', () => { @@ -45,17 +43,18 @@ describe('addDraftStampOrderDocketEntryInteractor', () => { beforeEach(() => { mockLock = undefined; - applicationContext.getCurrentUser.mockReturnValue(clerkOfCourtUser); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE); - - applicationContext.getCurrentUser.mockReturnValue(judgeUser); }); it('should add a draft order docket entry to the case', async () => { - await addDraftStampOrderDocketEntryInteractor(applicationContext, args); + await addDraftStampOrderDocketEntryInteractor( + applicationContext, + args, + mockJudgeUser, + ); const { caseToUpdate } = applicationContext.getUseCaseHelpers().updateCaseAndAssociations.mock @@ -79,20 +78,19 @@ describe('addDraftStampOrderDocketEntryInteractor', () => { docketEntryId: mockStampedDocketEntryId, docketNumber: caseToUpdate.docketNumber, documentType: ORDER_TYPES[0].documentType, - filedBy: judgeUser.judgeFullName, + filedBy: mockJudgeUser.name, freeText: `${motionDocumentType} some title with disposition and custom text`, isDraft: true, signedJudgeName: mockSigningName, }); }); - it("should set the filedBy to the current user's name if there is no judge full name on the user", async () => { - applicationContext.getCurrentUser.mockReturnValue({ - ...judgeUser, - judgeFullName: undefined, - }); - - await addDraftStampOrderDocketEntryInteractor(applicationContext, args); + it("should set the filedBy to the current user's name", async () => { + await addDraftStampOrderDocketEntryInteractor( + applicationContext, + args, + mockJudgeUser, + ); const { caseToUpdate } = applicationContext.getUseCaseHelpers().updateCaseAndAssociations.mock @@ -105,7 +103,7 @@ describe('addDraftStampOrderDocketEntryInteractor', () => { ); expect(draftDocketEntryEntity).toMatchObject({ - filedBy: judgeUser.name, + filedBy: mockJudgeUser.name, }); }); @@ -130,10 +128,14 @@ describe('addDraftStampOrderDocketEntryInteractor', () => { (getMessageThreadByParentId as jest.Mock).mockReturnValue([mockMessage]); - await addDraftStampOrderDocketEntryInteractor(applicationContext, { - ...args, - parentMessageId: mockParentMessageId, - }); + await addDraftStampOrderDocketEntryInteractor( + applicationContext, + { + ...args, + parentMessageId: mockParentMessageId, + }, + mockJudgeUser, + ); expect(updateMessage).toHaveBeenCalled(); expect((updateMessage as jest.Mock).mock.calls[0][0].message).toMatchObject( @@ -151,7 +153,11 @@ describe('addDraftStampOrderDocketEntryInteractor', () => { mockLock = MOCK_LOCK; await expect( - addDraftStampOrderDocketEntryInteractor(applicationContext, args), + addDraftStampOrderDocketEntryInteractor( + applicationContext, + args, + mockJudgeUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -160,7 +166,11 @@ describe('addDraftStampOrderDocketEntryInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await addDraftStampOrderDocketEntryInteractor(applicationContext, args); + await addDraftStampOrderDocketEntryInteractor( + applicationContext, + args, + mockJudgeUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -179,10 +189,12 @@ describe('addDraftStampOrderDocketEntryInteractor', () => { }); it('should throw an Unauthorized error if the user is not authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - addDraftStampOrderDocketEntryInteractor(applicationContext, args), + addDraftStampOrderDocketEntryInteractor( + applicationContext, + args, + {} as UnknownAuthUser, + ), ).rejects.toThrow(UnauthorizedError); }); }); diff --git a/web-api/src/business/useCaseHelper/stampDisposition/addDraftStampOrderDocketEntryInteractor.ts b/web-api/src/business/useCaseHelper/stampDisposition/addDraftStampOrderDocketEntryInteractor.ts index ac22759d375..867279a25a3 100644 --- a/web-api/src/business/useCaseHelper/stampDisposition/addDraftStampOrderDocketEntryInteractor.ts +++ b/web-api/src/business/useCaseHelper/stampDisposition/addDraftStampOrderDocketEntryInteractor.ts @@ -9,8 +9,10 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { Stamp } from '../../../../../shared/src/business/entities/Stamp'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { getMessageThreadByParentId } from '@web-api/persistence/postgres/messages/getMessageThreadByParentId'; import { orderBy } from 'lodash'; import { updateMessage } from '@web-api/persistence/postgres/messages/updateMessage'; @@ -28,7 +30,7 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; * @param {string} providers.stampData the stampData from the form */ export const addDraftStampOrderDocketEntry = async ( - applicationContext, + applicationContext: ServerApplicationContext, { docketNumber, formattedDraftDocumentTitle, @@ -47,10 +49,9 @@ export const addDraftStampOrderDocketEntry = async ( }; stampedDocketEntryId: string; }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.STAMP_MOTION)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.STAMP_MOTION)) { throw new UnauthorizedError('Unauthorized to update docket entry'); } @@ -60,7 +61,7 @@ export const addDraftStampOrderDocketEntry = async ( applicationContext, docketNumber, }); - const caseEntity = new Case(caseRecord, { applicationContext }); + const caseEntity = new Case(caseRecord, { authorizedUser }); const originalDocketEntryEntity = caseEntity.docketEntries.find( docketEntry => docketEntry.docketEntryId === originalDocketEntryId, ); @@ -87,7 +88,7 @@ export const addDraftStampOrderDocketEntry = async ( freeText: `${originalDocketEntryEntity.documentType} ${formattedDraftDocumentTitle}`, }, eventCode: orderDocumentInfo?.eventCode, - filedBy: user.judgeFullName || user.name, + filedBy: authorizedUser.name, freeText: `${originalDocketEntryEntity.documentType} ${formattedDraftDocumentTitle}`, isDraft: true, isFileAttached: true, @@ -95,12 +96,15 @@ export const addDraftStampOrderDocketEntry = async ( processingStatus: DOCUMENT_PROCESSING_STATUS_OPTIONS.COMPLETE, stampData: validatedStampData, }, - { applicationContext }, + { authorizedUser }, ); - stampedDocketEntryEntity.setFiledBy(user); + stampedDocketEntryEntity.setFiledBy(authorizedUser); - stampedDocketEntryEntity.setSigned(user.userId, stampData.nameForSigning); + stampedDocketEntryEntity.setSigned( + authorizedUser.userId, + stampData.nameForSigning, + ); caseEntity.addDocketEntry(stampedDocketEntryEntity); @@ -124,6 +128,7 @@ export const addDraftStampOrderDocketEntry = async ( await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); }; diff --git a/web-api/src/business/useCaseHelper/stampDisposition/generateStampedCoversheetInteractor.test.ts b/web-api/src/business/useCaseHelper/stampDisposition/generateStampedCoversheetInteractor.test.ts index 8c6dcf7fed3..8ada6af2192 100644 --- a/web-api/src/business/useCaseHelper/stampDisposition/generateStampedCoversheetInteractor.test.ts +++ b/web-api/src/business/useCaseHelper/stampDisposition/generateStampedCoversheetInteractor.test.ts @@ -2,6 +2,7 @@ import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOTION_DISPOSITIONS } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { generateStampedCoversheetInteractor } from './generateStampedCoversheetInteractor'; +import { mockPetitionerUser } from '@shared/test/mockAuthUsers'; describe('generateStampedCoversheetInteractor', () => { const mockDocketEntryId = MOCK_CASE.docketEntries[0].docketEntryId; @@ -35,12 +36,16 @@ describe('generateStampedCoversheetInteractor', () => { }); it('clears the servedAt property of the motion docket entry used for coversheet generation', async () => { - await generateStampedCoversheetInteractor(applicationContext, { - docketEntryId: mockDocketEntryId, - docketNumber: MOCK_CASE.docketNumber, - stampData: mockStampData, - stampedDocketEntryId: mockStampedDocketEntryId, - }); + await generateStampedCoversheetInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + docketNumber: MOCK_CASE.docketNumber, + stampData: mockStampData, + stampedDocketEntryId: mockStampedDocketEntryId, + }, + mockPetitionerUser, + ); expect( applicationContext.getDocumentGenerators().coverSheet.mock.calls[0][0] @@ -49,12 +54,16 @@ describe('generateStampedCoversheetInteractor', () => { }); it('generates a stamped coversheet pdf document with stampData', async () => { - await generateStampedCoversheetInteractor(applicationContext, { - docketEntryId: mockDocketEntryId, - docketNumber: MOCK_CASE.docketNumber, - stampData: mockStampData, - stampedDocketEntryId: mockStampedDocketEntryId, - }); + await generateStampedCoversheetInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + docketNumber: MOCK_CASE.docketNumber, + stampData: mockStampData, + stampedDocketEntryId: mockStampedDocketEntryId, + }, + mockPetitionerUser, + ); expect( applicationContext.getDocumentGenerators().coverSheet, @@ -68,12 +77,16 @@ describe('generateStampedCoversheetInteractor', () => { }); it('should save the stamped coversheet', async () => { - await generateStampedCoversheetInteractor(applicationContext, { - docketEntryId: mockDocketEntryId, - docketNumber: MOCK_CASE.docketNumber, - stampData: {}, - stampedDocketEntryId: mockStampedDocketEntryId, - }); + await generateStampedCoversheetInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + docketNumber: MOCK_CASE.docketNumber, + stampData: {}, + stampedDocketEntryId: mockStampedDocketEntryId, + }, + mockPetitionerUser, + ); expect( applicationContext.getPersistenceGateway().saveDocumentFromLambda.mock diff --git a/web-api/src/business/useCaseHelper/stampDisposition/generateStampedCoversheetInteractor.ts b/web-api/src/business/useCaseHelper/stampDisposition/generateStampedCoversheetInteractor.ts index d5c2ab3341a..743e6495cee 100644 --- a/web-api/src/business/useCaseHelper/stampDisposition/generateStampedCoversheetInteractor.ts +++ b/web-api/src/business/useCaseHelper/stampDisposition/generateStampedCoversheetInteractor.ts @@ -1,4 +1,5 @@ import { Case } from '../../../../../shared/src/business/entities/cases/Case'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { generateCoverSheetData } from '../../useCases/generateCoverSheetData'; /** @@ -44,20 +45,10 @@ const createStampedCoversheetPdf = async ({ }; }; -/** - * generateStampedCoversheetInteractor - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {string} providers.docketEntryId the docket entry id of the original motion - * @param {string} providers.docketNumber the docket number of the case - * @param {boolean} providers.stampData the stamp data from the form to be applied to the stamp order pdf - * @param {string} providers.stampedDocketEntryId the docket entry id of the new stamped order docket entry - * @returns {Promise<*>} updated docket entry entity - */ export const generateStampedCoversheetInteractor = async ( applicationContext, { docketEntryId, docketNumber, stampData, stampedDocketEntryId }, + authorizedUser: UnknownAuthUser, ) => { const caseRecord = await applicationContext .getPersistenceGateway() @@ -66,7 +57,9 @@ export const generateStampedCoversheetInteractor = async ( docketNumber, }); - const caseEntity = new Case(caseRecord, { applicationContext }); + const caseEntity = new Case(caseRecord, { + authorizedUser, + }); const motionDocketEntryEntity = caseEntity.getDocketEntryById({ docketEntryId, diff --git a/web-api/src/business/useCaseHelper/trialSessions/associateSwingTrialSessions.test.ts b/web-api/src/business/useCaseHelper/trialSessions/associateSwingTrialSessions.test.ts index 291b0fb4e33..bf9eea50bdf 100644 --- a/web-api/src/business/useCaseHelper/trialSessions/associateSwingTrialSessions.test.ts +++ b/web-api/src/business/useCaseHelper/trialSessions/associateSwingTrialSessions.test.ts @@ -4,60 +4,62 @@ import { TrialSession } from '../../../../../shared/src/business/entities/trialS import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { associateSwingTrialSessions } from '@web-api/business/useCaseHelper/trialSessions/associateSwingTrialSessions'; import { - petitionerUser, - petitionsClerkUser, -} from '../../../../../shared/src/test/mockUsers'; + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; -const MOCK_TRIAL_SESSION = { - ...MOCK_TRIAL_REGULAR, - proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.remote, - sessionType: 'Regular', - startDate: '3000-03-01T00:00:00.000Z', - term: 'Fall', - termYear: '3000', - trialSessionId: '959c4338-0fac-42eb-b0eb-d53b8d0195cc', -}; +describe('associateSwingTrialSessions', () => { + let mockCurrentTrialSessionEntity; -const MOCK_TRIAL_SESSION_FOR_ASSOCIATION = { - ...MOCK_TRIAL_REGULAR, - sessionType: 'Small', - startDate: '3000-03-03T00:00:00.000Z', - term: 'Fall', - termYear: '3000', - trialSessionId: '208a959f-9526-4db5-b262-e58c476a4604', -}; + const MOCK_TRIAL_SESSION = { + ...MOCK_TRIAL_REGULAR, + proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.remote, + sessionType: 'Regular', + startDate: '3000-03-01T00:00:00.000Z', + term: 'Fall', + termYear: '3000', + trialSessionId: '959c4338-0fac-42eb-b0eb-d53b8d0195cc', + }; -let mockCurrentTrialSessionEntity; + const MOCK_TRIAL_SESSION_FOR_ASSOCIATION = { + ...MOCK_TRIAL_REGULAR, + sessionType: 'Small', + startDate: '3000-03-03T00:00:00.000Z', + term: 'Fall', + termYear: '3000', + trialSessionId: '208a959f-9526-4db5-b262-e58c476a4604', + }; -describe('associateSwingTrialSessions', () => { beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - applicationContext .getPersistenceGateway() .getTrialSessionById.mockReturnValue(MOCK_TRIAL_SESSION_FOR_ASSOCIATION); - mockCurrentTrialSessionEntity = new TrialSession(MOCK_TRIAL_SESSION, { - applicationContext, - }); + mockCurrentTrialSessionEntity = new TrialSession(MOCK_TRIAL_SESSION); }); it('throws an error if user is unauthorized to associate swing sessions', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - await expect( - associateSwingTrialSessions(applicationContext, { - swingSessionId: MOCK_TRIAL_SESSION_FOR_ASSOCIATION.trialSessionId, - trialSessionEntity: mockCurrentTrialSessionEntity, - }), + associateSwingTrialSessions( + applicationContext, + { + swingSessionId: MOCK_TRIAL_SESSION_FOR_ASSOCIATION.trialSessionId, + trialSessionEntity: mockCurrentTrialSessionEntity, + }, + mockPetitionerUser, + ), ).rejects.toThrow(); }); it('retrieves the swing session to be associated with the current session from persistence', async () => { - await associateSwingTrialSessions(applicationContext, { - swingSessionId: MOCK_TRIAL_SESSION_FOR_ASSOCIATION.trialSessionId, - trialSessionEntity: mockCurrentTrialSessionEntity, - }); + await associateSwingTrialSessions( + applicationContext, + { + swingSessionId: MOCK_TRIAL_SESSION_FOR_ASSOCIATION.trialSessionId, + trialSessionEntity: mockCurrentTrialSessionEntity, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getTrialSessionById.mock @@ -66,10 +68,14 @@ describe('associateSwingTrialSessions', () => { }); it('updates the trial session to be associated with swing session information', async () => { - await associateSwingTrialSessions(applicationContext, { - swingSessionId: MOCK_TRIAL_SESSION_FOR_ASSOCIATION.trialSessionId, - trialSessionEntity: mockCurrentTrialSessionEntity, - }); + await associateSwingTrialSessions( + applicationContext, + { + swingSessionId: MOCK_TRIAL_SESSION_FOR_ASSOCIATION.trialSessionId, + trialSessionEntity: mockCurrentTrialSessionEntity, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateTrialSession.mock @@ -88,6 +94,7 @@ describe('associateSwingTrialSessions', () => { swingSessionId: MOCK_TRIAL_SESSION_FOR_ASSOCIATION.trialSessionId, trialSessionEntity: mockCurrentTrialSessionEntity, }, + mockPetitionsClerkUser, ); expect(updatedTrialSession).toMatchObject({ diff --git a/web-api/src/business/useCaseHelper/trialSessions/associateSwingTrialSessions.ts b/web-api/src/business/useCaseHelper/trialSessions/associateSwingTrialSessions.ts index 7c993d1c297..ad752243784 100644 --- a/web-api/src/business/useCaseHelper/trialSessions/associateSwingTrialSessions.ts +++ b/web-api/src/business/useCaseHelper/trialSessions/associateSwingTrialSessions.ts @@ -3,29 +3,23 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; +import { + RawTrialSession, + TrialSession, +} from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { ServerApplicationContext } from '@web-api/applicationContext'; -import { TrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; -/** - * associateSwingTrialSessions - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {string} providers.swingSessionId the id of the trial session to add as a swing session - * @param {string} providers.trialSession the trial session to add the swing session to - * @returns {Object} the updated trial session object - */ export const associateSwingTrialSessions = async ( applicationContext: ServerApplicationContext, { swingSessionId, trialSessionEntity, }: { swingSessionId: string; trialSessionEntity: TrialSession }, -) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + authorizedUser: UnknownAuthUser, +): Promise => { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } @@ -40,9 +34,7 @@ export const associateSwingTrialSessions = async ( throw new NotFoundError(`Trial session ${swingSessionId} was not found.`); } - const swingSessionEntity = new TrialSession(swingTrialSession, { - applicationContext, - }); + const swingSessionEntity = new TrialSession(swingTrialSession); trialSessionEntity.setAsSwingSession(swingSessionId); swingSessionEntity.setAsSwingSession(trialSessionEntity.trialSessionId); diff --git a/web-api/src/business/useCaseHelper/trialSessions/createTrialSessionAndWorkingCopy.test.ts b/web-api/src/business/useCaseHelper/trialSessions/createTrialSessionAndWorkingCopy.test.ts index 7d7052f26be..9b1fd9bea11 100644 --- a/web-api/src/business/useCaseHelper/trialSessions/createTrialSessionAndWorkingCopy.test.ts +++ b/web-api/src/business/useCaseHelper/trialSessions/createTrialSessionAndWorkingCopy.test.ts @@ -21,9 +21,7 @@ let trialSessionToAdd; describe('createTrialSessionAndWorkingCopy', () => { beforeEach(() => { - trialSessionToAdd = new TrialSession(trialSessionMetadata, { - applicationContext, - }); + trialSessionToAdd = new TrialSession(trialSessionMetadata); applicationContext .getPersistenceGateway() @@ -84,20 +82,15 @@ describe('createTrialSessionAndWorkingCopy', () => { await expect( createTrialSessionAndWorkingCopy({ applicationContext, - trialSessionToAdd: new TrialSession( - { - trialSessionId: 'a54ba5a9-b37b-479d-9201-067ec6e335cc', - }, - { applicationContext }, - ), + trialSessionToAdd: new TrialSession({ + trialSessionId: 'a54ba5a9-b37b-479d-9201-067ec6e335cc', + }), }), ).rejects.toThrow('The TrialSession entity was invalid'); }); it('should fail to migrate a trial session when the trialSessionId is not provided', async () => { - const trialSessionToCreate = new TrialSession(trialSessionToAdd, { - applicationContext, - }); + const trialSessionToCreate = new TrialSession(trialSessionToAdd); delete trialSessionToCreate.trialSessionId; await expect( diff --git a/web-api/src/business/useCaseHelper/trialSessions/createTrialSessionAndWorkingCopy.ts b/web-api/src/business/useCaseHelper/trialSessions/createTrialSessionAndWorkingCopy.ts index b49f1c98491..e02b2336787 100644 --- a/web-api/src/business/useCaseHelper/trialSessions/createTrialSessionAndWorkingCopy.ts +++ b/web-api/src/business/useCaseHelper/trialSessions/createTrialSessionAndWorkingCopy.ts @@ -52,7 +52,5 @@ export const createTrialSessionAndWorkingCopy = async ({ }); } - return new TrialSession(createdTrialSession, { applicationContext }) - .validate() - .toRawObject(); + return new TrialSession(createdTrialSession).validate().toRawObject(); }; diff --git a/web-api/src/business/useCaseHelper/trialSessions/generateNoticeOfChangeToInPersonProceeding.ts b/web-api/src/business/useCaseHelper/trialSessions/generateNoticeOfChangeToInPersonProceeding.ts index ee2380b5fb6..37d2e01f21c 100644 --- a/web-api/src/business/useCaseHelper/trialSessions/generateNoticeOfChangeToInPersonProceeding.ts +++ b/web-api/src/business/useCaseHelper/trialSessions/generateNoticeOfChangeToInPersonProceeding.ts @@ -14,7 +14,7 @@ export const generateNoticeOfChangeToInPersonProceeding = async ( docketNumber, trialSessionInformation, }: { docketNumber: string; trialSessionInformation: any }, -): Promise => { +): Promise => { const formattedStartDate = formatDateString( trialSessionInformation.startDate, FORMATS.MONTH_DAY_YEAR_WITH_DAY_OF_WEEK, diff --git a/web-api/src/business/useCaseHelper/trialSessions/serveGeneratedNoticesOnCase.test.ts b/web-api/src/business/useCaseHelper/trialSessions/serveGeneratedNoticesOnCase.test.ts index 07d8e33c367..6aaa23b6680 100644 --- a/web-api/src/business/useCaseHelper/trialSessions/serveGeneratedNoticesOnCase.test.ts +++ b/web-api/src/business/useCaseHelper/trialSessions/serveGeneratedNoticesOnCase.test.ts @@ -10,13 +10,13 @@ import { applicationContext } from '../../../../../shared/src/business/test/crea import { serveGeneratedNoticesOnCase } from './serveGeneratedNoticesOnCase'; describe('serveGeneratedNoticesOnCase', () => { - const mockOpenCaseEntity = new Case(MOCK_CASE, { applicationContext }); + const mockOpenCaseEntity = new Case(MOCK_CASE, { authorizedUser: undefined }); const mockNoticeDocketEntryEntity = new DocketEntry( { ...MOCK_CASE.docketEntries[0], }, - { applicationContext }, + { authorizedUser: undefined }, ); it('should sendServedPartiesEmails and append the paper service info to the docket entry on the case when the case has parties with paper service', async () => { diff --git a/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeOfTrialJudge.test.ts b/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeOfTrialJudge.test.ts index d201b559bf2..62f8be020f3 100644 --- a/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeOfTrialJudge.test.ts +++ b/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeOfTrialJudge.test.ts @@ -5,6 +5,7 @@ import { SYSTEM_GENERATED_DOCUMENT_TYPES } from '../../../../../shared/src/busin import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getFakeFile } from '../../../../../shared/src/business/test/getFakeFile'; import { getJudgeWithTitle } from '@shared/business/utilities/getJudgeWithTitle'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { setNoticeOfChangeOfTrialJudge } from './setNoticeOfChangeOfTrialJudge'; jest.mock('@shared/business/utilities/getJudgeWithTitle', () => ({ @@ -13,7 +14,6 @@ jest.mock('@shared/business/utilities/getJudgeWithTitle', () => ({ describe('setNoticeOfChangeOfTrialJudge', () => { const trialSessionId = '76a5b1c8-1eed-44b6-932a-967af060597a'; - const userId = '85a5b1c8-1eed-44b6-932a-967af060597a'; const currentTrialSession = { ...MOCK_TRIAL_INPERSON, @@ -39,7 +39,7 @@ describe('setNoticeOfChangeOfTrialJudge', () => { trialDate: '2019-03-01T21:42:29.073Z', trialSessionId, }, - { applicationContext }, + { authorizedUser: undefined }, ); beforeEach(() => { @@ -54,13 +54,16 @@ describe('setNoticeOfChangeOfTrialJudge', () => { }); it('should retrieve the judge title and fullname for the current and new judges', async () => { - await setNoticeOfChangeOfTrialJudge(applicationContext, { - caseEntity: mockOpenCase, - currentTrialSession, - newPdfDoc: getFakeFile, - newTrialSessionEntity: updatedTrialSession, - userId, - }); + await setNoticeOfChangeOfTrialJudge( + applicationContext, + { + caseEntity: mockOpenCase, + currentTrialSession, + newPdfDoc: getFakeFile, + newTrialSessionEntity: updatedTrialSession, + }, + mockDocketClerkUser, + ); expect(getJudgeWithTitle.mock.calls[0][0]).toMatchObject({ judgeUserName: currentTrialSession.judge.name, @@ -73,13 +76,16 @@ describe('setNoticeOfChangeOfTrialJudge', () => { }); it('should create a docket entry and serve the generated notice', async () => { - await setNoticeOfChangeOfTrialJudge(applicationContext, { - caseEntity: mockOpenCase, - currentTrialSession, - newPdfDoc: getFakeFile, - newTrialSessionEntity: updatedTrialSession, - userId, - }); + await setNoticeOfChangeOfTrialJudge( + applicationContext, + { + caseEntity: mockOpenCase, + currentTrialSession, + newPdfDoc: getFakeFile, + newTrialSessionEntity: updatedTrialSession, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().createAndServeNoticeDocketEntry diff --git a/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeOfTrialJudge.ts b/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeOfTrialJudge.ts index 51781b08c4e..bc448ac0b18 100644 --- a/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeOfTrialJudge.ts +++ b/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeOfTrialJudge.ts @@ -1,9 +1,12 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { SYSTEM_GENERATED_DOCUMENT_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { getJudgeWithTitle } from '../../../../../shared/src/business/utilities/getJudgeWithTitle'; export const setNoticeOfChangeOfTrialJudge = async ( - applicationContext, - { caseEntity, currentTrialSession, newPdfDoc, newTrialSessionEntity, user }, + applicationContext: ServerApplicationContext, + { caseEntity, currentTrialSession, newPdfDoc, newTrialSessionEntity }, + authorizedUser: AuthUser, ) => { const priorJudgeTitleWithFullName = await getJudgeWithTitle({ applicationContext, @@ -35,13 +38,14 @@ export const setNoticeOfChangeOfTrialJudge = async ( trialSessionInformation, }); - await applicationContext - .getUseCaseHelpers() - .createAndServeNoticeDocketEntry(applicationContext, { + await applicationContext.getUseCaseHelpers().createAndServeNoticeDocketEntry( + applicationContext, + { caseEntity, documentInfo: SYSTEM_GENERATED_DOCUMENT_TYPES.noticeOfChangeOfTrialJudge, newPdfDoc, noticePdf, - user, - }); + }, + authorizedUser, + ); }; diff --git a/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToInPersonProceeding.test.ts b/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToInPersonProceeding.test.ts index 040122ae8f6..88e7ed374f9 100644 --- a/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToInPersonProceeding.test.ts +++ b/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToInPersonProceeding.test.ts @@ -4,7 +4,7 @@ import { MOCK_TRIAL_INPERSON } from '../../../../../shared/src/test/mockTrial'; import { SYSTEM_GENERATED_DOCUMENT_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getFakeFile } from '../../../../../shared/src/business/test/getFakeFile'; -import { petitionsClerkUser } from '../../../../../shared/src/test/mockUsers'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { setNoticeOfChangeToInPersonProceeding } from './setNoticeOfChangeToInPersonProceeding'; describe('setNoticeOfChangeToInPersonProceeding', () => { @@ -22,7 +22,7 @@ describe('setNoticeOfChangeToInPersonProceeding', () => { trialDate: '2019-03-01T21:42:29.073Z', trialSessionId: mockTrialSessionId, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); beforeEach(() => { @@ -32,12 +32,15 @@ describe('setNoticeOfChangeToInPersonProceeding', () => { }); it('should make a call to generate the NOIP pdf', async () => { - await setNoticeOfChangeToInPersonProceeding(applicationContext, { - caseEntity: mockOpenCase, - newPdfDoc: getFakeFile, - newTrialSessionEntity: mockInPersonCalendaredTrialSession, - user: petitionsClerkUser, - }); + await setNoticeOfChangeToInPersonProceeding( + applicationContext, + { + caseEntity: mockOpenCase, + newPdfDoc: getFakeFile, + newTrialSessionEntity: mockInPersonCalendaredTrialSession, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers() @@ -62,12 +65,15 @@ describe('setNoticeOfChangeToInPersonProceeding', () => { }); it('should make a call to create and serve the NOIP docket entry on the case', async () => { - await setNoticeOfChangeToInPersonProceeding(applicationContext, { - caseEntity: mockOpenCase, - newPdfDoc: getFakeFile, - newTrialSessionEntity: mockInPersonCalendaredTrialSession, - user: petitionsClerkUser, - }); + await setNoticeOfChangeToInPersonProceeding( + applicationContext, + { + caseEntity: mockOpenCase, + newPdfDoc: getFakeFile, + newTrialSessionEntity: mockInPersonCalendaredTrialSession, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().createAndServeNoticeDocketEntry @@ -83,7 +89,6 @@ describe('setNoticeOfChangeToInPersonProceeding', () => { SYSTEM_GENERATED_DOCUMENT_TYPES.noticeOfChangeToInPersonProceeding, newPdfDoc: getFakeFile, noticePdf: getFakeFile, - user: petitionsClerkUser, }); }); }); diff --git a/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToInPersonProceeding.ts b/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToInPersonProceeding.ts index 2ea20ec1834..6846e1e6ebd 100644 --- a/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToInPersonProceeding.ts +++ b/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToInPersonProceeding.ts @@ -1,19 +1,17 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { Case } from '@shared/business/entities/cases/Case'; import { SYSTEM_GENERATED_DOCUMENT_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; +import { ServerApplicationContext } from '@web-api/applicationContext'; -/** - * setNoticeOfChangeToInPersonProceeding - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {object} providers.caseEntity the case data - * @param {object} providers.newPdfDoc the new PDF contents to be appended - * @param {object} providers.newTrialSessionEntity the new trial session data - * @param {object} providers.userId the user ID - */ export const setNoticeOfChangeToInPersonProceeding = async ( - applicationContext, - { caseEntity, newPdfDoc, newTrialSessionEntity, user }, -) => { + applicationContext: ServerApplicationContext, + { + caseEntity, + newPdfDoc, + newTrialSessionEntity, + }: { caseEntity: Case; newPdfDoc: any; newTrialSessionEntity: any }, + authorizedUser: AuthUser, +): Promise => { const trialSessionInformation = { address1: newTrialSessionEntity.address1, address2: newTrialSessionEntity.address2, @@ -41,15 +39,16 @@ export const setNoticeOfChangeToInPersonProceeding = async ( trialLocation: newTrialSessionEntity.trialLocation, }; - await applicationContext - .getUseCaseHelpers() - .createAndServeNoticeDocketEntry(applicationContext, { + await applicationContext.getUseCaseHelpers().createAndServeNoticeDocketEntry( + applicationContext, + { additionalDocketEntryInfo, caseEntity, documentInfo: SYSTEM_GENERATED_DOCUMENT_TYPES.noticeOfChangeToInPersonProceeding, newPdfDoc, noticePdf, - user, - }); + }, + authorizedUser, + ); }; diff --git a/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToRemoteProceeding.test.ts b/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToRemoteProceeding.test.ts index d7ea86828e9..87e5dcdce22 100644 --- a/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToRemoteProceeding.test.ts +++ b/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToRemoteProceeding.test.ts @@ -6,7 +6,10 @@ import { } from '../../../../../shared/src/test/mockTrial'; import { SYSTEM_GENERATED_DOCUMENT_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; -import { petitionsClerkUser } from '../../../../../shared/src/test/mockUsers'; +import { + mockDocketClerkUser, + mockTrialClerkUser, +} from '@shared/test/mockAuthUsers'; import { setNoticeOfChangeToRemoteProceeding } from './setNoticeOfChangeToRemoteProceeding'; describe('setNoticeOfChangeToRemoteProceeding', () => { @@ -19,7 +22,7 @@ describe('setNoticeOfChangeToRemoteProceeding', () => { trialDate: '2019-03-01T21:42:29.073Z', trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId, }, - { applicationContext }, + { authorizedUser: mockDocketClerkUser }, ); beforeEach(() => { @@ -31,12 +34,15 @@ describe('setNoticeOfChangeToRemoteProceeding', () => { }); it('should generate and serve a NORP when the proceeding type changes from in person to remote and the case status is not closed', async () => { - await setNoticeOfChangeToRemoteProceeding(applicationContext, { - caseEntity: mockOpenCase, - newPdfDoc: mockNewPdf, - newTrialSessionEntity: MOCK_TRIAL_REMOTE, - user: petitionsClerkUser, - }); + await setNoticeOfChangeToRemoteProceeding( + applicationContext, + { + caseEntity: mockOpenCase, + newPdfDoc: mockNewPdf, + newTrialSessionEntity: MOCK_TRIAL_REMOTE, + }, + mockTrialClerkUser, + ); expect( applicationContext.getUseCases() @@ -63,7 +69,6 @@ describe('setNoticeOfChangeToRemoteProceeding', () => { SYSTEM_GENERATED_DOCUMENT_TYPES.noticeOfChangeToRemoteProceeding, newPdfDoc: mockNewPdf, noticePdf: mockNoticePdf, - user: petitionsClerkUser, }); }); }); diff --git a/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToRemoteProceeding.ts b/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToRemoteProceeding.ts index ae1139abe3d..cd9b931b3a2 100644 --- a/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToRemoteProceeding.ts +++ b/web-api/src/business/useCaseHelper/trialSessions/setNoticeOfChangeToRemoteProceeding.ts @@ -1,4 +1,7 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { Case } from '@shared/business/entities/cases/Case'; import { SYSTEM_GENERATED_DOCUMENT_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; +import { ServerApplicationContext } from '@web-api/applicationContext'; export type TrialSessionInformationType = { chambersPhoneNumber: string; @@ -22,8 +25,13 @@ export type TrialSessionInformationType = { * @param {object} providers.userId the user ID */ export const setNoticeOfChangeToRemoteProceeding = async ( - applicationContext, - { caseEntity, newPdfDoc, newTrialSessionEntity, user }, + applicationContext: ServerApplicationContext, + { + caseEntity, + newPdfDoc, + newTrialSessionEntity, + }: { caseEntity: Case; newPdfDoc: any; newTrialSessionEntity: any }, + authorizedUser: AuthUser, ): Promise => { const trialSessionInformation: TrialSessionInformationType = { chambersPhoneNumber: newTrialSessionEntity.chambersPhoneNumber, @@ -43,14 +51,15 @@ export const setNoticeOfChangeToRemoteProceeding = async ( trialSessionInformation, }); - await applicationContext - .getUseCaseHelpers() - .createAndServeNoticeDocketEntry(applicationContext, { + await applicationContext.getUseCaseHelpers().createAndServeNoticeDocketEntry( + applicationContext, + { caseEntity, documentInfo: SYSTEM_GENERATED_DOCUMENT_TYPES.noticeOfChangeToRemoteProceeding, newPdfDoc, noticePdf, - user, - }); + }, + authorizedUser, + ); }; diff --git a/web-api/src/business/useCases/addCoversheetInteractor.test.ts b/web-api/src/business/useCases/addCoversheetInteractor.test.ts index 8cdcb2391e2..3fda5159c69 100644 --- a/web-api/src/business/useCases/addCoversheetInteractor.test.ts +++ b/web-api/src/business/useCases/addCoversheetInteractor.test.ts @@ -10,6 +10,7 @@ import { MOCK_CASE } from '../../../../shared/src/test/mockCase'; import { addCoverToPdf } from './addCoverToPdf'; import { addCoversheetInteractor } from './addCoversheetInteractor'; import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; jest.mock('./addCoverToPdf', () => ({ __esModule: true, @@ -79,10 +80,14 @@ describe('addCoversheetInteractor', () => { }); it('adds a cover page to a pdf document', async () => { - await addCoversheetInteractor(applicationContext, { - docketEntryId: mockDocketEntryId, - docketNumber: MOCK_CASE.docketNumber, - } as any); + await addCoversheetInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + docketNumber: MOCK_CASE.docketNumber, + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getDocumentGenerators().coverSheet, @@ -93,11 +98,15 @@ describe('addCoversheetInteractor', () => { }); it('replaces the cover page on a document', async () => { - await addCoversheetInteractor(applicationContext, { - docketEntryId: mockDocketEntryId, - docketNumber: MOCK_CASE.docketNumber, - replaceCoversheet: true, - } as any); + await addCoversheetInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + docketNumber: MOCK_CASE.docketNumber, + replaceCoversheet: true, + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getDocumentGenerators().coverSheet, @@ -108,10 +117,14 @@ describe('addCoversheetInteractor', () => { }); it("updates the docket entry's page numbers", async () => { - await addCoversheetInteractor(applicationContext, { - docketEntryId: mockDocketEntryId, - docketNumber: MOCK_CASE.docketNumber, - } as any); + await addCoversheetInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + docketNumber: MOCK_CASE.docketNumber, + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateDocketEntry, @@ -123,10 +136,14 @@ describe('addCoversheetInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(optionalTestingCaseData); - await addCoversheetInteractor(applicationContext, { - docketEntryId: 'b6b81f4d-1e47-423a-8caf-6d2fdc3d3858', - docketNumber: MOCK_CASE.docketNumber, - } as any); + await addCoversheetInteractor( + applicationContext, + { + docketEntryId: 'b6b81f4d-1e47-423a-8caf-6d2fdc3d3858', + docketNumber: MOCK_CASE.docketNumber, + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveDocumentFromLambda, @@ -140,6 +157,7 @@ describe('addCoversheetInteractor', () => { docketEntryId: mockDocketEntryId, docketNumber: MOCK_CASE.docketNumber, } as any, + mockDocketClerkUser, ); expect(updatedDocketEntryEntity).toMatchObject({ @@ -149,10 +167,14 @@ describe('addCoversheetInteractor', () => { }); it('should call getCaseByDocketNumber to retrieve case entity if it is not passed in', async () => { - await addCoversheetInteractor(applicationContext, { - docketEntryId: mockDocketEntryId, - docketNumber: MOCK_CASE.docketNumber, - } as any); + await addCoversheetInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + docketNumber: MOCK_CASE.docketNumber, + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber.mock @@ -161,11 +183,17 @@ describe('addCoversheetInteractor', () => { }); it('should not call getCaseByDocketNumber if case entity is passed in', async () => { - await addCoversheetInteractor(applicationContext, { - caseEntity: new Case(testingCaseData, { applicationContext }), - docketEntryId: mockDocketEntryId, - docketNumber: MOCK_CASE.docketNumber, - } as any); + await addCoversheetInteractor( + applicationContext, + { + caseEntity: new Case(testingCaseData, { + authorizedUser: mockDocketClerkUser, + }), + docketEntryId: mockDocketEntryId, + docketNumber: MOCK_CASE.docketNumber, + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -203,10 +231,14 @@ describe('addCoversheetInteractor', () => { docketNumber: '103-20', }); - await addCoversheetInteractor(applicationContext, { - docketEntryId: mockDocketEntryId, - docketNumber: MOCK_CASE.docketNumber, - } as any); + await addCoversheetInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + docketNumber: MOCK_CASE.docketNumber, + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateDocketEntry, @@ -240,10 +272,14 @@ describe('addCoversheetInteractor', () => { pdfData: 'gg', }); - await addCoversheetInteractor(applicationContext, { - docketEntryId: mockDocketEntryId, - docketNumber: MOCK_CASE.docketNumber, - } as any); + await addCoversheetInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + docketNumber: MOCK_CASE.docketNumber, + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateDocketEntry, @@ -294,17 +330,21 @@ describe('addCoversheetInteractor', () => { docketNumber: mockConsolidatedCaseNonSubjectCase, }); - await addCoversheetInteractor(applicationContext, { - caseEntity: new Case( - { - ...testingCaseData, - eventCode: SIMULTANEOUS_DOCUMENT_EVENT_CODES[0], - }, - { applicationContext }, - ), - docketEntryId: mockDocketEntryId, - docketNumber: MOCK_CASE.docketNumber, - } as any); + await addCoversheetInteractor( + applicationContext, + { + caseEntity: new Case( + { + ...testingCaseData, + eventCode: SIMULTANEOUS_DOCUMENT_EVENT_CODES[0], + }, + { authorizedUser: mockDocketClerkUser }, + ), + docketEntryId: mockDocketEntryId, + docketNumber: MOCK_CASE.docketNumber, + } as any, + mockDocketClerkUser, + ); const calls = applicationContext .getPersistenceGateway() @@ -351,17 +391,21 @@ describe('addCoversheetInteractor', () => { docketNumber: mockConsolidatedCaseNonSubjectCase, }); - await addCoversheetInteractor(applicationContext, { - caseEntity: new Case( - { - ...testingCaseData, - documentTitle: 'Super Duper Simultaneous but not really', - }, - { applicationContext }, - ), - docketEntryId: mockDocketEntryId, - docketNumber: MOCK_CASE.docketNumber, - } as any); + await addCoversheetInteractor( + applicationContext, + { + caseEntity: new Case( + { + ...testingCaseData, + documentTitle: 'Super Duper Simultaneous but not really', + }, + { authorizedUser: mockDocketClerkUser }, + ), + docketEntryId: mockDocketEntryId, + docketNumber: MOCK_CASE.docketNumber, + } as any, + mockDocketClerkUser, + ); const calls = applicationContext .getPersistenceGateway() diff --git a/web-api/src/business/useCases/addCoversheetInteractor.ts b/web-api/src/business/useCases/addCoversheetInteractor.ts index b081c4a81a5..58b86533038 100644 --- a/web-api/src/business/useCases/addCoversheetInteractor.ts +++ b/web-api/src/business/useCases/addCoversheetInteractor.ts @@ -1,6 +1,7 @@ import { Case } from '../../../../shared/src/business/entities/cases/Case'; import { SIMULTANEOUS_DOCUMENT_EVENT_CODES } from '../../../../shared/src/business/entities/EntityConstants'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { addCoverToPdf } from './addCoverToPdf'; /** @@ -31,6 +32,7 @@ export const addCoversheetInteractor = async ( replaceCoversheet?: boolean; useInitialData?: boolean; }, + authorizedUser: UnknownAuthUser, ) => { if (!caseEntity) { const caseRecord = await applicationContext @@ -40,7 +42,9 @@ export const addCoversheetInteractor = async ( docketNumber, }); - caseEntity = new Case(caseRecord, { applicationContext }); + caseEntity = new Case(caseRecord, { + authorizedUser, + }); } const pdfData = await applicationContext.getPersistenceGateway().getDocument({ @@ -92,7 +96,7 @@ export const addCoversheetInteractor = async ( docketNumber: caseDocketNumber, }); consolidatedCaseEntity = new Case(caseRecord, { - applicationContext, + authorizedUser, }); } diff --git a/web-api/src/business/useCases/addPetitionerToCaseInteractor.test.ts b/web-api/src/business/useCases/addPetitionerToCaseInteractor.test.ts index eb878746416..df800007eb5 100644 --- a/web-api/src/business/useCases/addPetitionerToCaseInteractor.test.ts +++ b/web-api/src/business/useCases/addPetitionerToCaseInteractor.test.ts @@ -3,17 +3,17 @@ import { CASE_STATUS_TYPES, CONTACT_TYPES, COUNTRY_TYPES, - ROLES, SERVICE_INDICATOR_TYPES, } from '../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE } from '../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../shared/src/test/mockLock'; -import { - ServiceUnavailableError, - UnauthorizedError, -} from '@web-api/errors/errors'; +import { ServiceUnavailableError } from '@web-api/errors/errors'; import { addPetitionerToCaseInteractor } from './addPetitionerToCaseInteractor'; import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('addPetitionerToCaseInteractor', () => { let mockContact; @@ -39,11 +39,6 @@ describe('addPetitionerToCaseInteractor', () => { state: 'CO', }; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketClerk', - }); - applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue({ @@ -53,17 +48,16 @@ describe('addPetitionerToCaseInteractor', () => { }); it('should throw an unauthorized error when the user is not authorized to add petitioner to case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }); - await expect( - addPetitionerToCaseInteractor(applicationContext, { - caseCaption: MOCK_CASE.caseCaption, - contact: mockContact, - docketNumber: MOCK_CASE.docketNumber, - }), + addPetitionerToCaseInteractor( + applicationContext, + { + caseCaption: MOCK_CASE.caseCaption, + contact: mockContact, + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('Unauthorized for adding petitioner to case'); }); @@ -76,27 +70,35 @@ describe('addPetitionerToCaseInteractor', () => { }); await expect( - addPetitionerToCaseInteractor(applicationContext, { - caseCaption: MOCK_CASE.caseCaption, - contact: mockContact, - docketNumber: MOCK_CASE.docketNumber, - }), + addPetitionerToCaseInteractor( + applicationContext, + { + caseCaption: MOCK_CASE.caseCaption, + contact: mockContact, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow( `Case with docketNumber ${MOCK_CASE.docketNumber} has not been served`, ); }); it('should add the petitioner to the case and send the updated case to persistence, and return the updated case', async () => { - await addPetitionerToCaseInteractor(applicationContext, { - caseCaption: MOCK_CASE.caseCaption, + await addPetitionerToCaseInteractor( + applicationContext, + { + caseCaption: MOCK_CASE.caseCaption, - contact: { - ...mockContact, - country: 'Georgia', - countryType: COUNTRY_TYPES.INTERNATIONAL, + contact: { + ...mockContact, + country: 'Georgia', + countryType: COUNTRY_TYPES.INTERNATIONAL, + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -115,6 +117,7 @@ describe('addPetitionerToCaseInteractor', () => { contact: mockContact, docketNumber: MOCK_CASE.docketNumber, }, + mockDocketClerkUser, ); expect(updatedCase.petitioners.length).toEqual(2); @@ -131,11 +134,15 @@ describe('addPetitionerToCaseInteractor', () => { const mockUpdatedCaption = 'An updated caption'; - await addPetitionerToCaseInteractor(applicationContext, { - caseCaption: mockUpdatedCaption, - contact: mockContact, - docketNumber: MOCK_CASE.docketNumber, - }); + await addPetitionerToCaseInteractor( + applicationContext, + { + caseCaption: mockUpdatedCaption, + contact: mockContact, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -147,11 +154,15 @@ describe('addPetitionerToCaseInteractor', () => { mockLock = MOCK_LOCK; await expect( - addPetitionerToCaseInteractor(applicationContext, { - caseCaption: MOCK_CASE.caseCaption, - contact: mockContact, - docketNumber: MOCK_CASE.docketNumber, - }), + addPetitionerToCaseInteractor( + applicationContext, + { + caseCaption: MOCK_CASE.caseCaption, + contact: mockContact, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -160,11 +171,15 @@ describe('addPetitionerToCaseInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await addPetitionerToCaseInteractor(applicationContext, { - caseCaption: MOCK_CASE.caseCaption, - contact: mockContact, - docketNumber: MOCK_CASE.docketNumber, - }); + await addPetitionerToCaseInteractor( + applicationContext, + { + caseCaption: MOCK_CASE.caseCaption, + contact: mockContact, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -181,16 +196,4 @@ describe('addPetitionerToCaseInteractor', () => { identifiers: [`case|${MOCK_CASE.docketNumber}`], }); }); - - it('should throw an Unauthorized error if the user is not authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - - await expect( - addPetitionerToCaseInteractor(applicationContext, { - caseCaption: MOCK_CASE.caseCaption, - contact: mockContact, - docketNumber: MOCK_CASE.docketNumber, - }), - ).rejects.toThrow(UnauthorizedError); - }); }); diff --git a/web-api/src/business/useCases/addPetitionerToCaseInteractor.ts b/web-api/src/business/useCases/addPetitionerToCaseInteractor.ts index 7caf59dab60..8a0c0e495b7 100644 --- a/web-api/src/business/useCases/addPetitionerToCaseInteractor.ts +++ b/web-api/src/business/useCases/addPetitionerToCaseInteractor.ts @@ -7,16 +7,9 @@ import { } from '../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; -/** - * used to add a petitioner to a case - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {object} providers.contact the contact data to add to the case - * @param {string} providers.docketNumber the docket number of the case - * @returns {object} the case data - */ export const addPetitionerToCase = async ( applicationContext: ServerApplicationContext, { @@ -24,9 +17,8 @@ export const addPetitionerToCase = async ( contact, docketNumber, }: { caseCaption: string; contact: any; docketNumber: string }, -) => { - const authorizedUser = applicationContext.getCurrentUser(); - + authorizedUser: UnknownAuthUser, +): Promise => { if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.ADD_PETITIONER_TO_CASE)) { throw new UnauthorizedError('Unauthorized for adding petitioner to case'); } @@ -38,7 +30,7 @@ export const addPetitionerToCase = async ( docketNumber, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); if (caseEntity.status === CASE_STATUS_TYPES.new) { throw new Error( @@ -48,9 +40,7 @@ export const addPetitionerToCase = async ( caseEntity.caseCaption = caseCaption; - const petitionerEntity = new Petitioner(contact, { - applicationContext, - }); + const petitionerEntity = new Petitioner(contact); caseEntity.addPetitioner(petitionerEntity); @@ -58,10 +48,11 @@ export const addPetitionerToCase = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const addPetitionerToCaseInteractor = withLocking( diff --git a/web-api/src/business/useCases/archiveDraftDocumentInteractor.test.ts b/web-api/src/business/useCases/archiveDraftDocumentInteractor.test.ts index ac940acb2cd..da39f5846e1 100644 --- a/web-api/src/business/useCases/archiveDraftDocumentInteractor.test.ts +++ b/web-api/src/business/useCases/archiveDraftDocumentInteractor.test.ts @@ -4,30 +4,34 @@ import { ROLES } from '../../../../shared/src/business/entities/EntityConstants' import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; import { archiveDraftDocumentInteractor } from './archiveDraftDocumentInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('archiveDraftDocumentInteractor', () => { let mockLock; + beforeAll(() => { applicationContext .getPersistenceGateway() .getLock.mockImplementation(() => mockLock); }); + beforeEach(() => { mockLock = undefined; - - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - }); }); it('returns an unauthorized error on non petitionsclerk users', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - archiveDraftDocumentInteractor(applicationContext, { - docketEntryId: 'a54ba5a9-b37b-479d-9201-067ec6e335bb', - docketNumber: '101-20', - }), + archiveDraftDocumentInteractor( + applicationContext, + { + docketEntryId: 'a54ba5a9-b37b-479d-9201-067ec6e335bb', + docketNumber: '101-20', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -36,15 +40,18 @@ describe('archiveDraftDocumentInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE); - await archiveDraftDocumentInteractor(applicationContext, { - docketEntryId: 'abc81f4d-1e47-423a-8caf-6d2fdc3d3859', - docketNumber: '101-20', - }); + await archiveDraftDocumentInteractor( + applicationContext, + { + docketEntryId: 'abc81f4d-1e47-423a-8caf-6d2fdc3d3859', + docketNumber: '101-20', + }, + mockPetitionsClerkUser, + ); const { caseToUpdate } = applicationContext.getUseCaseHelpers().updateCaseAndAssociations.mock .calls[0][0]; - expect( caseToUpdate.archivedDocketEntries.find( d => d.docketEntryId === 'abc81f4d-1e47-423a-8caf-6d2fdc3d3859', @@ -53,7 +60,6 @@ describe('archiveDraftDocumentInteractor', () => { archived: true, docketEntryId: 'abc81f4d-1e47-423a-8caf-6d2fdc3d3859', }); - expect( caseToUpdate.docketEntries.find( d => d.docketEntryId === 'abc81f4d-1e47-423a-8caf-6d2fdc3d3859', @@ -91,10 +97,14 @@ describe('archiveDraftDocumentInteractor', () => { ], }); - await archiveDraftDocumentInteractor(applicationContext, { - docketEntryId: '99981f4d-1e47-423a-8caf-6d2fdc3d3999', - docketNumber: '101-20', - }); + await archiveDraftDocumentInteractor( + applicationContext, + { + docketEntryId: '99981f4d-1e47-423a-8caf-6d2fdc3d3999', + docketNumber: '101-20', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().deleteWorkItem, @@ -105,10 +115,14 @@ describe('archiveDraftDocumentInteractor', () => { mockLock = MOCK_LOCK; await expect( - archiveDraftDocumentInteractor(applicationContext, { - docketEntryId: 'abc81f4d-1e47-423a-8caf-6d2fdc3d3859', - docketNumber: '101-20', - }), + archiveDraftDocumentInteractor( + applicationContext, + { + docketEntryId: 'abc81f4d-1e47-423a-8caf-6d2fdc3d3859', + docketNumber: '101-20', + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -117,10 +131,14 @@ describe('archiveDraftDocumentInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await await archiveDraftDocumentInteractor(applicationContext, { - docketEntryId: 'abc81f4d-1e47-423a-8caf-6d2fdc3d3859', - docketNumber: MOCK_CASE.docketNumber, - }); + await await archiveDraftDocumentInteractor( + applicationContext, + { + docketEntryId: 'abc81f4d-1e47-423a-8caf-6d2fdc3d3859', + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -129,7 +147,6 @@ describe('archiveDraftDocumentInteractor', () => { identifier: `case|${MOCK_CASE.docketNumber}`, ttl: 30, }); - expect( applicationContext.getPersistenceGateway().removeLock, ).toHaveBeenCalledWith({ diff --git a/web-api/src/business/useCases/archiveDraftDocumentInteractor.ts b/web-api/src/business/useCases/archiveDraftDocumentInteractor.ts index 91284553666..84ec8a788c4 100644 --- a/web-api/src/business/useCases/archiveDraftDocumentInteractor.ts +++ b/web-api/src/business/useCases/archiveDraftDocumentInteractor.ts @@ -5,26 +5,18 @@ import { } from '../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; -/** - * archiveDraftDocumentInteractor - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {string} providers.docketNumber the docket number of the case on which a document will be archived - * @param {string} providers.docketEntryId the id of the docket entry which will be archived - * @returns {object} the updated case note returned from persistence - */ export const archiveDraftDocument = async ( applicationContext: ServerApplicationContext, { docketEntryId, docketNumber, }: { docketEntryId: string; docketNumber: string }, -) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.ARCHIVE_DOCUMENT)) { + authorizedUser: UnknownAuthUser, +): Promise => { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.ARCHIVE_DOCUMENT)) { throw new UnauthorizedError('Unauthorized'); } @@ -35,7 +27,7 @@ export const archiveDraftDocument = async ( docketNumber, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); const docketEntryToArchive = caseEntity.getDocketEntryById({ docketEntryId, @@ -56,10 +48,11 @@ export const archiveDraftDocument = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const archiveDraftDocumentInteractor = withLocking( diff --git a/web-api/src/business/useCases/auth/changePasswordInteractor.ts b/web-api/src/business/useCases/auth/changePasswordInteractor.ts index 7634c8623e8..9f8f302b567 100644 --- a/web-api/src/business/useCases/auth/changePasswordInteractor.ts +++ b/web-api/src/business/useCases/auth/changePasswordInteractor.ts @@ -1,3 +1,4 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { ChangePasswordForm } from '@shared/business/entities/ChangePasswordForm'; import { InvalidEntityError, NotFoundError } from '@web-api/errors/errors'; import { MESSAGE_TYPES } from '@web-api/gateways/worker/workerRouter'; @@ -73,9 +74,9 @@ export const changePasswordInteractor = async ( .getWorkerGateway() .queueWork(applicationContext, { message: { + authorizedUser: updatedUser as AuthUser, // In this context, we know for certain that the user has an email address, and is assignable to AuthUser. payload: { user: updatedUser }, type: MESSAGE_TYPES.QUEUE_UPDATE_ASSOCIATED_CASES, - user: updatedUser, }, }); } diff --git a/web-api/src/business/useCases/auth/signUpUserInteractor.ts b/web-api/src/business/useCases/auth/signUpUserInteractor.ts index 87091c8894b..ab22dda09b1 100644 --- a/web-api/src/business/useCases/auth/signUpUserInteractor.ts +++ b/web-api/src/business/useCases/auth/signUpUserInteractor.ts @@ -28,6 +28,11 @@ export const signUpUserInteractor = async ( email: user.email, }); + // Note that this check can fail to catch two (nearly) simultaneous requests, + // and Cognito can therefore create accounts with the same email. + // (See https://stackoverflow.com/questions/50730759/user-pool-allows-two-users-with-same-email-despite-configuration) + // On the frontend, we can prevent multiple submissions; if we wanted to enforce non-duplicates on the backend, + // we would probably need to run an asynchronous task to delete duplicate records. if (existingAccount) { const accountUnconfirmed = existingAccount.accountStatus === UserStatusType.UNCONFIRMED; diff --git a/web-api/src/business/useCases/blockCaseFromTrialInteractor.test.ts b/web-api/src/business/useCases/blockCaseFromTrialInteractor.test.ts index 72ccfba2e17..6e3197f3113 100644 --- a/web-api/src/business/useCases/blockCaseFromTrialInteractor.test.ts +++ b/web-api/src/business/useCases/blockCaseFromTrialInteractor.test.ts @@ -1,9 +1,12 @@ import { MOCK_CASE } from '../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../shared/src/test/mockLock'; -import { ROLES } from '../../../../shared/src/business/entities/EntityConstants'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; import { blockCaseFromTrialInteractor } from './blockCaseFromTrialInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('blockCaseFromTrialInteractor', () => { let mockLock; @@ -14,10 +17,6 @@ describe('blockCaseFromTrialInteractor', () => { }); beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE); @@ -30,10 +29,14 @@ describe('blockCaseFromTrialInteractor', () => { }); it('should update the case with the blocked flag set as true and attach a reason', async () => { - const result = await blockCaseFromTrialInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - reason: 'just because', - }); + const result = await blockCaseFromTrialInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + reason: 'just because', + }, + mockPetitionsClerkUser, + ); expect(result).toMatchObject({ blocked: true, @@ -53,10 +56,14 @@ describe('blockCaseFromTrialInteractor', () => { mockLock = MOCK_LOCK; await expect( - blockCaseFromTrialInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - reason: 'just because', - }), + blockCaseFromTrialInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + reason: 'just because', + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -65,10 +72,14 @@ describe('blockCaseFromTrialInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await blockCaseFromTrialInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - reason: 'just because', - }); + await blockCaseFromTrialInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + reason: 'just because', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -87,15 +98,14 @@ describe('blockCaseFromTrialInteractor', () => { }); it('should throw an unauthorized error if the user has no access to block cases', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: 'nope', - userId: 'nope', - }); - await expect( - blockCaseFromTrialInteractor(applicationContext, { - docketNumber: '123-45', - } as any), + blockCaseFromTrialInteractor( + applicationContext, + { + docketNumber: '123-45', + } as any, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); }); diff --git a/web-api/src/business/useCases/blockCaseFromTrialInteractor.ts b/web-api/src/business/useCases/blockCaseFromTrialInteractor.ts index fea738451b4..1fe3133cfd8 100644 --- a/web-api/src/business/useCases/blockCaseFromTrialInteractor.ts +++ b/web-api/src/business/useCases/blockCaseFromTrialInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -18,9 +19,8 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; export const blockCaseFromTrial = async ( applicationContext: ServerApplicationContext, { docketNumber, reason }: { docketNumber: string; reason: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.BLOCK_CASE)) { throw new UnauthorizedError('Unauthorized'); } @@ -32,7 +32,7 @@ export const blockCaseFromTrial = async ( docketNumber, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); caseEntity.setAsBlocked(reason); @@ -47,10 +47,11 @@ export const blockCaseFromTrial = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const blockCaseFromTrialInteractor = withLocking( diff --git a/web-api/src/business/useCases/caseAdvancedSearchInteractor.test.ts b/web-api/src/business/useCases/caseAdvancedSearchInteractor.test.ts index 06f883c39bb..a156e16f313 100644 --- a/web-api/src/business/useCases/caseAdvancedSearchInteractor.test.ts +++ b/web-api/src/business/useCases/caseAdvancedSearchInteractor.test.ts @@ -1,38 +1,34 @@ -import { - MAX_SEARCH_RESULTS, - ROLES, -} from '../../../../shared/src/business/entities/EntityConstants'; +import { MAX_SEARCH_RESULTS } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; import { caseAdvancedSearchInteractor } from './caseAdvancedSearchInteractor'; +import { + mockIrsPractitionerUser, + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('caseAdvancedSearchInteractor', () => { - let mockUser; - - beforeEach(() => { - mockUser = { - role: ROLES.petitionsClerk, - }; - - applicationContext.environment.stage = 'local'; - applicationContext.getCurrentUser.mockImplementation(() => mockUser); - - applicationContext - .getPersistenceGateway() - .caseAdvancedSearch.mockResolvedValue([]); - }); - it('returns an unauthorized error on petitioner user role', async () => { - mockUser.role = ROLES.petitioner; - await expect( - caseAdvancedSearchInteractor(applicationContext, {} as any), + caseAdvancedSearchInteractor( + applicationContext, + { petitionerName: 'Janae Jacobs' }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('returns empty array if no search params are passed in', async () => { + applicationContext + .getPersistenceGateway() + .caseAdvancedSearch.mockResolvedValue([]); + const results = await caseAdvancedSearchInteractor( applicationContext, - {} as any, + { + petitionerName: 'Paul Billings', + }, + mockPetitionsClerkUser, ); expect(results).toEqual([]); @@ -52,9 +48,13 @@ describe('caseAdvancedSearchInteractor', () => { }, ]); - const results = await caseAdvancedSearchInteractor(applicationContext, { - petitionerName: 'test person', - } as any); + const results = await caseAdvancedSearchInteractor( + applicationContext, + { + petitionerName: 'test person', + }, + mockPetitionsClerkUser, + ); expect(results).toEqual([ { docketNumber: '101-20', petitioners: [] }, @@ -76,11 +76,15 @@ describe('caseAdvancedSearchInteractor', () => { }, ]); - const results = await caseAdvancedSearchInteractor(applicationContext, { - endDate: '07/29/1993', - petitionerName: 'test person', - startDate: '05/18/1985', - } as any); + const results = await caseAdvancedSearchInteractor( + applicationContext, + { + endDate: '07/29/1993', + petitionerName: 'test person', + startDate: '05/18/1985', + }, + mockPetitionsClerkUser, + ); expect(results).toEqual([ { docketNumber: '101-20', petitioners: [] }, @@ -89,11 +93,6 @@ describe('caseAdvancedSearchInteractor', () => { }); it('filters out sealed cases for non associated, non authorized users', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.irsPractitioner, - userId: 'b45a0633-acda-499e-8fab-8785baeafed7', - }); - applicationContext .getPersistenceGateway() .caseAdvancedSearch.mockResolvedValue([ @@ -105,19 +104,18 @@ describe('caseAdvancedSearchInteractor', () => { }, ]); - const results = await caseAdvancedSearchInteractor(applicationContext, { - petitionerName: 'test person', - } as any); + const results = await caseAdvancedSearchInteractor( + applicationContext, + { + petitionerName: 'test person', + }, + mockIrsPractitionerUser, + ); expect(results).toEqual([]); }); it('filters out sealed cases that do not have a sealedDate for non associated, non authorized users', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.irsPractitioner, - userId: 'b45a0633-acda-499e-8fab-8785baeafed7', - }); - applicationContext .getPersistenceGateway() .caseAdvancedSearch.mockResolvedValue([ @@ -129,19 +127,18 @@ describe('caseAdvancedSearchInteractor', () => { }, ]); - const results = await caseAdvancedSearchInteractor(applicationContext, { - petitionerName: 'test person', - } as any); + const results = await caseAdvancedSearchInteractor( + applicationContext, + { + petitionerName: 'test person', + }, + mockIrsPractitionerUser, + ); expect(results).toEqual([]); }); it('returns no more than MAX_SEARCH_RESULTS', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.irsPractitioner, - userId: 'b45a0633-acda-499e-8fab-8785baeafed7', - }); - const maxPlusOneResults = new Array(MAX_SEARCH_RESULTS + 1).fill({ docketNumber: '101-20', petitioners: [], @@ -152,19 +149,18 @@ describe('caseAdvancedSearchInteractor', () => { .getPersistenceGateway() .caseAdvancedSearch.mockResolvedValue(maxPlusOneResults); - const results = await caseAdvancedSearchInteractor(applicationContext, { - petitionerName: 'test person', - } as any); + const results = await caseAdvancedSearchInteractor( + applicationContext, + { + petitionerName: 'test person', + }, + mockIrsPractitionerUser, + ); expect(results.length).toBe(MAX_SEARCH_RESULTS); }); it('returns results if practitioner is associated', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.irsPractitioner, - userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', - }); - applicationContext .getPersistenceGateway() .caseAdvancedSearch.mockResolvedValue([ @@ -172,7 +168,7 @@ describe('caseAdvancedSearchInteractor', () => { docketNumber: '101-20', irsPractitioners: [ { - userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + userId: mockIrsPractitionerUser.userId, }, ], petitioners: [], @@ -180,16 +176,20 @@ describe('caseAdvancedSearchInteractor', () => { }, ]); - const results = await caseAdvancedSearchInteractor(applicationContext, { - petitionerName: 'test person', - } as any); + const results = await caseAdvancedSearchInteractor( + applicationContext, + { + petitionerName: 'test person', + }, + mockIrsPractitionerUser, + ); expect(results).toEqual([ { docketNumber: '101-20', irsPractitioners: [ { - userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', + userId: mockIrsPractitionerUser.userId, }, ], petitioners: [], @@ -199,10 +199,6 @@ describe('caseAdvancedSearchInteractor', () => { }); it('returns results for petitionsclerk or internal user always', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - }); - applicationContext .getPersistenceGateway() .caseAdvancedSearch.mockResolvedValue([ @@ -213,9 +209,13 @@ describe('caseAdvancedSearchInteractor', () => { }, ]); - const results = await caseAdvancedSearchInteractor(applicationContext, { - petitionerName: 'test person', - } as any); + const results = await caseAdvancedSearchInteractor( + applicationContext, + { + petitionerName: 'test person', + }, + mockPetitionsClerkUser, + ); expect(results).toEqual([ { diff --git a/web-api/src/business/useCases/caseAdvancedSearchInteractor.ts b/web-api/src/business/useCases/caseAdvancedSearchInteractor.ts index 0fb82456c91..cb2a7bdc571 100644 --- a/web-api/src/business/useCases/caseAdvancedSearchInteractor.ts +++ b/web-api/src/business/useCases/caseAdvancedSearchInteractor.ts @@ -9,6 +9,7 @@ import { } from '../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { caseSearchFilter } from '../../../../shared/src/business/utilities/caseFilter'; import { createEndOfDayISO, @@ -32,8 +33,8 @@ export const caseAdvancedSearchInteractor = async ( petitionerState, startDate, }: CaseAdvancedSearchParamsRequestType, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); let searchStartDate; let searchEndDate; diff --git a/web-api/src/business/useCases/caseAssociation/deleteCounselFromCaseInteractor.test.ts b/web-api/src/business/useCases/caseAssociation/deleteCounselFromCaseInteractor.test.ts index 98ea12947f9..7cfc848524b 100644 --- a/web-api/src/business/useCases/caseAssociation/deleteCounselFromCaseInteractor.test.ts +++ b/web-api/src/business/useCases/caseAssociation/deleteCounselFromCaseInteractor.test.ts @@ -12,7 +12,10 @@ import { deleteCounselFromCaseInteractor, setupServiceIndicatorForUnrepresentedPetitioners, } from './deleteCounselFromCaseInteractor'; -import { petitionerUser } from '@shared/test/mockUsers'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('deleteCounselFromCaseInteractor', () => { const mockPrivatePractitioners = [ @@ -74,11 +77,6 @@ describe('deleteCounselFromCaseInteractor', () => { beforeEach(() => { mockLock = undefined; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'fb39f224-7985-438d-8327-2df162c20c8e', - }); - applicationContext .getPersistenceGateway() .getUserById.mockImplementation(({ userId }) => { @@ -101,13 +99,15 @@ describe('deleteCounselFromCaseInteractor', () => { }); it('should return an unauthorized error when the user does not have permission to remove counsel from a case', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - await expect( - deleteCounselFromCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userId: '141d4c7c-4302-465d-89bd-3bc8ae16f07d', - }), + deleteCounselFromCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userId: '141d4c7c-4302-465d-89bd-3bc8ae16f07d', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -115,10 +115,14 @@ describe('deleteCounselFromCaseInteractor', () => { mockLock = MOCK_LOCK; await expect( - deleteCounselFromCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userId: '141d4c7c-4302-465d-89bd-3bc8ae16f07d', - }), + deleteCounselFromCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userId: '141d4c7c-4302-465d-89bd-3bc8ae16f07d', + }, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -127,10 +131,14 @@ describe('deleteCounselFromCaseInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await deleteCounselFromCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userId: '141d4c7c-4302-465d-89bd-3bc8ae16f07d', - }); + await deleteCounselFromCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userId: '141d4c7c-4302-465d-89bd-3bc8ae16f07d', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -148,10 +156,14 @@ describe('deleteCounselFromCaseInteractor', () => { }); it('should remove the private practitioner with the given user id from the case', async () => { - await deleteCounselFromCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userId: '141d4c7c-4302-465d-89bd-3bc8ae16f07d', - }); + await deleteCounselFromCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userId: '141d4c7c-4302-465d-89bd-3bc8ae16f07d', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().deleteUserFromCase, @@ -162,10 +174,14 @@ describe('deleteCounselFromCaseInteractor', () => { }); it('should remove the irs practitioner with the given userId from the case', async () => { - await deleteCounselFromCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userId: 'bfd97089-cda0-45e0-8454-dd879023d0af', - }); + await deleteCounselFromCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userId: 'bfd97089-cda0-45e0-8454-dd879023d0af', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().deleteUserFromCase, @@ -177,10 +193,14 @@ describe('deleteCounselFromCaseInteractor', () => { it('should throw an error when the user is NOT a private practitioner or irs practitioner', async () => { await expect( - deleteCounselFromCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userId: '835f072c-5ea1-493c-acb8-d67b05c96f85', - }), + deleteCounselFromCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userId: '835f072c-5ea1-493c-acb8-d67b05c96f85', + }, + mockDocketClerkUser, + ), ).rejects.toThrow('User is not a practitioner'); }); @@ -198,10 +218,14 @@ describe('deleteCounselFromCaseInteractor', () => { privatePractitioners: [mockPrivatePractitioners[0]], }); - await deleteCounselFromCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userId: mockPrivatePractitioners[0].userId, - }); + await deleteCounselFromCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userId: mockPrivatePractitioners[0].userId, + }, + mockDocketClerkUser, + ); const updatedCase = applicationContext.getUseCaseHelpers().updateCaseAndAssociations.mock @@ -228,10 +252,14 @@ describe('deleteCounselFromCaseInteractor', () => { privatePractitioners: [mockPrivatePractitioners[0]], }); - await deleteCounselFromCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userId: mockPrivatePractitioners[0].userId, - }); + await deleteCounselFromCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userId: mockPrivatePractitioners[0].userId, + }, + mockDocketClerkUser, + ); const updatedCase = applicationContext.getUseCaseHelpers().updateCaseAndAssociations.mock @@ -287,10 +315,14 @@ describe('deleteCounselFromCaseInteractor', () => { ({ caseToUpdate }) => caseToUpdate, ); - await deleteCounselFromCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userId: mockPrivatePractitioners[0].userId, - }); + await deleteCounselFromCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userId: mockPrivatePractitioners[0].userId, + }, + mockDocketClerkUser, + ); const updatedCase = applicationContext.getUseCaseHelpers().updateCaseAndAssociations.mock @@ -343,10 +375,14 @@ describe('deleteCounselFromCaseInteractor', () => { ({ caseToUpdate }) => caseToUpdate, ); - await deleteCounselFromCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userId: mockPrivatePractitioners[0].userId, - }); + await deleteCounselFromCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userId: mockPrivatePractitioners[0].userId, + }, + mockDocketClerkUser, + ); const updatedCase = applicationContext.getUseCaseHelpers().updateCaseAndAssociations.mock @@ -374,7 +410,7 @@ describe('deleteCounselFromCaseInteractor', () => { }; const result = setupServiceIndicatorForUnrepresentedPetitioners( - new Case(mockCase, { applicationContext }), + new Case(mockCase, { authorizedUser: mockDocketClerkUser }), ); expect(result.petitioners[0].serviceIndicator).toBeUndefined(); @@ -402,7 +438,7 @@ describe('deleteCounselFromCaseInteractor', () => { }; const result = setupServiceIndicatorForUnrepresentedPetitioners( - new Case(mockCase, { applicationContext }), + new Case(mockCase, { authorizedUser: mockDocketClerkUser }), ); expect(result.petitioners[0].serviceIndicator).toEqual( diff --git a/web-api/src/business/useCases/caseAssociation/deleteCounselFromCaseInteractor.ts b/web-api/src/business/useCases/caseAssociation/deleteCounselFromCaseInteractor.ts index b4b3804b959..ce4c7c43579 100644 --- a/web-api/src/business/useCases/caseAssociation/deleteCounselFromCaseInteractor.ts +++ b/web-api/src/business/useCases/caseAssociation/deleteCounselFromCaseInteractor.ts @@ -6,16 +6,18 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { aggregatePartiesForService } from '../../../../../shared/src/business/utilities/aggregatePartiesForService'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; export const deleteCounselFromCase = async ( applicationContext: ServerApplicationContext, { docketNumber, userId }: { docketNumber: string; userId: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.ASSOCIATE_USER_WITH_CASE)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.ASSOCIATE_USER_WITH_CASE) + ) { throw new UnauthorizedError('Unauthorized'); } @@ -33,7 +35,7 @@ export const deleteCounselFromCase = async ( userId, }); - let caseEntity = new Case(caseToUpdate, { applicationContext }); + let caseEntity = new Case(caseToUpdate, { authorizedUser }); if (userToDelete.role === ROLES.privatePractitioner) { caseEntity.removePrivatePractitioner(userToDelete); @@ -55,6 +57,7 @@ export const deleteCounselFromCase = async ( await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity.validate().toRawObject(), }); }; diff --git a/web-api/src/business/useCases/caseAssociation/updateCounselOnCaseInteractor.test.ts b/web-api/src/business/useCases/caseAssociation/updateCounselOnCaseInteractor.test.ts index a46e59dffd9..56719bbb81c 100644 --- a/web-api/src/business/useCases/caseAssociation/updateCounselOnCaseInteractor.test.ts +++ b/web-api/src/business/useCases/caseAssociation/updateCounselOnCaseInteractor.test.ts @@ -12,6 +12,10 @@ import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; import { PrivatePractitioner } from '../../../../../shared/src/business/entities/PrivatePractitioner'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { updateCounselOnCaseInteractor } from './updateCounselOnCaseInteractor'; describe('updateCounselOnCaseInteractor', () => { @@ -75,11 +79,6 @@ describe('updateCounselOnCaseInteractor', () => { beforeEach(() => { mockLock = undefined; - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Saul Goodman', - role: ROLES.docketClerk, - userId: '001', - }); applicationContext .getPersistenceGateway() .getUserById.mockImplementation(({ userId }) => { @@ -133,16 +132,18 @@ describe('updateCounselOnCaseInteractor', () => { }); it('returns an unauthorized error for a petitioner user', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - updateCounselOnCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userData: { - representing: ['9d914ca2-7876-43a7-acfa-ccb645717e11'], + updateCounselOnCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userData: { + representing: ['9d914ca2-7876-43a7-acfa-ccb645717e11'], + }, + userId: '9d914ca2-7876-43a7-acfa-ccb645717e11', }, - userId: '9d914ca2-7876-43a7-acfa-ccb645717e11', - }), + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -150,15 +151,19 @@ describe('updateCounselOnCaseInteractor', () => { mockLock = MOCK_LOCK; await expect( - updateCounselOnCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userData: { - name: 'Saul Goodman', - representing: ['9d914ca2-7876-43a7-acfa-ccb645717e11'], - serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + updateCounselOnCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userData: { + name: 'Saul Goodman', + representing: ['9d914ca2-7876-43a7-acfa-ccb645717e11'], + serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + }, + userId: '9d914ca2-7876-43a7-acfa-ccb645717e11', }, - userId: '9d914ca2-7876-43a7-acfa-ccb645717e11', - }), + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -167,15 +172,19 @@ describe('updateCounselOnCaseInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await updateCounselOnCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userData: { - name: 'Saul Goodman', - representing: ['9d914ca2-7876-43a7-acfa-ccb645717e11'], - serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + await updateCounselOnCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userData: { + name: 'Saul Goodman', + representing: ['9d914ca2-7876-43a7-acfa-ccb645717e11'], + serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + }, + userId: '9d914ca2-7876-43a7-acfa-ccb645717e11', }, - userId: '9d914ca2-7876-43a7-acfa-ccb645717e11', - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -194,15 +203,19 @@ describe('updateCounselOnCaseInteractor', () => { }); it('updates a practitioner with the given userId on the associated case', async () => { - await updateCounselOnCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userData: { - name: 'Saul Goodman', - representing: ['9d914ca2-7876-43a7-acfa-ccb645717e11'], - serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + await updateCounselOnCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userData: { + name: 'Saul Goodman', + representing: ['9d914ca2-7876-43a7-acfa-ccb645717e11'], + serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + }, + userId: '9d914ca2-7876-43a7-acfa-ccb645717e11', }, - userId: '9d914ca2-7876-43a7-acfa-ccb645717e11', - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -210,15 +223,19 @@ describe('updateCounselOnCaseInteractor', () => { }); it('updates an irsPractitioner with the given userId on the associated case', async () => { - await updateCounselOnCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userData: { - name: 'Saul Goodman', - representing: ['9d914ca2-7876-43a7-acfa-ccb645717e11'], - serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + await updateCounselOnCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userData: { + name: 'Saul Goodman', + representing: ['9d914ca2-7876-43a7-acfa-ccb645717e11'], + serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + }, + userId: '76c86b6b-6aad-4128-8fa2-53c5735cc0af', }, - userId: '76c86b6b-6aad-4128-8fa2-53c5735cc0af', - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -226,16 +243,20 @@ describe('updateCounselOnCaseInteractor', () => { }); it('updates only editable practitioner fields on the case', async () => { - await updateCounselOnCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userData: { - email: 'not.editable@example.com', - name: 'Saul Goodman', - representing: ['9d914ca2-7876-43a7-acfa-ccb645717e11'], - serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + await updateCounselOnCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userData: { + email: 'not.editable@example.com', + name: 'Saul Goodman', + representing: ['9d914ca2-7876-43a7-acfa-ccb645717e11'], + serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + }, + userId: '76c86b6b-6aad-4128-8fa2-53c5735cc0af', }, - userId: '76c86b6b-6aad-4128-8fa2-53c5735cc0af', - }); + mockDocketClerkUser, + ); const updatedPractitioner = applicationContext .getPersistenceGateway() @@ -250,16 +271,20 @@ describe('updateCounselOnCaseInteractor', () => { }); it('updates the service indicator on the contacts when they are being represented', async () => { - const results = await updateCounselOnCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userData: { - email: 'not.editable@example.com', - name: 'Saul Goodman', - representing: ['9d914ca2-7876-43a7-acfa-ccb645717e11'], - serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + const results = await updateCounselOnCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userData: { + email: 'not.editable@example.com', + name: 'Saul Goodman', + representing: ['9d914ca2-7876-43a7-acfa-ccb645717e11'], + serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + }, + userId: 'e23e2d08-561b-4930-a2e0-1f342a481268', }, - userId: 'e23e2d08-561b-4930-a2e0-1f342a481268', - }); + mockDocketClerkUser, + ); expect(results.petitioners[0].serviceIndicator).toBe( SERVICE_INDICATOR_TYPES.SI_NONE, @@ -270,16 +295,20 @@ describe('updateCounselOnCaseInteractor', () => { }); it('reverts the service indicator on the contacts when they are no longer being represented', async () => { - const results = await updateCounselOnCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userData: { - email: 'not.editable@example.com', - name: 'Saul Goodman', - representing: ['b7315e1b-b804-4e09-84c5-e0f3b4f229c5'], - serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + const results = await updateCounselOnCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userData: { + email: 'not.editable@example.com', + name: 'Saul Goodman', + representing: ['b7315e1b-b804-4e09-84c5-e0f3b4f229c5'], + serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + }, + userId: 'e23e2d08-561b-4930-a2e0-1f342a481268', }, - userId: 'e23e2d08-561b-4930-a2e0-1f342a481268', - }); + mockDocketClerkUser, + ); expect(results.petitioners[0].serviceIndicator).toBe( SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, @@ -297,13 +326,17 @@ describe('updateCounselOnCaseInteractor', () => { privatePractitioners: [mockPrivatePractitioners[1]], })); - const results = await updateCounselOnCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userData: { - representing: ['9905d1ab-18d0-43ec-bafb-654e83405416'], + const results = await updateCounselOnCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userData: { + representing: ['9905d1ab-18d0-43ec-bafb-654e83405416'], + }, + userId: 'e23e2d08-561b-4930-a2e0-1f342a481268', }, - userId: 'e23e2d08-561b-4930-a2e0-1f342a481268', - }); + mockDocketClerkUser, + ); expect(results.petitioners[0].serviceIndicator).toBe( MOCK_CASE.petitioners[0].serviceIndicator, @@ -312,13 +345,17 @@ describe('updateCounselOnCaseInteractor', () => { it('throws an error if the userId is not a privatePractitioner or irsPractitioner role', async () => { await expect( - updateCounselOnCaseInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - userData: { - email: 'petitioner@example.com', + updateCounselOnCaseInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + userData: { + email: 'petitioner@example.com', + }, + userId: 'aa335271-9a0f-4ad5-bcf1-3b89bd8b5dd6', }, - userId: 'aa335271-9a0f-4ad5-bcf1-3b89bd8b5dd6', - }), + mockDocketClerkUser, + ), ).rejects.toThrow('User is not a practitioner'); }); }); diff --git a/web-api/src/business/useCases/caseAssociation/updateCounselOnCaseInteractor.ts b/web-api/src/business/useCases/caseAssociation/updateCounselOnCaseInteractor.ts index 53b38f78e6f..953f385c377 100644 --- a/web-api/src/business/useCases/caseAssociation/updateCounselOnCaseInteractor.ts +++ b/web-api/src/business/useCases/caseAssociation/updateCounselOnCaseInteractor.ts @@ -9,6 +9,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -28,15 +29,16 @@ const updateCounselOnCase = async ( userData, userId, }: { docketNumber: string; userData: any; userId: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - const editableFields = { representing: userData.representing, serviceIndicator: userData.serviceIndicator, }; - if (!isAuthorized(user, ROLE_PERMISSIONS.ASSOCIATE_USER_WITH_CASE)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.ASSOCIATE_USER_WITH_CASE) + ) { throw new UnauthorizedError('Unauthorized'); } @@ -54,7 +56,7 @@ const updateCounselOnCase = async ( userId, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); if (userToUpdate.role === ROLES.privatePractitioner) { caseEntity.updatePrivatePractitioner({ @@ -87,10 +89,11 @@ const updateCounselOnCase = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const updateCounselOnCaseInteractor = withLocking( diff --git a/web-api/src/business/useCases/caseAssociationRequest/generateEntryOfAppearancePdfInteractor.test.ts b/web-api/src/business/useCases/caseAssociationRequest/generateEntryOfAppearancePdfInteractor.test.ts index 69a2cc642be..eae56f6b08d 100644 --- a/web-api/src/business/useCases/caseAssociationRequest/generateEntryOfAppearancePdfInteractor.test.ts +++ b/web-api/src/business/useCases/caseAssociationRequest/generateEntryOfAppearancePdfInteractor.test.ts @@ -1,12 +1,16 @@ +import { type AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { MOCK_PRACTITIONER, irsPractitionerUser, petitionerUser, - privatePractitionerUser, validUser, } from '@shared/test/mockUsers'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { generateEntryOfAppearancePdfInteractor } from './generateEntryOfAppearancePdfInteractor'; +import { + mockIrsPractitionerUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; describe('generateEntryOfAppearancePdfInteractor', () => { const mockFile = { @@ -25,7 +29,6 @@ describe('generateEntryOfAppearancePdfInteractor', () => { ]; beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(privatePractitionerUser); applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(MOCK_PRACTITIONER); @@ -38,19 +41,23 @@ describe('generateEntryOfAppearancePdfInteractor', () => { }); it('should throw an unauthorized error if the user has no access to associate self with case', async () => { - applicationContext.getCurrentUser.mockReturnValueOnce({ + let bogusUser = { role: 'nope', userId: 'nope', - }); + } as unknown as AuthUser; await expect( - generateEntryOfAppearancePdfInteractor(applicationContext, { - caseCaptionExtension, - caseTitle, - docketNumberWithSuffix, - filers, - petitioners, - }), + generateEntryOfAppearancePdfInteractor( + applicationContext, + { + caseCaptionExtension, + caseTitle, + docketNumberWithSuffix, + filers, + petitioners, + }, + bogusUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -65,6 +72,7 @@ describe('generateEntryOfAppearancePdfInteractor', () => { filers, petitioners, }, + mockPrivatePractitionerUser, ); expect( @@ -93,7 +101,6 @@ describe('generateEntryOfAppearancePdfInteractor', () => { }); it('should use Respondent as the filer name when an IRS practitioner is filing an entry of appearance', async () => { - applicationContext.getCurrentUser.mockReturnValueOnce(irsPractitionerUser); applicationContext .getPersistenceGateway() .getUserById.mockReturnValueOnce(irsPractitionerUser); @@ -108,6 +115,7 @@ describe('generateEntryOfAppearancePdfInteractor', () => { filers, petitioners, }, + mockIrsPractitionerUser, ); expect( diff --git a/web-api/src/business/useCases/caseAssociationRequest/generateEntryOfAppearancePdfInteractor.ts b/web-api/src/business/useCases/caseAssociationRequest/generateEntryOfAppearancePdfInteractor.ts index b9eec024c21..6cfb3955b5a 100644 --- a/web-api/src/business/useCases/caseAssociationRequest/generateEntryOfAppearancePdfInteractor.ts +++ b/web-api/src/business/useCases/caseAssociationRequest/generateEntryOfAppearancePdfInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export type EntryOfAppearanceProps = { caseCaptionExtension: string; @@ -26,10 +27,11 @@ export const generateEntryOfAppearancePdfInteractor = async ( filers, petitioners, }: EntryOfAppearanceProps, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.ASSOCIATE_SELF_WITH_CASE)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.ASSOCIATE_SELF_WITH_CASE) + ) { throw new UnauthorizedError('Unauthorized'); } @@ -37,11 +39,11 @@ export const generateEntryOfAppearancePdfInteractor = async ( .getPersistenceGateway() .getUserById({ applicationContext, - userId: user.userId, + userId: authorizedUser.userId, }); const filerNames: string[] = - user.role === ROLES.irsPractitioner + authorizedUser.role === ROLES.irsPractitioner ? ['Respondent'] : (filers .map(filerId => { diff --git a/web-api/src/business/useCases/caseAssociationRequest/submitCaseAssociationRequestInteractor.test.ts b/web-api/src/business/useCases/caseAssociationRequest/submitCaseAssociationRequestInteractor.test.ts index 8a43360f2da..87135f1a9f1 100644 --- a/web-api/src/business/useCases/caseAssociationRequest/submitCaseAssociationRequestInteractor.test.ts +++ b/web-api/src/business/useCases/caseAssociationRequest/submitCaseAssociationRequestInteractor.test.ts @@ -5,17 +5,19 @@ import { import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getContactPrimary } from '../../../../../shared/src/business/entities/cases/Case'; +import { + mockAdcUser, + mockIrsPractitionerUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; import { submitCaseAssociationRequestInteractor } from './submitCaseAssociationRequestInteractor'; describe('submitCaseAssociationRequest', () => { const mockContactId = getContactPrimary(MOCK_CASE).contactId; - let mockCurrentUser; let mockGetUserById; beforeAll(() => { - applicationContext.getCurrentUser.mockImplementation(() => mockCurrentUser); - applicationContext .getPersistenceGateway() .getUserById.mockImplementation(() => mockGetUserById); @@ -26,27 +28,19 @@ describe('submitCaseAssociationRequest', () => { }); it('should throw an error when not authorized', async () => { - mockCurrentUser = { - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.adc, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; - await expect( - submitCaseAssociationRequestInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - filers: [], - }), + submitCaseAssociationRequestInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + filers: [], + }, + mockAdcUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should not add mapping if already there', async () => { - mockCurrentUser = { - barNumber: 'BN1234', - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.privatePractitioner, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; mockGetUserById = { barNumber: 'BN1234', contact: { @@ -59,18 +53,22 @@ describe('submitCaseAssociationRequest', () => { postalCode: '61234', state: 'IL', }, - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', + name: mockPrivatePractitionerUser.name, role: ROLES.privatePractitioner, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + userId: mockPrivatePractitionerUser.userId, }; applicationContext .getPersistenceGateway() .verifyCaseForUser.mockReturnValue(true); - await submitCaseAssociationRequestInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - filers: [], - }); + await submitCaseAssociationRequestInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + filers: [], + }, + mockPrivatePractitionerUser, + ); expect( applicationContext.getUseCaseHelpers().updateCaseAndAssociations, @@ -78,30 +76,18 @@ describe('submitCaseAssociationRequest', () => { }); it('should add mapping for a practitioner', async () => { - mockCurrentUser = { - barNumber: 'BN1234', - contact: { - address1: '234 Main St', - address2: 'Apartment 4', - address3: 'Under the stairs', - city: 'Chicago', - countryType: COUNTRY_TYPES.DOMESTIC, - phone: '+1 (555) 555-5555', - postalCode: '61234', - state: 'IL', - }, - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.privatePractitioner, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; applicationContext .getPersistenceGateway() .verifyCaseForUser.mockReturnValue(false); - await submitCaseAssociationRequestInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - filers: [mockContactId], - }); + await submitCaseAssociationRequestInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + filers: [mockContactId], + }, + mockPrivatePractitionerUser, + ); expect( applicationContext.getUseCaseHelpers().associatePrivatePractitionerToCase, @@ -109,12 +95,6 @@ describe('submitCaseAssociationRequest', () => { }); it('should add mapping for an irsPractitioner', async () => { - mockCurrentUser = { - barNumber: 'BN1234', - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.irsPractitioner, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; mockGetUserById = { barNumber: 'BN1234', contact: { @@ -127,18 +107,22 @@ describe('submitCaseAssociationRequest', () => { postalCode: '61234', state: 'IL', }, - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', + name: mockIrsPractitionerUser.name, role: ROLES.irsPractitioner, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + userId: mockIrsPractitionerUser, }; applicationContext .getPersistenceGateway() .verifyCaseForUser.mockReturnValue(false); - await submitCaseAssociationRequestInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - filers: ['c54ba5a9-b37b-479d-9201-067ec6e335bb'], - }); + await submitCaseAssociationRequestInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + filers: ['c54ba5a9-b37b-479d-9201-067ec6e335bb'], + }, + mockIrsPractitionerUser, + ); expect( applicationContext.getUseCaseHelpers().associateIrsPractitionerToCase, diff --git a/web-api/src/business/useCases/caseAssociationRequest/submitCaseAssociationRequestInteractor.ts b/web-api/src/business/useCases/caseAssociationRequest/submitCaseAssociationRequestInteractor.ts index c60af66be6a..874b2cbf4fd 100644 --- a/web-api/src/business/useCases/caseAssociationRequest/submitCaseAssociationRequestInteractor.ts +++ b/web-api/src/business/useCases/caseAssociationRequest/submitCaseAssociationRequestInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -25,9 +26,8 @@ const submitCaseAssociationRequest = async ( docketNumber: string; filers: string[]; }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if ( !isAuthorized(authorizedUser, ROLE_PERMISSIONS.ASSOCIATE_SELF_WITH_CASE) ) { @@ -47,6 +47,7 @@ const submitCaseAssociationRequest = async ( .getUseCaseHelpers() .associatePrivatePractitionerToCase({ applicationContext, + authorizedUser, docketNumber, representing: filers, user, @@ -56,6 +57,7 @@ const submitCaseAssociationRequest = async ( .getUseCaseHelpers() .associateIrsPractitionerToCase({ applicationContext, + authorizedUser, docketNumber, user, }); diff --git a/web-api/src/business/useCases/caseAssociationRequest/submitPendingCaseAssociationRequestInteractor.test.ts b/web-api/src/business/useCases/caseAssociationRequest/submitPendingCaseAssociationRequestInteractor.test.ts index 60234aaa8b8..09d144ef9c2 100644 --- a/web-api/src/business/useCases/caseAssociationRequest/submitPendingCaseAssociationRequestInteractor.test.ts +++ b/web-api/src/business/useCases/caseAssociationRequest/submitPendingCaseAssociationRequestInteractor.test.ts @@ -1,5 +1,8 @@ -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockAdcUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; import { submitPendingCaseAssociationRequestInteractor } from './submitPendingCaseAssociationRequestInteractor'; describe('submitPendingCaseAssociationRequest', () => { @@ -8,37 +11,32 @@ describe('submitPendingCaseAssociationRequest', () => { }; it('should throw an error when not authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.adc, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); - await expect( - submitPendingCaseAssociationRequestInteractor(applicationContext, { - docketNumber: caseRecord.docketNumber, - }), + submitPendingCaseAssociationRequestInteractor( + applicationContext, + { + docketNumber: caseRecord.docketNumber, + }, + mockAdcUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should not add mapping if already associated', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.privatePractitioner, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); - applicationContext.getPersistenceGateway().getUserById.mockReturnValue({ - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.privatePractitioner, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + applicationContext + .getPersistenceGateway() + .getUserById.mockReturnValue(mockPrivatePractitionerUser); applicationContext .getPersistenceGateway() .verifyCaseForUser.mockReturnValue(true); - await submitPendingCaseAssociationRequestInteractor(applicationContext, { - docketNumber: caseRecord.docketNumber, - }); + await submitPendingCaseAssociationRequestInteractor( + applicationContext, + { + docketNumber: caseRecord.docketNumber, + }, + mockPrivatePractitionerUser, + ); expect( applicationContext.getPersistenceGateway().associateUserWithCasePending, @@ -46,9 +44,13 @@ describe('submitPendingCaseAssociationRequest', () => { }); it('should not add mapping if these is already a pending association', async () => { - await submitPendingCaseAssociationRequestInteractor(applicationContext, { - docketNumber: caseRecord.docketNumber, - }); + await submitPendingCaseAssociationRequestInteractor( + applicationContext, + { + docketNumber: caseRecord.docketNumber, + }, + mockPrivatePractitionerUser, + ); expect( applicationContext.getPersistenceGateway().associateUserWithCasePending, @@ -63,9 +65,13 @@ describe('submitPendingCaseAssociationRequest', () => { .getPersistenceGateway() .verifyPendingCaseForUser.mockReturnValue(false); - await submitPendingCaseAssociationRequestInteractor(applicationContext, { - docketNumber: caseRecord.docketNumber, - }); + await submitPendingCaseAssociationRequestInteractor( + applicationContext, + { + docketNumber: caseRecord.docketNumber, + }, + mockPrivatePractitionerUser, + ); expect( applicationContext.getPersistenceGateway().associateUserWithCasePending, diff --git a/web-api/src/business/useCases/caseAssociationRequest/submitPendingCaseAssociationRequestInteractor.ts b/web-api/src/business/useCases/caseAssociationRequest/submitPendingCaseAssociationRequestInteractor.ts index b47ebb934b3..377ed4dbd74 100644 --- a/web-api/src/business/useCases/caseAssociationRequest/submitPendingCaseAssociationRequestInteractor.ts +++ b/web-api/src/business/useCases/caseAssociationRequest/submitPendingCaseAssociationRequestInteractor.ts @@ -4,6 +4,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * submitPendingCaseAssociationRequestInteractor @@ -16,9 +17,8 @@ import { UnauthorizedError } from '@web-api/errors/errors'; export const submitPendingCaseAssociationRequestInteractor = async ( applicationContext: ServerApplicationContext, { docketNumber }: { docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if ( !isAuthorized(authorizedUser, ROLE_PERMISSIONS.ASSOCIATE_SELF_WITH_CASE) ) { diff --git a/web-api/src/business/useCases/caseConsolidation/addConsolidatedCaseInteractor.test.ts b/web-api/src/business/useCases/caseConsolidation/addConsolidatedCaseInteractor.test.ts index 11b0d335217..0679b9e788e 100644 --- a/web-api/src/business/useCases/caseConsolidation/addConsolidatedCaseInteractor.test.ts +++ b/web-api/src/business/useCases/caseConsolidation/addConsolidatedCaseInteractor.test.ts @@ -1,9 +1,12 @@ import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { addConsolidatedCaseInteractor } from './addConsolidatedCaseInteractor'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; let mockCases; let mockLock; @@ -59,9 +62,6 @@ describe('addConsolidatedCaseInteractor', () => { }, }; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - }); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockImplementation(({ docketNumber }) => { @@ -80,15 +80,15 @@ describe('addConsolidatedCaseInteractor', () => { }); it('Should return an Unauthorized error if the user does not have the CONSOLIDATE_CASES permission', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - }); - await expect( - addConsolidatedCaseInteractor(applicationContext, { - docketNumber: '519-19', - docketNumberToConsolidateWith: '319-19', - }), + addConsolidatedCaseInteractor( + applicationContext, + { + docketNumber: '519-19', + docketNumberToConsolidateWith: '319-19', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized for case consolidation'); }); @@ -96,10 +96,14 @@ describe('addConsolidatedCaseInteractor', () => { mockLock = MOCK_LOCK; await expect( - addConsolidatedCaseInteractor(applicationContext, { - docketNumber: '519-19', - docketNumberToConsolidateWith: '319-19', - }), + addConsolidatedCaseInteractor( + applicationContext, + { + docketNumber: '519-19', + docketNumberToConsolidateWith: '319-19', + }, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -108,10 +112,14 @@ describe('addConsolidatedCaseInteractor', () => { }); it('should acquire and remove the lock on the cases', async () => { - await addConsolidatedCaseInteractor(applicationContext, { - docketNumber: '519-19', - docketNumberToConsolidateWith: '319-19', - }); + await addConsolidatedCaseInteractor( + applicationContext, + { + docketNumber: '519-19', + docketNumberToConsolidateWith: '319-19', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -126,10 +134,14 @@ describe('addConsolidatedCaseInteractor', () => { }); it('Should try to get the case by its docketNumber', async () => { - await addConsolidatedCaseInteractor(applicationContext, { - docketNumber: '519-19', - docketNumberToConsolidateWith: '319-19', - }); + await addConsolidatedCaseInteractor( + applicationContext, + { + docketNumber: '519-19', + docketNumberToConsolidateWith: '319-19', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -138,27 +150,39 @@ describe('addConsolidatedCaseInteractor', () => { it('Should return a Not Found error if the case to update can not be found', async () => { await expect( - addConsolidatedCaseInteractor(applicationContext, { - docketNumber: '111-11', - docketNumberToConsolidateWith: '319-19', - }), + addConsolidatedCaseInteractor( + applicationContext, + { + docketNumber: '111-11', + docketNumberToConsolidateWith: '319-19', + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Case 111-11 was not found.'); }); it('Should return a Not Found error if the case to consolidate with cannot be found', async () => { await expect( - addConsolidatedCaseInteractor(applicationContext, { - docketNumber: '519-19', - docketNumberToConsolidateWith: '111-11', - }), + addConsolidatedCaseInteractor( + applicationContext, + { + docketNumber: '519-19', + docketNumberToConsolidateWith: '111-11', + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Case to consolidate with (111-11) was not found.'); }); it('Should update the case to consolidate with if it does not already have the leadDocketNumber', async () => { - await addConsolidatedCaseInteractor(applicationContext, { - docketNumber: '519-19', - docketNumberToConsolidateWith: '320-19', - }); + await addConsolidatedCaseInteractor( + applicationContext, + { + docketNumber: '519-19', + docketNumberToConsolidateWith: '320-19', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls.length, @@ -166,10 +190,14 @@ describe('addConsolidatedCaseInteractor', () => { }); it('Should NOT update the case to consolidate with if it already has the leadDocketNumber and is the lead case', async () => { - await addConsolidatedCaseInteractor(applicationContext, { - docketNumber: '519-19', - docketNumberToConsolidateWith: '319-19', - }); + await addConsolidatedCaseInteractor( + applicationContext, + { + docketNumber: '519-19', + docketNumberToConsolidateWith: '319-19', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls.length, @@ -177,10 +205,14 @@ describe('addConsolidatedCaseInteractor', () => { }); it('Should update both cases with the leadDocketNumber if neither have one', async () => { - await addConsolidatedCaseInteractor(applicationContext, { - docketNumber: '519-19', - docketNumberToConsolidateWith: '319-19', - }); + await addConsolidatedCaseInteractor( + applicationContext, + { + docketNumber: '519-19', + docketNumberToConsolidateWith: '319-19', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -192,10 +224,14 @@ describe('addConsolidatedCaseInteractor', () => { }); it('Should update all leadDocketNumber fields if the new case has the lower docket number', async () => { - await addConsolidatedCaseInteractor(applicationContext, { - docketNumber: '219-19', - docketNumberToConsolidateWith: '319-19', - }); + await addConsolidatedCaseInteractor( + applicationContext, + { + docketNumber: '219-19', + docketNumberToConsolidateWith: '319-19', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls.length, @@ -207,10 +243,14 @@ describe('addConsolidatedCaseInteractor', () => { }); it('Should combine all cases when both the case and case to consolidate with are in separate consolidated sets', async () => { - await addConsolidatedCaseInteractor(applicationContext, { - docketNumber: '119-19', - docketNumberToConsolidateWith: '419-19', - }); + await addConsolidatedCaseInteractor( + applicationContext, + { + docketNumber: '119-19', + docketNumberToConsolidateWith: '419-19', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls.length, diff --git a/web-api/src/business/useCases/caseConsolidation/addConsolidatedCaseInteractor.ts b/web-api/src/business/useCases/caseConsolidation/addConsolidatedCaseInteractor.ts index 4fc650f4e33..1e8935e68ee 100644 --- a/web-api/src/business/useCases/caseConsolidation/addConsolidatedCaseInteractor.ts +++ b/web-api/src/business/useCases/caseConsolidation/addConsolidatedCaseInteractor.ts @@ -5,6 +5,7 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -22,10 +23,9 @@ export const addConsolidatedCase = async ( docketNumber, docketNumberToConsolidateWith, }: { docketNumber: string; docketNumberToConsolidateWith: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.CONSOLIDATE_CASES)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CONSOLIDATE_CASES)) { throw new UnauthorizedError('Unauthorized for case consolidation'); } @@ -86,12 +86,15 @@ export const addConsolidatedCase = async ( const updateCasePromises: Promise[] = []; casesToUpdate.forEach(caseInCasesToUpdate => { - const caseEntity = new Case(caseInCasesToUpdate, { applicationContext }); + const caseEntity = new Case(caseInCasesToUpdate, { + authorizedUser, + }); caseEntity.setLeadCase(newLeadCase.docketNumber); updateCasePromises.push( applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }), ); diff --git a/web-api/src/business/useCases/caseConsolidation/removeConsolidatedCasesInteractor.test.ts b/web-api/src/business/useCases/caseConsolidation/removeConsolidatedCasesInteractor.test.ts index 1d862394c2f..b7e200db419 100644 --- a/web-api/src/business/useCases/caseConsolidation/removeConsolidatedCasesInteractor.test.ts +++ b/web-api/src/business/useCases/caseConsolidation/removeConsolidatedCasesInteractor.test.ts @@ -1,8 +1,11 @@ import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { removeConsolidatedCasesInteractor } from './removeConsolidatedCasesInteractor'; let mockCases; @@ -51,9 +54,6 @@ describe('removeConsolidatedCasesInteractor', () => { }, }; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - }); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockImplementation(({ docketNumber }) => { @@ -72,23 +72,27 @@ describe('removeConsolidatedCasesInteractor', () => { }); it('Should return an Unauthorized error if the user does not have the CONSOLIDATE_CASES permission', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - }); - await expect( - removeConsolidatedCasesInteractor(applicationContext, { - docketNumber: '102-19', - docketNumbersToRemove: ['101-19'], - }), + removeConsolidatedCasesInteractor( + applicationContext, + { + docketNumber: '102-19', + docketNumbersToRemove: ['101-19'], + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized for case consolidation'); }); it('Should try to get the case by its docketNumber', async () => { - await removeConsolidatedCasesInteractor(applicationContext, { - docketNumber: '102-19', - docketNumbersToRemove: ['101-19'], - }); + await removeConsolidatedCasesInteractor( + applicationContext, + { + docketNumber: '102-19', + docketNumbersToRemove: ['101-19'], + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -97,27 +101,39 @@ describe('removeConsolidatedCasesInteractor', () => { it('Should return a Not Found error if the case to update can not be found', async () => { await expect( - removeConsolidatedCasesInteractor(applicationContext, { - docketNumber: '111-11', - docketNumbersToRemove: ['101-19'], - }), + removeConsolidatedCasesInteractor( + applicationContext, + { + docketNumber: '111-11', + docketNumbersToRemove: ['101-19'], + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Case 111-11 was not found.'); }); it('Should return a Not Found error if the case to remove cannot be found', async () => { await expect( - removeConsolidatedCasesInteractor(applicationContext, { - docketNumber: '102-19', - docketNumbersToRemove: ['111-11'], - }), + removeConsolidatedCasesInteractor( + applicationContext, + { + docketNumber: '102-19', + docketNumbersToRemove: ['111-11'], + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Case to consolidate with (111-11) was not found.'); }); it('Should only update the removed case if the case to remove is not the lead case', async () => { - await removeConsolidatedCasesInteractor(applicationContext, { - docketNumber: '101-19', - docketNumbersToRemove: ['102-19'], - }); + await removeConsolidatedCasesInteractor( + applicationContext, + { + docketNumber: '101-19', + docketNumbersToRemove: ['102-19'], + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls.length, @@ -132,10 +148,14 @@ describe('removeConsolidatedCasesInteractor', () => { }); it('Should update the removed case and all other currently consolidated cases if the case to remove is the lead case', async () => { - await removeConsolidatedCasesInteractor(applicationContext, { - docketNumber: '102-19', - docketNumbersToRemove: ['101-19'], - }); + await removeConsolidatedCasesInteractor( + applicationContext, + { + docketNumber: '102-19', + docketNumbersToRemove: ['101-19'], + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls.length, @@ -167,10 +187,14 @@ describe('removeConsolidatedCasesInteractor', () => { it('Should update all cases to remove consolidation if new consolidated cases length is 0', async () => { const docketNumbersToRemove = allDocketNumbers; - await removeConsolidatedCasesInteractor(applicationContext, { - docketNumber: '101-19', - docketNumbersToRemove, - }); + await removeConsolidatedCasesInteractor( + applicationContext, + { + docketNumber: '101-19', + docketNumbersToRemove, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().updateCaseAndAssociations, ).toHaveBeenCalledTimes(docketNumbersToRemove.length); @@ -184,10 +208,14 @@ describe('removeConsolidatedCasesInteractor', () => { '104-19', '105-19', ]; - await removeConsolidatedCasesInteractor(applicationContext, { - docketNumber: '101-19', - docketNumbersToRemove, - }); + await removeConsolidatedCasesInteractor( + applicationContext, + { + docketNumber: '101-19', + docketNumbersToRemove, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().updateCaseAndAssociations, @@ -202,10 +230,14 @@ describe('removeConsolidatedCasesInteractor', () => { }); it('Should update the removed case and remove consolidation from the original lead case if there is only one case remaining after removal', async () => { - await removeConsolidatedCasesInteractor(applicationContext, { - docketNumber: '104-19', - docketNumbersToRemove: ['105-19'], - }); + await removeConsolidatedCasesInteractor( + applicationContext, + { + docketNumber: '104-19', + docketNumbersToRemove: ['105-19'], + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls.length, @@ -229,10 +261,14 @@ describe('removeConsolidatedCasesInteractor', () => { }); it('Should update the removed case and remove consolidation from the original non-lead case if there is only one case remaining after removal', async () => { - await removeConsolidatedCasesInteractor(applicationContext, { - docketNumber: '105-19', - docketNumbersToRemove: ['104-19'], - }); + await removeConsolidatedCasesInteractor( + applicationContext, + { + docketNumber: '105-19', + docketNumbersToRemove: ['104-19'], + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls.length, @@ -259,10 +295,14 @@ describe('removeConsolidatedCasesInteractor', () => { mockLock = MOCK_LOCK; await expect( - removeConsolidatedCasesInteractor(applicationContext, { - docketNumber: '105-19', - docketNumbersToRemove: ['104-19'], - }), + removeConsolidatedCasesInteractor( + applicationContext, + { + docketNumber: '105-19', + docketNumbersToRemove: ['104-19'], + }, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -271,10 +311,14 @@ describe('removeConsolidatedCasesInteractor', () => { }); it('should acquire and remove the lock on the cases', async () => { - await removeConsolidatedCasesInteractor(applicationContext, { - docketNumber: '105-19', - docketNumbersToRemove: ['104-19'], - }); + await removeConsolidatedCasesInteractor( + applicationContext, + { + docketNumber: '105-19', + docketNumbersToRemove: ['104-19'], + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/caseConsolidation/removeConsolidatedCasesInteractor.ts b/web-api/src/business/useCases/caseConsolidation/removeConsolidatedCasesInteractor.ts index 2079135d7bf..cf5e2314419 100644 --- a/web-api/src/business/useCases/caseConsolidation/removeConsolidatedCasesInteractor.ts +++ b/web-api/src/business/useCases/caseConsolidation/removeConsolidatedCasesInteractor.ts @@ -5,6 +5,7 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -22,10 +23,9 @@ export const removeConsolidatedCases = async ( docketNumber, docketNumbersToRemove, }: { docketNumber: string; docketNumbersToRemove: string[] }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.CONSOLIDATE_CASES)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CONSOLIDATE_CASES)) { throw new UnauthorizedError('Unauthorized for case consolidation'); } @@ -33,7 +33,7 @@ export const removeConsolidatedCases = async ( .getPersistenceGateway() .getCaseByDocketNumber({ applicationContext, docketNumber }); - if (!caseToUpdate) { + if (!caseToUpdate || !caseToUpdate?.leadDocketNumber) { throw new NotFoundError(`Case ${docketNumber} was not found.`); } @@ -61,13 +61,14 @@ export const removeConsolidatedCases = async ( for (let newConsolidatedCaseToUpdate of newConsolidatedCases) { const caseEntity = new Case(newConsolidatedCaseToUpdate, { - applicationContext, + authorizedUser, }); caseEntity.setLeadCase(newLeadCase.docketNumber); updateCasePromises.push( applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }), ); @@ -75,13 +76,14 @@ export const removeConsolidatedCases = async ( } else if (newConsolidatedCases.length == 1) { // a case cannot be consolidated with itself const caseEntity = new Case(newConsolidatedCases[0], { - applicationContext, + authorizedUser, }); caseEntity.removeConsolidation(); updateCasePromises.push( applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }), ); @@ -101,12 +103,13 @@ export const removeConsolidatedCases = async ( ); } - const caseEntity = new Case(caseToRemove, { applicationContext }); + const caseEntity = new Case(caseToRemove, { authorizedUser }); caseEntity.removeConsolidation(); updateCasePromises.push( applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }), ); diff --git a/web-api/src/business/useCases/caseDeadline/createCaseDeadlineInteractor.test.ts b/web-api/src/business/useCases/caseDeadline/createCaseDeadlineInteractor.test.ts index cd8356f69e5..5d33e245a78 100644 --- a/web-api/src/business/useCases/caseDeadline/createCaseDeadlineInteractor.test.ts +++ b/web-api/src/business/useCases/caseDeadline/createCaseDeadlineInteractor.test.ts @@ -1,7 +1,6 @@ import { AUTOMATIC_BLOCKED_REASONS, CHIEF_JUDGE, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE, @@ -12,9 +11,10 @@ import { ServiceUnavailableError, UnauthorizedError, } from '@web-api/errors/errors'; -import { User } from '../../../../../shared/src/business/entities/User'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { createCaseDeadlineInteractor } from './createCaseDeadlineInteractor'; +import { mockPetitionsClerkUser } from '@shared/test/mockAuthUsers'; describe('createCaseDeadlineInteractor', () => { const mockCaseDeadline = { @@ -22,7 +22,6 @@ describe('createCaseDeadlineInteractor', () => { description: 'hello world', docketNumber: MOCK_CASE.docketNumber, }; - let user; let mockCase; let mockLock; beforeAll(() => { @@ -34,14 +33,7 @@ describe('createCaseDeadlineInteractor', () => { beforeEach(() => { mockLock = undefined; - user = new User({ - name: 'Test Petitionsclerk', - role: ROLES.petitionsClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - applicationContext.environment.stage = 'local'; - applicationContext.getCurrentUser.mockImplementation(() => user); applicationContext .getPersistenceGateway() @@ -57,11 +49,15 @@ describe('createCaseDeadlineInteractor', () => { }); it('throws an error if the user is not valid or authorized', async () => { - user = {}; + let user = {} as UnknownAuthUser; await expect( - createCaseDeadlineInteractor(applicationContext, { - caseDeadline: mockCaseDeadline as any, - }), + createCaseDeadlineInteractor( + applicationContext, + { + caseDeadline: mockCaseDeadline as any, + }, + user, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -71,6 +67,7 @@ describe('createCaseDeadlineInteractor', () => { const caseDeadline = await createCaseDeadlineInteractor( applicationContext, { caseDeadline: mockCaseDeadline as any }, + mockPetitionsClerkUser, ); expect(caseDeadline).toBeDefined(); @@ -101,6 +98,7 @@ describe('createCaseDeadlineInteractor', () => { const caseDeadline = await createCaseDeadlineInteractor( applicationContext, { caseDeadline: mockCaseDeadline as any }, + mockPetitionsClerkUser, ); expect(caseDeadline).toBeDefined(); @@ -133,9 +131,13 @@ describe('createCaseDeadlineInteractor', () => { mockLock = MOCK_LOCK; await expect( - createCaseDeadlineInteractor(applicationContext, { - caseDeadline: mockCaseDeadline as any, - }), + createCaseDeadlineInteractor( + applicationContext, + { + caseDeadline: mockCaseDeadline as any, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -147,9 +149,13 @@ describe('createCaseDeadlineInteractor', () => { mockCase = MOCK_CASE; mockCase.associatedJudge = 'Judge Buch'; mockCase.associatedJudgeId = 'dabbad02-18d0-43ec-bafb-654e83405416'; - await createCaseDeadlineInteractor(applicationContext, { - caseDeadline: mockCaseDeadline as any, - }); + await createCaseDeadlineInteractor( + applicationContext, + { + caseDeadline: mockCaseDeadline as any, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/caseDeadline/createCaseDeadlineInteractor.ts b/web-api/src/business/useCases/caseDeadline/createCaseDeadlineInteractor.ts index df116ae6fa4..9e040f51c51 100644 --- a/web-api/src/business/useCases/caseDeadline/createCaseDeadlineInteractor.ts +++ b/web-api/src/business/useCases/caseDeadline/createCaseDeadlineInteractor.ts @@ -6,15 +6,15 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; export const createCaseDeadline = async ( applicationContext: ServerApplicationContext, { caseDeadline }: { caseDeadline: CaseDeadline }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.CASE_DEADLINE)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CASE_DEADLINE)) { throw new UnauthorizedError('Unauthorized for create case deadline'); } @@ -24,7 +24,7 @@ export const createCaseDeadline = async ( applicationContext, docketNumber: caseDeadline.docketNumber, }); - let caseEntity = new Case(caseDetail, { applicationContext }); + let caseEntity = new Case(caseDetail, { authorizedUser }); const newCaseDeadline = new CaseDeadline( { @@ -51,6 +51,7 @@ export const createCaseDeadline = async ( await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); diff --git a/web-api/src/business/useCases/caseDeadline/deleteCaseDeadlineInteractor.test.ts b/web-api/src/business/useCases/caseDeadline/deleteCaseDeadlineInteractor.test.ts index 36fcea717f8..526fe875438 100644 --- a/web-api/src/business/useCases/caseDeadline/deleteCaseDeadlineInteractor.test.ts +++ b/web-api/src/business/useCases/caseDeadline/deleteCaseDeadlineInteractor.test.ts @@ -1,16 +1,13 @@ -import { - AUTOMATIC_BLOCKED_REASONS, - ROLES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { AUTOMATIC_BLOCKED_REASONS } from '../../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE_WITHOUT_PENDING } from '../../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; import { ServiceUnavailableError, UnauthorizedError, } from '@web-api/errors/errors'; -import { User } from '../../../../../shared/src/business/entities/User'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { deleteCaseDeadlineInteractor } from './deleteCaseDeadlineInteractor'; +import { mockPetitionsClerkUser } from '@shared/test/mockAuthUsers'; describe('deleteCaseDeadlineInteractor', () => { let user; @@ -34,23 +31,21 @@ describe('deleteCaseDeadlineInteractor', () => { }); beforeEach(() => { - user = new User({ - name: 'Test Petitionsclerk', - role: ROLES.petitionsClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); mockLock = undefined; - applicationContext.getCurrentUser.mockImplementation(() => user); }); it('should throw a ServiceUnavailableError if the Case is currently locked', async () => { mockLock = MOCK_LOCK; await expect( - deleteCaseDeadlineInteractor(applicationContext, { - caseDeadlineId: '6805d1ab-18d0-43ec-bafb-654e83405416', - docketNumber: MOCK_CASE_WITHOUT_PENDING.docketNumber, - }), + deleteCaseDeadlineInteractor( + applicationContext, + { + caseDeadlineId: '6805d1ab-18d0-43ec-bafb-654e83405416', + docketNumber: MOCK_CASE_WITHOUT_PENDING.docketNumber, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -59,10 +54,14 @@ describe('deleteCaseDeadlineInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await deleteCaseDeadlineInteractor(applicationContext, { - caseDeadlineId: '6805d1ab-18d0-43ec-bafb-654e83405416', - docketNumber: MOCK_CASE_WITHOUT_PENDING.docketNumber, - }); + await deleteCaseDeadlineInteractor( + applicationContext, + { + caseDeadlineId: '6805d1ab-18d0-43ec-bafb-654e83405416', + docketNumber: MOCK_CASE_WITHOUT_PENDING.docketNumber, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -83,20 +82,28 @@ describe('deleteCaseDeadlineInteractor', () => { it('throws an error if the user is not valid or authorized', async () => { user = {}; await expect( - deleteCaseDeadlineInteractor(applicationContext, { - caseDeadlineId: '6805d1ab-18d0-43ec-bafb-654e83405416', - docketNumber: '123-20', - }), + deleteCaseDeadlineInteractor( + applicationContext, + { + caseDeadlineId: '6805d1ab-18d0-43ec-bafb-654e83405416', + docketNumber: '123-20', + }, + user, + ), ).rejects.toThrow(UnauthorizedError); }); it('calls persistence to delete a case deadline and sets the case as no longer automatically blocked if there are no more deadlines', async () => { mockDeadlines = []; - await deleteCaseDeadlineInteractor(applicationContext, { - caseDeadlineId: '6805d1ab-18d0-43ec-bafb-654e83405416', - docketNumber: '123-20', - }); + await deleteCaseDeadlineInteractor( + applicationContext, + { + caseDeadlineId: '6805d1ab-18d0-43ec-bafb-654e83405416', + docketNumber: '123-20', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().deleteCaseDeadline.mock @@ -122,10 +129,14 @@ describe('deleteCaseDeadlineInteractor', () => { it('calls persistence to delete a case deadline and leaves the case automatically blocked if there are more deadlines', async () => { mockDeadlines = [{ deadline: 'something' }]; - await deleteCaseDeadlineInteractor(applicationContext, { - caseDeadlineId: '6805d1ab-18d0-43ec-bafb-654e83405416', - docketNumber: '123-20', - }); + await deleteCaseDeadlineInteractor( + applicationContext, + { + caseDeadlineId: '6805d1ab-18d0-43ec-bafb-654e83405416', + docketNumber: '123-20', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().deleteCaseDeadline.mock diff --git a/web-api/src/business/useCases/caseDeadline/deleteCaseDeadlineInteractor.ts b/web-api/src/business/useCases/caseDeadline/deleteCaseDeadlineInteractor.ts index 396fe93da7b..e950c02150a 100644 --- a/web-api/src/business/useCases/caseDeadline/deleteCaseDeadlineInteractor.ts +++ b/web-api/src/business/useCases/caseDeadline/deleteCaseDeadlineInteractor.ts @@ -5,27 +5,18 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; -/** - * deleteCaseDeadline - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {string} providers.caseDeadlineId the id of the case deadline to delete - * @param {string} providers.docketNumber the docket number of the case the case deadline is attached to - * @returns {Promise} the promise of the delete call - */ export const deleteCaseDeadline = async ( applicationContext: ServerApplicationContext, { caseDeadlineId, docketNumber, }: { caseDeadlineId: string; docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.CASE_DEADLINE)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CASE_DEADLINE)) { throw new UnauthorizedError('Unauthorized for deleting case deadline'); } @@ -33,7 +24,7 @@ export const deleteCaseDeadline = async ( .getPersistenceGateway() .getCaseByDocketNumber({ applicationContext, docketNumber }); - let updatedCase = new Case(caseToUpdate, { applicationContext }); + let updatedCase = new Case(caseToUpdate, { authorizedUser }); await applicationContext.getPersistenceGateway().deleteCaseDeadline({ applicationContext, @@ -52,9 +43,10 @@ export const deleteCaseDeadline = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: updatedCase, }); - return new Case(result, { applicationContext }).validate().toRawObject(); + return new Case(result, { authorizedUser }).validate().toRawObject(); }; export const deleteCaseDeadlineInteractor = withLocking( diff --git a/web-api/src/business/useCases/caseDeadline/getCaseDeadlinesForCaseInteractor.test.ts b/web-api/src/business/useCases/caseDeadline/getCaseDeadlinesForCaseInteractor.test.ts index ff9946cf065..25e68fa89b9 100644 --- a/web-api/src/business/useCases/caseDeadline/getCaseDeadlinesForCaseInteractor.test.ts +++ b/web-api/src/business/useCases/caseDeadline/getCaseDeadlinesForCaseInteractor.test.ts @@ -1,5 +1,3 @@ -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; -import { User } from '../../../../../shared/src/business/entities/User'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getCaseDeadlinesForCaseInteractor } from './getCaseDeadlinesForCaseInteractor'; @@ -12,15 +10,8 @@ describe('getCaseDeadlinesForCaseInteractor', () => { docketNumber: '123-20', }; - const mockUser = new User({ - name: 'Test Petitionsclerk', - role: ROLES.petitionsClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - it('gets the case deadlines', async () => { applicationContext.environment.stage = 'local'; - applicationContext.getCurrentUser.mockReturnValue(mockUser); applicationContext .getPersistenceGateway() diff --git a/web-api/src/business/useCases/caseDeadline/updateCaseDeadlineInteractor.test.ts b/web-api/src/business/useCases/caseDeadline/updateCaseDeadlineInteractor.test.ts index 9d0e2c225f4..1a588295df6 100644 --- a/web-api/src/business/useCases/caseDeadline/updateCaseDeadlineInteractor.test.ts +++ b/web-api/src/business/useCases/caseDeadline/updateCaseDeadlineInteractor.test.ts @@ -1,6 +1,6 @@ -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; -import { User } from '../../../../../shared/src/business/entities/User'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { mockPetitionsClerkUser } from '@shared/test/mockAuthUsers'; import { updateCaseDeadlineInteractor } from './updateCaseDeadlineInteractor'; describe('updateCaseDeadlineInteractor', () => { @@ -16,29 +16,26 @@ describe('updateCaseDeadlineInteractor', () => { } as any; it('throws an error if the user is not valid or authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - updateCaseDeadlineInteractor(applicationContext, { - caseDeadline: mockCaseDeadline, - }), + updateCaseDeadlineInteractor( + applicationContext, + { + caseDeadline: mockCaseDeadline, + }, + {} as UnknownAuthUser, + ), ).rejects.toThrow('Unauthorized'); }); it('updates a case deadline', async () => { - const mockPetitionsClerk = new User({ - name: 'Test Petitionsclerk', - role: ROLES.petitionsClerk, - userId: '65370e00-f608-4118-980c-56b6c0fe8df5', - }); applicationContext.environment.stage = 'local'; - applicationContext.getCurrentUser.mockReturnValue(mockPetitionsClerk); const caseDeadline = await updateCaseDeadlineInteractor( applicationContext, { caseDeadline: mockCaseDeadline, }, + mockPetitionsClerkUser, ); expect( diff --git a/web-api/src/business/useCases/caseDeadline/updateCaseDeadlineInteractor.ts b/web-api/src/business/useCases/caseDeadline/updateCaseDeadlineInteractor.ts index 8ea56e04307..ffc19a64f35 100644 --- a/web-api/src/business/useCases/caseDeadline/updateCaseDeadlineInteractor.ts +++ b/web-api/src/business/useCases/caseDeadline/updateCaseDeadlineInteractor.ts @@ -5,22 +5,14 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; -/** - * updateCaseDeadlineInteractor - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {object} providers.caseDeadline the case deadline data - * @returns {object} the updated case deadline - */ export const updateCaseDeadlineInteractor = async ( applicationContext: ServerApplicationContext, { caseDeadline }: { caseDeadline: CaseDeadline }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.CASE_DEADLINE)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CASE_DEADLINE)) { throw new UnauthorizedError('Unauthorized for updating case deadline'); } diff --git a/web-api/src/business/useCases/caseInventoryReport/generatePrintableCaseInventoryReportInteractor.test.ts b/web-api/src/business/useCases/caseInventoryReport/generatePrintableCaseInventoryReportInteractor.test.ts index e5a9d95add6..4d91778b073 100644 --- a/web-api/src/business/useCases/caseInventoryReport/generatePrintableCaseInventoryReportInteractor.test.ts +++ b/web-api/src/business/useCases/caseInventoryReport/generatePrintableCaseInventoryReportInteractor.test.ts @@ -1,13 +1,12 @@ -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { generatePrintableCaseInventoryReportInteractor } from './generatePrintableCaseInventoryReportInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('generatePrintableCaseInventoryReportInteractor', () => { beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }); applicationContext .getUseCaseHelpers() .generateCaseInventoryReportPdf.mockReturnValue('https://example.com'); @@ -22,6 +21,7 @@ describe('generatePrintableCaseInventoryReportInteractor', () => { { associatedJudge: 'Judge Colvin', }, + mockPetitionsClerkUser, ); expect( @@ -31,26 +31,24 @@ describe('generatePrintableCaseInventoryReportInteractor', () => { }); it('should throw an unauthorized error if the user does not have access', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: 'petitioner', - }); - await expect( - generatePrintableCaseInventoryReportInteractor(applicationContext, { - associatedJudge: 'Judge Colvin', - }), + generatePrintableCaseInventoryReportInteractor( + applicationContext, + { + associatedJudge: 'Judge Colvin', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should throw an error if associatedJudge and status are not passed in', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }); - await expect( - generatePrintableCaseInventoryReportInteractor(applicationContext, {}), + generatePrintableCaseInventoryReportInteractor( + applicationContext, + {}, + mockPetitionsClerkUser, + ), ).rejects.toThrow('Either judge or status must be provided'); }); }); diff --git a/web-api/src/business/useCases/caseInventoryReport/generatePrintableCaseInventoryReportInteractor.ts b/web-api/src/business/useCases/caseInventoryReport/generatePrintableCaseInventoryReportInteractor.ts index 57c6cc03e00..6063adf9a0c 100644 --- a/web-api/src/business/useCases/caseInventoryReport/generatePrintableCaseInventoryReportInteractor.ts +++ b/web-api/src/business/useCases/caseInventoryReport/generatePrintableCaseInventoryReportInteractor.ts @@ -4,13 +4,13 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const generatePrintableCaseInventoryReportInteractor = async ( applicationContext: ServerApplicationContext, { associatedJudge, status }: { associatedJudge?: string; status?: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CASE_INVENTORY_REPORT)) { throw new UnauthorizedError('Unauthorized for case inventory report'); } @@ -37,6 +37,7 @@ export const generatePrintableCaseInventoryReportInteractor = async ( .getUseCaseHelpers() .generateCaseInventoryReportPdf({ applicationContext, + authorizedUser, cases: foundCases, filters: { associatedJudge, status }, }); diff --git a/web-api/src/business/useCases/caseInventoryReport/getCaseInventoryReportInteractor.test.ts b/web-api/src/business/useCases/caseInventoryReport/getCaseInventoryReportInteractor.test.ts index 8229b3adc4c..82ffc7b1a1c 100644 --- a/web-api/src/business/useCases/caseInventoryReport/getCaseInventoryReportInteractor.test.ts +++ b/web-api/src/business/useCases/caseInventoryReport/getCaseInventoryReportInteractor.test.ts @@ -2,35 +2,34 @@ import { CASE_STATUS_TYPES, CHIEF_JUDGE, DOCKET_NUMBER_SUFFIXES, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getCaseInventoryReportInteractor } from './getCaseInventoryReportInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getCaseInventoryReportInteractor', () => { - beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: '9754a349-1013-44fa-9e61-d39aba2637e0', - }); - }); - it('throws an error if user is not authorized for case inventory report', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, //petitioner does not have CASE_INVENTORY_REPORT permission - userId: '8e20dd1b-d142-40f4-8362-6297f1be68bf', - }); - await expect( - getCaseInventoryReportInteractor(applicationContext, { - associatedJudge: CHIEF_JUDGE, - }), + getCaseInventoryReportInteractor( + applicationContext, + { + associatedJudge: CHIEF_JUDGE, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized for case inventory report'); }); it('throws an error if associatedJudge and status are not passed in', async () => { await expect( - getCaseInventoryReportInteractor(applicationContext, {}), + getCaseInventoryReportInteractor( + applicationContext, + {}, + mockDocketClerkUser, + ), ).rejects.toThrow('Either judge or status must be provided'); }); @@ -43,21 +42,25 @@ describe('getCaseInventoryReportInteractor', () => { caseCaption: 'A Test Caption', docketNumber: '123-20', docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.LIEN_LEVY, - status: CASE_STATUS_TYPES.NEW, + status: CASE_STATUS_TYPES.new, }, ]); - const result = await getCaseInventoryReportInteractor(applicationContext, { - associatedJudge: CHIEF_JUDGE, - status: CASE_STATUS_TYPES.NEW, - }); + const result = await getCaseInventoryReportInteractor( + applicationContext, + { + associatedJudge: CHIEF_JUDGE, + status: CASE_STATUS_TYPES.new, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseInventoryReport, ).toHaveBeenCalledWith({ applicationContext: expect.anything(), associatedJudge: CHIEF_JUDGE, - status: CASE_STATUS_TYPES.NEW, + status: CASE_STATUS_TYPES.new, }); expect(result).toEqual([ { @@ -65,7 +68,7 @@ describe('getCaseInventoryReportInteractor', () => { caseCaption: 'A Test Caption', docketNumber: '123-20', docketNumberSuffix: DOCKET_NUMBER_SUFFIXES.LIEN_LEVY, - status: CASE_STATUS_TYPES.NEW, + status: CASE_STATUS_TYPES.new, }, ]); }); diff --git a/web-api/src/business/useCases/caseInventoryReport/getCaseInventoryReportInteractor.ts b/web-api/src/business/useCases/caseInventoryReport/getCaseInventoryReportInteractor.ts index 5c0d993dc0f..8be78f158c3 100644 --- a/web-api/src/business/useCases/caseInventoryReport/getCaseInventoryReportInteractor.ts +++ b/web-api/src/business/useCases/caseInventoryReport/getCaseInventoryReportInteractor.ts @@ -3,6 +3,7 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const getCaseInventoryReportInteractor = async ( applicationContext, { @@ -16,9 +17,8 @@ export const getCaseInventoryReportInteractor = async ( pageSize?: number; status?: string; }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CASE_INVENTORY_REPORT)) { throw new UnauthorizedError('Unauthorized for case inventory report'); } diff --git a/web-api/src/business/useCases/caseNote/deleteCaseNoteInteractor.test.ts b/web-api/src/business/useCases/caseNote/deleteCaseNoteInteractor.test.ts index 4861a8ca4bc..05b7392ee7c 100644 --- a/web-api/src/business/useCases/caseNote/deleteCaseNoteInteractor.test.ts +++ b/web-api/src/business/useCases/caseNote/deleteCaseNoteInteractor.test.ts @@ -1,16 +1,17 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { ServiceUnavailableError, UnauthorizedError, } from '@web-api/errors/errors'; -import { User } from '../../../../../shared/src/business/entities/User'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { deleteCaseNoteInteractor } from './deleteCaseNoteInteractor'; +import { mockJudgeUser } from '@shared/test/mockAuthUsers'; describe('deleteCaseNoteInteractor', () => { let mockLock; + let mockUser: AuthUser; beforeAll(() => { applicationContext @@ -20,22 +21,20 @@ describe('deleteCaseNoteInteractor', () => { beforeEach(() => { mockLock = undefined; - const mockUser = new User({ - name: 'Judge Colvin', - role: ROLES.judge, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - applicationContext.getCurrentUser.mockReturnValue(mockUser); + mockUser = mockJudgeUser; }); it('throws an error if the user is not valid or authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - + mockUser = {} as AuthUser; let error; try { - await deleteCaseNoteInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }); + await deleteCaseNoteInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockUser, + ); } catch (err) { error = err; } @@ -62,9 +61,13 @@ describe('deleteCaseNoteInteractor', () => { let result; try { - result = await deleteCaseNoteInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }); + result = await deleteCaseNoteInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockUser, + ); } catch (e) { error = e; } @@ -84,9 +87,13 @@ describe('deleteCaseNoteInteractor', () => { mockLock = MOCK_LOCK; await expect( - deleteCaseNoteInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }), + deleteCaseNoteInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -95,9 +102,13 @@ describe('deleteCaseNoteInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await deleteCaseNoteInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - }); + await deleteCaseNoteInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + }, + mockUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/caseNote/deleteCaseNoteInteractor.ts b/web-api/src/business/useCases/caseNote/deleteCaseNoteInteractor.ts index b498695e62f..48c7128c62f 100644 --- a/web-api/src/business/useCases/caseNote/deleteCaseNoteInteractor.ts +++ b/web-api/src/business/useCases/caseNote/deleteCaseNoteInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -18,10 +19,9 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; export const deleteCaseNote = async ( applicationContext: ServerApplicationContext, { docketNumber }: { docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.CASE_NOTES)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CASE_NOTES)) { throw new UnauthorizedError('Unauthorized'); } @@ -38,10 +38,11 @@ export const deleteCaseNote = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseRecord, }); - return new Case(result, { applicationContext }).validate().toRawObject(); + return new Case(result, { authorizedUser }).validate().toRawObject(); }; export const deleteCaseNoteInteractor = withLocking( diff --git a/web-api/src/business/useCases/caseNote/deleteUserCaseNoteInteractor.test.ts b/web-api/src/business/useCases/caseNote/deleteUserCaseNoteInteractor.test.ts index f819cabc826..d47eb43b837 100644 --- a/web-api/src/business/useCases/caseNote/deleteUserCaseNoteInteractor.test.ts +++ b/web-api/src/business/useCases/caseNote/deleteUserCaseNoteInteractor.test.ts @@ -1,31 +1,35 @@ import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { User } from '../../../../../shared/src/business/entities/User'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { deleteUserCaseNoteInteractor } from './deleteUserCaseNoteInteractor'; +import { mockJudgeUser } from '@shared/test/mockAuthUsers'; import { omit } from 'lodash'; describe('deleteUserCaseNoteInteractor', () => { it('throws an error if the user is not valid or authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); + let user = {} as UnknownAuthUser; await expect( - deleteUserCaseNoteInteractor(applicationContext, { - docketNumber: '123-45', - }), + deleteUserCaseNoteInteractor( + applicationContext, + { + docketNumber: '123-45', + }, + user, + ), ).rejects.toThrow(new UnauthorizedError('Unauthorized')); }); it('deletes a case note', async () => { const mockUser = new User({ + email: 'email@example.com', name: 'Judge Colvin', role: ROLES.judge, section: 'colvinChambers', userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - applicationContext.getCurrentUser.mockReturnValue( - omit(mockUser, 'section'), - ); + }) as UnknownAuthUser; applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(mockUser); @@ -37,23 +41,22 @@ describe('deleteUserCaseNoteInteractor', () => { userId: '6805d1ab-18d0-43ec-bafb-654e83405416', }); - const caseNote = await deleteUserCaseNoteInteractor(applicationContext, { - docketNumber: '123-45', - }); + const caseNote = await deleteUserCaseNoteInteractor( + applicationContext, + { + docketNumber: '123-45', + }, + omit(mockUser, 'section'), + ); expect(caseNote).toBeDefined(); }); it('deletes a case note associated with the current userId when there is no associated judge', async () => { - const mockUser = new User({ - name: 'Judge Colvin', - role: ROLES.judge, + const mockUser = { + ...mockJudgeUser, section: 'colvinChambers', - userId: '123456', - }); - applicationContext.getCurrentUser.mockReturnValue( - omit(mockUser, 'section'), - ); + } as UnknownAuthUser; applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(mockUser); @@ -61,13 +64,17 @@ describe('deleteUserCaseNoteInteractor', () => { applicationContext .getUseCaseHelpers() .getJudgeInSectionHelper.mockReturnValue(null); - await deleteUserCaseNoteInteractor(applicationContext, { - docketNumber: '123-45', - }); + await deleteUserCaseNoteInteractor( + applicationContext, + { + docketNumber: '123-45', + }, + omit(mockUser, 'section'), + ); expect( applicationContext.getPersistenceGateway().deleteUserCaseNote.mock .calls[0][0].userId, - ).toEqual('123456'); + ).toEqual(mockJudgeUser.userId); }); }); diff --git a/web-api/src/business/useCases/caseNote/deleteUserCaseNoteInteractor.ts b/web-api/src/business/useCases/caseNote/deleteUserCaseNoteInteractor.ts index 30f1af0481e..65809d66eaf 100644 --- a/web-api/src/business/useCases/caseNote/deleteUserCaseNoteInteractor.ts +++ b/web-api/src/business/useCases/caseNote/deleteUserCaseNoteInteractor.ts @@ -4,6 +4,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * deleteUserCaseNoteInteractor @@ -16,17 +17,18 @@ import { UnauthorizedError } from '@web-api/errors/errors'; export const deleteUserCaseNoteInteractor = async ( applicationContext: ServerApplicationContext, { docketNumber }: { docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSION_WORKING_COPY)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSION_WORKING_COPY) + ) { throw new UnauthorizedError('Unauthorized'); } const userId = await applicationContext .getUseCaseHelpers() .getUserIdForNote(applicationContext, { - userIdMakingRequest: user.userId, + userIdMakingRequest: authorizedUser.userId, }); return await applicationContext.getPersistenceGateway().deleteUserCaseNote({ diff --git a/web-api/src/business/useCases/caseNote/getUserCaseNoteForCasesInteractor.test.ts b/web-api/src/business/useCases/caseNote/getUserCaseNoteForCasesInteractor.test.ts index 81df6e33e92..31f054dfec4 100644 --- a/web-api/src/business/useCases/caseNote/getUserCaseNoteForCasesInteractor.test.ts +++ b/web-api/src/business/useCases/caseNote/getUserCaseNoteForCasesInteractor.test.ts @@ -1,13 +1,13 @@ import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; -import { User } from '../../../../../shared/src/business/entities/User'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getUserCaseNoteForCasesInteractor } from './getUserCaseNoteForCasesInteractor'; +import { mockJudgeUser } from '@shared/test/mockAuthUsers'; import { omit } from 'lodash'; describe('getUserCaseNoteForCasesInteractor', () => { - let mockCurrentUser; + let mockCurrentUser: UnknownAuthUser; let mockNote; const MOCK_NOTE = { @@ -17,17 +17,13 @@ describe('getUserCaseNoteForCasesInteractor', () => { }; const mockJudge = { - role: ROLES.judge, + ...mockJudgeUser, section: 'colvinChambers', - userId: 'd7d90c05-f6cd-442c-a168-202db587f16f', - }; + } as UnknownAuthUser; beforeEach(() => { mockCurrentUser = mockJudge; mockNote = MOCK_NOTE; - applicationContext.getCurrentUser.mockImplementation(() => - omit(new User(mockCurrentUser), 'section'), - ); applicationContext .getPersistenceGateway() .getUserById.mockImplementation(() => mockCurrentUser); @@ -43,11 +39,15 @@ describe('getUserCaseNoteForCasesInteractor', () => { mockCurrentUser = { role: 'unauthorizedRole', userId: 'unauthorizedUser', - }; + } as unknown as UnknownAuthUser; await expect( - getUserCaseNoteForCasesInteractor(applicationContext, { - docketNumbers: [MOCK_NOTE.docketNumber], - }), + getUserCaseNoteForCasesInteractor( + applicationContext, + { + docketNumbers: [MOCK_NOTE.docketNumber], + }, + omit(mockCurrentUser, 'section'), + ), ).rejects.toThrow(UnauthorizedError); }); @@ -57,42 +57,48 @@ describe('getUserCaseNoteForCasesInteractor', () => { .getUserCaseNoteForCases.mockResolvedValue([omit(MOCK_NOTE, 'userId')]); await expect( - getUserCaseNoteForCasesInteractor(applicationContext, { - docketNumbers: [MOCK_NOTE.docketNumber], - }), + getUserCaseNoteForCasesInteractor( + applicationContext, + { + docketNumbers: [MOCK_NOTE.docketNumber], + }, + mockCurrentUser, + ), ).rejects.toThrow('The UserCaseNote entity was invalid'); }); it('correctly returns data from persistence', async () => { - const result = await getUserCaseNoteForCasesInteractor(applicationContext, { - docketNumbers: [MOCK_NOTE.docketNumber], - }); + const result = await getUserCaseNoteForCasesInteractor( + applicationContext, + { + docketNumbers: [MOCK_NOTE.docketNumber], + }, + mockCurrentUser, + ); expect(result).toMatchObject([MOCK_NOTE]); }); it('uses the current user userId when there is no associated judge', async () => { const userIdToExpect = 'f922e1fc-567f-4f7d-b1f5-c9eec1567643'; - const mockUser = new User({ - name: 'Judge Colvin', - role: ROLES.judge, - section: 'colvinChambers', + const mockUser = { + ...mockJudge, userId: userIdToExpect, - }); - applicationContext.getCurrentUser.mockImplementation(() => - omit(mockUser, 'section'), - ); + } as UnknownAuthUser; applicationContext .getPersistenceGateway() .getUserById.mockImplementation(() => mockUser); - applicationContext.getCurrentUser.mockReturnValue(mockUser); applicationContext .getUseCaseHelpers() .getJudgeInSectionHelper.mockReturnValue(null); - await getUserCaseNoteForCasesInteractor(applicationContext, { - docketNumbers: [MOCK_NOTE.docketNumber], - }); + await getUserCaseNoteForCasesInteractor( + applicationContext, + { + docketNumbers: [MOCK_NOTE.docketNumber], + }, + omit(mockUser, 'section'), + ); expect( applicationContext.getPersistenceGateway().getUserCaseNoteForCases.mock diff --git a/web-api/src/business/useCases/caseNote/getUserCaseNoteForCasesInteractor.ts b/web-api/src/business/useCases/caseNote/getUserCaseNoteForCasesInteractor.ts index 826afc0bd44..91257ab2877 100644 --- a/web-api/src/business/useCases/caseNote/getUserCaseNoteForCasesInteractor.ts +++ b/web-api/src/business/useCases/caseNote/getUserCaseNoteForCasesInteractor.ts @@ -3,30 +3,22 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { UserCaseNote } from '../../../../../shared/src/business/entities/notes/UserCaseNote'; -/** - * getUserCaseNoteForCasesInteractor - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {string} providers.docketNumbers the docket numbers of the cases to get notes for - * @returns {object} the case note object if one is found - */ export const getUserCaseNoteForCasesInteractor = async ( applicationContext, { docketNumbers }: { docketNumbers: string[] }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } const userId = await applicationContext .getUseCaseHelpers() .getUserIdForNote(applicationContext, { - userIdMakingRequest: user.userId, + userIdMakingRequest: authorizedUser.userId, }); const caseNotes = await applicationContext diff --git a/web-api/src/business/useCases/caseNote/getUserCaseNoteInteractor.test.ts b/web-api/src/business/useCases/caseNote/getUserCaseNoteInteractor.test.ts index 1011b3736ec..c1e25eacca5 100644 --- a/web-api/src/business/useCases/caseNote/getUserCaseNoteInteractor.test.ts +++ b/web-api/src/business/useCases/caseNote/getUserCaseNoteInteractor.test.ts @@ -1,33 +1,25 @@ import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { User } from '../../../../../shared/src/business/entities/User'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getUserCaseNoteInteractor } from './getUserCaseNoteInteractor'; +import { mockJudgeUser } from '@shared/test/mockAuthUsers'; import { omit } from 'lodash'; describe('Get case note', () => { const MOCK_NOTE = { docketNumber: MOCK_CASE.docketNumber, notes: 'something', - userId: 'd7d90c05-f6cd-442c-a168-202db587f16f', + userId: mockJudgeUser.userId, }; const mockUnauthorizedUser = { role: 'unauthorizedRole', userId: 'unauthorizedUser', - }; - - const mockJudge = { - role: ROLES.judge, - section: 'colvinChambers', - userId: 'd7d90c05-f6cd-442c-a168-202db587f16f', - }; + } as unknown as UnknownAuthUser; it('throws error if user is unauthorized', async () => { - applicationContext.getCurrentUser.mockImplementation(() => - omit(new User(mockUnauthorizedUser), 'section'), - ); applicationContext .getPersistenceGateway() .getUserById.mockImplementation(() => new User(mockUnauthorizedUser)); @@ -39,61 +31,64 @@ describe('Get case note', () => { .getJudgeInSectionHelper.mockReturnValue(null); await expect( - getUserCaseNoteInteractor(applicationContext, { - docketNumber: MOCK_NOTE.docketNumber, - }), + getUserCaseNoteInteractor( + applicationContext, + { + docketNumber: MOCK_NOTE.docketNumber, + }, + mockUnauthorizedUser, + ), ).rejects.toThrow(UnauthorizedError); }); it('throws an error if the entity returned from persistence is invalid', async () => { - applicationContext.getCurrentUser.mockImplementation(() => - omit(new User(mockJudge), 'section'), - ); applicationContext .getPersistenceGateway() - .getUserById.mockImplementation(() => new User(mockJudge)); + .getUserById.mockImplementation(() => new User(mockJudgeUser)); applicationContext .getPersistenceGateway() .getUserCaseNote.mockResolvedValue(omit(MOCK_NOTE, 'userId')); applicationContext .getUseCaseHelpers() - .getJudgeInSectionHelper.mockReturnValue(mockJudge); + .getJudgeInSectionHelper.mockReturnValue(mockJudgeUser); await expect( - getUserCaseNoteInteractor(applicationContext, { - docketNumber: MOCK_NOTE.docketNumber, - }), + getUserCaseNoteInteractor( + applicationContext, + { + docketNumber: MOCK_NOTE.docketNumber, + }, + omit(mockJudgeUser, 'section'), + ), ).rejects.toThrow('The UserCaseNote entity was invalid'); }); it('correctly returns data from persistence if a judgeUser exists', async () => { - applicationContext.getCurrentUser.mockImplementation(() => - omit(new User(mockJudge), 'section'), - ); applicationContext .getPersistenceGateway() - .getUserById.mockImplementation(() => new User(mockJudge)); + .getUserById.mockImplementation(() => new User(mockJudgeUser)); applicationContext .getPersistenceGateway() .getUserCaseNote.mockResolvedValue(MOCK_NOTE); applicationContext .getUseCaseHelpers() - .getJudgeInSectionHelper.mockReturnValue(mockJudge); + .getJudgeInSectionHelper.mockReturnValue(mockJudgeUser); - const result = await getUserCaseNoteInteractor(applicationContext, { - docketNumber: MOCK_NOTE.docketNumber, - }); + const result = await getUserCaseNoteInteractor( + applicationContext, + { + docketNumber: MOCK_NOTE.docketNumber, + }, + omit(mockJudgeUser, 'section'), + ); expect(result).toMatchObject(MOCK_NOTE); }); it('correctly returns data from persistence for the current user if a judgeUser does not exist', async () => { - applicationContext.getCurrentUser.mockImplementation(() => - omit(new User(mockJudge), 'section'), - ); applicationContext .getPersistenceGateway() - .getUserById.mockImplementation(() => new User(mockJudge)); + .getUserById.mockImplementation(() => new User(mockJudgeUser)); applicationContext .getPersistenceGateway() .getUserCaseNote.mockResolvedValue(MOCK_NOTE); @@ -101,30 +96,38 @@ describe('Get case note', () => { .getUseCaseHelpers() .getJudgeInSectionHelper.mockReturnValue(null); - const result = await getUserCaseNoteInteractor(applicationContext, { - docketNumber: MOCK_NOTE.docketNumber, - }); + const result = await getUserCaseNoteInteractor( + applicationContext, + { + docketNumber: MOCK_NOTE.docketNumber, + }, + mockJudgeUser, + ); - expect(result).toMatchObject({ ...MOCK_NOTE, userId: mockJudge.userId }); + expect(result).toMatchObject({ + ...MOCK_NOTE, + userId: mockJudgeUser.userId, + }); }); it('does not return anything if nothing is returned from persistence', async () => { - applicationContext.getCurrentUser.mockImplementation(() => - omit(new User(mockJudge), 'section'), - ); applicationContext .getPersistenceGateway() - .getUserById.mockImplementation(() => new User(mockJudge)); + .getUserById.mockImplementation(() => new User(mockJudgeUser)); applicationContext .getPersistenceGateway() .getUserCaseNote.mockReturnValue(null); applicationContext .getUseCaseHelpers() - .getJudgeInSectionHelper.mockReturnValue(mockJudge); + .getJudgeInSectionHelper.mockReturnValue(mockJudgeUser); - const result = await getUserCaseNoteInteractor(applicationContext, { - docketNumber: MOCK_NOTE.docketNumber, - }); + const result = await getUserCaseNoteInteractor( + applicationContext, + { + docketNumber: MOCK_NOTE.docketNumber, + }, + mockJudgeUser, + ); expect(result).toEqual(undefined); }); diff --git a/web-api/src/business/useCases/caseNote/getUserCaseNoteInteractor.ts b/web-api/src/business/useCases/caseNote/getUserCaseNoteInteractor.ts index 91f1adb7429..d7c1c37af7d 100644 --- a/web-api/src/business/useCases/caseNote/getUserCaseNoteInteractor.ts +++ b/web-api/src/business/useCases/caseNote/getUserCaseNoteInteractor.ts @@ -4,6 +4,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { UserCaseNote } from '../../../../../shared/src/business/entities/notes/UserCaseNote'; /** @@ -17,17 +18,18 @@ import { UserCaseNote } from '../../../../../shared/src/business/entities/notes/ export const getUserCaseNoteInteractor = async ( applicationContext: ServerApplicationContext, { docketNumber }: { docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSION_WORKING_COPY)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSION_WORKING_COPY) + ) { throw new UnauthorizedError('Unauthorized'); } const userId = await applicationContext .getUseCaseHelpers() .getUserIdForNote(applicationContext, { - userIdMakingRequest: user.userId, + userIdMakingRequest: authorizedUser.userId, }); const caseNote = await applicationContext diff --git a/web-api/src/business/useCases/caseNote/saveCaseNoteInteractor.test.ts b/web-api/src/business/useCases/caseNote/saveCaseNoteInteractor.test.ts index fd982ea2a47..eea1f25a8ac 100644 --- a/web-api/src/business/useCases/caseNote/saveCaseNoteInteractor.test.ts +++ b/web-api/src/business/useCases/caseNote/saveCaseNoteInteractor.test.ts @@ -1,9 +1,8 @@ import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { ServiceUnavailableError } from '@web-api/errors/errors'; -import { User } from '../../../../../shared/src/business/entities/User'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { mockJudgeUser, mockPetitionerUser } from '@shared/test/mockAuthUsers'; import { saveCaseNoteInteractor } from './saveCaseNoteInteractor'; describe('saveCaseNoteInteractor', () => { @@ -16,12 +15,6 @@ describe('saveCaseNoteInteractor', () => { beforeEach(() => { mockLock = undefined; - const mockJudge = new User({ - name: 'Judge Colvin', - role: ROLES.judge, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - applicationContext.getCurrentUser.mockReturnValue(mockJudge); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockResolvedValue(MOCK_CASE); @@ -30,21 +23,27 @@ describe('saveCaseNoteInteractor', () => { .updateCase.mockImplementation(({ caseToUpdate }) => caseToUpdate); }); it('throws an error if the user is not valid or authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - saveCaseNoteInteractor(applicationContext, { - caseNote: 'testing', - docketNumber: MOCK_CASE.docketNumber, - }), + saveCaseNoteInteractor( + applicationContext, + { + caseNote: 'testing', + docketNumber: MOCK_CASE.docketNumber, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('saves a case note', async () => { - const result = await saveCaseNoteInteractor(applicationContext, { - caseNote: 'This is my case note', - docketNumber: MOCK_CASE.docketNumber, - }); + const result = await saveCaseNoteInteractor( + applicationContext, + { + caseNote: 'This is my case note', + docketNumber: MOCK_CASE.docketNumber, + }, + mockJudgeUser, + ); expect(result).toBeDefined(); expect( @@ -60,10 +59,14 @@ describe('saveCaseNoteInteractor', () => { mockLock = MOCK_LOCK; await expect( - saveCaseNoteInteractor(applicationContext, { - caseNote: 'This is my case note', - docketNumber: MOCK_CASE.docketNumber, - }), + saveCaseNoteInteractor( + applicationContext, + { + caseNote: 'This is my case note', + docketNumber: MOCK_CASE.docketNumber, + }, + mockJudgeUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -72,10 +75,14 @@ describe('saveCaseNoteInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await saveCaseNoteInteractor(applicationContext, { - caseNote: 'This is my case note', - docketNumber: MOCK_CASE.docketNumber, - }); + await saveCaseNoteInteractor( + applicationContext, + { + caseNote: 'This is my case note', + docketNumber: MOCK_CASE.docketNumber, + }, + mockJudgeUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/caseNote/saveCaseNoteInteractor.ts b/web-api/src/business/useCases/caseNote/saveCaseNoteInteractor.ts index 7be7e75a943..cd716d0ab0d 100644 --- a/web-api/src/business/useCases/caseNote/saveCaseNoteInteractor.ts +++ b/web-api/src/business/useCases/caseNote/saveCaseNoteInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -19,9 +20,9 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; export const saveCaseNote = async ( applicationContext: ServerApplicationContext, { caseNote, docketNumber }: { caseNote: string; docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - if (!isAuthorized(user, ROLE_PERMISSIONS.CASE_NOTES)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CASE_NOTES)) { throw new UnauthorizedError('Unauthorized'); } @@ -35,7 +36,7 @@ export const saveCaseNote = async ( const caseToUpdate = new Case( { ...caseRecord, caseNote }, { - applicationContext, + authorizedUser, }, ) .validate() @@ -45,10 +46,11 @@ export const saveCaseNote = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate, }); - return new Case(result, { applicationContext }).validate().toRawObject(); + return new Case(result, { authorizedUser }).validate().toRawObject(); }; export const saveCaseNoteInteractor = withLocking( diff --git a/web-api/src/business/useCases/caseNote/updateUserCaseNoteInteractor.test.ts b/web-api/src/business/useCases/caseNote/updateUserCaseNoteInteractor.test.ts index 1e6c6e4c308..d907227899e 100644 --- a/web-api/src/business/useCases/caseNote/updateUserCaseNoteInteractor.test.ts +++ b/web-api/src/business/useCases/caseNote/updateUserCaseNoteInteractor.test.ts @@ -1,7 +1,8 @@ import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; -import { User } from '../../../../../shared/src/business/entities/User'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { mockJudgeUser } from '@shared/test/mockAuthUsers'; import { omit } from 'lodash'; import { updateUserCaseNoteInteractor } from './updateUserCaseNoteInteractor'; @@ -13,26 +14,23 @@ describe('updateUserCaseNoteInteractor', () => { }; it('throws an error if the user is not valid or authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - updateUserCaseNoteInteractor(applicationContext, { - docketNumber: mockCaseNote.docketNumber, - notes: mockCaseNote.notes, - }), + updateUserCaseNoteInteractor( + applicationContext, + { + docketNumber: mockCaseNote.docketNumber, + notes: mockCaseNote.notes, + }, + {} as UnknownAuthUser, + ), ).rejects.toThrow(new UnauthorizedError('Unauthorized')); }); it('updates a case note', async () => { - const mockUser = new User({ - name: 'Judge Colvin', - role: ROLES.judge, + const mockUser = { + ...mockJudgeUser, section: 'colvinChambers', - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - applicationContext.getCurrentUser.mockImplementation(() => - omit(mockUser, 'section'), - ); + } as UnknownAuthUser; applicationContext .getPersistenceGateway() .getUserById.mockImplementation(() => mockUser); @@ -43,28 +41,29 @@ describe('updateUserCaseNoteInteractor', () => { .getUseCaseHelpers() .getJudgeInSectionHelper.mockReturnValue({ role: ROLES.judge, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', + userId: mockJudgeUser.userId, }); - const caseNote = await updateUserCaseNoteInteractor(applicationContext, { - docketNumber: mockCaseNote.docketNumber, - notes: mockCaseNote.notes, - }); + const caseNote = await updateUserCaseNoteInteractor( + applicationContext, + { + docketNumber: mockCaseNote.docketNumber, + notes: mockCaseNote.notes, + }, + omit(mockUser, 'section'), + ); expect(caseNote).toBeDefined(); }); it('updates a case note associated with the current userId when there is no associated judge', async () => { const userIdToExpect = 'f922e1fc-567f-4f7d-b1f5-c9eec1567643'; - const mockUser = new User({ - name: 'Judge Colvin', - role: ROLES.judge, + const mockUser = { + ...mockJudgeUser, section: 'colvinChambers', userId: userIdToExpect, - }); - applicationContext.getCurrentUser.mockImplementation(() => - omit(mockUser, 'section'), - ); + } as UnknownAuthUser; + applicationContext .getPersistenceGateway() .getUserById.mockImplementation(() => mockUser); @@ -73,10 +72,14 @@ describe('updateUserCaseNoteInteractor', () => { .getUseCaseHelpers() .getJudgeInSectionHelper.mockReturnValue(null); - await updateUserCaseNoteInteractor(applicationContext, { - docketNumber: mockCaseNote.docketNumber, - notes: mockCaseNote.notes, - }); + await updateUserCaseNoteInteractor( + applicationContext, + { + docketNumber: mockCaseNote.docketNumber, + notes: mockCaseNote.notes, + }, + omit(mockUser, 'section'), + ); expect( applicationContext.getPersistenceGateway().updateUserCaseNote.mock diff --git a/web-api/src/business/useCases/caseNote/updateUserCaseNoteInteractor.ts b/web-api/src/business/useCases/caseNote/updateUserCaseNoteInteractor.ts index 7a16ad63efa..b4894a0a629 100644 --- a/web-api/src/business/useCases/caseNote/updateUserCaseNoteInteractor.ts +++ b/web-api/src/business/useCases/caseNote/updateUserCaseNoteInteractor.ts @@ -3,31 +3,24 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { UserCaseNote } from '../../../../../shared/src/business/entities/notes/UserCaseNote'; -/** - * updateUserCaseNoteInteractor - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {string} providers.docketNumber the docket number of the case to update notes - * @param {string} providers.notes the notes to update - * @returns {object} the updated case note returned from persistence - */ export const updateUserCaseNoteInteractor = async ( applicationContext, { docketNumber, notes }: { docketNumber: string; notes: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSION_WORKING_COPY)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSION_WORKING_COPY) + ) { throw new UnauthorizedError('Unauthorized'); } const userId = await applicationContext .getUseCaseHelpers() .getUserIdForNote(applicationContext, { - userIdMakingRequest: user.userId, + userIdMakingRequest: authorizedUser.userId, }); const caseNoteEntity = new UserCaseNote({ diff --git a/web-api/src/business/useCases/caseStatistics/addDeficiencyStatisticInteractor.test.ts b/web-api/src/business/useCases/caseStatistics/addDeficiencyStatisticInteractor.test.ts index 6f7bcc995df..8acce62e9bf 100644 --- a/web-api/src/business/useCases/caseStatistics/addDeficiencyStatisticInteractor.test.ts +++ b/web-api/src/business/useCases/caseStatistics/addDeficiencyStatisticInteractor.test.ts @@ -1,9 +1,9 @@ import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { addDeficiencyStatisticInteractor } from './addDeficiencyStatisticInteractor'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('addDeficiencyStatisticInteractor', () => { const mockStatistic = { @@ -39,11 +39,6 @@ describe('addDeficiencyStatisticInteractor', () => { beforeEach(() => { mockLock = undefined; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketClerk', - }); - applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(Promise.resolve(MOCK_CASE)); @@ -53,10 +48,14 @@ describe('addDeficiencyStatisticInteractor', () => { mockLock = MOCK_LOCK; await expect( - addDeficiencyStatisticInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - ...mockStatistic, - } as any), + addDeficiencyStatisticInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + ...mockStatistic, + } as any, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -65,10 +64,14 @@ describe('addDeficiencyStatisticInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await addDeficiencyStatisticInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - ...mockStatistic, - } as any); + await addDeficiencyStatisticInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + ...mockStatistic, + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -87,20 +90,26 @@ describe('addDeficiencyStatisticInteractor', () => { }); it('should throw an error if the user is unauthorized to update case statistics', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - addDeficiencyStatisticInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - } as any), + addDeficiencyStatisticInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + } as any, + undefined, + ), ).rejects.toThrow('Unauthorized for editing statistics'); }); it('should call updateCase with the updated case statistics and return the updated case', async () => { - const result = await addDeficiencyStatisticInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - ...mockStatistic, - } as any); + const result = await addDeficiencyStatisticInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + ...mockStatistic, + } as any, + mockDocketClerkUser, + ); expect(result).toMatchObject({ statistics: [mockStatistic], diff --git a/web-api/src/business/useCases/caseStatistics/addDeficiencyStatisticInteractor.ts b/web-api/src/business/useCases/caseStatistics/addDeficiencyStatisticInteractor.ts index c95ea191833..ef95c8361f1 100644 --- a/web-api/src/business/useCases/caseStatistics/addDeficiencyStatisticInteractor.ts +++ b/web-api/src/business/useCases/caseStatistics/addDeficiencyStatisticInteractor.ts @@ -6,6 +6,7 @@ import { import { ServerApplicationContext } from '@web-api/applicationContext'; import { Statistic } from '../../../../../shared/src/business/entities/Statistic'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -51,10 +52,9 @@ export const addDeficiencyStatistic = async ( year: string; yearOrPeriod: string; }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.ADD_EDIT_STATISTICS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.ADD_EDIT_STATISTICS)) { throw new UnauthorizedError('Unauthorized for editing statistics'); } @@ -62,31 +62,29 @@ export const addDeficiencyStatistic = async ( .getPersistenceGateway() .getCaseByDocketNumber({ applicationContext, docketNumber }); - const statisticEntity = new Statistic( - { - determinationDeficiencyAmount, - determinationTotalPenalties, - irsDeficiencyAmount, - irsTotalPenalties, - lastDateOfPeriod, - penalties, - year, - yearOrPeriod, - }, - { applicationContext }, - ).validate(); + const statisticEntity = new Statistic({ + determinationDeficiencyAmount, + determinationTotalPenalties, + irsDeficiencyAmount, + irsTotalPenalties, + lastDateOfPeriod, + penalties, + year, + yearOrPeriod, + }).validate(); - const newCase = new Case(oldCase, { applicationContext }); + const newCase = new Case(oldCase, { authorizedUser }); newCase.addStatistic(statisticEntity); const updatedCase = await applicationContext .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: newCase, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const addDeficiencyStatisticInteractor = withLocking( diff --git a/web-api/src/business/useCases/caseStatistics/deleteDeficiencyStatisticInteractor.test.ts b/web-api/src/business/useCases/caseStatistics/deleteDeficiencyStatisticInteractor.test.ts index 29b461e5c40..f8093b119c5 100644 --- a/web-api/src/business/useCases/caseStatistics/deleteDeficiencyStatisticInteractor.test.ts +++ b/web-api/src/business/useCases/caseStatistics/deleteDeficiencyStatisticInteractor.test.ts @@ -1,12 +1,11 @@ -import { - CASE_TYPES_MAP, - ROLES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { CASE_TYPES_MAP } from '../../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; import { ServiceUnavailableError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { deleteDeficiencyStatisticInteractor } from './deleteDeficiencyStatisticInteractor'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('deleteDeficiencyStatisticInteractor', () => { const statisticId = 'f7a1cdb5-f534-4d12-a046-86ca3b46ddc4'; @@ -30,10 +29,6 @@ describe('deleteDeficiencyStatisticInteractor', () => { beforeEach(() => { mockLock = undefined; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketClerk', - }); applicationContext .getPersistenceGateway() @@ -43,12 +38,14 @@ describe('deleteDeficiencyStatisticInteractor', () => { }); it('should throw an error if the user is unauthorized to update case statistics', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - deleteDeficiencyStatisticInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - } as any), + deleteDeficiencyStatisticInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + } as any, + {} as unknown as UnknownAuthUser, + ), ).rejects.toThrow('Unauthorized for editing statistics'); }); @@ -59,6 +56,7 @@ describe('deleteDeficiencyStatisticInteractor', () => { docketNumber: MOCK_CASE.docketNumber, statisticId, }, + mockDocketClerkUser, ); expect(result).toMatchObject({ statistics: [], @@ -79,6 +77,7 @@ describe('deleteDeficiencyStatisticInteractor', () => { docketNumber: MOCK_CASE.docketNumber, statisticId: '8b864301-a0d9-43aa-8029-e1a0ed8ad4c9', }, + mockDocketClerkUser, ); expect(result).toMatchObject({ statistics: [statistic], @@ -105,10 +104,14 @@ describe('deleteDeficiencyStatisticInteractor', () => { ); await expect( - deleteDeficiencyStatisticInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - statisticId: statistic.statisticId, - }), + deleteDeficiencyStatisticInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + statisticId: statistic.statisticId, + }, + mockDocketClerkUser, + ), ).rejects.toThrow('The Case entity was invalid'); expect( applicationContext.getPersistenceGateway().updateCase, @@ -119,10 +122,14 @@ describe('deleteDeficiencyStatisticInteractor', () => { mockLock = MOCK_LOCK; await expect( - deleteDeficiencyStatisticInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - statisticId: '8b864301-a0d9-43aa-8029-e1a0ed8ad4c9', - }), + deleteDeficiencyStatisticInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + statisticId: '8b864301-a0d9-43aa-8029-e1a0ed8ad4c9', + }, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -131,10 +138,14 @@ describe('deleteDeficiencyStatisticInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await deleteDeficiencyStatisticInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - statisticId: '8b864301-a0d9-43aa-8029-e1a0ed8ad4c9', - }); + await deleteDeficiencyStatisticInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + statisticId: '8b864301-a0d9-43aa-8029-e1a0ed8ad4c9', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/caseStatistics/deleteDeficiencyStatisticInteractor.ts b/web-api/src/business/useCases/caseStatistics/deleteDeficiencyStatisticInteractor.ts index f538b3a1c4a..0f920830691 100644 --- a/web-api/src/business/useCases/caseStatistics/deleteDeficiencyStatisticInteractor.ts +++ b/web-api/src/business/useCases/caseStatistics/deleteDeficiencyStatisticInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -19,10 +20,9 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; export const deleteDeficiencyStatistic = async ( applicationContext: ServerApplicationContext, { docketNumber, statisticId }: { docketNumber: string; statisticId: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.ADD_EDIT_STATISTICS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.ADD_EDIT_STATISTICS)) { throw new UnauthorizedError('Unauthorized for editing statistics'); } @@ -30,17 +30,18 @@ export const deleteDeficiencyStatistic = async ( .getPersistenceGateway() .getCaseByDocketNumber({ applicationContext, docketNumber }); - const newCase = new Case(oldCase, { applicationContext }); + const newCase = new Case(oldCase, { authorizedUser }); newCase.deleteStatistic(statisticId); const updatedCase = await applicationContext .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: newCase, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const deleteDeficiencyStatisticInteractor = withLocking( diff --git a/web-api/src/business/useCases/caseStatistics/updateDeficiencyStatisticInteractor.test.ts b/web-api/src/business/useCases/caseStatistics/updateDeficiencyStatisticInteractor.test.ts index 71e158f54e3..d8ea74fb509 100644 --- a/web-api/src/business/useCases/caseStatistics/updateDeficiencyStatisticInteractor.test.ts +++ b/web-api/src/business/useCases/caseStatistics/updateDeficiencyStatisticInteractor.test.ts @@ -1,8 +1,9 @@ import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { ServiceUnavailableError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { updateDeficiencyStatisticInteractor } from './updateDeficiencyStatisticInteractor'; describe('updateDeficiencyStatisticInteractor', () => { @@ -30,6 +31,7 @@ describe('updateDeficiencyStatisticInteractor', () => { yearOrPeriod: 'Year', }; let mockLock; + let authorizedUser: UnknownAuthUser; beforeAll(() => { applicationContext @@ -39,10 +41,7 @@ describe('updateDeficiencyStatisticInteractor', () => { beforeEach(() => { mockLock = undefined; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketClerk', - }); + authorizedUser = mockDocketClerkUser; applicationContext .getPersistenceGateway() @@ -52,12 +51,16 @@ describe('updateDeficiencyStatisticInteractor', () => { }); it('should throw an error if the user is unauthorized to update case statistics', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); + authorizedUser = {} as unknown as UnknownAuthUser; await expect( - updateDeficiencyStatisticInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - } as any), + updateDeficiencyStatisticInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + } as any, + authorizedUser, + ), ).rejects.toThrow('Unauthorized for editing statistics'); }); @@ -73,6 +76,7 @@ describe('updateDeficiencyStatisticInteractor', () => { docketNumber: MOCK_CASE.docketNumber, ...statisticToUpdate, } as any, + authorizedUser, ); expect(result).toMatchObject({ statistics: [statisticToUpdate], @@ -92,6 +96,7 @@ describe('updateDeficiencyStatisticInteractor', () => { docketNumber: MOCK_CASE.docketNumber, ...statisticToUpdate, } as any, + authorizedUser, ); expect(result).toMatchObject({ statistics: [statistic], @@ -102,10 +107,14 @@ describe('updateDeficiencyStatisticInteractor', () => { mockLock = MOCK_LOCK; await expect( - updateDeficiencyStatisticInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - ...statistic, - } as any), + updateDeficiencyStatisticInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + ...statistic, + } as any, + authorizedUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -114,10 +123,14 @@ describe('updateDeficiencyStatisticInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await updateDeficiencyStatisticInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - ...statistic, - } as any); + await updateDeficiencyStatisticInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + ...statistic, + } as any, + authorizedUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/caseStatistics/updateDeficiencyStatisticInteractor.ts b/web-api/src/business/useCases/caseStatistics/updateDeficiencyStatisticInteractor.ts index 56bcb204e85..33230cc7959 100644 --- a/web-api/src/business/useCases/caseStatistics/updateDeficiencyStatisticInteractor.ts +++ b/web-api/src/business/useCases/caseStatistics/updateDeficiencyStatisticInteractor.ts @@ -6,6 +6,7 @@ import { import { ServerApplicationContext } from '@web-api/applicationContext'; import { Statistic } from '../../../../../shared/src/business/entities/Statistic'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -54,10 +55,9 @@ export const updateDeficiencyStatistic = async ( year: string; yearOrPeriod: string; }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.ADD_EDIT_STATISTICS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.ADD_EDIT_STATISTICS)) { throw new UnauthorizedError('Unauthorized for editing statistics'); } @@ -65,32 +65,30 @@ export const updateDeficiencyStatistic = async ( .getPersistenceGateway() .getCaseByDocketNumber({ applicationContext, docketNumber }); - const statisticEntity = new Statistic( - { - determinationDeficiencyAmount, - determinationTotalPenalties, - irsDeficiencyAmount, - irsTotalPenalties, - lastDateOfPeriod, - penalties, - statisticId, - year, - yearOrPeriod, - }, - { applicationContext }, - ).validate(); + const statisticEntity = new Statistic({ + determinationDeficiencyAmount, + determinationTotalPenalties, + irsDeficiencyAmount, + irsTotalPenalties, + lastDateOfPeriod, + penalties, + statisticId, + year, + yearOrPeriod, + }).validate(); - const newCase = new Case(oldCase, { applicationContext }); + const newCase = new Case(oldCase, { authorizedUser }); newCase.updateStatistic(statisticEntity, statisticId); const updatedCase = await applicationContext .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: newCase, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const updateDeficiencyStatisticInteractor = withLocking( diff --git a/web-api/src/business/useCases/caseStatistics/updateOtherStatisticsInteractor.test.ts b/web-api/src/business/useCases/caseStatistics/updateOtherStatisticsInteractor.test.ts index e215fb1b2f9..bac8d35e215 100644 --- a/web-api/src/business/useCases/caseStatistics/updateOtherStatisticsInteractor.test.ts +++ b/web-api/src/business/useCases/caseStatistics/updateOtherStatisticsInteractor.test.ts @@ -1,12 +1,14 @@ import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { ServiceUnavailableError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { updateOtherStatisticsInteractor } from './updateOtherStatisticsInteractor'; describe('updateOtherStatisticsInteractor', () => { let mockLock; + let authorizedUser: UnknownAuthUser; beforeAll(() => { applicationContext @@ -16,10 +18,7 @@ describe('updateOtherStatisticsInteractor', () => { beforeEach(() => { mockLock = undefined; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketClerk', - }); + authorizedUser = mockDocketClerkUser; applicationContext .getPersistenceGateway() @@ -27,21 +26,27 @@ describe('updateOtherStatisticsInteractor', () => { }); it('should throw an error if the user is unauthorized to update case statistics', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); + authorizedUser = {} as UnknownAuthUser; await expect( - updateOtherStatisticsInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - } as any), + updateOtherStatisticsInteractor( + applicationContext, + { docketNumber: MOCK_CASE.docketNumber } as any, + authorizedUser, + ), ).rejects.toThrow('Unauthorized for editing statistics'); }); it('should call updateCase with the updated case statistics and return the updated case', async () => { - const result = await updateOtherStatisticsInteractor(applicationContext, { - damages: 1234, - docketNumber: MOCK_CASE.docketNumber, - litigationCosts: 5678, - }); + const result = await updateOtherStatisticsInteractor( + applicationContext, + { + damages: 1234, + docketNumber: MOCK_CASE.docketNumber, + litigationCosts: 5678, + }, + authorizedUser, + ); expect(result).toMatchObject({ damages: 1234, litigationCosts: 5678, @@ -51,11 +56,15 @@ describe('updateOtherStatisticsInteractor', () => { mockLock = MOCK_LOCK; await expect( - updateOtherStatisticsInteractor(applicationContext, { - damages: 1234, - docketNumber: MOCK_CASE.docketNumber, - litigationCosts: 5678, - }), + updateOtherStatisticsInteractor( + applicationContext, + { + damages: 1234, + docketNumber: MOCK_CASE.docketNumber, + litigationCosts: 5678, + }, + authorizedUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -64,11 +73,15 @@ describe('updateOtherStatisticsInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await updateOtherStatisticsInteractor(applicationContext, { - damages: 1234, - docketNumber: MOCK_CASE.docketNumber, - litigationCosts: 5678, - }); + await updateOtherStatisticsInteractor( + applicationContext, + { + damages: 1234, + docketNumber: MOCK_CASE.docketNumber, + litigationCosts: 5678, + }, + authorizedUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/caseStatistics/updateOtherStatisticsInteractor.ts b/web-api/src/business/useCases/caseStatistics/updateOtherStatisticsInteractor.ts index 428861ce94b..526c22494b4 100644 --- a/web-api/src/business/useCases/caseStatistics/updateOtherStatisticsInteractor.ts +++ b/web-api/src/business/useCases/caseStatistics/updateOtherStatisticsInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -24,10 +25,9 @@ export const updateOtherStatistics = async ( docketNumber, litigationCosts, }: { damages: number; docketNumber: string; litigationCosts: number }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.ADD_EDIT_STATISTICS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.ADD_EDIT_STATISTICS)) { throw new UnauthorizedError('Unauthorized for editing statistics'); } @@ -37,17 +37,18 @@ export const updateOtherStatistics = async ( const newCase = new Case( { ...oldCase, damages, litigationCosts }, - { applicationContext }, + { authorizedUser }, ); const updatedCase = await applicationContext .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: newCase, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const updateOtherStatisticsInteractor = withLocking( diff --git a/web-api/src/business/useCases/caseWorksheet/updateCaseWorksheetInteractor.test.ts b/web-api/src/business/useCases/caseWorksheet/updateCaseWorksheetInteractor.test.ts index 30822f5a027..c177ffd3625 100644 --- a/web-api/src/business/useCases/caseWorksheet/updateCaseWorksheetInteractor.test.ts +++ b/web-api/src/business/useCases/caseWorksheet/updateCaseWorksheetInteractor.test.ts @@ -1,11 +1,12 @@ import { InvalidEntityError, UnauthorizedError } from '@web-api/errors/errors'; import { RawCaseWorksheet } from '@shared/business/entities/caseWorksheet/CaseWorksheet'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { judgeColvin } from '@shared/test/mockUsers'; import { - colvinsChambersUser, - judgeColvin, - petitionsClerkUser, -} from '@shared/test/mockUsers'; + mockChambersUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { updateCaseWorksheetInteractor } from './updateCaseWorksheetInteractor'; describe('updateCaseWorksheetInteractor', () => { @@ -22,34 +23,38 @@ describe('updateCaseWorksheetInteractor', () => { }); it('should throw an error when the user does not have access to the case worksheet feature', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); // Only judges and judges chambers have access to case worksheets - await expect( - updateCaseWorksheetInteractor(applicationContext, { - worksheet: mockCaseWorksheet, - }), + updateCaseWorksheetInteractor( + applicationContext, + { + worksheet: mockCaseWorksheet, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(UnauthorizedError); }); it('should throw an error when the updated case worksheet is invalid', async () => { - applicationContext.getCurrentUser.mockReturnValue(judgeColvin); applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(judgeColvin); await expect( - updateCaseWorksheetInteractor(applicationContext, { - worksheet: { - ...mockCaseWorksheet, - finalBriefDueDate: 'abc', // finalBriefDueDate should be a date formatted as YYYY-MM-DD + updateCaseWorksheetInteractor( + applicationContext, + { + worksheet: { + ...mockCaseWorksheet, + finalBriefDueDate: 'abc', // finalBriefDueDate should be a date formatted as YYYY-MM-DD + }, }, - }), + judgeColvin as UnknownAuthUser, + ), ).rejects.toThrow(InvalidEntityError); }); it('should persist and return the updated case worksheet when the updates are valid', async () => { const mockFinalBriefDueDate = '2023-08-29'; - applicationContext.getCurrentUser.mockReturnValue(judgeColvin); applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(judgeColvin); @@ -57,12 +62,16 @@ describe('updateCaseWorksheetInteractor', () => { .getPersistenceGateway() .getCaseWorksheet.mockResolvedValue(mockCaseWorksheet); - const result = await updateCaseWorksheetInteractor(applicationContext, { - worksheet: { - ...mockCaseWorksheet, - finalBriefDueDate: mockFinalBriefDueDate, + const result = await updateCaseWorksheetInteractor( + applicationContext, + { + worksheet: { + ...mockCaseWorksheet, + finalBriefDueDate: mockFinalBriefDueDate, + }, }, - }); + judgeColvin as UnknownAuthUser, + ); const expectedUpdatedCaseWorksheet = { ...mockCaseWorksheet, @@ -83,17 +92,20 @@ describe('updateCaseWorksheetInteractor', () => { it('should persist the updated case worksheet when the updates are valid, using the judge`s userId in the section when the current user is a chambers user', async () => { const mockFinalBriefDueDate = '2023-08-29'; - applicationContext.getCurrentUser.mockReturnValue(colvinsChambersUser); applicationContext .getPersistenceGateway() .getCaseWorksheet.mockResolvedValue(mockCaseWorksheet); - const result = await updateCaseWorksheetInteractor(applicationContext, { - worksheet: { - ...mockCaseWorksheet, - finalBriefDueDate: mockFinalBriefDueDate, + const result = await updateCaseWorksheetInteractor( + applicationContext, + { + worksheet: { + ...mockCaseWorksheet, + finalBriefDueDate: mockFinalBriefDueDate, + }, }, - }); + mockChambersUser, + ); const expectedUpdatedCaseWorksheet = { ...mockCaseWorksheet, @@ -103,7 +115,7 @@ describe('updateCaseWorksheetInteractor', () => { applicationContext.getUseCaseHelpers().getJudgeForUserHelper.mock .calls[0][1], ).toEqual({ - user: colvinsChambersUser, + user: mockChambersUser, }); expect( applicationContext.getPersistenceGateway().updateCaseWorksheet, diff --git a/web-api/src/business/useCases/caseWorksheet/updateCaseWorksheetInteractor.ts b/web-api/src/business/useCases/caseWorksheet/updateCaseWorksheetInteractor.ts index b9f37ca87fc..92b85e1e96d 100644 --- a/web-api/src/business/useCases/caseWorksheet/updateCaseWorksheetInteractor.ts +++ b/web-api/src/business/useCases/caseWorksheet/updateCaseWorksheetInteractor.ts @@ -8,6 +8,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const updateCaseWorksheetInteractor = async ( applicationContext: ServerApplicationContext, @@ -16,16 +17,15 @@ export const updateCaseWorksheetInteractor = async ( }: { worksheet: RawCaseWorksheet; }, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.CASE_WORKSHEET)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CASE_WORKSHEET)) { throw new UnauthorizedError('Unauthorized'); } const judgeUser = await applicationContext .getUseCaseHelpers() - .getJudgeForUserHelper(applicationContext, { user }); + .getJudgeForUserHelper(applicationContext, { user: authorizedUser }); const caseWorksheetEntity = new CaseWorksheet(worksheet).validate(); diff --git a/web-api/src/business/useCases/checkForReadyForTrialCasesInteractor.test.ts b/web-api/src/business/useCases/checkForReadyForTrialCasesInteractor.test.ts index 3129cde14e8..b0150090c0d 100644 --- a/web-api/src/business/useCases/checkForReadyForTrialCasesInteractor.test.ts +++ b/web-api/src/business/useCases/checkForReadyForTrialCasesInteractor.test.ts @@ -2,7 +2,6 @@ import '@web-api/persistence/postgres/messages/mocks.jest'; import { CASE_STATUS_TYPES } from '../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE } from '../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../shared/src/test/mockLock'; -import { MOCK_USERS } from '../../../../shared/src/test/mockUsers'; import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; import { checkForReadyForTrialCasesInteractor } from './checkForReadyForTrialCasesInteractor'; @@ -10,10 +9,6 @@ describe('checkForReadyForTrialCasesInteractor', () => { let mockCasesReadyForTrial; beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue( - MOCK_USERS['a7d90c05-f6cd-442c-a168-202db587f16f'], - ); - applicationContext .getPersistenceGateway() .getReadyForTrialCases.mockImplementation(() => mockCasesReadyForTrial); diff --git a/web-api/src/business/useCases/checkForReadyForTrialCasesInteractor.ts b/web-api/src/business/useCases/checkForReadyForTrialCasesInteractor.ts index e9d0241e660..c1913452ef3 100644 --- a/web-api/src/business/useCases/checkForReadyForTrialCasesInteractor.ts +++ b/web-api/src/business/useCases/checkForReadyForTrialCasesInteractor.ts @@ -25,6 +25,7 @@ export const checkForReadyForTrialCasesInteractor = async ( const caseEntity = entity.validate(); await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser: undefined, caseToUpdate: caseEntity, }); @@ -50,6 +51,7 @@ export const checkForReadyForTrialCasesInteractor = async ( try { await acquireLock({ applicationContext, + authorizedUser: undefined, identifiers: [`case|${docketNumber}`], onLockError: new ServiceUnavailableError( `${docketNumber} is currently being updated`, @@ -80,7 +82,9 @@ export const checkForReadyForTrialCasesInteractor = async ( }); if (caseToCheck) { - const caseEntity = new Case(caseToCheck, { applicationContext }); + const caseEntity = new Case(caseToCheck, { + authorizedUser: undefined, + }); if (caseEntity.status === CASE_STATUS_TYPES.generalDocket) { caseEntity.checkForReadyForTrial(); if ( diff --git a/web-api/src/business/useCases/correspondence/archiveCorrespondenceDocumentInteractor.test.ts b/web-api/src/business/useCases/correspondence/archiveCorrespondenceDocumentInteractor.test.ts index 1b794a832b4..49648b0c6f8 100644 --- a/web-api/src/business/useCases/correspondence/archiveCorrespondenceDocumentInteractor.test.ts +++ b/web-api/src/business/useCases/correspondence/archiveCorrespondenceDocumentInteractor.test.ts @@ -5,9 +5,9 @@ import { ROLES } from '../../../../../shared/src/business/entities/EntityConstan import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { archiveCorrespondenceDocumentInteractor } from './archiveCorrespondenceDocumentInteractor'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('archiveCorrespondenceDocumentInteractor', () => { - let mockUser; let mockUserId = '2474e5c0-f741-4120-befa-b77378ac8bf0'; const mockCorrespondenceId = applicationContext.getUniqueId(); let mockCorrespondence; @@ -28,13 +28,6 @@ describe('archiveCorrespondenceDocumentInteractor', () => { userId: mockUserId, }); - mockUser = { - name: 'Docket Clerk', - role: ROLES.docketClerk, - userId: mockUserId, - }; - - applicationContext.getCurrentUser.mockImplementation(() => mockUser); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue({ @@ -44,22 +37,29 @@ describe('archiveCorrespondenceDocumentInteractor', () => { }); it('should throw an Unauthorized error if the user role does not have the CASE_CORRESPONDENCE permission', async () => { - const user = { ...mockUser, role: ROLES.petitioner }; - applicationContext.getCurrentUser.mockReturnValue(user); + const user = { ...mockDocketClerkUser, role: ROLES.petitioner }; await expect( - archiveCorrespondenceDocumentInteractor(applicationContext, { - correspondenceId: mockCorrespondenceId, - docketNumber: MOCK_CASE.docketNumber, - } as any), + archiveCorrespondenceDocumentInteractor( + applicationContext, + { + correspondenceId: mockCorrespondenceId, + docketNumber: MOCK_CASE.docketNumber, + } as any, + user, + ), ).rejects.toThrow('Unauthorized'); }); it('should delete the specified correspondence document from s3', async () => { - await archiveCorrespondenceDocumentInteractor(applicationContext, { - correspondenceId: mockCorrespondenceId, - docketNumber: MOCK_CASE.docketNumber, - }); + await archiveCorrespondenceDocumentInteractor( + applicationContext, + { + correspondenceId: mockCorrespondenceId, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().deleteDocumentFile.mock @@ -70,10 +70,14 @@ describe('archiveCorrespondenceDocumentInteractor', () => { }); it('should update the specified correspondence document on the case to be marked as archived', async () => { - await archiveCorrespondenceDocumentInteractor(applicationContext, { - correspondenceId: mockCorrespondenceId, - docketNumber: MOCK_CASE.docketNumber, - }); + await archiveCorrespondenceDocumentInteractor( + applicationContext, + { + correspondenceId: mockCorrespondenceId, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCaseCorrespondence.mock @@ -88,10 +92,14 @@ describe('archiveCorrespondenceDocumentInteractor', () => { }); it('should update the case to reflect the archived correspondence', async () => { - await archiveCorrespondenceDocumentInteractor(applicationContext, { - correspondenceId: mockCorrespondenceId, - docketNumber: MOCK_CASE.docketNumber, - }); + await archiveCorrespondenceDocumentInteractor( + applicationContext, + { + correspondenceId: mockCorrespondenceId, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -107,10 +115,14 @@ describe('archiveCorrespondenceDocumentInteractor', () => { mockLock = MOCK_LOCK; await expect( - archiveCorrespondenceDocumentInteractor(applicationContext, { - correspondenceId: mockCorrespondenceId, - docketNumber: MOCK_CASE.docketNumber, - }), + archiveCorrespondenceDocumentInteractor( + applicationContext, + { + correspondenceId: mockCorrespondenceId, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -119,10 +131,14 @@ describe('archiveCorrespondenceDocumentInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await archiveCorrespondenceDocumentInteractor(applicationContext, { - correspondenceId: mockCorrespondenceId, - docketNumber: MOCK_CASE.docketNumber, - }); + await archiveCorrespondenceDocumentInteractor( + applicationContext, + { + correspondenceId: mockCorrespondenceId, + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/correspondence/archiveCorrespondenceDocumentInteractor.ts b/web-api/src/business/useCases/correspondence/archiveCorrespondenceDocumentInteractor.ts index 7d5cd7f7108..758b9d52246 100644 --- a/web-api/src/business/useCases/correspondence/archiveCorrespondenceDocumentInteractor.ts +++ b/web-api/src/business/useCases/correspondence/archiveCorrespondenceDocumentInteractor.ts @@ -5,27 +5,18 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; -/** - * archiveCorrespondenceDocument - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {object} providers.correspondenceId case correspondence id - * @param {string} providers.docketNumber the docket number of the case - * @returns {void} - */ export const archiveCorrespondenceDocument = async ( applicationContext: ServerApplicationContext, { correspondenceId, docketNumber, }: { correspondenceId: string; docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.CASE_CORRESPONDENCE)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CASE_CORRESPONDENCE)) { throw new UnauthorizedError('Unauthorized'); } @@ -38,7 +29,7 @@ export const archiveCorrespondenceDocument = async ( .getPersistenceGateway() .getCaseByDocketNumber({ applicationContext, docketNumber }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); const correspondenceToArchiveEntity = caseEntity.correspondence.find( c => c.correspondenceId === correspondenceId, ); @@ -53,6 +44,7 @@ export const archiveCorrespondenceDocument = async ( await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); }; diff --git a/web-api/src/business/useCases/correspondence/fileCorrespondenceDocumentInteractor.test.ts b/web-api/src/business/useCases/correspondence/fileCorrespondenceDocumentInteractor.test.ts index f0a0e00eec1..c3b9005e29b 100644 --- a/web-api/src/business/useCases/correspondence/fileCorrespondenceDocumentInteractor.test.ts +++ b/web-api/src/business/useCases/correspondence/fileCorrespondenceDocumentInteractor.test.ts @@ -7,11 +7,12 @@ import { } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { createISODateString } from '../../../../../shared/src/business/utilities/DateHandler'; -import { - docketClerkUser, - petitionerUser, -} from '../../../../../shared/src/test/mockUsers'; +import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; import { fileCorrespondenceDocumentInteractor } from './fileCorrespondenceDocumentInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('fileCorrespondenceDocumentInteractor', () => { const mockCase = { @@ -57,7 +58,6 @@ describe('fileCorrespondenceDocumentInteractor', () => { const mockCorrespondenceId = '14bb669b-0962-4781-87a0-50718f556e2b'; beforeEach(() => { - applicationContext.getCurrentUser.mockImplementation(() => docketClerkUser); applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(docketClerkUser); @@ -68,16 +68,17 @@ describe('fileCorrespondenceDocumentInteractor', () => { }); it('should throw an Unauthorized error if the user role does not have theCASE_CORRESPONDENCE permission', async () => { - const user = petitionerUser; - applicationContext.getCurrentUser.mockReturnValue(user); - await expect( - fileCorrespondenceDocumentInteractor(applicationContext, { - documentMetadata: { - docketNumber: mockCase.docketNumber, - } as any, - primaryDocumentFileId: mockCorrespondenceId, - }), + fileCorrespondenceDocumentInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: mockCase.docketNumber, + } as any, + primaryDocumentFileId: mockCorrespondenceId, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -87,10 +88,14 @@ describe('fileCorrespondenceDocumentInteractor', () => { .getCaseByDocketNumber.mockReturnValue(null); await expect( - fileCorrespondenceDocumentInteractor(applicationContext, { - documentMetadata: { docketNumber: mockCase.docketNumber } as any, - primaryDocumentFileId: mockCorrespondenceId, - }), + fileCorrespondenceDocumentInteractor( + applicationContext, + { + documentMetadata: { docketNumber: mockCase.docketNumber } as any, + primaryDocumentFileId: mockCorrespondenceId, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(`Case ${mockCase.docketNumber} was not found`); }); @@ -102,14 +107,18 @@ describe('fileCorrespondenceDocumentInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(mockCase); - await fileCorrespondenceDocumentInteractor(applicationContext, { - documentMetadata: { - docketNumber: mockCase.docketNumber, - documentTitle: mockDocumentTitle, - filingDate: mockFilingDate, - } as any, - primaryDocumentFileId: mockCorrespondenceId, - }); + await fileCorrespondenceDocumentInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: mockCase.docketNumber, + documentTitle: mockDocumentTitle, + filingDate: mockFilingDate, + } as any, + primaryDocumentFileId: mockCorrespondenceId, + }, + docketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCaseCorrespondence.mock .calls[0][0], @@ -140,6 +149,7 @@ describe('fileCorrespondenceDocumentInteractor', () => { } as any, primaryDocumentFileId: mockCorrespondenceId, }, + mockDocketClerkUser, ); expect(result).toMatchObject({ ...mockCase, diff --git a/web-api/src/business/useCases/correspondence/fileCorrespondenceDocumentInteractor.ts b/web-api/src/business/useCases/correspondence/fileCorrespondenceDocumentInteractor.ts index 97b05446386..75fdb4eacea 100644 --- a/web-api/src/business/useCases/correspondence/fileCorrespondenceDocumentInteractor.ts +++ b/web-api/src/business/useCases/correspondence/fileCorrespondenceDocumentInteractor.ts @@ -6,6 +6,7 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * fileCorrespondenceDocumentInteractor @@ -22,8 +23,8 @@ export const fileCorrespondenceDocumentInteractor = async ( documentMetadata, primaryDocumentFileId, }: { documentMetadata: TDocumentMetaData; primaryDocumentFileId: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); const { docketNumber } = documentMetadata; if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CASE_CORRESPONDENCE)) { @@ -45,7 +46,7 @@ export const fileCorrespondenceDocumentInteractor = async ( throw new NotFoundError(`Case ${docketNumber} was not found`); } - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); const correspondenceEntity = new Correspondence({ ...documentMetadata, diff --git a/web-api/src/business/useCases/correspondence/updateCorrespondenceDocumentInteractor.test.ts b/web-api/src/business/useCases/correspondence/updateCorrespondenceDocumentInteractor.test.ts index b2cdd1bdb03..1e3e186b510 100644 --- a/web-api/src/business/useCases/correspondence/updateCorrespondenceDocumentInteractor.test.ts +++ b/web-api/src/business/useCases/correspondence/updateCorrespondenceDocumentInteractor.test.ts @@ -8,16 +8,14 @@ import { import { Correspondence } from '../../../../../shared/src/business/entities/Correspondence'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { createISODateString } from '../../../../../shared/src/business/utilities/DateHandler'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { updateCorrespondenceDocumentInteractor } from './updateCorrespondenceDocumentInteractor'; describe('updateCorrespondenceDocumentInteractor', () => { - let mockUser; const mockDocketEntryId = 'cf105788-5d34-4451-aa8d-dfd9a851b675'; - const mockUserFixture = { - name: 'Docket Clerk', - role: ROLES.docketClerk, - userId: '2474e5c0-f741-4120-befa-b77378ac8bf0', - }; const mockCorrespondence = new Correspondence({ correspondenceId: '74e36bf7-dcbd-4ee7-a9ec-6d7446096df8', @@ -67,32 +65,35 @@ describe('updateCorrespondenceDocumentInteractor', () => { }; beforeEach(() => { - mockUser = mockUserFixture; - - applicationContext.getCurrentUser.mockImplementation(() => mockUser); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(mockCase); }); it('should throw an Unauthorized error if the user role does not have the CASE_CORRESPONDENCE permission', async () => { - mockUser = { ...mockUser, role: ROLES.petitioner }; - await expect( - updateCorrespondenceDocumentInteractor(applicationContext, { - documentMetadata: { docketNumber: mockCase.docketNumber } as any, - }), + updateCorrespondenceDocumentInteractor( + applicationContext, + { + documentMetadata: { docketNumber: mockCase.docketNumber } as any, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should update the specified correspondence document title when the case entity is valid', async () => { - await updateCorrespondenceDocumentInteractor(applicationContext, { - documentMetadata: { - correspondenceId: mockCorrespondence.correspondenceId, - docketNumber: mockCase.docketNumber, - documentTitle: 'A title that has been updated', - } as any, - }); + await updateCorrespondenceDocumentInteractor( + applicationContext, + { + documentMetadata: { + correspondenceId: mockCorrespondence.correspondenceId, + docketNumber: mockCase.docketNumber, + documentTitle: 'A title that has been updated', + } as any, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCaseCorrespondence.mock @@ -116,6 +117,7 @@ describe('updateCorrespondenceDocumentInteractor', () => { documentTitle: 'A title that has been updated', } as any, }, + mockDocketClerkUser, ); expect(result).toMatchObject({ diff --git a/web-api/src/business/useCases/correspondence/updateCorrespondenceDocumentInteractor.ts b/web-api/src/business/useCases/correspondence/updateCorrespondenceDocumentInteractor.ts index 061a1fc1382..80228e52194 100644 --- a/web-api/src/business/useCases/correspondence/updateCorrespondenceDocumentInteractor.ts +++ b/web-api/src/business/useCases/correspondence/updateCorrespondenceDocumentInteractor.ts @@ -6,20 +6,13 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; -/** - * updateCorrespondenceDocumentInteractor - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {object} providers.documentMetadata the document metadata - * @returns {Promise<*>} the updated case entity after the correspondence document is updated - */ export const updateCorrespondenceDocumentInteractor = async ( applicationContext: ServerApplicationContext, { documentMetadata }: { documentMetadata: TDocumentMetaData }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); const { docketNumber } = documentMetadata; if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CASE_CORRESPONDENCE)) { @@ -33,7 +26,7 @@ export const updateCorrespondenceDocumentInteractor = async ( docketNumber, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); const currentCorrespondenceDocument = caseEntity.getCorrespondenceById({ correspondenceId: documentMetadata.correspondenceId, diff --git a/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.consolidatedCases.test.ts b/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.consolidatedCases.test.ts index fe4d742f633..c0188ec36b1 100644 --- a/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.consolidatedCases.test.ts +++ b/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.consolidatedCases.test.ts @@ -11,6 +11,7 @@ import { MOCK_DOCUMENTS } from '../../../../../shared/src/test/mockDocketEntry'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; import { fileAndServeCourtIssuedDocumentInteractor } from './fileAndServeCourtIssuedDocumentInteractor'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { v4 as uuidv4 } from 'uuid'; describe('consolidated cases', () => { @@ -52,8 +53,6 @@ describe('consolidated cases', () => { .getPersistenceGateway() .getUserById.mockReturnValue(docketClerkUser); - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getUseCaseHelpers() .countPagesInDocument.mockReturnValue(1); @@ -127,16 +126,21 @@ describe('consolidated cases', () => { .mockRejectedValueOnce(new Error(expectedErrorString)); await expect( - fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId, - docketEntryId: leadCaseDocketEntries[0].docketEntryId, - docketNumbers: [ - MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, - MOCK_CONSOLIDATED_2_CASE_WITH_PAPER_SERVICE.docketNumber, - ], - form: leadCaseDocketEntries[0], - subjectCaseDocketNumber: MOCK_LEAD_CASE_WITH_PAPER_SERVICE.docketNumber, - }), + fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: leadCaseDocketEntries[0].docketEntryId, + docketNumbers: [ + MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, + MOCK_CONSOLIDATED_2_CASE_WITH_PAPER_SERVICE.docketNumber, + ], + form: leadCaseDocketEntries[0], + subjectCaseDocketNumber: + MOCK_LEAD_CASE_WITH_PAPER_SERVICE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(expectedErrorString); const initialCall = 1; @@ -175,16 +179,21 @@ describe('consolidated cases', () => { .mockRejectedValueOnce(innerError); await expect( - fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId, - docketEntryId: leadCaseDocketEntries[0].docketEntryId, - docketNumbers: [ - MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, - MOCK_CONSOLIDATED_2_CASE_WITH_PAPER_SERVICE.docketNumber, - ], - form: leadCaseDocketEntries[0], - subjectCaseDocketNumber: MOCK_LEAD_CASE_WITH_PAPER_SERVICE.docketNumber, - }), + fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: leadCaseDocketEntries[0].docketEntryId, + docketNumbers: [ + MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, + MOCK_CONSOLIDATED_2_CASE_WITH_PAPER_SERVICE.docketNumber, + ], + form: leadCaseDocketEntries[0], + subjectCaseDocketNumber: + MOCK_LEAD_CASE_WITH_PAPER_SERVICE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(expectedErrorString); expect(applicationContext.logger.error).toHaveBeenCalledTimes(1); @@ -194,16 +203,20 @@ describe('consolidated cases', () => { }); it('should create a single source of truth for the document by saving only one copy', async () => { - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId, - docketEntryId: leadCaseDocketEntries[0].docketEntryId, - docketNumbers: [ - MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, - MOCK_CONSOLIDATED_2_CASE_WITH_PAPER_SERVICE.docketNumber, - ], - form: leadCaseDocketEntries[0], - subjectCaseDocketNumber: MOCK_LEAD_CASE_WITH_PAPER_SERVICE.docketNumber, - }); + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: leadCaseDocketEntries[0].docketEntryId, + docketNumbers: [ + MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, + MOCK_CONSOLIDATED_2_CASE_WITH_PAPER_SERVICE.docketNumber, + ], + form: leadCaseDocketEntries[0], + subjectCaseDocketNumber: MOCK_LEAD_CASE_WITH_PAPER_SERVICE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveDocumentFromLambda, diff --git a/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.locking.test.ts b/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.locking.test.ts index 977ef019006..9d7603e0182 100644 --- a/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.locking.test.ts +++ b/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.locking.test.ts @@ -8,6 +8,7 @@ import { handleLockError, } from './fileAndServeCourtIssuedDocumentInteractor'; import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('determineEntitiesToLock', () => { let mockParams; @@ -43,13 +44,11 @@ describe('determineEntitiesToLock', () => { describe('handleLockError', () => { const mockClientConnectionId = '987654'; - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - }); - - it('should determine who the user is based on applicationContext', async () => { - await handleLockError(applicationContext, { foo: 'bar' }); - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); + it('should not send a notification if there is no authorizedUser', async () => { + await handleLockError(applicationContext, { foo: 'bar' }, undefined); + expect( + applicationContext.getNotificationGateway().sendNotificationToUser, + ).not.toHaveBeenCalled(); }); it('should send a notification to the user with "retry_file_and_serve_court_issued_document" and the originalRequest', async () => { @@ -57,7 +56,11 @@ describe('handleLockError', () => { clientConnectionId: mockClientConnectionId, foo: 'bar', }; - await handleLockError(applicationContext, mockOriginalRequest); + await handleLockError( + applicationContext, + mockOriginalRequest, + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock .calls[0][0].message, @@ -96,7 +99,6 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { applicationContext .getPersistenceGateway() .getLock.mockImplementation(() => mockLock); - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(docketClerkUser); @@ -132,6 +134,7 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { fileAndServeCourtIssuedDocumentInteractor( applicationContext, mockRequest, + mockDocketClerkUser, ), ).rejects.toThrow(ServiceUnavailableError); @@ -145,6 +148,7 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { fileAndServeCourtIssuedDocumentInteractor( applicationContext, mockRequest, + mockDocketClerkUser, ), ).rejects.toThrow(ServiceUnavailableError); @@ -158,7 +162,7 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { originalRequest: mockRequest, requestToRetry: 'file_and_serve_court_issued_document', }, - userId: docketClerkUser.userId, + userId: mockDocketClerkUser.userId, }); expect( @@ -176,6 +180,7 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { await fileAndServeCourtIssuedDocumentInteractor( applicationContext, mockRequest, + mockDocketClerkUser, ); expect( @@ -198,6 +203,7 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { await fileAndServeCourtIssuedDocumentInteractor( applicationContext, mockRequest, + mockDocketClerkUser, ); expect( applicationContext.getPersistenceGateway().removeLock, diff --git a/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.test.ts b/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.test.ts index 7d9e63e1784..fcb2e63892f 100644 --- a/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.test.ts +++ b/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.test.ts @@ -12,6 +12,7 @@ import { judgeUser, } from '../../../../../shared/src/test/mockUsers'; import { fileAndServeCourtIssuedDocumentInteractor } from './fileAndServeCourtIssuedDocumentInteractor'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { testPdfDoc } from '../../../../../shared/src/business/test/getFakeFile'; let MOCK_DATE; @@ -87,8 +88,6 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { ], }; - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(docketClerkUser); @@ -115,16 +114,18 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { }); it('should throw an error when the user is not authorized to file and serve a court issued document', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: caseRecord.docketEntries[1].docketEntryId, - docketNumbers: [], - form: {}, - subjectCaseDocketNumber: caseRecord.docketNumber, - }), + fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: caseRecord.docketEntries[1].docketEntryId, + docketNumbers: [], + form: {}, + subjectCaseDocketNumber: caseRecord.docketNumber, + }, + undefined, + ), ).rejects.toThrow('Unauthorized'); }); @@ -132,13 +133,17 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { const notFoundDocketEntryId = 'c54ba5a9-b37b-479d-9201-067ec6e335bd'; await expect( - fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: notFoundDocketEntryId, - docketNumbers: [], - form: {}, - subjectCaseDocketNumber: caseRecord.docketNumber, - }), + fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: notFoundDocketEntryId, + docketNumbers: [], + form: {}, + subjectCaseDocketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(`Docket entry ${notFoundDocketEntryId} was not found.`); }); @@ -146,15 +151,19 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { caseRecord.docketEntries[1].servedAt = MOCK_DATE; await expect( - fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: caseRecord.docketEntries[1].docketEntryId, - docketNumbers: [], - form: { - documentType: 'Order', + fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: caseRecord.docketEntries[1].docketEntryId, + docketNumbers: [], + form: { + documentType: 'Order', + }, + subjectCaseDocketNumber: caseRecord.docketNumber, }, - subjectCaseDocketNumber: caseRecord.docketNumber, - }), + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry has already been served'); }); @@ -163,13 +172,17 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { docketEntry.isPendingService = true; await expect( - fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: docketEntry.docketEntryId, - docketNumbers: [], - form: docketEntry, - subjectCaseDocketNumber: docketEntry.docketNumber, - }), + fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: docketEntry.docketEntryId, + docketNumbers: [], + form: docketEntry, + subjectCaseDocketNumber: docketEntry.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry is already being served'); expect( @@ -192,13 +205,17 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { caseRecord.docketEntries.push(mockAutoGeneratedDeadlineDocketEntry); - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockAutoGeneratedDeadlineDocketEntry.docketEntryId, - docketNumbers: [], - form: mockAutoGeneratedDeadlineForm, - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockAutoGeneratedDeadlineDocketEntry.docketEntryId, + docketNumbers: [], + form: mockAutoGeneratedDeadlineForm, + subjectCaseDocketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().autoGenerateDeadline.mock @@ -225,13 +242,17 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { caseRecord.docketEntries.push(mockOrderDocketEntry); - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockOrderDocketEntry.docketEntryId, - docketNumbers: [], - form: mockOrderForm, - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockOrderDocketEntry.docketEntryId, + docketNumbers: [], + form: mockOrderForm, + subjectCaseDocketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().autoGenerateDeadline, @@ -264,13 +285,17 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { eventCode: AUTO_GENERATED_DEADLINE_DOCUMENT_TYPES[0].eventCode, }; - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockAutoGeneratedDeadlineDocketEntry.docketEntryId, - docketNumbers: [nonSubjectCaseRecord.docketNumber], - form: mockAutoGeneratedDeadlineForm, - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockAutoGeneratedDeadlineDocketEntry.docketEntryId, + docketNumbers: [nonSubjectCaseRecord.docketNumber], + form: mockAutoGeneratedDeadlineForm, + subjectCaseDocketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().autoGenerateDeadline.mock @@ -279,13 +304,17 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { }); it('should make a call to stamp the document as served', async () => { - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: caseRecord.docketEntries[0].docketEntryId, - docketNumbers: [], - form: caseRecord.docketEntries[0], - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: caseRecord.docketEntries[0].docketEntryId, + docketNumbers: [], + form: caseRecord.docketEntries[0], + subjectCaseDocketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().stampDocumentForService, @@ -298,13 +327,17 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { .getUseCaseHelpers() .countPagesInDocument.mockReturnValue(mockNumberOfPages); - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: caseRecord.docketEntries[0].docketEntryId, - docketNumbers: [], - form: caseRecord.docketEntries[0], - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: caseRecord.docketEntries[0].docketEntryId, + docketNumbers: [], + form: caseRecord.docketEntries[0], + subjectCaseDocketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().countPagesInDocument.mock @@ -330,13 +363,17 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { serviceStamp: 'Blah blah blah', }; - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockDocketEntryId, - docketNumbers: [], - form: mockForm, - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockDocketEntryId, + docketNumbers: [], + form: mockForm, + subjectCaseDocketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ); const expectedDocketEntry = applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -367,13 +404,17 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { serviceStamp: 'Blah blah blah', }; - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockDocketEntryId, - docketNumbers: [], - form: mockForm, - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockDocketEntryId, + docketNumbers: [], + form: mockForm, + subjectCaseDocketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ); const expectedDocketEntry = applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -393,13 +434,17 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { serviceStamp: 'Blah blah blah', }; - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockDocketEntryId, - docketNumbers: [], - form: mockForm, - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockDocketEntryId, + docketNumbers: [], + form: mockForm, + subjectCaseDocketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ); const expectedDocketEntry = applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -420,13 +465,17 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { trialLocation: 'San Diego, CA', }; - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockDocketEntryId, - docketNumbers: [], - form: mockForm, - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockDocketEntryId, + docketNumbers: [], + form: mockForm, + subjectCaseDocketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ); const expectedDocketEntry = applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -447,13 +496,17 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { }; caseRecord.docketEntries[0].filingDate = '2009-03-01T21:40:46.415Z'; - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockDocketEntryId, - docketNumbers: [], - form: mockForm, - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockDocketEntryId, + docketNumbers: [], + form: mockForm, + subjectCaseDocketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ); const expectedDocketEntry = applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -473,13 +526,17 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { serviceStamp: 'Blah blah blah', }; - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockDocketEntryId, - docketNumbers: [], - form: mockForm, - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockDocketEntryId, + docketNumbers: [], + form: mockForm, + subjectCaseDocketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ); const expectedDocketEntry = applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -491,13 +548,17 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { caseRecord.petitioners[0].serviceIndicator = SERVICE_INDICATOR_TYPES.SI_PAPER; - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: caseRecord.docketEntries[0].docketEntryId, - docketNumbers: [], - form: caseRecord.docketEntries[0], - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: caseRecord.docketEntries[0].docketEntryId, + docketNumbers: [], + form: caseRecord.docketEntries[0], + subjectCaseDocketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock @@ -520,13 +581,17 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { const docketEntry = caseRecord.docketEntries[0]; docketEntry.isPendingService = false; - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: docketEntry.docketEntryId, - docketNumbers: [], - form: docketEntry, - subjectCaseDocketNumber: docketEntry.docketNumber, - }); + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: docketEntry.docketEntryId, + docketNumbers: [], + form: docketEntry, + subjectCaseDocketNumber: docketEntry.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -554,17 +619,21 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { .getUseCaseHelpers() .addServedStampToDocument.mockReturnValue({}); - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: caseRecord.docketEntries[0].docketEntryId, - docketNumbers: [], - form: { - ...caseRecord.docketEntries[0], - documentType: 'Notice', - eventCode: 'ODJ', + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: caseRecord.docketEntries[0].docketEntryId, + docketNumbers: [], + form: { + ...caseRecord.docketEntries[0], + documentType: 'Notice', + eventCode: 'ODJ', + }, + subjectCaseDocketNumber: caseRecord.docketNumber, }, - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveDocumentFromLambda.mock @@ -576,17 +645,21 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { }); it('should attempt to scrape the pdf if event code is scrape enabled', async () => { - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: caseRecord.docketEntries[0].docketEntryId, - docketNumbers: [], - form: { - ...caseRecord.docketEntries[0], - documentType: 'Notice', - eventCode: 'O', + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: caseRecord.docketEntries[0].docketEntryId, + docketNumbers: [], + form: { + ...caseRecord.docketEntries[0], + documentType: 'Notice', + eventCode: 'O', + }, + subjectCaseDocketNumber: caseRecord.docketNumber, }, - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().parseAndScrapePdfContents, @@ -603,17 +676,21 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { it('should not attempt to scrape the pdf if event code is non-scrapable', async () => { mockDocketEntryWithWorkItem.eventCode = 'EXH'; - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: caseRecord.docketEntries[0].docketEntryId, - docketNumbers: [], - form: { - ...caseRecord.docketEntries[0], - documentType: 'Notice', - eventCode: 'EXH', + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: caseRecord.docketEntries[0].docketEntryId, + docketNumbers: [], + form: { + ...caseRecord.docketEntries[0], + documentType: 'Notice', + eventCode: 'EXH', + }, + subjectCaseDocketNumber: caseRecord.docketNumber, }, - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().parseAndScrapePdfContents, @@ -625,17 +702,21 @@ describe('fileAndServeCourtIssuedDocumentInteractor', () => { .getUseCaseHelpers() .parseAndScrapePdfContents.mockRejectedValue(new Error('error')); - await fileAndServeCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: caseRecord.docketEntries[0].docketEntryId, - docketNumbers: [], - form: { - ...caseRecord.docketEntries[0], - documentType: 'Notice', - eventCode: 'O', + await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: caseRecord.docketEntries[0].docketEntryId, + docketNumbers: [], + form: { + ...caseRecord.docketEntries[0], + documentType: 'Notice', + eventCode: 'O', + }, + subjectCaseDocketNumber: caseRecord.docketNumber, }, - subjectCaseDocketNumber: caseRecord.docketNumber, - }); + mockDocketClerkUser, + ); expect(applicationContext.logger.error).toHaveBeenCalled(); expect( diff --git a/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.ts b/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.ts index db321fb7bf7..75ad15952cf 100644 --- a/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.ts +++ b/web-api/src/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor.ts @@ -10,6 +10,7 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { createISODateString } from '@shared/business/utilities/DateHandler'; import { omit } from 'lodash'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; @@ -29,9 +30,8 @@ export const fileAndServeCourtIssuedDocument = async ( form: any; subjectCaseDocketNumber: string; }, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); - const hasPermission = (isAuthorized(authorizedUser, ROLE_PERMISSIONS.DOCKET_ENTRY) || isAuthorized( @@ -55,7 +55,7 @@ export const fileAndServeCourtIssuedDocument = async ( docketNumber: subjectCaseDocketNumber, }); - const subjectCaseEntity = new Case(subjectCase, { applicationContext }); + const subjectCaseEntity = new Case(subjectCase, { authorizedUser }); const docketEntryToServe = subjectCaseEntity.getDocketEntryById({ docketEntryId, @@ -152,7 +152,7 @@ export const fileAndServeCourtIssuedDocument = async ( docketNumber, }); - caseEntities.push(new Case(caseToUpdate, { applicationContext })); + caseEntities.push(new Case(caseToUpdate, { authorizedUser })); } caseEntities = await Promise.all( @@ -184,7 +184,7 @@ export const fileAndServeCourtIssuedDocument = async ( serviceStamp: form.serviceStamp, trialLocation: form.trialLocation, }, - { applicationContext }, + { authorizedUser }, ); docketEntryEntity.setFiledBy(user); @@ -284,19 +284,23 @@ export const determineEntitiesToLock = ( ttl: 900, }); -export const handleLockError = async (applicationContext, originalRequest) => { - const user = applicationContext.getCurrentUser(); - - await applicationContext.getNotificationGateway().sendNotificationToUser({ - applicationContext, - clientConnectionId: originalRequest.clientConnectionId, - message: { - action: 'retry_async_request', - originalRequest, - requestToRetry: 'file_and_serve_court_issued_document', - }, - userId: user.userId, - }); +export const handleLockError = async ( + applicationContext, + originalRequest, + authorizedUser: UnknownAuthUser, +) => { + if (authorizedUser?.userId) { + await applicationContext.getNotificationGateway().sendNotificationToUser({ + applicationContext, + clientConnectionId: originalRequest.clientConnectionId, + message: { + action: 'retry_async_request', + originalRequest, + requestToRetry: 'file_and_serve_court_issued_document', + }, + userId: authorizedUser.userId, + }); + } }; export const fileAndServeCourtIssuedDocumentInteractor = withLocking( diff --git a/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.consolidatedCases.test.ts b/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.consolidatedCases.test.ts index 49f6d3e9afa..143ab721fba 100644 --- a/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.consolidatedCases.test.ts +++ b/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.consolidatedCases.test.ts @@ -11,6 +11,7 @@ import { import { MOCK_DOCUMENTS } from '../../../../../shared/src/test/mockDocketEntry'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { serveCourtIssuedDocumentInteractor } from './serveCourtIssuedDocumentInteractor'; import { v4 as uuidv4 } from 'uuid'; @@ -52,9 +53,6 @@ describe('serveCourtIssuedDocumentInteractor consolidated cases', () => { applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(docketClerkUser); - - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getUseCaseHelpers() .countPagesInDocument.mockReturnValue(1); @@ -120,15 +118,19 @@ describe('serveCourtIssuedDocumentInteractor consolidated cases', () => { }); it('should call serveDocumentAndGetPaperServicePdf and pass the resulting url and success message to `sendNotificationToUser` along with the `clientConnectionId`', async () => { - await serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId, - docketEntryId: leadCaseDocketEntries[0].docketEntryId, - docketNumbers: [ - MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, - MOCK_CONSOLIDATED_2_CASE_WITH_PAPER_SERVICE.docketNumber, - ], - subjectCaseDocketNumber: MOCK_LEAD_CASE_WITH_PAPER_SERVICE.docketNumber, - }); + await serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: leadCaseDocketEntries[0].docketEntryId, + docketNumbers: [ + MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, + MOCK_CONSOLIDATED_2_CASE_WITH_PAPER_SERVICE.docketNumber, + ], + subjectCaseDocketNumber: MOCK_LEAD_CASE_WITH_PAPER_SERVICE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().serveDocumentAndGetPaperServicePdf, @@ -170,15 +172,20 @@ describe('serveCourtIssuedDocumentInteractor consolidated cases', () => { .mockRejectedValueOnce(new Error(expectedErrorString)); await expect( - serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId, - docketEntryId: leadCaseDocketEntries[0].docketEntryId, - docketNumbers: [ - MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, - MOCK_CONSOLIDATED_2_CASE_WITH_PAPER_SERVICE.docketNumber, - ], - subjectCaseDocketNumber: MOCK_LEAD_CASE_WITH_PAPER_SERVICE.docketNumber, - }), + serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: leadCaseDocketEntries[0].docketEntryId, + docketNumbers: [ + MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, + MOCK_CONSOLIDATED_2_CASE_WITH_PAPER_SERVICE.docketNumber, + ], + subjectCaseDocketNumber: + MOCK_LEAD_CASE_WITH_PAPER_SERVICE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(expectedErrorString); const initialCall = 1; @@ -217,15 +224,20 @@ describe('serveCourtIssuedDocumentInteractor consolidated cases', () => { .mockRejectedValueOnce(innerError); await expect( - serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId, - docketEntryId: leadCaseDocketEntries[0].docketEntryId, - docketNumbers: [ - MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, - MOCK_CONSOLIDATED_2_CASE_WITH_PAPER_SERVICE.docketNumber, - ], - subjectCaseDocketNumber: MOCK_LEAD_CASE_WITH_PAPER_SERVICE.docketNumber, - }), + serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: leadCaseDocketEntries[0].docketEntryId, + docketNumbers: [ + MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, + MOCK_CONSOLIDATED_2_CASE_WITH_PAPER_SERVICE.docketNumber, + ], + subjectCaseDocketNumber: + MOCK_LEAD_CASE_WITH_PAPER_SERVICE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(expectedErrorString); expect(applicationContext.logger.error).toHaveBeenCalledTimes(1); @@ -235,15 +247,19 @@ describe('serveCourtIssuedDocumentInteractor consolidated cases', () => { }); it('should create a single source of truth for the document by saving only one copy', async () => { - await serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId, - docketEntryId: leadCaseDocketEntries[0].docketEntryId, - docketNumbers: [ - MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, - MOCK_CONSOLIDATED_2_CASE_WITH_PAPER_SERVICE.docketNumber, - ], - subjectCaseDocketNumber: MOCK_LEAD_CASE_WITH_PAPER_SERVICE.docketNumber, - }); + await serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: leadCaseDocketEntries[0].docketEntryId, + docketNumbers: [ + MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, + MOCK_CONSOLIDATED_2_CASE_WITH_PAPER_SERVICE.docketNumber, + ], + subjectCaseDocketNumber: MOCK_LEAD_CASE_WITH_PAPER_SERVICE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveDocumentFromLambda, diff --git a/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.locking.test.ts b/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.locking.test.ts index 466e9be08a3..670774e07bb 100644 --- a/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.locking.test.ts +++ b/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.locking.test.ts @@ -9,6 +9,7 @@ import { serveCourtIssuedDocumentInteractor, } from './serveCourtIssuedDocumentInteractor'; import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { testPdfDoc } from '../../../../../shared/src/business/test/getFakeFile'; jest.mock('@web-api/business/useCases/addCoverToPdf'); @@ -53,17 +54,16 @@ describe('handleLockError', () => { .getUserById.mockReturnValue(docketClerkUser); }); - it('should determine who the user is based on applicationContext', async () => { - await handleLockError(applicationContext, { foo: 'bar' }); - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); - }); - it('should send a notification to the user with "retry_async_request" and the originalRequest', async () => { const mockOriginalRequest = { clientConnectionId: mockClientConnectionId, foo: 'bar', }; - await handleLockError(applicationContext, mockOriginalRequest); + await handleLockError( + applicationContext, + mockOriginalRequest, + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock .calls[0][0].message, @@ -104,8 +104,6 @@ describe('serveCourtIssuedDocumentInteractor', () => { beforeEach(() => { mockLock = undefined; // unlocked - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getUseCaseHelpers() .fileAndServeDocumentOnOneCase.mockImplementation( @@ -134,7 +132,11 @@ describe('serveCourtIssuedDocumentInteractor', () => { it('should throw a ServiceUnavailableError if a Case is currently locked', async () => { await expect( - serveCourtIssuedDocumentInteractor(applicationContext, mockRequest), + serveCourtIssuedDocumentInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -144,7 +146,11 @@ describe('serveCourtIssuedDocumentInteractor', () => { it('should return a "retry_async_request" notification with the original request', async () => { await expect( - serveCourtIssuedDocumentInteractor(applicationContext, mockRequest), + serveCourtIssuedDocumentInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -157,7 +163,7 @@ describe('serveCourtIssuedDocumentInteractor', () => { originalRequest: mockRequest, requestToRetry: 'serve_court_issued_document', }, - userId: docketClerkUser.userId, + userId: mockDocketClerkUser.userId, }); expect( @@ -172,7 +178,11 @@ describe('serveCourtIssuedDocumentInteractor', () => { }); it('should acquire a lock that lasts for 15 minutes', async () => { - await serveCourtIssuedDocumentInteractor(applicationContext, mockRequest); + await serveCourtIssuedDocumentInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -184,7 +194,11 @@ describe('serveCourtIssuedDocumentInteractor', () => { }); it('should remove the lock', async () => { - await serveCourtIssuedDocumentInteractor(applicationContext, mockRequest); + await serveCourtIssuedDocumentInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().removeLock, diff --git a/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.test.ts b/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.test.ts index 4f8308e3a15..81976784251 100644 --- a/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.test.ts +++ b/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.test.ts @@ -2,11 +2,13 @@ import { AUTO_GENERATED_DEADLINE_DOCUMENT_TYPES } from '../../../../../shared/sr import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_DOCUMENTS } from '../../../../../shared/src/test/mockDocketEntry'; import { MOCK_TRIAL_REGULAR } from '../../../../../shared/src/test/mockTrial'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { docketClerkUser, judgeUser, } from '../../../../../shared/src/test/mockUsers'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { serveCourtIssuedDocumentInteractor } from './serveCourtIssuedDocumentInteractor'; describe('serveCourtIssuedDocumentInteractor', () => { @@ -14,8 +16,6 @@ describe('serveCourtIssuedDocumentInteractor', () => { const mockClientConnectionId = 'ABC123'; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(docketClerkUser); @@ -42,15 +42,17 @@ describe('serveCourtIssuedDocumentInteractor', () => { }); it('should throw an error when the user role does not have permission to serve a court issued document', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: '', - docketNumbers: [], - subjectCaseDocketNumber: '', - }), + serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: '', + docketNumbers: [], + subjectCaseDocketNumber: '', + }, + {} as UnknownAuthUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -60,12 +62,16 @@ describe('serveCourtIssuedDocumentInteractor', () => { .getCaseByDocketNumber.mockReturnValue({}); await expect( - serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: '', - docketNumbers: [], - subjectCaseDocketNumber: MOCK_CASE.docketNumber, - }), + serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: '', + docketNumbers: [], + subjectCaseDocketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(`Case ${MOCK_CASE.docketNumber} was not found`); }); @@ -78,12 +84,16 @@ describe('serveCourtIssuedDocumentInteractor', () => { }); await expect( - serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: MOCK_CASE.docketNumber, - }), + serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(`Docket entry ${mockDocketEntryId} was not found`); }); @@ -101,12 +111,16 @@ describe('serveCourtIssuedDocumentInteractor', () => { }); await expect( - serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: MOCK_CASE.docketNumber, - }), + serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry has already been served'); }); @@ -124,12 +138,16 @@ describe('serveCourtIssuedDocumentInteractor', () => { }); await expect( - serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: MOCK_CASE.docketNumber, - }), + serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry is already being served'); expect( @@ -155,12 +173,16 @@ describe('serveCourtIssuedDocumentInteractor', () => { .getUseCaseHelpers() .countPagesInDocument.mockReturnValue(3256); - await serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: MOCK_CASE.docketNumber, - }); + await serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); const servedDocketEntry = applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -182,12 +204,16 @@ describe('serveCourtIssuedDocumentInteractor', () => { ], }); - await serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockDocketEntryId, - docketNumbers: [MOCK_CASE.docketNumber], - subjectCaseDocketNumber: MOCK_CASE.docketNumber, - }); + await serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockDocketEntryId, + docketNumbers: [MOCK_CASE.docketNumber], + subjectCaseDocketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().autoGenerateDeadline, @@ -218,12 +244,16 @@ describe('serveCourtIssuedDocumentInteractor', () => { ], }); - await serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockDocketEntryId, - docketNumbers: [MOCK_CASE.docketNumber], - subjectCaseDocketNumber: MOCK_CASE.docketNumber, - }); + await serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockDocketEntryId, + docketNumbers: [MOCK_CASE.docketNumber], + subjectCaseDocketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().autoGenerateDeadline.mock @@ -250,12 +280,16 @@ describe('serveCourtIssuedDocumentInteractor', () => { ], }); - await serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: ['200-21', '300-33'], - subjectCaseDocketNumber: MOCK_CASE.docketNumber, - }); + await serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: ['200-21', '300-33'], + subjectCaseDocketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase, @@ -276,12 +310,16 @@ describe('serveCourtIssuedDocumentInteractor', () => { ], }); - await serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: MOCK_CASE.docketNumber, - }); + await serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); const expectedDocketEntry = applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -302,12 +340,16 @@ describe('serveCourtIssuedDocumentInteractor', () => { ], }); - await serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: MOCK_CASE.docketNumber, - }); + await serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -348,12 +390,16 @@ describe('serveCourtIssuedDocumentInteractor', () => { ); await expect( - serveCourtIssuedDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: MOCK_CASE.docketNumber, - }), + serveCourtIssuedDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow('whoops, that is an error!'); expect( diff --git a/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.ts b/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.ts index af115179693..d9aca4768a4 100644 --- a/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.ts +++ b/web-api/src/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor.ts @@ -7,6 +7,7 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { createISODateString } from '../../../../../shared/src/business/utilities/DateHandler'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; @@ -23,9 +24,8 @@ export const serveCourtIssuedDocument = async ( docketNumbers: string[]; subjectCaseDocketNumber: string; }, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); - const hasPermission = (isAuthorized(authorizedUser, ROLE_PERMISSIONS.DOCKET_ENTRY) || isAuthorized( @@ -49,7 +49,7 @@ export const serveCourtIssuedDocument = async ( throw new NotFoundError(`Case ${subjectCaseDocketNumber} was not found.`); } - const subjectCaseEntity = new Case(subjectCase, { applicationContext }); + const subjectCaseEntity = new Case(subjectCase, { authorizedUser }); const docketEntryToServe = subjectCaseEntity.getDocketEntryById({ docketEntryId, @@ -115,7 +115,7 @@ export const serveCourtIssuedDocument = async ( docketNumber, }); - caseEntities.push(new Case(caseToUpdate, { applicationContext })); + caseEntities.push(new Case(caseToUpdate, { authorizedUser })); } caseEntities = await Promise.all( @@ -127,7 +127,7 @@ export const serveCourtIssuedDocument = async ( isOnDocketRecord: true, }, { - applicationContext, + authorizedUser, }, ); @@ -213,19 +213,23 @@ export const determineEntitiesToLock = ( ttl: 15 * 60, }); -export const handleLockError = async (applicationContext, originalRequest) => { - const user = applicationContext.getCurrentUser(); - - await applicationContext.getNotificationGateway().sendNotificationToUser({ - applicationContext, - clientConnectionId: originalRequest.clientConnectionId, - message: { - action: 'retry_async_request', - originalRequest, - requestToRetry: 'serve_court_issued_document', - }, - userId: user.userId, - }); +export const handleLockError = async ( + applicationContext, + originalRequest, + authorizedUser: UnknownAuthUser, +) => { + if (authorizedUser?.userId) { + await applicationContext.getNotificationGateway().sendNotificationToUser({ + applicationContext, + clientConnectionId: originalRequest.clientConnectionId, + message: { + action: 'retry_async_request', + originalRequest, + requestToRetry: 'serve_court_issued_document', + }, + userId: authorizedUser?.userId, + }); + } }; export const serveCourtIssuedDocumentInteractor = withLocking( diff --git a/web-api/src/business/useCases/courtIssuedOrder/appendAmendedPetitionFormInteractor.test.ts b/web-api/src/business/useCases/courtIssuedOrder/appendAmendedPetitionFormInteractor.test.ts index 2452637b918..9c70f91280c 100644 --- a/web-api/src/business/useCases/courtIssuedOrder/appendAmendedPetitionFormInteractor.test.ts +++ b/web-api/src/business/useCases/courtIssuedOrder/appendAmendedPetitionFormInteractor.test.ts @@ -1,9 +1,10 @@ -import { - AMENDED_PETITION_FORM_NAME, - ROLES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { AMENDED_PETITION_FORM_NAME } from '../../../../../shared/src/business/entities/EntityConstants'; import { appendAmendedPetitionFormInteractor } from './appendAmendedPetitionFormInteractor'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { testPdfDoc } from '@shared/business/test/getFakeFile'; describe('appendAmendedPetitionFormInteractor', () => { @@ -11,31 +12,29 @@ describe('appendAmendedPetitionFormInteractor', () => { const mockDocketEntryId = 'd594360c-0514-4acd-a2ac-24a402060756'; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: '432', - }); - applicationContext .getUtilities() .combineTwoPdfs.mockReturnValue(returnedCombinedPdf); }); it('should throw an error when the user is not authorized to modify docket entries', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '432', - }); - await expect( - appendAmendedPetitionFormInteractor(applicationContext, {} as any), + appendAmendedPetitionFormInteractor( + applicationContext, + {} as any, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should use the provided docketEntryId to retrieve the file from s3', async () => { - await appendAmendedPetitionFormInteractor(applicationContext, { - docketEntryId: mockDocketEntryId, - }); + await appendAmendedPetitionFormInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getDocument.mock.calls[0][0] @@ -44,9 +43,13 @@ describe('appendAmendedPetitionFormInteractor', () => { }); it('should make a call to retrieve the amended petition form from s3', async () => { - await appendAmendedPetitionFormInteractor(applicationContext, { - docketEntryId: mockDocketEntryId, - }); + await appendAmendedPetitionFormInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getDocument.mock.calls[1][0] @@ -55,9 +58,13 @@ describe('appendAmendedPetitionFormInteractor', () => { }); it('should make a call to combine the order and form documents', async () => { - await appendAmendedPetitionFormInteractor(applicationContext, { - docketEntryId: mockDocketEntryId, - }); + await appendAmendedPetitionFormInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getUtilities().combineTwoPdfs.mock.calls[0][0], @@ -68,9 +75,13 @@ describe('appendAmendedPetitionFormInteractor', () => { }); it('should use the provided docketEntryId to overwrite the order file in s3', async () => { - await appendAmendedPetitionFormInteractor(applicationContext, { - docketEntryId: mockDocketEntryId, - }); + await appendAmendedPetitionFormInteractor( + applicationContext, + { + docketEntryId: mockDocketEntryId, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().uploadDocument.mock diff --git a/web-api/src/business/useCases/courtIssuedOrder/appendAmendedPetitionFormInteractor.ts b/web-api/src/business/useCases/courtIssuedOrder/appendAmendedPetitionFormInteractor.ts index 4e63d017a3d..70aa388b588 100644 --- a/web-api/src/business/useCases/courtIssuedOrder/appendAmendedPetitionFormInteractor.ts +++ b/web-api/src/business/useCases/courtIssuedOrder/appendAmendedPetitionFormInteractor.ts @@ -5,13 +5,13 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const appendAmendedPetitionFormInteractor = async ( applicationContext: ServerApplicationContext, { docketEntryId }: { docketEntryId: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); - const hasPermission = isAuthorized( authorizedUser, ROLE_PERMISSIONS.EDIT_ORDER, diff --git a/web-api/src/business/useCases/courtIssuedOrder/createCourtIssuedOrderPdfFromHtmlInteractor.test.ts b/web-api/src/business/useCases/courtIssuedOrder/createCourtIssuedOrderPdfFromHtmlInteractor.test.ts index 0d0a263b37d..c142fb004de 100644 --- a/web-api/src/business/useCases/courtIssuedOrder/createCourtIssuedOrderPdfFromHtmlInteractor.test.ts +++ b/web-api/src/business/useCases/courtIssuedOrder/createCourtIssuedOrderPdfFromHtmlInteractor.test.ts @@ -1,6 +1,9 @@ -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { createCourtIssuedOrderPdfFromHtmlInteractor } from './createCourtIssuedOrderPdfFromHtmlInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('createCourtIssuedOrderPdfFromHtmlInteractor', () => { const mockPdfUrl = 'www.example.com'; @@ -26,23 +29,12 @@ describe('createCourtIssuedOrderPdfFromHtmlInteractor', () => { }); }); - beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: '321', - }); - }); - it('throws an error if the user is not authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '432', - }); - await expect( createCourtIssuedOrderPdfFromHtmlInteractor( applicationContext, {} as any, + mockPetitionerUser, ), ).rejects.toThrow('Unauthorized'); }); @@ -50,7 +42,10 @@ describe('createCourtIssuedOrderPdfFromHtmlInteractor', () => { it('fetches the case by id', async () => { await createCourtIssuedOrderPdfFromHtmlInteractor( applicationContext, - {} as any, + { + addedDocketNumbers: [], + } as any, + mockDocketClerkUser, ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -60,8 +55,12 @@ describe('createCourtIssuedOrderPdfFromHtmlInteractor', () => { it('calls the pdf document generator function', async () => { await createCourtIssuedOrderPdfFromHtmlInteractor( applicationContext, - {} as any, + { + addedDocketNumbers: [], + } as any, + mockDocketClerkUser, ); + expect( applicationContext.getDocumentGenerators().order, ).toHaveBeenCalledWith( @@ -76,7 +75,10 @@ describe('createCourtIssuedOrderPdfFromHtmlInteractor', () => { it('returns the pdf url from the temp documents bucket', async () => { const result = await createCourtIssuedOrderPdfFromHtmlInteractor( applicationContext, - {} as any, + { + addedDocketNumbers: [], + } as any, + mockDocketClerkUser, ); expect( @@ -91,6 +93,7 @@ describe('createCourtIssuedOrderPdfFromHtmlInteractor', () => { { addedDocketNumbers: ['101-20'], } as any, + mockDocketClerkUser, ); expect( @@ -107,8 +110,10 @@ describe('createCourtIssuedOrderPdfFromHtmlInteractor', () => { const result = await createCourtIssuedOrderPdfFromHtmlInteractor( applicationContext, { + addedDocketNumbers: [], eventCode: 'NOT', } as any, + mockDocketClerkUser, ); expect( @@ -125,9 +130,14 @@ describe('createCourtIssuedOrderPdfFromHtmlInteractor', () => { }); it('calls the generate the order pdf WITHOUT a defined name or title of the clerk for non-NOT event codes', async () => { - await createCourtIssuedOrderPdfFromHtmlInteractor(applicationContext, { - eventCode: 'O', - } as any); + await createCourtIssuedOrderPdfFromHtmlInteractor( + applicationContext, + { + addedDocketNumbers: [], + eventCode: 'O', + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getConfigurationItemValue, @@ -144,4 +154,37 @@ describe('createCourtIssuedOrderPdfFromHtmlInteractor', () => { }), ); }); + + describe('BUG: Order the Docket Numbers', () => { + it('should order the docket numbers correctly by year and index', async () => { + await createCourtIssuedOrderPdfFromHtmlInteractor( + applicationContext, + { + addedDocketNumbers: [ + '101-24', + '101-19', + '103-19', + '101-26', + '101-16', + '102-19', + '101-20', + ], + } as any, + mockDocketClerkUser, + ); + + const orderCalls = + applicationContext.getDocumentGenerators().order.mock.calls; + expect(orderCalls.length).toEqual(1); + expect(orderCalls[0][0].data.addedDocketNumbers).toEqual([ + '101-16', + '101-19', + '102-19', + '103-19', + '101-20', + '101-24', + '101-26', + ]); + }); + }); }); diff --git a/web-api/src/business/useCases/courtIssuedOrder/createCourtIssuedOrderPdfFromHtmlInteractor.ts b/web-api/src/business/useCases/courtIssuedOrder/createCourtIssuedOrderPdfFromHtmlInteractor.ts index 91a5238ba8d..47fcf0b5f46 100644 --- a/web-api/src/business/useCases/courtIssuedOrder/createCourtIssuedOrderPdfFromHtmlInteractor.ts +++ b/web-api/src/business/useCases/courtIssuedOrder/createCourtIssuedOrderPdfFromHtmlInteractor.ts @@ -2,12 +2,14 @@ import { CLERK_OF_THE_COURT_CONFIGURATION, NOTICE_EVENT_CODE, } from '@shared/business/entities/EntityConstants'; +import { Case } from '@shared/business/entities/cases/Case'; import { ROLE_PERMISSIONS, isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { getCaseCaptionMeta } from '../../../../../shared/src/business/utilities/getCaseCaptionMeta'; export const createCourtIssuedOrderPdfFromHtmlInteractor = async ( @@ -25,13 +27,12 @@ export const createCourtIssuedOrderPdfFromHtmlInteractor = async ( documentTitle: string; eventCode: string; }, + authorizedUser: UnknownAuthUser, ): Promise<{ fileId: string; url: string; }> => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.COURT_ISSUED_DOCUMENT)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.COURT_ISSUED_DOCUMENT)) { throw new UnauthorizedError('Unauthorized'); } @@ -64,7 +65,9 @@ export const createCourtIssuedOrderPdfFromHtmlInteractor = async ( const orderPdf = await applicationContext.getDocumentGenerators().order({ applicationContext, data: { - addedDocketNumbers, + addedDocketNumbers: addedDocketNumbers.sort((a, b) => + Case.docketNumberSort(a, b), + ), caseCaptionExtension, caseTitle, docketNumberWithSuffix, diff --git a/web-api/src/business/useCases/courtIssuedOrder/fileCourtIssuedOrderInteractor.test.ts b/web-api/src/business/useCases/courtIssuedOrder/fileCourtIssuedOrderInteractor.test.ts index 129fb7f5318..a84d6940c77 100644 --- a/web-api/src/business/useCases/courtIssuedOrder/fileCourtIssuedOrderInteractor.test.ts +++ b/web-api/src/business/useCases/courtIssuedOrder/fileCourtIssuedOrderInteractor.test.ts @@ -14,6 +14,10 @@ import { User } from '../../../../../shared/src/business/entities/User'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { fileCourtIssuedOrderInteractor } from './fileCourtIssuedOrderInteractor'; import { getMessageThreadByParentId } from '@web-api/persistence/postgres/messages/getMessageThreadByParentId'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { updateMessage } from '@web-api/persistence/postgres/messages/updateMessage'; describe('fileCourtIssuedOrderInteractor', () => { @@ -84,13 +88,6 @@ describe('fileCourtIssuedOrderInteractor', () => { beforeEach(() => { mockLock = undefined; - applicationContext.getCurrentUser.mockReturnValue( - new User({ - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.petitionsClerk, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), - ); applicationContext.getPersistenceGateway().getUserById.mockReturnValue( new User({ @@ -106,32 +103,38 @@ describe('fileCourtIssuedOrderInteractor', () => { }); it('should throw an error if not authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - fileCourtIssuedOrderInteractor(applicationContext, { + fileCourtIssuedOrderInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentType: 'Order to Show Cause', + eventCode: 'OSC', + }, + primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockPetitionerUser, + ), + ).rejects.toThrow('Unauthorized'); + }); + + it('should add order document to case', async () => { + await fileCourtIssuedOrderInteractor( + applicationContext, + { documentMetadata: { docketNumber: caseRecord.docketNumber, documentType: 'Order to Show Cause', eventCode: 'OSC', + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', }, primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), - ).rejects.toThrow('Unauthorized'); - }); - - it('should add order document to case', async () => { - await fileCourtIssuedOrderInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentType: 'Order to Show Cause', - eventCode: 'OSC', - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', }, - primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -143,19 +146,23 @@ describe('fileCourtIssuedOrderInteractor', () => { }); it('should add order document to case and set freeText and draftOrderState.freeText to the document title if it is a generic order (eventCode O)', async () => { - await fileCourtIssuedOrderInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'Order to do anything', - documentType: 'Order', - draftOrderState: {}, - eventCode: 'O', - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', + await fileCourtIssuedOrderInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'Order to do anything', + documentType: 'Order', + draftOrderState: {}, + eventCode: 'O', + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', + }, + primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }, - primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -174,24 +181,28 @@ describe('fileCourtIssuedOrderInteractor', () => { }); it('should delete draftOrderState properties if they exists on the documentMetadata, after saving the document', async () => { - await fileCourtIssuedOrderInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentContents: {}, - documentTitle: 'Order to do anything', - documentType: 'Order', - draftOrderState: { - documentContents: 'something', - editorDelta: 'something', - richText: 'something', + await fileCourtIssuedOrderInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentContents: {}, + documentTitle: 'Order to do anything', + documentType: 'Order', + draftOrderState: { + documentContents: 'something', + editorDelta: 'something', + richText: 'something', + }, + eventCode: 'O', + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', }, - eventCode: 'O', - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', + primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }, - primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -208,18 +219,22 @@ describe('fileCourtIssuedOrderInteractor', () => { }); it('should add a generic notice document to case, set freeText to the document title, and set the document to signed', async () => { - await fileCourtIssuedOrderInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'Notice to be nice', - documentType: 'Notice', - eventCode: 'NOT', - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', + await fileCourtIssuedOrderInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'Notice to be nice', + documentType: 'Notice', + eventCode: 'NOT', + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', + }, + primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }, - primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -236,18 +251,22 @@ describe('fileCourtIssuedOrderInteractor', () => { }); it('should store documentMetadata.documentContents in S3 and delete from data sent to persistence', async () => { - await fileCourtIssuedOrderInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentContents: 'I am some document contents', - documentType: 'Order to Show Cause', - eventCode: 'OSC', - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', + await fileCourtIssuedOrderInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentContents: 'I am some document contents', + documentType: 'Order to Show Cause', + eventCode: 'OSC', + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', + }, + primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }, - primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveDocumentFromLambda.mock @@ -269,18 +288,22 @@ describe('fileCourtIssuedOrderInteractor', () => { }); it('should append docket number with suffix and case caption to document contents before storing', async () => { - await fileCourtIssuedOrderInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentContents: 'I am some document contents', - documentType: 'Order to Show Cause', - eventCode: 'OSC', - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', + await fileCourtIssuedOrderInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentContents: 'I am some document contents', + documentType: 'Order to Show Cause', + eventCode: 'OSC', + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', + }, + primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }, - primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + mockDocketClerkUser, + ); const savedDocumentContents = JSON.parse( applicationContext @@ -293,18 +316,22 @@ describe('fileCourtIssuedOrderInteractor', () => { }); it('should append the docket number and case caption to the document contents if document contents was defined', async () => { - await fileCourtIssuedOrderInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentContents: 'hello', - documentType: 'Order to Show Cause', - eventCode: 'OSC', - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', + await fileCourtIssuedOrderInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentContents: 'hello', + documentType: 'Order to Show Cause', + eventCode: 'OSC', + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', + }, + primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }, - primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + mockDocketClerkUser, + ); const savedDocumentContents = JSON.parse( applicationContext @@ -336,19 +363,23 @@ describe('fileCourtIssuedOrderInteractor', () => { }, ]); - await fileCourtIssuedOrderInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'Order to do anything', - documentType: 'Order', - eventCode: 'O', - parentMessageId: '6c1fd626-c1e1-4367-bca6-e00f9ef98cf5', - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', + await fileCourtIssuedOrderInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'Order to do anything', + documentType: 'Order', + eventCode: 'O', + parentMessageId: '6c1fd626-c1e1-4367-bca6-e00f9ef98cf5', + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', + }, + primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }, - primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + mockDocketClerkUser, + ); expect(updateMessage).toHaveBeenCalled(); expect( @@ -384,19 +415,23 @@ describe('fileCourtIssuedOrderInteractor', () => { }, ]); - await fileCourtIssuedOrderInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'Order to do anything', - documentType: 'Order', - eventCode: 'O', - parentMessageId: '6c1fd626-c1e1-4367-bca6-e00f9ef98cf5', - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', + await fileCourtIssuedOrderInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'Order to do anything', + documentType: 'Order', + eventCode: 'O', + parentMessageId: '6c1fd626-c1e1-4367-bca6-e00f9ef98cf5', + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', + }, + primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }, - primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + mockDocketClerkUser, + ); const lastDocumentIndex = applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -415,7 +450,33 @@ describe('fileCourtIssuedOrderInteractor', () => { mockLock = MOCK_LOCK; await expect( - fileCourtIssuedOrderInteractor(applicationContext, { + fileCourtIssuedOrderInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentContents: 'I am some document contents', + documentType: 'Order to Show Cause', + eventCode: 'OSC', + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', + }, + primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ), + ).rejects.toThrow(ServiceUnavailableError); + + expect( + applicationContext.getPersistenceGateway().getCaseByDocketNumber, + ).not.toHaveBeenCalled(); + }); + + it('should acquire and remove the lock on the case', async () => { + await fileCourtIssuedOrderInteractor( + applicationContext, + { documentMetadata: { docketNumber: caseRecord.docketNumber, documentContents: 'I am some document contents', @@ -426,27 +487,9 @@ describe('fileCourtIssuedOrderInteractor', () => { signedJudgeName: 'Dredd', }, primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), - ).rejects.toThrow(ServiceUnavailableError); - - expect( - applicationContext.getPersistenceGateway().getCaseByDocketNumber, - ).not.toHaveBeenCalled(); - }); - - it('should acquire and remove the lock on the case', async () => { - await fileCourtIssuedOrderInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentContents: 'I am some document contents', - documentType: 'Order to Show Cause', - eventCode: 'OSC', - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', }, - primaryDocumentFileId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/courtIssuedOrder/fileCourtIssuedOrderInteractor.ts b/web-api/src/business/useCases/courtIssuedOrder/fileCourtIssuedOrderInteractor.ts index 9805e59f232..b7402b20a36 100644 --- a/web-api/src/business/useCases/courtIssuedOrder/fileCourtIssuedOrderInteractor.ts +++ b/web-api/src/business/useCases/courtIssuedOrder/fileCourtIssuedOrderInteractor.ts @@ -8,6 +8,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { getMessageThreadByParentId } from '@web-api/persistence/postgres/messages/getMessageThreadByParentId'; import { orderBy, some } from 'lodash'; import { updateMessage } from '@web-api/persistence/postgres/messages/updateMessage'; @@ -19,8 +20,8 @@ export const fileCourtIssuedOrder = async ( documentMetadata, primaryDocumentFileId, }: { documentMetadata: any; primaryDocumentFileId: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); const { docketNumber } = documentMetadata; if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.COURT_ISSUED_DOCUMENT)) { @@ -37,7 +38,7 @@ export const fileCourtIssuedOrder = async ( applicationContext, docketNumber, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); if (['O', 'NOT'].includes(documentMetadata.eventCode)) { documentMetadata.freeText = documentMetadata.documentTitle; @@ -87,7 +88,7 @@ export const fileCourtIssuedOrder = async ( isFileAttached: true, relationship: DOCUMENT_RELATIONSHIPS.PRIMARY, }, - { applicationContext }, + { authorizedUser }, ); docketEntryEntity.setFiledBy(user); @@ -98,6 +99,7 @@ export const fileCourtIssuedOrder = async ( await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); diff --git a/web-api/src/business/useCases/courtIssuedOrder/updateCourtIssuedOrderInteractor.test.ts b/web-api/src/business/useCases/courtIssuedOrder/updateCourtIssuedOrderInteractor.test.ts index bb048b01b37..ffd804e606b 100644 --- a/web-api/src/business/useCases/courtIssuedOrder/updateCourtIssuedOrderInteractor.test.ts +++ b/web-api/src/business/useCases/courtIssuedOrder/updateCourtIssuedOrderInteractor.test.ts @@ -8,14 +8,17 @@ import { import { Case } from '@shared/business/entities/cases/Case'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; import { ServiceUnavailableError } from '@web-api/errors/errors'; -import { User } from '../../../../../shared/src/business/entities/User'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; import { updateCourtIssuedOrderInteractor } from './updateCourtIssuedOrderInteractor'; describe('updateCourtIssuedOrderInteractor', () => { - let mockCurrentUser; - let mockUserById; const mockUserId = applicationContext.getUniqueId(); + let mockUserById; let caseRecord = { caseCaption: 'Caption', @@ -83,14 +86,6 @@ describe('updateCourtIssuedOrderInteractor', () => { beforeEach(() => { mockLock = undefined; - mockCurrentUser = new User({ - name: 'Naveen Jaron', - role: ROLES.petitionsClerk, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); - - applicationContext.getCurrentUser.mockImplementation(() => mockCurrentUser); - mockUserById = { name: 'bob', userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', @@ -106,18 +101,22 @@ describe('updateCourtIssuedOrderInteractor', () => { }); it('should throw an error if not authorized', async () => { - mockCurrentUser.role = ROLES.privatePractitioner; + // mockCurrentUser.role = ROLES.privatePractitioner; mockUserById = { name: 'bob' }; await expect( - updateCourtIssuedOrderInteractor(applicationContext, { - docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentType: 'Order to Show Cause', - eventCode: 'OSC', + updateCourtIssuedOrderInteractor( + applicationContext, + { + docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentType: 'Order to Show Cause', + eventCode: 'OSC', + }, }, - }), + mockPrivatePractitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -125,31 +124,39 @@ describe('updateCourtIssuedOrderInteractor', () => { applicationContext.getPersistenceGateway().getUserById.mockResolvedValue(); await expect( - updateCourtIssuedOrderInteractor(applicationContext, { - docketEntryIdToEdit: '986fece3-6325-4418-bb28-a7095e6707b4', - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentType: 'Order to Show Cause', - eventCode: 'OSC', + updateCourtIssuedOrderInteractor( + applicationContext, + { + docketEntryIdToEdit: '986fece3-6325-4418-bb28-a7095e6707b4', + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentType: 'Order to Show Cause', + eventCode: 'OSC', + }, }, - }), + mockPetitionsClerkUser, + ), ).rejects.toThrow('Document not found'); }); it('update existing document within case', async () => { - await updateCourtIssuedOrderInteractor(applicationContext, { - docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'Order of Dismissal for Lack of Jurisdiction', - documentType: 'Notice', - draftOrderState: { - documentType: 'Order of Dismissal for Lack of Jurisdiction', - eventCode: 'ODJ', + await updateCourtIssuedOrderInteractor( + applicationContext, + { + docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'Order of Dismissal for Lack of Jurisdiction', + documentType: 'Notice', + draftOrderState: { + documentType: 'Order of Dismissal for Lack of Jurisdiction', + eventCode: 'ODJ', + }, + eventCode: 'NOT', }, - eventCode: 'NOT', }, - }); + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -178,19 +185,23 @@ describe('updateCourtIssuedOrderInteractor', () => { it('should not populate free text for OSCP', async () => { const mockDocumentTitle = 'Order to Show Cause Title'; - await updateCourtIssuedOrderInteractor(applicationContext, { - docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: mockDocumentTitle, - documentType: 'Notice', - draftOrderState: { - documentType: 'Order to Show Cause', - eventCode: 'OSCP', + await updateCourtIssuedOrderInteractor( + applicationContext, + { + docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: mockDocumentTitle, + documentType: 'Notice', + draftOrderState: { + documentType: 'Order to Show Cause', + eventCode: 'OSCP', + }, + eventCode: 'NOT', }, - eventCode: 'NOT', }, - }); + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -217,19 +228,23 @@ describe('updateCourtIssuedOrderInteractor', () => { it('should not populate free text for OF', async () => { const mockDocumentTitle = 'Order for Filing Fee Title'; - await updateCourtIssuedOrderInteractor(applicationContext, { - docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: mockDocumentTitle, - documentType: 'Notice', - draftOrderState: { - documentType: 'Order for Filing Fee', - eventCode: 'OF', + await updateCourtIssuedOrderInteractor( + applicationContext, + { + docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: mockDocumentTitle, + documentType: 'Notice', + draftOrderState: { + documentType: 'Order for Filing Fee', + eventCode: 'OF', + }, + eventCode: 'NOT', }, - eventCode: 'NOT', }, - }); + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -255,19 +270,23 @@ describe('updateCourtIssuedOrderInteractor', () => { it('should not populate free text for OAP', async () => { const mockDocumentTitle = 'Order for Amended Petition Title'; - await updateCourtIssuedOrderInteractor(applicationContext, { - docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: mockDocumentTitle, - documentType: 'Notice', - draftOrderState: { - documentType: 'Order for Amended Petition', - eventCode: 'OAP', + await updateCourtIssuedOrderInteractor( + applicationContext, + { + docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: mockDocumentTitle, + documentType: 'Notice', + draftOrderState: { + documentType: 'Order for Amended Petition', + eventCode: 'OAP', + }, + eventCode: 'NOT', }, - eventCode: 'NOT', }, - }); + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -292,15 +311,19 @@ describe('updateCourtIssuedOrderInteractor', () => { }); it('should not update freeText on existing document within case if not an order type', async () => { - await updateCourtIssuedOrderInteractor(applicationContext, { - docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'Notice Title', - documentType: 'Notice', - eventCode: 'A', + await updateCourtIssuedOrderInteractor( + applicationContext, + { + docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'Notice Title', + documentType: 'Notice', + eventCode: 'A', + }, }, - }); + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -327,23 +350,27 @@ describe('updateCourtIssuedOrderInteractor', () => { }); it('stores documentContents in S3 if present', async () => { - await updateCourtIssuedOrderInteractor(applicationContext, { - docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentContents: 'the contents!', - documentType: 'Order to Show Cause', - draftOrderState: { + await updateCourtIssuedOrderInteractor( + applicationContext, + { + docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: caseRecord.docketNumber, documentContents: 'the contents!', + documentType: 'Order to Show Cause', + draftOrderState: { + documentContents: 'the contents!', + richText: 'the contents!', + }, + eventCode: 'OSC', richText: 'the contents!', + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', }, - eventCode: 'OSC', - richText: 'the contents!', - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', }, - }); + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveDocumentFromLambda.mock @@ -362,32 +389,36 @@ describe('updateCourtIssuedOrderInteractor', () => { it('should still contain the case caption in documentContents when edited', async () => { let mockContents = 'the contents!'; - await updateCourtIssuedOrderInteractor(applicationContext, { - docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentContents: mockContents, - documentType: 'Order to Show Cause', - draftOrderState: { + await updateCourtIssuedOrderInteractor( + applicationContext, + { + docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: caseRecord.docketNumber, documentContents: mockContents, + documentType: 'Order to Show Cause', + draftOrderState: { + documentContents: mockContents, + richText: 'the contents!', + }, + eventCode: 'OSC', richText: 'the contents!', + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', }, - eventCode: 'OSC', - richText: 'the contents!', - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', }, - }); + mockPetitionsClerkUser, + ); - const newCaseEntity = new Case(caseRecord, { applicationContext }); + const newCaseEntity = new Case(caseRecord, { + authorizedUser: mockPetitionerUser, + }); const expectedDocumentContents = mockContents + ` ${newCaseEntity.docketNumberWithSuffix} ${newCaseEntity.caseCaption}`; - console.log('expectedDocumentContents', expectedDocumentContents); - const expectedContentsToStore = { documentContents: expectedDocumentContents, richText: `${mockContents}`, @@ -402,16 +433,20 @@ describe('updateCourtIssuedOrderInteractor', () => { }); it('does not update non-editable fields on document', async () => { - await updateCourtIssuedOrderInteractor(applicationContext, { - docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentType: 'Order to Show Cause', - draftOrderState: undefined, - eventCode: 'OSC', - judge: 'Judge Judgy', + await updateCourtIssuedOrderInteractor( + applicationContext, + { + docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentType: 'Order to Show Cause', + draftOrderState: undefined, + eventCode: 'OSC', + judge: 'Judge Judgy', + }, }, - }); + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -426,19 +461,23 @@ describe('updateCourtIssuedOrderInteractor', () => { mockLock = MOCK_LOCK; await expect( - updateCourtIssuedOrderInteractor(applicationContext, { - docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'Order of Dismissal for Lack of Jurisdiction', - documentType: 'Notice', - draftOrderState: { - documentType: 'Order of Dismissal for Lack of Jurisdiction', - eventCode: 'ODJ', + updateCourtIssuedOrderInteractor( + applicationContext, + { + docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'Order of Dismissal for Lack of Jurisdiction', + documentType: 'Notice', + draftOrderState: { + documentType: 'Order of Dismissal for Lack of Jurisdiction', + eventCode: 'ODJ', + }, + eventCode: 'NOT', }, - eventCode: 'NOT', }, - }), + mockPetitionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -447,19 +486,23 @@ describe('updateCourtIssuedOrderInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await updateCourtIssuedOrderInteractor(applicationContext, { - docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'Order of Dismissal for Lack of Jurisdiction', - documentType: 'Notice', - draftOrderState: { - documentType: 'Order of Dismissal for Lack of Jurisdiction', - eventCode: 'ODJ', + await updateCourtIssuedOrderInteractor( + applicationContext, + { + docketEntryIdToEdit: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'Order of Dismissal for Lack of Jurisdiction', + documentType: 'Notice', + draftOrderState: { + documentType: 'Order of Dismissal for Lack of Jurisdiction', + eventCode: 'ODJ', + }, + eventCode: 'NOT', }, - eventCode: 'NOT', }, - }); + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/courtIssuedOrder/updateCourtIssuedOrderInteractor.ts b/web-api/src/business/useCases/courtIssuedOrder/updateCourtIssuedOrderInteractor.ts index 0b67c06f6fb..e43f1042615 100644 --- a/web-api/src/business/useCases/courtIssuedOrder/updateCourtIssuedOrderInteractor.ts +++ b/web-api/src/business/useCases/courtIssuedOrder/updateCourtIssuedOrderInteractor.ts @@ -10,22 +10,15 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { get } from 'lodash'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; -/** - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {object} providers.docketEntryIdToEdit the id of the docket entry to update - * @param {object} providers.documentMetadata the document metadata - * @returns {Promise<*>} the updated case entity after the document is updated - */ export const updateCourtIssuedOrder = async ( - applicationContext, + applicationContext: ServerApplicationContext, { docketEntryIdToEdit, documentMetadata }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); const { docketNumber } = documentMetadata; if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.COURT_ISSUED_DOCUMENT)) { @@ -43,7 +36,7 @@ export const updateCourtIssuedOrder = async ( docketNumber, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); const currentDocument = caseEntity.getDocketEntryById({ docketEntryId: docketEntryIdToEdit, @@ -115,7 +108,7 @@ export const updateCourtIssuedOrder = async ( numberOfPages, relationship: DOCUMENT_RELATIONSHIPS.PRIMARY, }, - { applicationContext }, + { authorizedUser }, ); docketEntryEntity.setFiledBy(user); @@ -131,10 +124,11 @@ export const updateCourtIssuedOrder = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); - return new Case(result, { applicationContext }).validate().toRawObject(); + return new Case(result, { authorizedUser }).validate().toRawObject(); }; export const updateCourtIssuedOrderInteractor = withLocking( diff --git a/web-api/src/business/useCases/createCaseFromPaperInteractor.test.ts b/web-api/src/business/useCases/createCaseFromPaperInteractor.test.ts index aa75a280cfc..7278ba35957 100644 --- a/web-api/src/business/useCases/createCaseFromPaperInteractor.test.ts +++ b/web-api/src/business/useCases/createCaseFromPaperInteractor.test.ts @@ -10,10 +10,13 @@ import { ROLES, } from '../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; -import { User } from '../../../../shared/src/business/entities/User'; import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; import { createCaseFromPaperInteractor } from './createCaseFromPaperInteractor'; import { createISODateString } from '@shared/business/utilities/DateHandler'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; jest.mock('@shared/business/utilities/DateHandler', () => { const originalModule = jest.requireActual( @@ -28,11 +31,7 @@ jest.mock('@shared/business/utilities/DateHandler', () => { describe('createCaseFromPaperInteractor', () => { const date = '2018-11-21T20:49:28.192Z'; - let user = new User({ - name: 'Test Petitionsclerk', - role: ROLES.petitionsClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); + const mockCreateIsoDateString = createISODateString as jest.Mock; mockCreateIsoDateString.mockReturnValue(date); beforeEach(() => { @@ -40,7 +39,6 @@ describe('createCaseFromPaperInteractor', () => { '00101-00', ); applicationContext.environment.stage = 'local'; - applicationContext.getCurrentUser.mockReturnValue(user); applicationContext .getUseCaseHelpers() @@ -68,10 +66,12 @@ describe('createCaseFromPaperInteractor', () => { }); it('throws an error if the user is not valid or authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - createCaseFromPaperInteractor(applicationContext, {} as any), + createCaseFromPaperInteractor( + applicationContext, + {} as any, + mockPetitionerUser, + ), ).rejects.toThrow(new UnauthorizedError('Unauthorized')); }); @@ -120,10 +120,11 @@ describe('createCaseFromPaperInteractor', () => { }, requestForPlaceOfTrialFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', } as any, + mockPetitionsClerkUser, ); const expectedCaseStatus = { - changedBy: user.name, + changedBy: mockPetitionsClerkUser.name, date: createISODateString(), updatedCaseStatus: CASE_STATUS_TYPES.new, }; @@ -172,6 +173,7 @@ describe('createCaseFromPaperInteractor', () => { receivedAt: applicationContext.getUtilities().createISODateString(), }, } as any, + mockPetitionsClerkUser, ); const applicationForWaiverOfFilingFeeDocketEntry = @@ -235,6 +237,7 @@ describe('createCaseFromPaperInteractor', () => { receivedAt: applicationContext.getUtilities().createISODateString(), }, } as any, + mockPetitionsClerkUser, ); const corporateDisclosureDocketEntry = caseFromPaper.docketEntries.find( @@ -292,6 +295,7 @@ describe('createCaseFromPaperInteractor', () => { }, stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', } as any, + mockPetitionsClerkUser, ); const stinDocketEntry = caseFromPaper.docketEntries.find( @@ -352,6 +356,7 @@ describe('createCaseFromPaperInteractor', () => { }, requestForPlaceOfTrialFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', } as any, + mockPetitionsClerkUser, ); const rqtDocketEntry = caseFromPaper.docketEntries.find( @@ -408,6 +413,7 @@ describe('createCaseFromPaperInteractor', () => { receivedAt: applicationContext.getUtilities().createISODateString(), }, } as any, + mockPetitionsClerkUser, ); const atpDocketEntry = caseFromPaper.docketEntries.find( @@ -484,6 +490,7 @@ describe('createCaseFromPaperInteractor', () => { requestForPlaceOfTrialFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', } as any, + mockPetitionsClerkUser, ); expect(caseFromPaper).toBeDefined(); @@ -535,6 +542,7 @@ describe('createCaseFromPaperInteractor', () => { }, requestForPlaceOfTrialFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', } as any, + mockPetitionsClerkUser, ); const reqForPlaceOfTrialDocketEntry = caseFromPaper.docketEntries.find( diff --git a/web-api/src/business/useCases/createCaseFromPaperInteractor.ts b/web-api/src/business/useCases/createCaseFromPaperInteractor.ts index c6110229d12..ac579205f1f 100644 --- a/web-api/src/business/useCases/createCaseFromPaperInteractor.ts +++ b/web-api/src/business/useCases/createCaseFromPaperInteractor.ts @@ -12,16 +12,15 @@ import { import { RawUser } from '@shared/business/entities/User'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '../../errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { WorkItem } from '../../../../shared/src/business/entities/WorkItem'; import { replaceBracketed } from '../../../../shared/src/business/utilities/replaceBracketed'; const addPetitionDocketEntryWithWorkItemToCase = ({ - applicationContext, caseToAdd, docketEntryEntity, user, }: { - applicationContext: ServerApplicationContext; caseToAdd: Case; docketEntryEntity: DocketEntry; user: RawUser; @@ -51,8 +50,7 @@ const addPetitionDocketEntryWithWorkItemToCase = ({ trialDate: caseToAdd.trialDate, trialLocation: caseToAdd.trialLocation, }, - { applicationContext }, - caseToAdd, + { caseEntity: caseToAdd }, ); docketEntryEntity.setWorkItem(workItemEntity); @@ -82,9 +80,8 @@ export const createCaseFromPaperInteractor = async ( requestForPlaceOfTrialFileId?: string; stinFileId?: string; }, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.START_PAPER_CASE)) { throw new UnauthorizedError('Unauthorized'); } @@ -94,7 +91,7 @@ export const createCaseFromPaperInteractor = async ( .getUserById({ applicationContext, userId: authorizedUser.userId }); const petitionEntity = new PaperPetition(petitionMetadata, { - applicationContext, + authorizedUser, }).validate(); const docketNumber = @@ -112,7 +109,7 @@ export const createCaseFromPaperInteractor = async ( userId: user.userId, }, { - applicationContext, + authorizedUser, isNewCase: true, }, ); @@ -143,13 +140,12 @@ export const createCaseFromPaperInteractor = async ( mailingDate: petitionEntity.mailingDate, receivedAt: caseToAdd.receivedAt, }, - { applicationContext, petitioners: caseToAdd.petitioners }, + { authorizedUser, petitioners: caseToAdd.petitioners }, ); petitionDocketEntryEntity.setFiledBy(user); const { workItem: newWorkItem } = addPetitionDocketEntryWithWorkItemToCase({ - applicationContext, caseToAdd, docketEntryEntity: petitionDocketEntryEntity, user, @@ -175,7 +171,7 @@ export const createCaseFromPaperInteractor = async ( mailingDate: petitionEntity.mailingDate, receivedAt: caseToAdd.receivedAt, }, - { applicationContext, petitioners: caseToAdd.petitioners }, + { authorizedUser, petitioners: caseToAdd.petitioners }, ); applicationForWaiverOfFilingFeeDocketEntryEntity.setFiledBy(user); @@ -208,7 +204,7 @@ export const createCaseFromPaperInteractor = async ( mailingDate: petitionEntity.mailingDate, receivedAt: caseToAdd.receivedAt, }, - { applicationContext, petitioners: caseToAdd.petitioners }, + { authorizedUser, petitioners: caseToAdd.petitioners }, ); requestForPlaceOfTrialDocketEntryEntity.setFiledBy(user); @@ -232,7 +228,7 @@ export const createCaseFromPaperInteractor = async ( mailingDate: petitionEntity.mailingDate, receivedAt: caseToAdd.receivedAt, }, - { applicationContext, petitioners: caseToAdd.petitioners }, + { authorizedUser, petitioners: caseToAdd.petitioners }, ); stinDocketEntryEntity.setFiledBy(user); @@ -255,7 +251,7 @@ export const createCaseFromPaperInteractor = async ( mailingDate: petitionEntity.mailingDate, receivedAt: caseToAdd.receivedAt, }, - { applicationContext, petitioners: caseToAdd.petitioners }, + { authorizedUser, petitioners: caseToAdd.petitioners }, ); cdsDocketEntryEntity.setFiledBy(user); @@ -279,7 +275,7 @@ export const createCaseFromPaperInteractor = async ( mailingDate: petitionEntity.mailingDate, receivedAt: caseToAdd.receivedAt, }, - { applicationContext, petitioners: caseToAdd.petitioners }, + { authorizedUser, petitioners: caseToAdd.petitioners }, ); atpDocketEntryEntity.setFiledBy(user); @@ -290,6 +286,7 @@ export const createCaseFromPaperInteractor = async ( await Promise.all([ applicationContext.getUseCaseHelpers().createCaseAndAssociations({ applicationContext, + authorizedUser, caseToCreate: caseToAdd.validate().toRawObject(), }), applicationContext.getPersistenceGateway().saveWorkItem({ @@ -298,5 +295,5 @@ export const createCaseFromPaperInteractor = async ( }), ]); - return new Case(caseToAdd, { applicationContext }).toRawObject(); + return new Case(caseToAdd, { authorizedUser }).toRawObject(); }; diff --git a/web-api/src/business/useCases/createCaseInteractor.test.ts b/web-api/src/business/useCases/createCaseInteractor.test.ts index d14ef2df043..1ccd9e0c555 100644 --- a/web-api/src/business/useCases/createCaseInteractor.test.ts +++ b/web-api/src/business/useCases/createCaseInteractor.test.ts @@ -63,12 +63,12 @@ describe('createCaseInteractor', () => { beforeEach(() => { user = new User({ + email: 'tom.petitioner@example.com', name: 'Test Petitioner', role: ROLES.petitioner, userId: '6805d1ab-18d0-43ec-bafb-654e83405416', }); - applicationContext.getCurrentUser.mockImplementation(() => user); applicationContext.docketNumberGenerator.createDocketNumber.mockResolvedValue( '00101-00', ); @@ -86,18 +86,22 @@ describe('createCaseInteractor', () => { user = {}; await expect( - createCaseInteractor(applicationContext, { - petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', - petitionMetadata: { - caseType: CASE_TYPES_MAP.other, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.petitioner, - preferredTrialCity: 'Fresno, California', - procedureType: 'Small', - }, - stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', - } as any), + createCaseInteractor( + applicationContext, + { + petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', + petitionMetadata: { + caseType: CASE_TYPES_MAP.other, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.petitioner, + preferredTrialCity: 'Fresno, California', + procedureType: 'Small', + }, + stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', + } as any, + user, + ), ).rejects.toThrow('Unauthorized'); expect( applicationContext.getUseCaseHelpers().createCaseAndAssociations, @@ -108,11 +112,15 @@ describe('createCaseInteractor', () => { }); it('should create a case (with a case status history) successfully as a petitioner', async () => { - const result = await createCaseInteractor(applicationContext, { - petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', - petitionMetadata: mockPetitionMetadata, - stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', - } as any); + const result = await createCaseInteractor( + applicationContext, + { + petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', + petitionMetadata: mockPetitionMetadata, + stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', + } as any, + user, + ); expect(result).toBeDefined(); expect( @@ -138,16 +146,21 @@ describe('createCaseInteractor', () => { it('should create a case (with a case status history) successfully as a private practitioner', async () => { user = { barNumber: 'BN1234', + email: 'privateprac@example.com', name: 'Attorney One', role: ROLES.privatePractitioner, userId: '330d4b65-620a-489d-8414-6623653ebc4f', }; - const result = await createCaseInteractor(applicationContext, { - petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', - petitionMetadata: mockPetitionMetadata, - stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', - } as any); + const result = await createCaseInteractor( + applicationContext, + { + petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', + petitionMetadata: mockPetitionMetadata, + stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', + } as any, + user, + ); expect(result).toBeDefined(); expect( @@ -171,47 +184,55 @@ describe('createCaseInteractor', () => { }); it('should match the current user id to the contactId when the user is petitioner', async () => { - const result = await createCaseInteractor(applicationContext, { - petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', - petitionMetadata: mockPetitionMetadata, - stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', - } as any); + const result = await createCaseInteractor( + applicationContext, + { + petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', + petitionMetadata: mockPetitionMetadata, + stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', + } as any, + user, + ); expect(result.petitioners[0].contactId).toEqual(user.userId); expect(result.petitioners[0].address1).toEqual('99 South Oak Lane'); }); it('should create a STIN docket entry on the case with index 0', async () => { - const result = await createCaseInteractor(applicationContext, { - petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', - petitionMetadata: { - caseType: CASE_TYPES_MAP.other, - contactPrimary: { - address1: '99 South Oak Lane', - address2: 'Culpa numquam saepe ', - address3: 'Eaque voluptates com', - city: 'Dignissimos voluptat', - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'petitioner1@example.com', - name: 'Diana Prince', - phone: '+1 (215) 128-6587', - postalCode: '69580', - state: 'AR', + const result = await createCaseInteractor( + applicationContext, + { + petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', + petitionMetadata: { + caseType: CASE_TYPES_MAP.other, + contactPrimary: { + address1: '99 South Oak Lane', + address2: 'Culpa numquam saepe ', + address3: 'Eaque voluptates com', + city: 'Dignissimos voluptat', + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'petitioner1@example.com', + name: 'Diana Prince', + phone: '+1 (215) 128-6587', + postalCode: '69580', + state: 'AR', + }, + contactSecondary: {}, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.petitioner, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 1, + preferredTrialCity: 'Fresno, California', + procedureType: 'Small', + signature: true, + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, }, - contactSecondary: {}, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.petitioner, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 1, - preferredTrialCity: 'Fresno, California', - procedureType: 'Small', - signature: true, - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, - }, - stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', - } as any); + stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', + } as any, + user, + ); const stinDocketEntry = result.docketEntries.find( d => d.eventCode === INITIAL_DOCUMENT_TYPES.stin.eventCode, @@ -222,42 +243,47 @@ describe('createCaseInteractor', () => { it('should create a case successfully as a practitioner', async () => { user = new PrivatePractitioner({ barNumber: 'BN1234', + email: 'pbventures@example.com', name: 'Mister Peanutbutter', role: ROLES.privatePractitioner, userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }); - const result = await createCaseInteractor(applicationContext, { - corporateDisclosureFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', - petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', - petitionMetadata: { - caseType: CASE_TYPES_MAP.other, - contactPrimary: { - address1: '99 South Oak Lane', - address2: 'Culpa numquam saepe ', - address3: 'Eaque voluptates com', - city: 'Dignissimos voluptat', - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'petitioner1@example.com', - name: 'Diana Prince', - phone: '+1 (215) 128-6587', - postalCode: '69580', - state: 'AR', + const result = await createCaseInteractor( + applicationContext, + { + corporateDisclosureFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', + petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', + petitionMetadata: { + caseType: CASE_TYPES_MAP.other, + contactPrimary: { + address1: '99 South Oak Lane', + address2: 'Culpa numquam saepe ', + address3: 'Eaque voluptates com', + city: 'Dignissimos voluptat', + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'petitioner1@example.com', + name: 'Diana Prince', + phone: '+1 (215) 128-6587', + postalCode: '69580', + state: 'AR', + }, + contactSecondary: {}, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.petitioner, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 1, + preferredTrialCity: 'Fresno, California', + procedureType: 'Small', + signature: true, + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, }, - contactSecondary: {}, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.petitioner, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 1, - preferredTrialCity: 'Fresno, California', - procedureType: 'Small', - signature: true, - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, + stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', }, - stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', - }); + user, + ); expect(result).toBeDefined(); expect(result.privatePractitioners).toBeDefined(); @@ -273,37 +299,41 @@ describe('createCaseInteractor', () => { }); it('should create a case successfully with an "Attachment to Petition" document', async () => { - const result = await createCaseInteractor(applicationContext, { - attachmentToPetitionFileIds: ['f09116b1-6a8c-4198-b661-0f06e9c6cbdc'], - petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', - petitionMetadata: { - caseType: CASE_TYPES_MAP.other, - contactPrimary: { - address1: '99 South Oak Lane', - address2: 'Culpa numquam saepe ', - address3: 'Eaque voluptates com', - city: 'Dignissimos voluptat', - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'petitioner1@example.com', - name: 'Diana Prince', - phone: '+1 (215) 128-6587', - postalCode: '69580', - state: 'AR', + const result = await createCaseInteractor( + applicationContext, + { + attachmentToPetitionFileIds: ['f09116b1-6a8c-4198-b661-0f06e9c6cbdc'], + petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', + petitionMetadata: { + caseType: CASE_TYPES_MAP.other, + contactPrimary: { + address1: '99 South Oak Lane', + address2: 'Culpa numquam saepe ', + address3: 'Eaque voluptates com', + city: 'Dignissimos voluptat', + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'petitioner1@example.com', + name: 'Diana Prince', + phone: '+1 (215) 128-6587', + postalCode: '69580', + state: 'AR', + }, + contactSecondary: {}, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.petitioner, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 1, + preferredTrialCity: 'Fresno, California', + procedureType: 'Small', + signature: true, + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, }, - contactSecondary: {}, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.petitioner, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 1, - preferredTrialCity: 'Fresno, California', - procedureType: 'Small', - signature: true, - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, + stinFileId: '96759830-8970-486f-916b-23439a8ebb70', }, - stinFileId: '96759830-8970-486f-916b-23439a8ebb70', - }); + user, + ); const atpDocketEntry = result.docketEntries.find( d => @@ -314,40 +344,44 @@ describe('createCaseInteractor', () => { }); it('should create a case successfully with multiple "Attachment to Petition" documents', async () => { - const result = await createCaseInteractor(applicationContext, { - attachmentToPetitionFileIds: [ - 'f09116b1-6a8c-4198-b661-0f06e9c6cbdc', - '550e8400-e29b-41d4-a716-446655440000', - ], - petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', - petitionMetadata: { - caseType: CASE_TYPES_MAP.other, - contactPrimary: { - address1: '99 South Oak Lane', - address2: 'Culpa numquam saepe ', - address3: 'Eaque voluptates com', - city: 'Dignissimos voluptat', - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'petitioner1@example.com', - name: 'Diana Prince', - phone: '+1 (215) 128-6587', - postalCode: '69580', - state: 'AR', + const result = await createCaseInteractor( + applicationContext, + { + attachmentToPetitionFileIds: [ + 'f09116b1-6a8c-4198-b661-0f06e9c6cbdc', + '550e8400-e29b-41d4-a716-446655440000', + ], + petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', + petitionMetadata: { + caseType: CASE_TYPES_MAP.other, + contactPrimary: { + address1: '99 South Oak Lane', + address2: 'Culpa numquam saepe ', + address3: 'Eaque voluptates com', + city: 'Dignissimos voluptat', + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'petitioner1@example.com', + name: 'Diana Prince', + phone: '+1 (215) 128-6587', + postalCode: '69580', + state: 'AR', + }, + contactSecondary: {}, + filingType: 'Myself', + hasIrsNotice: true, + partyType: PARTY_TYPES.petitioner, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 1, + preferredTrialCity: 'Fresno, California', + procedureType: 'Small', + signature: true, + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, }, - contactSecondary: {}, - filingType: 'Myself', - hasIrsNotice: true, - partyType: PARTY_TYPES.petitioner, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 1, - preferredTrialCity: 'Fresno, California', - procedureType: 'Small', - signature: true, - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, + stinFileId: '96759830-8970-486f-916b-23439a8ebb70', }, - stinFileId: '96759830-8970-486f-916b-23439a8ebb70', - }); + user, + ); const atpDocketEntries = result.docketEntries.filter( d => @@ -359,53 +393,58 @@ describe('createCaseInteractor', () => { it('should create a case with contact primary and secondary successfully as a practitioner', async () => { user = new PrivatePractitioner({ barNumber: 'BN1234', - name: 'Carole Baskin', + email: 'kb@example.com', + name: 'Karen Baskinostan', role: ROLES.privatePractitioner, userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }); - const result = await createCaseInteractor(applicationContext, { - corporateDisclosureFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', - petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', - petitionMetadata: { - caseType: CASE_TYPES_MAP.other, - contactPrimary: { - address1: '99 South Oak Lane', - address2: 'Culpa numquam saepe ', - address3: 'Eaque voluptates com', - city: 'Dignissimos voluptat', - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'petitioner1@example.com', - name: 'Diana Prince', - phone: '+1 (215) 128-6587', - postalCode: '69580', - state: 'AR', - }, - contactSecondary: { - address1: '99 South Oak Lane', - address2: 'Culpa numquam saepe ', - address3: 'Eaque voluptates com', - city: 'Dignissimos voluptat', - countryType: COUNTRY_TYPES.DOMESTIC, - name: 'Bob Prince', - phone: '+1 (215) 128-6587', - postalCode: '69580', - state: 'AR', + const result = await createCaseInteractor( + applicationContext, + { + corporateDisclosureFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', + petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', + petitionMetadata: { + caseType: CASE_TYPES_MAP.other, + contactPrimary: { + address1: '99 South Oak Lane', + address2: 'Culpa numquam saepe ', + address3: 'Eaque voluptates com', + city: 'Dignissimos voluptat', + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'petitioner1@example.com', + name: 'Diana Prince', + phone: '+1 (215) 128-6587', + postalCode: '69580', + state: 'AR', + }, + contactSecondary: { + address1: '99 South Oak Lane', + address2: 'Culpa numquam saepe ', + address3: 'Eaque voluptates com', + city: 'Dignissimos voluptat', + countryType: COUNTRY_TYPES.DOMESTIC, + name: 'Bob Prince', + phone: '+1 (215) 128-6587', + postalCode: '69580', + state: 'AR', + }, + filingType: 'Myself and my spouse', + hasIrsNotice: true, + isSpouseDeceased: 'No', + partyType: PARTY_TYPES.petitionerSpouse, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 1, + preferredTrialCity: 'Fresno, California', + procedureType: 'Small', + signature: true, + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, }, - filingType: 'Myself and my spouse', - hasIrsNotice: true, - isSpouseDeceased: 'No', - partyType: PARTY_TYPES.petitionerSpouse, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 1, - preferredTrialCity: 'Fresno, California', - procedureType: 'Small', - signature: true, - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, + stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', }, - stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', - }); + user, + ); expect(result).toBeDefined(); expect(result.privatePractitioners).toBeDefined(); @@ -424,58 +463,63 @@ describe('createCaseInteractor', () => { it('should set serviceIndicators for each petitioner on the case', async () => { user = new PrivatePractitioner({ barNumber: 'BN1234', - name: 'Carole Baskin', + email: 'kb@example.com', + name: 'Karen Baskinostan', role: ROLES.privatePractitioner, userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }); - const result = await createCaseInteractor(applicationContext, { - corporateDisclosureFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', - petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', - petitionMetadata: { - caseType: CASE_TYPES_MAP.other, - contactPrimary: { - address1: '99 South Oak Lane', - address2: 'Culpa numquam saepe ', - address3: 'Eaque voluptates com', - city: 'Dignissimos voluptat', - contactType: CONTACT_TYPES.primary, - countryType: COUNTRY_TYPES.DOMESTIC, - email: 'petitioner1@example.com', - name: 'Diana Prince', - phone: '+1 (215) 128-6587', - postalCode: '69580', - serviceIndicator: undefined, - state: 'AR', - }, - contactSecondary: { - address1: '99 South Oak Lane', - address2: 'Culpa numquam saepe ', - address3: 'Eaque voluptates com', - city: 'Dignissimos voluptat', - contactType: CONTACT_TYPES.secondary, - countryType: COUNTRY_TYPES.DOMESTIC, - name: 'Bob Prince', - phone: '+1 (215) 128-6587', - postalCode: '69580', - serviceIndicator: undefined, - state: 'AR', + const result = await createCaseInteractor( + applicationContext, + { + corporateDisclosureFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', + petitionFileId: '413f62ce-d7c8-446e-aeda-14a2a625a626', + petitionMetadata: { + caseType: CASE_TYPES_MAP.other, + contactPrimary: { + address1: '99 South Oak Lane', + address2: 'Culpa numquam saepe ', + address3: 'Eaque voluptates com', + city: 'Dignissimos voluptat', + contactType: CONTACT_TYPES.primary, + countryType: COUNTRY_TYPES.DOMESTIC, + email: 'petitioner1@example.com', + name: 'Diana Prince', + phone: '+1 (215) 128-6587', + postalCode: '69580', + serviceIndicator: undefined, + state: 'AR', + }, + contactSecondary: { + address1: '99 South Oak Lane', + address2: 'Culpa numquam saepe ', + address3: 'Eaque voluptates com', + city: 'Dignissimos voluptat', + contactType: CONTACT_TYPES.secondary, + countryType: COUNTRY_TYPES.DOMESTIC, + name: 'Bob Prince', + phone: '+1 (215) 128-6587', + postalCode: '69580', + serviceIndicator: undefined, + state: 'AR', + }, + filedBy: 'Resp.', + filingType: 'Myself and my spouse', + hasIrsNotice: true, + isSpouseDeceased: 'No', + partyType: PARTY_TYPES.petitionerSpouse, + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 1, + preferredTrialCity: 'Fresno, California', + procedureType: 'Small', + signature: true, + stinFile: new File([], 'test.pdf'), + stinFileSize: 1, }, - filedBy: 'Resp.', - filingType: 'Myself and my spouse', - hasIrsNotice: true, - isSpouseDeceased: 'No', - partyType: PARTY_TYPES.petitionerSpouse, - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 1, - preferredTrialCity: 'Fresno, California', - procedureType: 'Small', - signature: true, - stinFile: new File([], 'test.pdf'), - stinFileSize: 1, + stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', }, - stinFileId: '413f62ce-7c8d-446e-aeda-14a2a625a611', - }); + user, + ); result.petitioners.forEach(p => { expect(p.serviceIndicator).not.toBeUndefined(); @@ -485,41 +529,46 @@ describe('createCaseInteractor', () => { it('should set serviceIndicator to none for petitioner when case is created by a private petitioner', async () => { user = new PrivatePractitioner({ barNumber: 'BN1234', - name: 'Carole Baskin', + email: 'kb@example.com', + name: 'Karen Baskinostan', role: ROLES.privatePractitioner, userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }); - const result = await createCaseInteractor(applicationContext, { - petitionFileId: '6722d660-d241-45ad-b7b2-0326cbfee40d', - petitionMetadata: { - caseType: 'Deficiency', - contactPrimary: { - address1: '25 Second Lane', - address2: 'Adipisci qui et est ', - address3: 'Cumque reprehenderit', - city: 'Consequatur Iusto e', - countryType: 'domestic', - email: 'privatePractitioner@example.com', - name: 'Inez Martinez', - phone: '+1 (756) 271-3574', - postalCode: '68964', - state: 'VA', + const result = await createCaseInteractor( + applicationContext, + { + petitionFileId: '6722d660-d241-45ad-b7b2-0326cbfee40d', + petitionMetadata: { + caseType: 'Deficiency', + contactPrimary: { + address1: '25 Second Lane', + address2: 'Adipisci qui et est ', + address3: 'Cumque reprehenderit', + city: 'Consequatur Iusto e', + countryType: 'domestic', + email: 'privatePractitioner@example.com', + name: 'Inez Martinez', + phone: '+1 (756) 271-3574', + postalCode: '68964', + state: 'VA', + }, + contactSecondary: {}, + filingType: 'Individual petitioner', + hasIrsNotice: true, + partyType: 'Petitioner', + petitionFile: new File([], 'test.pdf'), + petitionFileSize: 13264, + preferredTrialCity: 'Birmingham, Alabama', + procedureType: 'Regular', + stinFile: new File([], 'test.pdf'), + stinFileSize: 13264, + wizardStep: '5', }, - contactSecondary: {}, - filingType: 'Individual petitioner', - hasIrsNotice: true, - partyType: 'Petitioner', - petitionFile: new File([], 'test.pdf'), - petitionFileSize: 13264, - preferredTrialCity: 'Birmingham, Alabama', - procedureType: 'Regular', - stinFile: new File([], 'test.pdf'), - stinFileSize: 13264, - wizardStep: '5', - }, - stinFileId: 'e8bd0522-84ec-41fb-b490-0f4b8aa8a430', - } as any); + stinFileId: 'e8bd0522-84ec-41fb-b490-0f4b8aa8a430', + } as any, + user, + ); result.petitioners.forEach(p => { expect(p.serviceIndicator).toBe(SERVICE_INDICATOR_TYPES.SI_NONE); diff --git a/web-api/src/business/useCases/createCaseInteractor.ts b/web-api/src/business/useCases/createCaseInteractor.ts index a68acf73092..5a73e91f99d 100644 --- a/web-api/src/business/useCases/createCaseInteractor.ts +++ b/web-api/src/business/useCases/createCaseInteractor.ts @@ -13,6 +13,7 @@ import { } from '../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { UserCase } from '../../../../shared/src/business/entities/UserCase'; import { UserRecord } from '@web-api/persistence/dynamo/dynamoTypes'; import { WorkItem } from '../../../../shared/src/business/entities/WorkItem'; @@ -21,7 +22,6 @@ import { setServiceIndicatorsForCase } from '../../../../shared/src/business/uti export type ElectronicCreatedCaseType = Omit; const addPetitionDocketEntryToCase = ({ - applicationContext, caseToAdd, docketEntryEntity, user, @@ -47,8 +47,7 @@ const addPetitionDocketEntryToCase = ({ trialDate: caseToAdd.trialDate, trialLocation: caseToAdd.trialLocation, }, - { applicationContext }, - caseToAdd, + { caseEntity: caseToAdd }, ); docketEntryEntity.setWorkItem(workItemEntity); @@ -72,9 +71,8 @@ export const createCaseInteractor = async ( petitionMetadata: any; stinFileId: string; }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.PETITION)) { throw new UnauthorizedError('Unauthorized'); } @@ -83,9 +81,7 @@ export const createCaseInteractor = async ( .getPersistenceGateway() .getUserById({ applicationContext, userId: authorizedUser.userId }); - const petitionEntity = new ElectronicPetition(petitionMetadata, { - applicationContext, - }).validate(); + const petitionEntity = new ElectronicPetition(petitionMetadata).validate(); const docketNumber = await applicationContext.docketNumberGenerator.createDocketNumber({ @@ -130,7 +126,7 @@ export const createCaseInteractor = async ( privatePractitioners, }, { - applicationContext, + authorizedUser, isNewCase: true, }, ); @@ -167,13 +163,12 @@ export const createCaseInteractor = async ( isOnDocketRecord: true, privatePractitioners, }, - { applicationContext, petitioners: caseToAdd.petitioners }, + { authorizedUser, petitioners: caseToAdd.petitioners }, ); petitionDocketEntryEntity.setFiledBy(user); const newWorkItem = addPetitionDocketEntryToCase({ - applicationContext, caseToAdd, docketEntryEntity: petitionDocketEntryEntity, user, @@ -190,7 +185,7 @@ export const createCaseInteractor = async ( processingStatus: 'complete', }, { - applicationContext, + authorizedUser, petitioners: caseToAdd.petitioners, }, ); @@ -213,7 +208,7 @@ export const createCaseInteractor = async ( isFileAttached: true, privatePractitioners, }, - { applicationContext, petitioners: caseToAdd.petitioners }, + { authorizedUser, petitioners: caseToAdd.petitioners }, ); stinDocketEntryEntity.setFiledBy(user); @@ -235,7 +230,7 @@ export const createCaseInteractor = async ( isOnDocketRecord: true, privatePractitioners, }, - { applicationContext, petitioners: caseToAdd.petitioners }, + { authorizedUser, petitioners: caseToAdd.petitioners }, ); cdsDocketEntryEntity.setFiledBy(user); @@ -270,7 +265,7 @@ export const createCaseInteractor = async ( petitionMetadata.hasIrsNotice && petitionMetadata.irsNotices?.[index]?.taxYear, }, - { applicationContext, petitioners: caseToAdd.petitioners }, + { authorizedUser, petitioners: caseToAdd.petitioners }, ); atpDocketEntryEntity.setFiledBy(user); @@ -281,6 +276,7 @@ export const createCaseInteractor = async ( await applicationContext.getUseCaseHelpers().createCaseAndAssociations({ applicationContext, + authorizedUser, caseToCreate: caseToAdd.validate().toRawObject(), }); @@ -302,5 +298,5 @@ export const createCaseInteractor = async ( docketNumber: caseToAdd.docketNumber, }); - return new Case(caseToAdd, { applicationContext }).toRawObject(); + return new Case(caseToAdd, { authorizedUser }).toRawObject(); }; diff --git a/web-api/src/business/useCases/customCaseReport/createCsvCustomCaseReportFileInteractor.test.ts b/web-api/src/business/useCases/customCaseReport/createCsvCustomCaseReportFileInteractor.test.ts index ece7a54be42..bbc1f8c325d 100644 --- a/web-api/src/business/useCases/customCaseReport/createCsvCustomCaseReportFileInteractor.test.ts +++ b/web-api/src/business/useCases/customCaseReport/createCsvCustomCaseReportFileInteractor.test.ts @@ -1,9 +1,9 @@ import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { createCsvCustomCaseReportFileInteractor } from '@web-api/business/useCases/customCaseReport/createCsvCustomCaseReportFileInteractor'; import { - docketClerkUser, - privatePractitionerUser, -} from '@shared/test/mockUsers'; + mockDocketClerkUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; describe('createCsvCustomCaseReportFileInteractor', () => { const DEFAULT_PARAMS = { @@ -21,10 +21,6 @@ describe('createCsvCustomCaseReportFileInteractor', () => { } as any; beforeEach(() => { - applicationContext.getCurrentUser = jest - .fn() - .mockReturnValue(docketClerkUser); - applicationContext.getNotificationGateway().sendNotificationToUser = jest .fn() .mockReturnValue(null); @@ -63,6 +59,7 @@ describe('createCsvCustomCaseReportFileInteractor', () => { await createCsvCustomCaseReportFileInteractor( applicationContext, DEFAULT_PARAMS, + mockDocketClerkUser, ); const sendNotificationCalls = @@ -105,14 +102,11 @@ describe('createCsvCustomCaseReportFileInteractor', () => { }); it('should throw an error if a user is not authorized', async () => { - applicationContext.getCurrentUser = jest - .fn() - .mockReturnValue(privatePractitionerUser); - await expect( createCsvCustomCaseReportFileInteractor( applicationContext, DEFAULT_PARAMS, + mockPrivatePractitionerUser, ), ).rejects.toThrow('Unauthorized'); }); @@ -122,10 +116,14 @@ describe('createCsvCustomCaseReportFileInteractor', () => { .fn() .mockImplementation(callback => callback()); - await createCsvCustomCaseReportFileInteractor(applicationContext, { - ...DEFAULT_PARAMS, - totalCount: 100000, - }); + await createCsvCustomCaseReportFileInteractor( + applicationContext, + { + ...DEFAULT_PARAMS, + totalCount: 100000, + }, + mockDocketClerkUser, + ); expect(applicationContext.setTimeout).toHaveBeenCalledTimes(1); }); @@ -151,6 +149,7 @@ describe('createCsvCustomCaseReportFileInteractor', () => { await createCsvCustomCaseReportFileInteractor( applicationContext, DEFAULT_PARAMS, + mockDocketClerkUser, ); const saveFileAndGenerateUrlCalls = @@ -188,6 +187,7 @@ describe('createCsvCustomCaseReportFileInteractor', () => { await createCsvCustomCaseReportFileInteractor( applicationContext, DEFAULT_PARAMS, + mockDocketClerkUser, ); const saveFileAndGenerateUrlCalls = diff --git a/web-api/src/business/useCases/customCaseReport/createCsvCustomCaseReportFileInteractor.ts b/web-api/src/business/useCases/customCaseReport/createCsvCustomCaseReportFileInteractor.ts index 98a7d53ffab..c2437f63dd0 100644 --- a/web-api/src/business/useCases/customCaseReport/createCsvCustomCaseReportFileInteractor.ts +++ b/web-api/src/business/useCases/customCaseReport/createCsvCustomCaseReportFileInteractor.ts @@ -12,6 +12,7 @@ import { } from '@shared/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { stringify } from 'csv-stringify/sync'; export type CustomCaseReportCsvRequest = CustomCaseReportFilters & { @@ -34,9 +35,8 @@ export const createCsvCustomCaseReportFileInteractor = async ( startDate, totalCount, }: CustomCaseReportCsvRequest, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CASE_INVENTORY_REPORT)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/docketEntry/addPaperFilingInteractor.locking.test.ts b/web-api/src/business/useCases/docketEntry/addPaperFilingInteractor.locking.test.ts index fc305fef91a..1bc5d9e951b 100644 --- a/web-api/src/business/useCases/docketEntry/addPaperFilingInteractor.locking.test.ts +++ b/web-api/src/business/useCases/docketEntry/addPaperFilingInteractor.locking.test.ts @@ -49,9 +49,11 @@ describe('handleLockError', () => { .getUserById.mockReturnValue(docketClerkUser); }); - it('should determine who the user is based on applicationContext', async () => { - await handleLockError(applicationContext, { foo: 'bar' }); - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); + it('should send notification to user when there is a lock error', async () => { + await handleLockError(applicationContext, { foo: 'bar' }, docketClerkUser); + expect( + applicationContext.getNotificationGateway().sendNotificationToUser, + ).toHaveBeenCalled(); }); it('should send a notification to the user with "retry_async_request" and the originalRequest', async () => { @@ -59,7 +61,11 @@ describe('handleLockError', () => { clientConnectionId: mockClientConnectionId, foo: 'bar', }; - await handleLockError(applicationContext, mockOriginalRequest); + await handleLockError( + applicationContext, + mockOriginalRequest, + docketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock .calls[0][0].message, @@ -99,8 +105,6 @@ describe('addPaperFilingInteractor', () => { beforeEach(() => { mockLock = undefined; // unlocked - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(docketClerkUser); @@ -117,7 +121,11 @@ describe('addPaperFilingInteractor', () => { it('should throw a ServiceUnavailableError if a Case is currently locked', async () => { await expect( - addPaperFilingInteractor(applicationContext, mockRequest), + addPaperFilingInteractor( + applicationContext, + mockRequest, + docketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -127,7 +135,11 @@ describe('addPaperFilingInteractor', () => { it('should return a "retry_async_request" notification with the original request', async () => { await expect( - addPaperFilingInteractor(applicationContext, mockRequest), + addPaperFilingInteractor( + applicationContext, + mockRequest, + docketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -155,7 +167,11 @@ describe('addPaperFilingInteractor', () => { }); it('should acquire a lock that lasts for 15 minutes', async () => { - await addPaperFilingInteractor(applicationContext, mockRequest); + await addPaperFilingInteractor( + applicationContext, + mockRequest, + docketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -166,7 +182,11 @@ describe('addPaperFilingInteractor', () => { }); }); it('should remove the lock', async () => { - await addPaperFilingInteractor(applicationContext, mockRequest); + await addPaperFilingInteractor( + applicationContext, + mockRequest, + docketClerkUser, + ); expect( applicationContext.getPersistenceGateway().removeLock, diff --git a/web-api/src/business/useCases/docketEntry/addPaperFilingInteractor.test.ts b/web-api/src/business/useCases/docketEntry/addPaperFilingInteractor.test.ts index b0861d602c0..4c6f24fedf0 100644 --- a/web-api/src/business/useCases/docketEntry/addPaperFilingInteractor.test.ts +++ b/web-api/src/business/useCases/docketEntry/addPaperFilingInteractor.test.ts @@ -10,9 +10,11 @@ import { MOCK_CONSOLIDATED_2_CASE_WITH_PAPER_SERVICE, MOCK_LEAD_CASE_WITH_PAPER_SERVICE, } from '../../../../../shared/src/test/mockCase'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { addPaperFilingInteractor } from './addPaperFilingInteractor'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('addPaperFilingInteractor', () => { const mockClientConnectionId = '987654'; @@ -34,8 +36,6 @@ describe('addPaperFilingInteractor', () => { isSavingForLater: false, }; - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(docketClerkUser); @@ -46,10 +46,12 @@ describe('addPaperFilingInteractor', () => { }); it('should throw an error when the user is not authorized to add a paper filing', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - addPaperFilingInteractor(applicationContext, defaultParamaters), + addPaperFilingInteractor( + applicationContext, + defaultParamaters, + {} as UnknownAuthUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -57,7 +59,11 @@ describe('addPaperFilingInteractor', () => { defaultParamaters.docketEntryId = undefined as any; await expect( - addPaperFilingInteractor(applicationContext, defaultParamaters), + addPaperFilingInteractor( + applicationContext, + defaultParamaters, + mockDocketClerkUser, + ), ).rejects.toThrow('Did not receive a docketEntryId'); }); @@ -65,28 +71,36 @@ describe('addPaperFilingInteractor', () => { defaultParamaters.documentMetadata = undefined as any; await expect( - addPaperFilingInteractor(applicationContext, defaultParamaters), + addPaperFilingInteractor( + applicationContext, + defaultParamaters, + mockDocketClerkUser, + ), ).rejects.toThrow('Did not receive meta data for docket entry'); }); it('should add documents and send service emails for electronic service parties', async () => { const mockdocketEntryId = 'c54ba5a9-b37b-479d-9201-067ec6e335bb'; - await addPaperFilingInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - consolidatedGroupDocketNumbers: [], - docketEntryId: mockdocketEntryId, - documentMetadata: { - docketNumber: mockCase.docketNumber, - documentTitle: 'Memorandum in Support', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - filedBy: 'Test Petitioner', - isFileAttached: true, - isPaper: true, + await addPaperFilingInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + consolidatedGroupDocketNumbers: [], + docketEntryId: mockdocketEntryId, + documentMetadata: { + docketNumber: mockCase.docketNumber, + documentTitle: 'Memorandum in Support', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + filedBy: 'Test Petitioner', + isFileAttached: true, + isPaper: true, + }, + isSavingForLater: false, }, - isSavingForLater: false, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().putWorkItemInUsersOutbox, @@ -115,21 +129,25 @@ describe('addPaperFilingInteractor', () => { pdfUrl: mockPdfUrl, }); - await addPaperFilingInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - consolidatedGroupDocketNumbers: [], - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: mockCase.docketNumber, - documentTitle: 'Memorandum in Support', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - filedBy: 'Test Petitioner', - isFileAttached: true, - isPaper: true, + await addPaperFilingInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + consolidatedGroupDocketNumbers: [], + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: mockCase.docketNumber, + documentTitle: 'Memorandum in Support', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + filedBy: 'Test Petitioner', + isFileAttached: true, + isPaper: true, + }, + isSavingForLater: false, }, - isSavingForLater: false, - }); + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock @@ -153,23 +171,27 @@ describe('addPaperFilingInteractor', () => { pdfUrl: mockPdfUrl, }); - await addPaperFilingInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - consolidatedGroupDocketNumbers: [ - MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, - ], - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: mockCase.docketNumber, - documentTitle: 'Memorandum in Support', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - filedBy: 'Test Petitioner', - isFileAttached: true, - isPaper: true, + await addPaperFilingInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + consolidatedGroupDocketNumbers: [ + MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, + ], + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: mockCase.docketNumber, + documentTitle: 'Memorandum in Support', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + filedBy: 'Test Petitioner', + isFileAttached: true, + isPaper: true, + }, + isSavingForLater: false, }, - isSavingForLater: false, - }); + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock @@ -178,21 +200,25 @@ describe('addPaperFilingInteractor', () => { }); it('should add documents and workItem to inbox when saving for later when a document is attached', async () => { - await addPaperFilingInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - consolidatedGroupDocketNumbers: [], - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: mockCase.docketNumber, - documentTitle: 'Memorandum in Support', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - filedBy: 'Test Petitioner', - isFileAttached: true, - isPaper: true, + await addPaperFilingInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + consolidatedGroupDocketNumbers: [], + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: mockCase.docketNumber, + documentTitle: 'Memorandum in Support', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + filedBy: 'Test Petitioner', + isFileAttached: true, + isPaper: true, + }, + isSavingForLater: true, }, - isSavingForLater: true, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().putWorkItemInUsersOutbox, @@ -210,21 +236,25 @@ describe('addPaperFilingInteractor', () => { }); it('should add documents and workItem to inbox when saving for later when a document is NOT attached', async () => { - await addPaperFilingInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - consolidatedGroupDocketNumbers: [], - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: mockCase.docketNumber, - documentTitle: 'Memorandum in Support', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - filedBy: 'Test Petitioner', - isFileAttached: false, - isPaper: true, + await addPaperFilingInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + consolidatedGroupDocketNumbers: [], + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: mockCase.docketNumber, + documentTitle: 'Memorandum in Support', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + filedBy: 'Test Petitioner', + isFileAttached: false, + isPaper: true, + }, + isSavingForLater: true, }, - isSavingForLater: true, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -242,21 +272,25 @@ describe('addPaperFilingInteractor', () => { }); it('should add workItem to the user outbox when NOT saving for later if a document is attached', async () => { - await addPaperFilingInteractor(applicationContext, { - clientConnectionId: undefined as any, - consolidatedGroupDocketNumbers: [], - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: mockCase.docketNumber, - documentTitle: 'Memorandum in Support', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - filedBy: 'Test Petitioner', - isFileAttached: true, - isPaper: true, + await addPaperFilingInteractor( + applicationContext, + { + clientConnectionId: undefined as any, + consolidatedGroupDocketNumbers: [], + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: mockCase.docketNumber, + documentTitle: 'Memorandum in Support', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + filedBy: 'Test Petitioner', + isFileAttached: true, + isPaper: true, + }, + isSavingForLater: false, }, - isSavingForLater: false, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().putWorkItemInUsersOutbox.mock @@ -268,22 +302,26 @@ describe('addPaperFilingInteractor', () => { }); it('sets the case as blocked if the document filed is a tracked document type', async () => { - await addPaperFilingInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - consolidatedGroupDocketNumbers: [], - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - category: 'Application', - docketNumber: mockCase.docketNumber, - documentTitle: 'Application for Examination Pursuant to Rule 73', - documentType: 'Application for Examination Pursuant to Rule 73', - eventCode: 'AFE', - filedBy: 'Test Petitioner', - isFileAttached: true, - isPaper: true, + await addPaperFilingInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + consolidatedGroupDocketNumbers: [], + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + category: 'Application', + docketNumber: mockCase.docketNumber, + documentTitle: 'Application for Examination Pursuant to Rule 73', + documentType: 'Application for Examination Pursuant to Rule 73', + eventCode: 'AFE', + filedBy: 'Test Petitioner', + isFileAttached: true, + isPaper: true, + }, + isSavingForLater: false, }, - isSavingForLater: false, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -309,22 +347,26 @@ describe('addPaperFilingInteractor', () => { { deadline: 'something' }, ]); - await addPaperFilingInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - consolidatedGroupDocketNumbers: [], - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - category: 'Application', - docketNumber: mockCase.docketNumber, - documentTitle: 'Application for Examination Pursuant to Rule 73', - documentType: 'Application for Examination Pursuant to Rule 73', - eventCode: 'AFE', - filedBy: 'Test Petitioner', - isFileAttached: true, - isPaper: true, + await addPaperFilingInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + consolidatedGroupDocketNumbers: [], + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + category: 'Application', + docketNumber: mockCase.docketNumber, + documentTitle: 'Application for Examination Pursuant to Rule 73', + documentType: 'Application for Examination Pursuant to Rule 73', + eventCode: 'AFE', + filedBy: 'Test Petitioner', + isFileAttached: true, + isPaper: true, + }, + isSavingForLater: false, }, - isSavingForLater: false, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -349,7 +391,36 @@ describe('addPaperFilingInteractor', () => { .updateCase.mockRejectedValueOnce(new Error('bad!')); await expect( - addPaperFilingInteractor(applicationContext, { + addPaperFilingInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + consolidatedGroupDocketNumbers: [], + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: mockCase.docketNumber, + documentTitle: 'Memorandum in Support', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + filedBy: 'Test Petitioner', + isFileAttached: true, + isPaper: true, + }, + isSavingForLater: false, + }, + mockDocketClerkUser, + ), + ).rejects.toThrow(new Error('bad!')); + + expect( + applicationContext.getUseCaseHelpers().serveDocumentAndGetPaperServicePdf, + ).not.toHaveBeenCalled(); + }); + + it('should use original case caption to create case title when creating work item', async () => { + await addPaperFilingInteractor( + applicationContext, + { clientConnectionId: mockClientConnectionId, consolidatedGroupDocketNumbers: [], docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', @@ -362,31 +433,10 @@ describe('addPaperFilingInteractor', () => { isFileAttached: true, isPaper: true, }, - isSavingForLater: false, - }), - ).rejects.toThrow(new Error('bad!')); - - expect( - applicationContext.getUseCaseHelpers().serveDocumentAndGetPaperServicePdf, - ).not.toHaveBeenCalled(); - }); - - it('should use original case caption to create case title when creating work item', async () => { - await addPaperFilingInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - consolidatedGroupDocketNumbers: [], - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: mockCase.docketNumber, - documentTitle: 'Memorandum in Support', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - filedBy: 'Test Petitioner', - isFileAttached: true, - isPaper: true, + isSavingForLater: true, }, - isSavingForLater: true, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveWorkItem.mock.calls[0][0] @@ -397,21 +447,25 @@ describe('addPaperFilingInteractor', () => { }); it('should send a serve_document_complete notification with a success message when all document processing has completed', async () => { - await addPaperFilingInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - consolidatedGroupDocketNumbers: [], - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: mockCase.docketNumber, - documentTitle: 'Memorandum in Support', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - filedBy: 'Test Petitioner', - isFileAttached: true, - isPaper: true, + await addPaperFilingInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + consolidatedGroupDocketNumbers: [], + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: mockCase.docketNumber, + documentTitle: 'Memorandum in Support', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + filedBy: 'Test Petitioner', + isFileAttached: true, + isPaper: true, + }, + isSavingForLater: true, }, - isSavingForLater: true, - }); + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock @@ -430,21 +484,25 @@ describe('addPaperFilingInteractor', () => { }); it('should send a serve_document_complete notification with generateCoversheet true when the docket entry has a file attached and the user is NOT saving for later', async () => { - await addPaperFilingInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - consolidatedGroupDocketNumbers: [], - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: mockCase.docketNumber, - documentTitle: 'Memorandum in Support', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - filedBy: 'Test Petitioner', - isFileAttached: true, - isPaper: true, + await addPaperFilingInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + consolidatedGroupDocketNumbers: [], + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: mockCase.docketNumber, + documentTitle: 'Memorandum in Support', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + filedBy: 'Test Petitioner', + isFileAttached: true, + isPaper: true, + }, + isSavingForLater: false, }, - isSavingForLater: false, - }); + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock @@ -453,21 +511,25 @@ describe('addPaperFilingInteractor', () => { }); it('should send a serve_document_complete notification with generateCoversheet false when the docket entry does NOT have a file attached', async () => { - await addPaperFilingInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - consolidatedGroupDocketNumbers: [], - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - documentMetadata: { - docketNumber: mockCase.docketNumber, - documentTitle: 'Memorandum in Support', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - filedBy: 'Test Petitioner', - isFileAttached: false, - isPaper: true, + await addPaperFilingInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + consolidatedGroupDocketNumbers: [], + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + documentMetadata: { + docketNumber: mockCase.docketNumber, + documentTitle: 'Memorandum in Support', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + filedBy: 'Test Petitioner', + isFileAttached: false, + isPaper: true, + }, + isSavingForLater: true, }, - isSavingForLater: true, - }); + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock @@ -503,6 +565,7 @@ describe('addPaperFilingInteractor', () => { await addPaperFilingInteractor( applicationContext, mockConsolidatedGroupRequest, + mockDocketClerkUser, ); expect( @@ -525,6 +588,7 @@ describe('addPaperFilingInteractor', () => { await addPaperFilingInteractor( applicationContext, mockConsolidatedGroupRequest, + mockDocketClerkUser, ); expect( @@ -537,21 +601,25 @@ describe('addPaperFilingInteractor', () => { it('should pass in an empty array for electronicParties when calling "serveDocumentAndGetPaperServicePdf" when dealing with ATP docket entry', async () => { const mockdocketEntryId = 'c54ba5a9-b37b-479d-9201-067ec6e335bb'; - await addPaperFilingInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - consolidatedGroupDocketNumbers: [], - docketEntryId: mockdocketEntryId, - documentMetadata: { - docketNumber: mockCase.docketNumber, - documentTitle: 'Memorandum in Support', - documentType: 'Memorandum in Support', - eventCode: 'ATP', - filedBy: 'Test Petitioner', - isFileAttached: true, - isPaper: true, + await addPaperFilingInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + consolidatedGroupDocketNumbers: [], + docketEntryId: mockdocketEntryId, + documentMetadata: { + docketNumber: mockCase.docketNumber, + documentTitle: 'Memorandum in Support', + documentType: 'Memorandum in Support', + eventCode: 'ATP', + filedBy: 'Test Petitioner', + isFileAttached: true, + isPaper: true, + }, + isSavingForLater: false, }, - isSavingForLater: false, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().serveDocumentAndGetPaperServicePdf, diff --git a/web-api/src/business/useCases/docketEntry/addPaperFilingInteractor.ts b/web-api/src/business/useCases/docketEntry/addPaperFilingInteractor.ts index 6f2ba296240..cfe1686cbf6 100644 --- a/web-api/src/business/useCases/docketEntry/addPaperFilingInteractor.ts +++ b/web-api/src/business/useCases/docketEntry/addPaperFilingInteractor.ts @@ -14,21 +14,11 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { WorkItem } from '../../../../../shared/src/business/entities/WorkItem'; import { aggregatePartiesForService } from '../../../../../shared/src/business/utilities/aggregatePartiesForService'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; -/** - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {object} providers.clientConnectionId the client connection Id - * @param {string} providers.docketEntryId the id of the docket entry to add - * @param {object} providers.consolidatedGroupDocketNumbers the docket numbers from the consolidated group - * @param {object} providers.documentMetadata the document metadata - * @param {boolean} providers.isSavingForLater flag for saving docket entry for later instead of serving it - * @returns {object} the updated case after the documents are added - */ export const addPaperFiling = async ( applicationContext: ServerApplicationContext, { @@ -44,9 +34,8 @@ export const addPaperFiling = async ( isSavingForLater: boolean; docketEntryId: string; }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.DOCKET_ENTRY)) { throw new UnauthorizedError('Unauthorized'); } @@ -92,7 +81,7 @@ export const addPaperFiling = async ( docketNumber, }); - let caseEntity = new Case(rawCase, { applicationContext }); + let caseEntity = new Case(rawCase, { authorizedUser }); const docketEntryEntity = new DocketEntry( { @@ -106,7 +95,7 @@ export const addPaperFiling = async ( mailingDate: documentMetadata.mailingDate, relationship: DOCUMENT_RELATIONSHIPS.PRIMARY, }, - { applicationContext, petitioners: caseEntity.petitioners }, + { authorizedUser, petitioners: caseEntity.petitioners }, ); docketEntryEntity.setFiledBy(user); @@ -144,8 +133,7 @@ export const addPaperFiling = async ( trialDate: caseEntity.trialDate, trialLocation: caseEntity.trialLocation, }, - { applicationContext }, - caseEntity, + { caseEntity }, ); if (isReadyForService) { @@ -188,6 +176,7 @@ export const addPaperFiling = async ( await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity.validate().toRawObject(), }); } @@ -297,19 +286,23 @@ export const determineEntitiesToLock = ( ttl: 900, }); -export const handleLockError = async (applicationContext, originalRequest) => { - const user = applicationContext.getCurrentUser(); - - await applicationContext.getNotificationGateway().sendNotificationToUser({ - applicationContext, - clientConnectionId: originalRequest.clientConnectionId, - message: { - action: 'retry_async_request', - originalRequest, - requestToRetry: 'add_paper_filing', - }, - userId: user.userId, - }); +export const handleLockError = async ( + applicationContext, + originalRequest, + authorizedUser: UnknownAuthUser, +) => { + if (authorizedUser?.userId) { + await applicationContext.getNotificationGateway().sendNotificationToUser({ + applicationContext, + clientConnectionId: originalRequest.clientConnectionId, + message: { + action: 'retry_async_request', + originalRequest, + requestToRetry: 'add_paper_filing', + }, + userId: authorizedUser.userId, + }); + } }; export const addPaperFilingInteractor = withLocking( diff --git a/web-api/src/business/useCases/docketEntry/completeDocketEntryQCInteractor.needsNewCoversheet.test.ts b/web-api/src/business/useCases/docketEntry/completeDocketEntryQCInteractor.needsNewCoversheet.test.ts index f656e387889..e2ff44d58ef 100644 --- a/web-api/src/business/useCases/docketEntry/completeDocketEntryQCInteractor.needsNewCoversheet.test.ts +++ b/web-api/src/business/useCases/docketEntry/completeDocketEntryQCInteractor.needsNewCoversheet.test.ts @@ -13,7 +13,7 @@ describe('completeDocketEntryQCInteractor needsNewCoversheet', () => { filedBy: 'petitioner.high', receivedAt: '2019-08-25T05:00:00.000Z', }, - { applicationContext }, + { authorizedUser: undefined }, ); updatedDocketEntry = new DocketEntry( @@ -23,7 +23,7 @@ describe('completeDocketEntryQCInteractor needsNewCoversheet', () => { filedBy: 'petitioner.high', receivedAt: '2019-08-25T05:00:00.000Z', }, - { applicationContext }, + { authorizedUser: undefined }, ); }); it('should return true when receivedAt is updated', () => { diff --git a/web-api/src/business/useCases/docketEntry/completeDocketEntryQCInteractor.test.ts b/web-api/src/business/useCases/docketEntry/completeDocketEntryQCInteractor.test.ts index c6709dedb54..f561a1ee72b 100644 --- a/web-api/src/business/useCases/docketEntry/completeDocketEntryQCInteractor.test.ts +++ b/web-api/src/business/useCases/docketEntry/completeDocketEntryQCInteractor.test.ts @@ -13,6 +13,11 @@ import { docketClerkUser, } from '../../../../../shared/src/test/mockUsers'; import { completeDocketEntryQCInteractor } from './completeDocketEntryQCInteractor'; +import { + mockCaseServicesSupervisorUser, + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('completeDocketEntryQCInteractor', () => { let caseRecord; @@ -72,8 +77,6 @@ describe('completeDocketEntryQCInteractor', () => { ], }; - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(docketClerkUser); @@ -104,26 +107,32 @@ describe('completeDocketEntryQCInteractor', () => { }); it('should throw an error if not authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - leadDocketNumber: caseRecord.docketNumber, + completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + leadDocketNumber: caseRecord.docketNumber, + }, }, - }), + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('adds documents and workitems', async () => { await expect( - completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - leadDocketNumber: caseRecord.docketNumber, + completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + leadDocketNumber: caseRecord.docketNumber, + }, }, - }), + mockDocketClerkUser, + ), ).resolves.not.toThrow(); expect( @@ -144,9 +153,13 @@ describe('completeDocketEntryQCInteractor', () => { }); it('serves the document for electronic-only parties if a notice of docket change is generated', async () => { - const result = await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: caseRecord.docketEntries[0], - }); + const result = await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: caseRecord.docketEntries[0], + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -163,15 +176,19 @@ describe('completeDocketEntryQCInteractor', () => { }); it('should generate a notice of docket change with a new coversheet when additional info fields are added and addToCoversheet is true', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: true, - additionalInfo: '123', - additionalInfo2: 'abc', - certificateOfService: false, + await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + addToCoversheet: true, + additionalInfo: '123', + additionalInfo2: 'abc', + certificateOfService: false, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -186,15 +203,19 @@ describe('completeDocketEntryQCInteractor', () => { }); it('should generate a notice of docket change with the name and title of the clerk of the court', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: true, - additionalInfo: '123', - additionalInfo2: 'abc', - certificateOfService: false, + await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + addToCoversheet: true, + additionalInfo: '123', + additionalInfo2: 'abc', + certificateOfService: false, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getDocumentGenerators().noticeOfDocketChange.mock @@ -206,15 +227,19 @@ describe('completeDocketEntryQCInteractor', () => { }); it('should save the notice of docket change on the case', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: true, - additionalInfo: '123', - additionalInfo2: 'abc', - certificateOfService: false, + await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + addToCoversheet: true, + additionalInfo: '123', + additionalInfo2: 'abc', + certificateOfService: false, + }, }, - }); + mockDocketClerkUser, + ); const updatedCaseDocketEntries = applicationContext.getUseCaseHelpers().updateCaseAndAssociations.mock @@ -231,13 +256,17 @@ describe('completeDocketEntryQCInteractor', () => { }); it('should generate a notice of docket change without a new coversheet when the certificate of service date has been updated', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - certificateOfService: true, - certificateOfServiceDate: '2019-08-06T07:53:09.001Z', + await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + certificateOfService: true, + certificateOfServiceDate: '2019-08-06T07:53:09.001Z', + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -252,12 +281,16 @@ describe('completeDocketEntryQCInteractor', () => { }); it('should generate a notice of docket change without a new coversheet when attachments has been updated', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - attachments: true, + await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + attachments: true, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -273,15 +306,19 @@ describe('completeDocketEntryQCInteractor', () => { }); it('should generate a notice of docket change with a new coversheet when additional info fields are removed and addToCoversheet is true', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: true, - additionalInfo: undefined, - additionalInfo2: undefined, - certificateOfService: false, + await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + addToCoversheet: true, + additionalInfo: undefined, + additionalInfo2: undefined, + certificateOfService: false, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -296,16 +333,20 @@ describe('completeDocketEntryQCInteractor', () => { }); it('should generate a notice of docket change with a new coversheet when documentTitle has changed and addToCoversheeet is false', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: false, - additionalInfo: undefined, - additionalInfo2: undefined, - certificateOfService: false, - documentTitle: 'Something Different', + await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + addToCoversheet: false, + additionalInfo: undefined, + additionalInfo2: undefined, + certificateOfService: false, + documentTitle: 'Something Different', + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -320,12 +361,16 @@ describe('completeDocketEntryQCInteractor', () => { }); it('should not generate a new coversheet when the documentTitle has not changed and addToCoversheet is false', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: false, + await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + addToCoversheet: false, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -336,15 +381,19 @@ describe('completeDocketEntryQCInteractor', () => { }); it('should generate a new coversheet when additionalInfo is changed and addToCoversheet is true', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: true, - additionalInfo: 'additional info', - additionalInfo2: 'additional info 221', - certificateOfService: false, + await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + addToCoversheet: true, + additionalInfo: 'additional info', + additionalInfo2: 'additional info 221', + certificateOfService: false, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -359,15 +408,19 @@ describe('completeDocketEntryQCInteractor', () => { }); it('should generate a new coversheet when additionalInfo is NOT changed and addToCoversheet is true', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: true, - additionalInfo: 'additional info', - additionalInfo2: 'additional info', - certificateOfService: false, + await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + addToCoversheet: true, + additionalInfo: 'additional info', + additionalInfo2: 'additional info', + certificateOfService: false, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -403,13 +456,17 @@ describe('completeDocketEntryQCInteractor', () => { return mockNumberOfPages; }); - const result = await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - documentTitle: 'Something Else', - documentType: 'Memorandum in Support', + const result = await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + documentTitle: 'Something Else', + documentType: 'Memorandum in Support', + }, }, - }); + mockDocketClerkUser, + ); const noticeOfDocketChange = result.caseDetail.docketEntries.find( docketEntry => docketEntry.eventCode === 'NODC', @@ -454,13 +511,17 @@ describe('completeDocketEntryQCInteractor', () => { ], }); - const result = await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - documentTitle: 'Notice of Change of Address', - documentType: 'Notice of Change of Address', + const result = await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + documentTitle: 'Notice of Change of Address', + documentType: 'Notice of Change of Address', + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -477,13 +538,17 @@ describe('completeDocketEntryQCInteractor', () => { }); it('does not generate a document for paper service if the document is a Notice of Change of Address and the case has no paper service parties', async () => { - const result = await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - documentTitle: 'Notice of Change of Address', - documentType: 'Notice of Change of Address', + const result = await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + documentTitle: 'Notice of Change of Address', + documentType: 'Notice of Change of Address', + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -500,25 +565,29 @@ describe('completeDocketEntryQCInteractor', () => { }); it('should update only allowed editable fields on a docket entry document', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - documentTitle: 'My Edited Document', - documentType: 'Notice of Change of Address', - eventCode: 'NCA', - filedBy: 'Resp.', - filers: [mockPrimaryId], - freeText: 'Some text about this document', - hasOtherFilingParty: true, - isPaper: true, - otherFilingParty: 'Bert Brooks', - scenario: 'Nonstandard H', - secondaryDocument: { + await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + documentTitle: 'My Edited Document', documentType: 'Notice of Change of Address', - eventCode: 'A', + eventCode: 'NCA', + filedBy: 'Resp.', + filers: [mockPrimaryId], + freeText: 'Some text about this document', + hasOtherFilingParty: true, + isPaper: true, + otherFilingParty: 'Bert Brooks', + scenario: 'Nonstandard H', + secondaryDocument: { + documentType: 'Notice of Change of Address', + eventCode: 'A', + }, }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -548,6 +617,7 @@ describe('completeDocketEntryQCInteractor', () => { pending: true, }, }, + mockDocketClerkUser, ); expect( @@ -569,6 +639,7 @@ describe('completeDocketEntryQCInteractor', () => { receivedAt: '2021-01-01', // date only }, }, + mockDocketClerkUser, ); expect(caseDetail.docketEntries[0].receivedAt).toEqual( @@ -577,20 +648,20 @@ describe('completeDocketEntryQCInteractor', () => { }); it('sets the assigned users section from the selected section when it is defined and the user is a case services user', async () => { - applicationContext.getCurrentUser.mockReturnValue( - caseServicesSupervisorUser, - ); - await applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(caseServicesSupervisorUser); - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - selectedSection: DOCKET_SECTION, + await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + selectedSection: DOCKET_SECTION, + }, }, - }); + mockCaseServicesSupervisorUser, + ); const assignedWorkItem = applicationContext.getPersistenceGateway() @@ -601,20 +672,20 @@ describe('completeDocketEntryQCInteractor', () => { }); it('sets the section as Case Services when selected section is NOT defined and the user is a case services user', async () => { - applicationContext.getCurrentUser.mockReturnValue( - caseServicesSupervisorUser, - ); - await applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(caseServicesSupervisorUser); - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - selectedSection: undefined, + await completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + selectedSection: undefined, + }, }, - }); + mockCaseServicesSupervisorUser, + ); const assignedWorkItem = applicationContext.getPersistenceGateway() @@ -625,19 +696,19 @@ describe('completeDocketEntryQCInteractor', () => { }); it('throws the expected error if the lock is already acquired by another process', async () => { - applicationContext.getCurrentUser.mockReturnValue( - caseServicesSupervisorUser, - ); - mockLock = MOCK_ACTIVE_LOCK; await expect(() => - completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - selectedSection: undefined, + completeDocketEntryQCInteractor( + applicationContext, + { + entryMetadata: { + ...caseRecord.docketEntries[0], + selectedSection: undefined, + }, }, - }), + mockCaseServicesSupervisorUser, + ), ).rejects.toThrow('The document is currently being updated'); }); }); diff --git a/web-api/src/business/useCases/docketEntry/completeDocketEntryQCInteractor.ts b/web-api/src/business/useCases/docketEntry/completeDocketEntryQCInteractor.ts index f4ad5cbb587..610c88fc1c2 100644 --- a/web-api/src/business/useCases/docketEntry/completeDocketEntryQCInteractor.ts +++ b/web-api/src/business/useCases/docketEntry/completeDocketEntryQCInteractor.ts @@ -17,6 +17,7 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { User } from '../../../../../shared/src/business/entities/User'; import { addServedStampToDocument } from '@web-api/business/useCases/courtIssuedDocument/addServedStampToDocument'; import { aggregatePartiesForService } from '@shared/business/utilities/aggregatePartiesForService'; @@ -29,9 +30,8 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; const completeDocketEntryQC = async ( applicationContext: ServerApplicationContext, { entryMetadata }: { entryMetadata: any }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - const { PDFDocument } = await applicationContext.getPdfLib(); if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.DOCKET_ENTRY)) { @@ -57,7 +57,7 @@ const completeDocketEntryQC = async ( docketNumber, }); - let caseEntity = new Case(caseToUpdate, { applicationContext }); + let caseEntity = new Case(caseToUpdate, { authorizedUser }); const { index: docketRecordIndexUpdated } = caseEntity.docketEntries.find( record => record.docketEntryId === docketEntryId, ); @@ -114,7 +114,7 @@ const completeDocketEntryQC = async ( trialLocation: caseEntity.trialLocation, }, }, - { applicationContext, petitioners: caseToUpdate.petitioners }, + { authorizedUser, petitioners: caseToUpdate.petitioners }, ).validate(); updatedDocketEntry.setQCed(user); @@ -265,6 +265,7 @@ const completeDocketEntryQC = async ( } else if (needsNoticeOfDocketChange) { const noticeDocketEntryId = await generateNoticeOfDocketChangePdf({ applicationContext, + authorizedUser, docketChangeInfo, }); @@ -280,7 +281,7 @@ const completeDocketEntryQC = async ( isOnDocketRecord: true, processingStatus: DOCUMENT_PROCESSING_STATUS_OPTIONS.COMPLETE, }, - { applicationContext, petitioners: caseToUpdate.petitioners }, + { authorizedUser, petitioners: caseToUpdate.petitioners }, ); noticeUpdatedDocketEntry.setFiledBy(user); @@ -336,16 +337,19 @@ const completeDocketEntryQC = async ( await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); if (isNewCoverSheetNeeded) { - await applicationContext - .getUseCases() - .addCoversheetInteractor(applicationContext, { + await applicationContext.getUseCases().addCoversheetInteractor( + applicationContext, + { docketEntryId, docketNumber: caseEntity.docketNumber, - }); + }, + authorizedUser, + ); } return { diff --git a/web-api/src/business/useCases/docketEntry/editPaperFilingInteractor.locking.test.ts b/web-api/src/business/useCases/docketEntry/editPaperFilingInteractor.locking.test.ts index a72571e1ba3..8bc572d3751 100644 --- a/web-api/src/business/useCases/docketEntry/editPaperFilingInteractor.locking.test.ts +++ b/web-api/src/business/useCases/docketEntry/editPaperFilingInteractor.locking.test.ts @@ -7,8 +7,9 @@ import { editPaperFilingInteractor, handleLockError, } from './editPaperFilingInteractor'; -import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; +import { docketClerkUser } from '@shared/test/mockUsers'; import { getContactPrimary } from '../../../../../shared/src/business/entities/cases/Case'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('determineEntitiesToLock', () => { let mockParams; @@ -46,21 +47,16 @@ describe('determineEntitiesToLock', () => { describe('handleLockError', () => { const mockClientConnectionId = '987654'; - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - }); - - it('should determine who the user is based on applicationContext', async () => { - await handleLockError(applicationContext, { foo: 'bar' }); - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); - }); - it('should send a notification to the user with "retry_async_request" and the originalRequest', async () => { const mockOriginalRequest = { clientConnectionId: mockClientConnectionId, foo: 'bar', }; - await handleLockError(applicationContext, mockOriginalRequest); + await handleLockError( + applicationContext, + mockOriginalRequest, + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock .calls[0][0].message, @@ -99,7 +95,6 @@ describe('editPaperFilingInteractor', () => { applicationContext .getPersistenceGateway() .getLock.mockImplementation(() => mockLock); - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(docketClerkUser); @@ -133,7 +128,11 @@ describe('editPaperFilingInteractor', () => { it('should throw a ServiceUnavailableError if a Case is currently locked', async () => { await expect( - editPaperFilingInteractor(applicationContext, mockRequest), + editPaperFilingInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -143,7 +142,11 @@ describe('editPaperFilingInteractor', () => { it('should return a "retry_async_request" notification with the original request', async () => { await expect( - editPaperFilingInteractor(applicationContext, mockRequest), + editPaperFilingInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -156,7 +159,7 @@ describe('editPaperFilingInteractor', () => { originalRequest: mockRequest, requestToRetry: 'edit_paper_filing', }, - userId: docketClerkUser.userId, + userId: mockDocketClerkUser.userId, }); expect( @@ -171,7 +174,11 @@ describe('editPaperFilingInteractor', () => { }); it('should acquire a lock that lasts for 15 minutes', async () => { - await editPaperFilingInteractor(applicationContext, mockRequest); + await editPaperFilingInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -190,7 +197,11 @@ describe('editPaperFilingInteractor', () => { }); it('should remove the lock', async () => { - await editPaperFilingInteractor(applicationContext, mockRequest); + await editPaperFilingInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().removeLock, ).toHaveBeenCalledWith({ diff --git a/web-api/src/business/useCases/docketEntry/editPaperFilingInteractor.test.ts b/web-api/src/business/useCases/docketEntry/editPaperFilingInteractor.test.ts index aa6251949e4..e1d7318e0e8 100644 --- a/web-api/src/business/useCases/docketEntry/editPaperFilingInteractor.test.ts +++ b/web-api/src/business/useCases/docketEntry/editPaperFilingInteractor.test.ts @@ -6,12 +6,13 @@ import { } from '../../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; -import { - docketClerkUser, - petitionerUser, -} from '../../../../../shared/src/test/mockUsers'; +import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; import { editPaperFilingInteractor } from './editPaperFilingInteractor'; import { getContactPrimary } from '../../../../../shared/src/business/entities/cases/Case'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('editPaperFilingInteractor', () => { let caseRecord; @@ -73,8 +74,6 @@ describe('editPaperFilingInteractor', () => { ], }; - applicationContext.getCurrentUser.mockImplementation(() => docketClerkUser); - applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(docketClerkUser); @@ -87,24 +86,24 @@ describe('editPaperFilingInteractor', () => { describe('Save For Later or Serve Agnostic', () => { describe('Sad Path', () => { it('should throw an error when the user is not authorized to edit docket entries', async () => { - applicationContext.getCurrentUser.mockImplementation( - () => petitionerUser, - ); - await expect( - editPaperFilingInteractor(applicationContext, { - clientConnectionId, - docketEntryId: mockDocketEntryId, - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'My Document', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - filers: [mockPrimaryId], - isFileAttached: false, + editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: mockDocketEntryId, + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'My Document', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + filers: [mockPrimaryId], + isFileAttached: false, + }, + isSavingForLater: false, }, - isSavingForLater: false, - }), + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -112,12 +111,16 @@ describe('editPaperFilingInteractor', () => { const notFoundDocketEntryId = 'this is not an ID'; await expect( - editPaperFilingInteractor(applicationContext, { - clientConnectionId, - docketEntryId: notFoundDocketEntryId, - documentMetadata: {}, - isSavingForLater: true, - }), + editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: notFoundDocketEntryId, + documentMetadata: {}, + isSavingForLater: true, + }, + mockDocketClerkUser, + ), ).rejects.toThrow( `Docket entry ${notFoundDocketEntryId} was not found.`, ); @@ -125,15 +128,19 @@ describe('editPaperFilingInteractor', () => { it('should throw an error when the docket entry has already been served', async () => { await expect( - editPaperFilingInteractor(applicationContext, { - clientConnectionId, + editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, - docketEntryId: mockServedDocketEntryId, - documentMetadata: { - docketNumber: caseRecord.docketNumber, + docketEntryId: mockServedDocketEntryId, + documentMetadata: { + docketNumber: caseRecord.docketNumber, + }, + isSavingForLater: false, }, - isSavingForLater: false, - }), + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry has already been served'); }); @@ -142,12 +149,16 @@ describe('editPaperFilingInteractor', () => { docketEntry.isPendingService = true; await expect( - editPaperFilingInteractor(applicationContext, { - clientConnectionId, - docketEntryId: docketEntry.docketEntryId, - documentMetadata: docketEntry, - isSavingForLater: false, - }), + editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: docketEntry.docketEntryId, + documentMetadata: docketEntry, + isSavingForLater: false, + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry is already being served'); expect( @@ -165,19 +176,23 @@ describe('editPaperFilingInteractor', () => { .getUseCaseHelpers() .countPagesInDocument.mockResolvedValueOnce(2); - await editPaperFilingInteractor(applicationContext, { - clientConnectionId, - docketEntryId: mockDocketEntryId, - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'My Document', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - filers: [mockPrimaryId], - isFileAttached: true, + await editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: mockDocketEntryId, + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'My Document', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + filers: [mockPrimaryId], + isFileAttached: true, + }, + isSavingForLater: true, }, - isSavingForLater: true, - }); + mockDocketClerkUser, + ); const updatedDocketEntry = applicationContext .getUseCaseHelpers() @@ -194,19 +209,23 @@ describe('editPaperFilingInteractor', () => { }); it('should update the docket entry without updating the page count when the docket entry does NOT have a file attached', async () => { - await editPaperFilingInteractor(applicationContext, { - clientConnectionId, - docketEntryId: mockDocketEntryId, - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'My Document', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - filers: [mockPrimaryId], - isFileAttached: false, + await editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: mockDocketEntryId, + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'My Document', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + filers: [mockPrimaryId], + isFileAttached: false, + }, + isSavingForLater: true, }, - isSavingForLater: true, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -223,12 +242,16 @@ describe('editPaperFilingInteractor', () => { }); it('should not call the persistence method to set and unset the pending service status on the docket entry', async () => { - await editPaperFilingInteractor(applicationContext, { - clientConnectionId, - docketEntryId: mockDocketEntryId, - documentMetadata: caseRecord.docketEntries[0], - isSavingForLater: true, - }); + await editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: mockDocketEntryId, + documentMetadata: caseRecord.docketEntries[0], + isSavingForLater: true, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -237,12 +260,16 @@ describe('editPaperFilingInteractor', () => { }); it('should not generate a paper service url', async () => { - await editPaperFilingInteractor(applicationContext, { - clientConnectionId, - docketEntryId: mockDocketEntryId, - documentMetadata: caseRecord.docketEntries[0], - isSavingForLater: true, - }); + await editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: mockDocketEntryId, + documentMetadata: caseRecord.docketEntries[0], + isSavingForLater: true, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers() @@ -251,12 +278,16 @@ describe('editPaperFilingInteractor', () => { }); it('should send a message to the user when persisting edits has completed', async () => { - await editPaperFilingInteractor(applicationContext, { - clientConnectionId, - docketEntryId: mockDocketEntryId, - documentMetadata: caseRecord.docketEntries[0], - isSavingForLater: true, - }); + await editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: mockDocketEntryId, + documentMetadata: caseRecord.docketEntries[0], + isSavingForLater: true, + }, + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser, @@ -281,25 +312,30 @@ describe('editPaperFilingInteractor', () => { describe('Single Docketing', () => { describe('Happy Path', () => { it('should update only allowed editable fields on a docket entry document', async () => { - await editPaperFilingInteractor(applicationContext, { - clientConnectionId, - docketEntryId: mockDocketEntryId, - documentMetadata: { - docketEntryId: - 'maliciously Update Docket Entry Id. DONT SAVE ME.', - docketNumber: 'maliciously Updated Docket Number. DONT SAVE ME.', - documentTitle: 'My Edited Document', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - filers: [mockPrimaryId], - freeText: 'Some text about this document', - hasOtherFilingParty: true, - isFileAttached: true, - isPaper: true, - otherFilingParty: 'Bert Brooks', + await editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: mockDocketEntryId, + documentMetadata: { + docketEntryId: + 'maliciously Update Docket Entry Id. DONT SAVE ME.', + docketNumber: + 'maliciously Updated Docket Number. DONT SAVE ME.', + documentTitle: 'My Edited Document', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + filers: [mockPrimaryId], + freeText: 'Some text about this document', + hasOtherFilingParty: true, + isFileAttached: true, + isPaper: true, + otherFilingParty: 'Bert Brooks', + }, + isSavingForLater: false, }, - isSavingForLater: false, - }); + mockDocketClerkUser, + ); const updatedDocketEntry = applicationContext .getPersistenceGateway() @@ -318,12 +354,16 @@ describe('editPaperFilingInteractor', () => { }); it('should call the persistence method to set and unset the pending service status on the docket entry', async () => { - await editPaperFilingInteractor(applicationContext, { - clientConnectionId, - docketEntryId: mockDocketEntryId, - documentMetadata: caseRecord.docketEntries[0], - isSavingForLater: false, - }); + await editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: mockDocketEntryId, + documentMetadata: caseRecord.docketEntries[0], + isSavingForLater: false, + }, + mockDocketClerkUser, + ); const firstStatusCall = applicationContext.getPersistenceGateway() @@ -345,17 +385,21 @@ describe('editPaperFilingInteractor', () => { pdfUrl: mockPdfUrl, }); - await editPaperFilingInteractor(applicationContext, { - clientConnectionId, - docketEntryId: mockDocketEntryId, - documentMetadata: { - documentTitle: 'My Document', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - isFileAttached: true, + await editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: mockDocketEntryId, + documentMetadata: { + documentTitle: 'My Document', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + isFileAttached: true, + }, + isSavingForLater: false, }, - isSavingForLater: false, - }); + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser, @@ -386,12 +430,16 @@ describe('editPaperFilingInteractor', () => { ); await expect( - editPaperFilingInteractor(applicationContext, { - clientConnectionId, - docketEntryId: mockDocketEntryId, - documentMetadata: caseRecord.docketEntries[0], - isSavingForLater: false, - }), + editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + docketEntryId: mockDocketEntryId, + documentMetadata: caseRecord.docketEntries[0], + isSavingForLater: false, + }, + mockDocketClerkUser, + ), ).rejects.toThrow('whoops, that is an error!'); const firstStatusCall = @@ -425,18 +473,23 @@ describe('editPaperFilingInteractor', () => { }); const mockConsolidatedGroupDocketNumbers = ['101-23', '101-24']; - await editPaperFilingInteractor(applicationContext, { - clientConnectionId, - consolidatedGroupDocketNumbers: mockConsolidatedGroupDocketNumbers, - docketEntryId: mockDocketEntryId, - documentMetadata: { - documentTitle: 'My Document', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - isFileAttached: true, + await editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + consolidatedGroupDocketNumbers: + mockConsolidatedGroupDocketNumbers, + docketEntryId: mockDocketEntryId, + documentMetadata: { + documentTitle: 'My Document', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + isFileAttached: true, + }, + isSavingForLater: false, }, - isSavingForLater: false, - }); + mockDocketClerkUser, + ); const expectedCount = [ caseRecord.docketNumber, @@ -476,19 +529,23 @@ describe('editPaperFilingInteractor', () => { pdfUrl: mockedPaperServicePdfUrl, }); - await editPaperFilingInteractor(applicationContext, { - clientConnectionId, - consolidatedGroupDocketNumbers: ['101-23', '101-24'], - docketEntryId: mockDocketEntryId, - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'My Document', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - isFileAttached: true, + await editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + consolidatedGroupDocketNumbers: ['101-23', '101-24'], + docketEntryId: mockDocketEntryId, + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'My Document', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + isFileAttached: true, + }, + isSavingForLater: false, }, - isSavingForLater: false, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers() @@ -542,19 +599,23 @@ describe('editPaperFilingInteractor', () => { .getUseCaseHelpers() .serveDocumentAndGetPaperServicePdf.mockResolvedValue(undefined); - await editPaperFilingInteractor(applicationContext, { - clientConnectionId, - consolidatedGroupDocketNumbers: ['101-23', '101-24'], - docketEntryId: mockDocketEntryId, - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'My Document', - documentType: 'Memorandum in Support', - eventCode: 'MISP', - isFileAttached: true, + await editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + consolidatedGroupDocketNumbers: ['101-23', '101-24'], + docketEntryId: mockDocketEntryId, + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'My Document', + documentType: 'Memorandum in Support', + eventCode: 'MISP', + isFileAttached: true, + }, + isSavingForLater: false, }, - isSavingForLater: false, - }); + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser, @@ -593,13 +654,17 @@ describe('editPaperFilingInteractor', () => { }); await expect( - editPaperFilingInteractor(applicationContext, { - clientConnectionId, - consolidatedGroupDocketNumbers: [nonConsolidatedDocketNumber], - docketEntryId: mockDocketEntryId, - documentMetadata: caseRecord.docketEntries[0], - isSavingForLater: false, - }), + editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + consolidatedGroupDocketNumbers: [nonConsolidatedDocketNumber], + docketEntryId: mockDocketEntryId, + documentMetadata: caseRecord.docketEntries[0], + isSavingForLater: false, + }, + mockDocketClerkUser, + ), ).rejects.toThrow( 'Cannot multi-docket on a case that is not consolidated', ); @@ -614,16 +679,20 @@ describe('editPaperFilingInteractor', () => { }); await expect( - editPaperFilingInteractor(applicationContext, { - clientConnectionId, - consolidatedGroupDocketNumbers: ['101-23'], - docketEntryId: mockDocketEntryId, - documentMetadata: { - docketNumber: caseRecord.docketNumber, - isFileAttached: true, + editPaperFilingInteractor( + applicationContext, + { + clientConnectionId, + consolidatedGroupDocketNumbers: ['101-23'], + docketEntryId: mockDocketEntryId, + documentMetadata: { + docketNumber: caseRecord.docketNumber, + isFileAttached: true, + }, + isSavingForLater: false, }, - isSavingForLater: false, - }), + mockDocketClerkUser, + ), ).rejects.toThrow( 'Cannot multi-docket on a case that is not consolidated', ); diff --git a/web-api/src/business/useCases/docketEntry/editPaperFilingInteractor.ts b/web-api/src/business/useCases/docketEntry/editPaperFilingInteractor.ts index 349721d5279..86e1003bd8a 100644 --- a/web-api/src/business/useCases/docketEntry/editPaperFilingInteractor.ts +++ b/web-api/src/business/useCases/docketEntry/editPaperFilingInteractor.ts @@ -1,3 +1,7 @@ +import { + AuthUser, + UnknownAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; import { Case, isLeadCase, @@ -34,14 +38,18 @@ interface IEditPaperFilingRequest { export const editPaperFiling = async ( applicationContext: ServerApplicationContext, request: IEditPaperFilingRequest, + authorizedUser: UnknownAuthUser, ) => { request.consolidatedGroupDocketNumbers = request.consolidatedGroupDocketNumbers || []; - authorizeRequest(applicationContext); + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.DOCKET_ENTRY)) { + throw new UnauthorizedError('Unauthorized'); + } const { caseEntity, docketEntryEntity } = await getDocketEntryToEdit({ applicationContext, + authorizedUser, docketEntryId: request.docketEntryId, docketNumber: request.documentMetadata.docketNumber, }); @@ -58,6 +66,7 @@ export const editPaperFiling = async ( return editPaperFilingStrategy({ applicationContext, + authorizedUser, caseEntity, docketEntryEntity, request, @@ -88,6 +97,7 @@ const getEditPaperFilingStrategy = ({ const saveForLaterStrategy = async ({ applicationContext, + authorizedUser, caseEntity, docketEntryEntity, request, @@ -96,15 +106,15 @@ const saveForLaterStrategy = async ({ request: IEditPaperFilingRequest; caseEntity: Case; docketEntryEntity: DocketEntry; + authorizedUser: AuthUser; }) => { - const authorizedUser = applicationContext.getCurrentUser(); - const user = await applicationContext .getPersistenceGateway() .getUserById({ applicationContext, userId: authorizedUser.userId }); const updatedDocketEntryEntity = await updateDocketEntry({ applicationContext, + authorizedUser, caseEntity, docketEntry: docketEntryEntity, documentMetadata: request.documentMetadata, @@ -119,6 +129,7 @@ const saveForLaterStrategy = async ({ await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); @@ -141,6 +152,7 @@ const saveForLaterStrategy = async ({ const multiDocketServeStrategy = async ({ applicationContext, + authorizedUser, caseEntity, docketEntryEntity, request, @@ -149,6 +161,7 @@ const multiDocketServeStrategy = async ({ caseEntity: Case; docketEntryEntity: DocketEntry; request: IEditPaperFilingRequest; + authorizedUser: AuthUser; }) => { validateDocketEntryCanBeServed({ documentMetadata: request.documentMetadata, @@ -164,7 +177,10 @@ const multiDocketServeStrategy = async ({ ); const consolidatedCaseEntities = consolidatedCaseRecords.map( - consolidatedCase => new Case(consolidatedCase, { applicationContext }), + consolidatedCase => + new Case(consolidatedCase, { + authorizedUser, + }), ); validateMultiDocketPaperFilingRequest({ @@ -174,10 +190,9 @@ const multiDocketServeStrategy = async ({ const caseEntitiesToFileOn = [caseEntity, ...consolidatedCaseEntities]; - const authorizedUser = applicationContext.getCurrentUser(); - await serveDocketEntry({ applicationContext, + authorizedUser, caseEntitiesToFileOn, clientConnectionId: request.clientConnectionId, docketEntryEntity, @@ -190,6 +205,7 @@ const multiDocketServeStrategy = async ({ const singleDocketServeStrategy = async ({ applicationContext, + authorizedUser, caseEntity, docketEntryEntity, request, @@ -198,6 +214,7 @@ const singleDocketServeStrategy = async ({ caseEntity: Case; docketEntryEntity: DocketEntry; request: IEditPaperFilingRequest; + authorizedUser: AuthUser; }) => { validateDocketEntryCanBeServed({ documentMetadata: request.documentMetadata, @@ -205,10 +222,9 @@ const singleDocketServeStrategy = async ({ const caseEntitiesToFileOn = [caseEntity]; - const authorizedUser = applicationContext.getCurrentUser(); - await serveDocketEntry({ applicationContext, + authorizedUser, caseEntitiesToFileOn, clientConnectionId: request.clientConnectionId, docketEntryEntity, @@ -222,6 +238,7 @@ const singleDocketServeStrategy = async ({ // *********************************** Small Helper Functions *********************************** const serveDocketEntry = async ({ applicationContext, + authorizedUser, caseEntitiesToFileOn, clientConnectionId, docketEntryEntity, @@ -238,6 +255,7 @@ const serveDocketEntry = async ({ userId: string; subjectCaseEntity: Case; message: string; + authorizedUser: AuthUser; }) => { await applicationContext .getPersistenceGateway() @@ -255,6 +273,7 @@ const serveDocketEntry = async ({ const updatedDocketEntry = await updateDocketEntry({ applicationContext, + authorizedUser, caseEntity: subjectCaseEntity, docketEntry: docketEntryEntity, documentMetadata, @@ -267,7 +286,7 @@ const serveDocketEntry = async ({ applicationContext, caseEntity: aCase, docketEntryEntity: new DocketEntry(cloneDeep(updatedDocketEntry), { - applicationContext, + authorizedUser, }), subjectCaseDocketNumber: subjectCaseEntity.docketNumber, user, @@ -367,18 +386,9 @@ const validateMultiDocketPaperFilingRequest = ({ }); }; -const authorizeRequest = ( - applicationContext: ServerApplicationContext, -): void => { - const authorizedUser = applicationContext.getCurrentUser(); - - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.DOCKET_ENTRY)) { - throw new UnauthorizedError('Unauthorized'); - } -}; - const updateDocketEntry = async ({ applicationContext, + authorizedUser, caseEntity, docketEntry, documentMetadata, @@ -389,6 +399,7 @@ const updateDocketEntry = async ({ docketEntry: DocketEntry; documentMetadata: any; userId: string; + authorizedUser: AuthUser; }): Promise => { const editableFields = { addToCoversheet: documentMetadata.addToCoversheet, @@ -427,7 +438,10 @@ const updateDocketEntry = async ({ relationship: DOCUMENT_RELATIONSHIPS.PRIMARY, userId, }, - { applicationContext, petitioners: caseEntity.petitioners }, + { + authorizedUser, + petitioners: caseEntity.petitioners, + }, ); if (editableFields.isFileAttached) { @@ -474,12 +488,14 @@ const updateAndSaveWorkItem = async ({ const getDocketEntryToEdit = async ({ applicationContext, + authorizedUser, docketEntryId, docketNumber, }: { applicationContext: ServerApplicationContext; docketNumber: string; docketEntryId: string; + authorizedUser: AuthUser; }): Promise<{ caseEntity: Case; docketEntryEntity: DocketEntry; @@ -491,7 +507,9 @@ const getDocketEntryToEdit = async ({ docketNumber, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { + authorizedUser, + }); const docketEntryEntity = caseEntity.getDocketEntryById({ docketEntryId, @@ -519,19 +537,23 @@ export const determineEntitiesToLock = ( ttl: 900, }); -export const handleLockError = async (applicationContext, originalRequest) => { - const user = applicationContext.getCurrentUser(); - - await applicationContext.getNotificationGateway().sendNotificationToUser({ - applicationContext, - clientConnectionId: originalRequest.clientConnectionId, - message: { - action: 'retry_async_request', - originalRequest, - requestToRetry: 'edit_paper_filing', - }, - userId: user.userId, - }); +export const handleLockError = async ( + applicationContext, + originalRequest, + authorizedUser: UnknownAuthUser, +) => { + if (authorizedUser?.userId) { + await applicationContext.getNotificationGateway().sendNotificationToUser({ + applicationContext, + clientConnectionId: originalRequest.clientConnectionId, + message: { + action: 'retry_async_request', + originalRequest, + requestToRetry: 'edit_paper_filing', + }, + userId: authorizedUser.userId, + }); + } }; export const editPaperFilingInteractor = withLocking( diff --git a/web-api/src/business/useCases/docketEntry/fileCourtIssuedDocketEntryInteractor.test.ts b/web-api/src/business/useCases/docketEntry/fileCourtIssuedDocketEntryInteractor.test.ts index d854e48b237..0d1be995e20 100644 --- a/web-api/src/business/useCases/docketEntry/fileCourtIssuedDocketEntryInteractor.test.ts +++ b/web-api/src/business/useCases/docketEntry/fileCourtIssuedDocketEntryInteractor.test.ts @@ -12,10 +12,14 @@ import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { fileCourtIssuedDocketEntryInteractor } from './fileCourtIssuedDocketEntryInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('fileCourtIssuedDocketEntryInteractor', () => { let caseRecord; - const mockUserId = applicationContext.getUniqueId(); + const mockUserId = mockDocketClerkUser.userId; const docketClerkUser = { name: 'Emmett Lathrop "Doc" Brown, Ph.D.', role: ROLES.docketClerk, @@ -35,7 +39,6 @@ describe('fileCourtIssuedDocketEntryInteractor', () => { applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(docketClerkUser); - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); caseRecord = { ...MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE, @@ -82,30 +85,36 @@ describe('fileCourtIssuedDocketEntryInteractor', () => { }); it('should throw an error if not authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - fileCourtIssuedDocketEntryInteractor(applicationContext, { - docketNumbers: [], - documentMeta: { - docketEntryId: caseRecord.docketEntries[1].docketEntryId, - documentType: 'Memorandum in Support', - }, - subjectDocketNumber: caseRecord.docketNumber, - } as any), + fileCourtIssuedDocketEntryInteractor( + applicationContext, + { + docketNumbers: [], + documentMeta: { + docketEntryId: caseRecord.docketEntries[1].docketEntryId, + documentType: 'Memorandum in Support', + }, + subjectDocketNumber: caseRecord.docketNumber, + } as any, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should throw an error if the document is not found on the case', async () => { await expect( - fileCourtIssuedDocketEntryInteractor(applicationContext, { - documentMeta: { - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bd', - docketNumbers: [], - documentType: 'Order', - }, - subjectDocketNumber: caseRecord.docketNumber, - } as any), + fileCourtIssuedDocketEntryInteractor( + applicationContext, + { + documentMeta: { + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bd', + docketNumbers: [], + documentType: 'Order', + }, + subjectDocketNumber: caseRecord.docketNumber, + } as any, + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry not found'); }); @@ -113,29 +122,37 @@ describe('fileCourtIssuedDocketEntryInteractor', () => { caseRecord.docketEntries[1].isOnDocketRecord = true; await expect( - fileCourtIssuedDocketEntryInteractor(applicationContext, { + fileCourtIssuedDocketEntryInteractor( + applicationContext, + { + docketNumbers: [], + documentMeta: { + docketEntryId: caseRecord.docketEntries[1].docketEntryId, + documentType: 'Order', + }, + subjectDocketNumber: caseRecord.docketNumber, + } as any, + mockDocketClerkUser, + ), + ).rejects.toThrow('Docket entry has already been added to docket record'); + }); + + it('should call countPagesInDocument, updateCase, and saveWorkItem', async () => { + await fileCourtIssuedDocketEntryInteractor( + applicationContext, + { docketNumbers: [], documentMeta: { - docketEntryId: caseRecord.docketEntries[1].docketEntryId, + docketEntryId: caseRecord.docketEntries[0].docketEntryId, + documentTitle: 'Order', documentType: 'Order', + eventCode: 'O', + generatedDocumentTitle: 'Generated Order Document Title', }, subjectDocketNumber: caseRecord.docketNumber, - } as any), - ).rejects.toThrow('Docket entry has already been added to docket record'); - }); - - it('should call countPagesInDocument, updateCase, and saveWorkItem', async () => { - await fileCourtIssuedDocketEntryInteractor(applicationContext, { - docketNumbers: [], - documentMeta: { - docketEntryId: caseRecord.docketEntries[0].docketEntryId, - documentTitle: 'Order', - documentType: 'Order', - eventCode: 'O', - generatedDocumentTitle: 'Generated Order Document Title', - }, - subjectDocketNumber: caseRecord.docketNumber, - } as any); + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -146,17 +163,21 @@ describe('fileCourtIssuedDocketEntryInteractor', () => { }); it('should call putWorkItemInUsersOutbox with correct leadDocketNumber when documentType is unservable', async () => { - await fileCourtIssuedDocketEntryInteractor(applicationContext, { - docketNumbers: [], - documentMeta: { - docketEntryId: caseRecord.docketEntries[0].docketEntryId, - documentTitle: 'Hearing Exhibits for [anything]', - documentType: 'Hearing Exhibits', - eventCode: 'HE', - generatedDocumentTitle: 'Hearing Exhibits for meeeeeee', - }, - subjectDocketNumber: caseRecord.docketNumber, - } as any); + await fileCourtIssuedDocketEntryInteractor( + applicationContext, + { + docketNumbers: [], + documentMeta: { + docketEntryId: caseRecord.docketEntries[0].docketEntryId, + documentTitle: 'Hearing Exhibits for [anything]', + documentType: 'Hearing Exhibits', + eventCode: 'HE', + generatedDocumentTitle: 'Hearing Exhibits for meeeeeee', + }, + subjectDocketNumber: caseRecord.docketNumber, + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -171,18 +192,22 @@ describe('fileCourtIssuedDocketEntryInteractor', () => { }); it('should call updateCase with the docket entry set as pending if the document is a tracked document', async () => { - await fileCourtIssuedDocketEntryInteractor(applicationContext, { - docketNumbers: [], - documentMeta: { - docketEntryId: caseRecord.docketEntries[1].docketEntryId, - documentTitle: 'Order to Show Cause', - documentType: 'Order to Show Cause', - eventCode: 'OSC', - filingDate: '2011-03-01T21:40:46.415Z', - generatedDocumentTitle: 'Generated Order Document Title', - }, - subjectDocketNumber: caseRecord.docketNumber, - } as any); + await fileCourtIssuedDocketEntryInteractor( + applicationContext, + { + docketNumbers: [], + documentMeta: { + docketEntryId: caseRecord.docketEntries[1].docketEntryId, + documentTitle: 'Order to Show Cause', + documentType: 'Order to Show Cause', + eventCode: 'OSC', + filingDate: '2011-03-01T21:40:46.415Z', + generatedDocumentTitle: 'Generated Order Document Title', + }, + subjectDocketNumber: caseRecord.docketNumber, + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -200,20 +225,24 @@ describe('fileCourtIssuedDocketEntryInteractor', () => { }); it('should set isDraft to false on a document when creating a court issued docket entry', async () => { - await fileCourtIssuedDocketEntryInteractor(applicationContext, { - docketNumbers: [], - documentMeta: { - date: '2019-03-01T21:40:46.415Z', - docketEntryId: caseRecord.docketEntries[2].docketEntryId, - documentTitle: 'Transcript of [anything] on [date]', - documentType: 'Transcript', - eventCode: TRANSCRIPT_EVENT_CODE, - freeText: 'Dogs', - generatedDocumentTitle: 'Transcript of Dogs on 03-01-19', - isDraft: true, - }, - subjectDocketNumber: caseRecord.docketNumber, - } as any); + await fileCourtIssuedDocketEntryInteractor( + applicationContext, + { + docketNumbers: [], + documentMeta: { + date: '2019-03-01T21:40:46.415Z', + docketEntryId: caseRecord.docketEntries[2].docketEntryId, + documentTitle: 'Transcript of [anything] on [date]', + documentType: 'Transcript', + eventCode: TRANSCRIPT_EVENT_CODE, + freeText: 'Dogs', + generatedDocumentTitle: 'Transcript of Dogs on 03-01-19', + isDraft: true, + }, + subjectDocketNumber: caseRecord.docketNumber, + } as any, + mockDocketClerkUser, + ); const lastDocumentIndex = applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -230,20 +259,24 @@ describe('fileCourtIssuedDocketEntryInteractor', () => { it('should delete the draftOrderState from the docketEntry', async () => { const docketEntryToUpdate = caseRecord.docketEntries[2]; - await fileCourtIssuedDocketEntryInteractor(applicationContext, { - docketNumbers: [], - documentMeta: { - docketEntryId: docketEntryToUpdate.docketEntryId, - documentTitle: docketEntryToUpdate.documentTitle, - documentType: docketEntryToUpdate.documentType, - draftOrderState: { - documentContents: 'Some content', - richText: 'some content', + await fileCourtIssuedDocketEntryInteractor( + applicationContext, + { + docketNumbers: [], + documentMeta: { + docketEntryId: docketEntryToUpdate.docketEntryId, + documentTitle: docketEntryToUpdate.documentTitle, + documentType: docketEntryToUpdate.documentType, + draftOrderState: { + documentContents: 'Some content', + richText: 'some content', + }, + eventCode: docketEntryToUpdate.eventCode, }, - eventCode: docketEntryToUpdate.eventCode, - }, - subjectDocketNumber: caseRecord.docketNumber, - } as any); + subjectDocketNumber: caseRecord.docketNumber, + } as any, + mockDocketClerkUser, + ); const updatedDocketEntry = applicationContext .getUseCaseHelpers() @@ -255,20 +288,24 @@ describe('fileCourtIssuedDocketEntryInteractor', () => { }); it('should use original case caption to create case title when creating work item', async () => { - await fileCourtIssuedDocketEntryInteractor(applicationContext, { - docketNumbers: [], - documentMeta: { - date: '2019-03-01T21:40:46.415Z', - docketEntryId: caseRecord.docketEntries[0].docketEntryId, - documentTitle: 'Order', - documentType: 'Order', - eventCode: 'O', - freeText: 'Dogs', - generatedDocumentTitle: 'Transcript of Dogs on 03-01-19', - serviceStamp: 'Served', - }, - subjectDocketNumber: caseRecord.docketNumber, - } as any); + await fileCourtIssuedDocketEntryInteractor( + applicationContext, + { + docketNumbers: [], + documentMeta: { + date: '2019-03-01T21:40:46.415Z', + docketEntryId: caseRecord.docketEntries[0].docketEntryId, + documentTitle: 'Order', + documentType: 'Order', + eventCode: 'O', + freeText: 'Dogs', + generatedDocumentTitle: 'Transcript of Dogs on 03-01-19', + serviceStamp: 'Served', + }, + subjectDocketNumber: caseRecord.docketNumber, + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveWorkItem.mock.calls[0][0] @@ -310,17 +347,23 @@ describe('fileCourtIssuedDocketEntryInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockResolvedValueOnce(LEAD_CASE); - await fileCourtIssuedDocketEntryInteractor(applicationContext, { - docketNumbers: [MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber], - documentMeta: { - docketEntryId: LEAD_CASE.docketEntries[0].docketEntryId, + await fileCourtIssuedDocketEntryInteractor( + applicationContext, + { + docketNumbers: [ + MOCK_CONSOLIDATED_1_CASE_WITH_PAPER_SERVICE.docketNumber, + ], + documentMeta: { + docketEntryId: LEAD_CASE.docketEntries[0].docketEntryId, - documentType: 'Trial Exhibits', - eventCode: 'TE', - freeText: 'free text testing', + documentType: 'Trial Exhibits', + eventCode: 'TE', + freeText: 'free text testing', + }, + subjectDocketNumber: LEAD_CASE.docketNumber, }, - subjectDocketNumber: LEAD_CASE.docketNumber, - }); + mockDocketClerkUser, + ); const docketEntryOnNonLead = applicationContext .getUseCaseHelpers() @@ -346,7 +389,32 @@ describe('fileCourtIssuedDocketEntryInteractor', () => { mockLock = MOCK_LOCK; await expect( - fileCourtIssuedDocketEntryInteractor(applicationContext, { + fileCourtIssuedDocketEntryInteractor( + applicationContext, + { + docketNumbers: [], + documentMeta: { + docketEntryId: caseRecord.docketEntries[0].docketEntryId, + documentTitle: 'Order', + documentType: 'Order', + eventCode: 'O', + generatedDocumentTitle: 'Generated Order Document Title', + }, + subjectDocketNumber: caseRecord.docketNumber, + } as any, + mockDocketClerkUser, + ), + ).rejects.toThrow(ServiceUnavailableError); + + expect( + applicationContext.getPersistenceGateway().getCaseByDocketNumber, + ).not.toHaveBeenCalled(); + }); + + it('should acquire and remove the lock on the case', async () => { + await fileCourtIssuedDocketEntryInteractor( + applicationContext, + { docketNumbers: [], documentMeta: { docketEntryId: caseRecord.docketEntries[0].docketEntryId, @@ -356,26 +424,9 @@ describe('fileCourtIssuedDocketEntryInteractor', () => { generatedDocumentTitle: 'Generated Order Document Title', }, subjectDocketNumber: caseRecord.docketNumber, - } as any), - ).rejects.toThrow(ServiceUnavailableError); - - expect( - applicationContext.getPersistenceGateway().getCaseByDocketNumber, - ).not.toHaveBeenCalled(); - }); - - it('should acquire and remove the lock on the case', async () => { - await fileCourtIssuedDocketEntryInteractor(applicationContext, { - docketNumbers: [], - documentMeta: { - docketEntryId: caseRecord.docketEntries[0].docketEntryId, - documentTitle: 'Order', - documentType: 'Order', - eventCode: 'O', - generatedDocumentTitle: 'Generated Order Document Title', - }, - subjectDocketNumber: caseRecord.docketNumber, - } as any); + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -395,17 +446,21 @@ describe('fileCourtIssuedDocketEntryInteractor', () => { it('should acquire and remove the lock for every case', async () => { const docketNumbers = ['888-88', '999-99']; - await fileCourtIssuedDocketEntryInteractor(applicationContext, { - docketNumbers, - documentMeta: { - docketEntryId: caseRecord.docketEntries[0].docketEntryId, - documentTitle: 'Order', - documentType: 'Order', - eventCode: 'O', - generatedDocumentTitle: 'Generated Order Document Title', - }, - subjectDocketNumber: caseRecord.docketNumber, - } as any); + await fileCourtIssuedDocketEntryInteractor( + applicationContext, + { + docketNumbers, + documentMeta: { + docketEntryId: caseRecord.docketEntries[0].docketEntryId, + documentTitle: 'Order', + documentType: 'Order', + eventCode: 'O', + generatedDocumentTitle: 'Generated Order Document Title', + }, + subjectDocketNumber: caseRecord.docketNumber, + } as any, + mockDocketClerkUser, + ); const expectedIdentifiers = docketNumbers.map( docketNumber => `case|${docketNumber}`, diff --git a/web-api/src/business/useCases/docketEntry/fileCourtIssuedDocketEntryInteractor.ts b/web-api/src/business/useCases/docketEntry/fileCourtIssuedDocketEntryInteractor.ts index 51224cf11f2..225809039cb 100644 --- a/web-api/src/business/useCases/docketEntry/fileCourtIssuedDocketEntryInteractor.ts +++ b/web-api/src/business/useCases/docketEntry/fileCourtIssuedDocketEntryInteractor.ts @@ -7,6 +7,7 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { WorkItem } from '../../../../../shared/src/business/entities/WorkItem'; import { omit } from 'lodash'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; @@ -29,9 +30,8 @@ export const fileCourtIssuedDocketEntry = async ( documentMeta: any; subjectDocketNumber: string; }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - const hasPermission = isAuthorized(authorizedUser, ROLE_PERMISSIONS.DOCKET_ENTRY) || isAuthorized(authorizedUser, ROLE_PERMISSIONS.CREATE_ORDER_DOCKET_ENTRY); @@ -50,7 +50,7 @@ export const fileCourtIssuedDocketEntry = async ( }); let subjectCaseToUpdateEntity = new Case(subjectCaseToUpdate, { - applicationContext, + authorizedUser, }); const subjectDocketEntry = subjectCaseToUpdateEntity.getDocketEntryById({ @@ -84,7 +84,7 @@ export const fileCourtIssuedDocketEntry = async ( docketNumber, }); - let caseEntity = new Case(caseToUpdate, { applicationContext }); + let caseEntity = new Case(caseToUpdate, { authorizedUser }); const docketEntryEntity = new DocketEntry( { @@ -108,7 +108,7 @@ export const fileCourtIssuedDocketEntry = async ( serviceStamp: documentMeta.serviceStamp, trialLocation: documentMeta.trialLocation, }, - { applicationContext }, + { authorizedUser }, ); docketEntryEntity.setFiledBy(user); @@ -135,8 +135,7 @@ export const fileCourtIssuedDocketEntry = async ( trialDate: caseEntity.trialDate, trialLocation: caseEntity.trialLocation, }, - { applicationContext }, - caseEntity, + { caseEntity }, ); if (isUnservable) { @@ -167,6 +166,7 @@ export const fileCourtIssuedDocketEntry = async ( const saveItems = [ applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }), ]; @@ -202,7 +202,7 @@ export const fileCourtIssuedDocketEntry = async ( }); const subjectCase = new Case(rawSubjectCase, { - applicationContext, + authorizedUser, }).validate(); return subjectCase.toRawObject(); }; diff --git a/web-api/src/business/useCases/docketEntry/generatePrintableFilingReceiptInteractor.test.ts b/web-api/src/business/useCases/docketEntry/generatePrintableFilingReceiptInteractor.test.ts index 392d3f30873..4b8d02a2cf4 100644 --- a/web-api/src/business/useCases/docketEntry/generatePrintableFilingReceiptInteractor.test.ts +++ b/web-api/src/business/useCases/docketEntry/generatePrintableFilingReceiptInteractor.test.ts @@ -1,12 +1,12 @@ import { MOCK_CASE, MOCK_CONSOLIDATED_CASE_SUMMARY, -} from '../../../../../shared/src/test/mockCase'; -import { MOCK_USERS } from '../../../../../shared/src/test/mockUsers'; +} from '@shared/test/mockCase'; import { RawConsolidatedCaseSummary } from '@shared/business/dto/cases/ConsolidatedCaseSummary'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { generatePrintableFilingReceiptInteractor } from './generatePrintableFilingReceiptInteractor'; -import { getContactPrimary } from '../../../../../shared/src/business/entities/cases/Case'; +import { getContactPrimary } from '@shared/business/entities/cases/Case'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('generatePrintableFilingReceiptInteractor', () => { const mockPrimaryDocketEntryId = MOCK_CASE.docketEntries[0].docketEntryId; @@ -45,9 +45,6 @@ describe('generatePrintableFilingReceiptInteractor', () => { }; beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue( - MOCK_USERS['a7d90c05-f6cd-442c-a168-202db587f16f'], - ); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(mockCase); @@ -59,13 +56,17 @@ describe('generatePrintableFilingReceiptInteractor', () => { }); it('should call the Receipt of Filing document generator', async () => { - await generatePrintableFilingReceiptInteractor(applicationContext, { - docketNumber: mockCase.docketNumber, - documentsFiled: { - primaryDocumentId: mockPrimaryDocketEntryId, + await generatePrintableFilingReceiptInteractor( + applicationContext, + { + docketNumber: mockCase.docketNumber, + documentsFiled: { + primaryDocumentId: mockPrimaryDocketEntryId, + }, + fileAcrossConsolidatedGroup: false, }, - fileAcrossConsolidatedGroup: false, - }); + mockDocketClerkUser, + ); expect( applicationContext.getDocumentGenerators().receiptOfFiling, @@ -79,22 +80,26 @@ describe('generatePrintableFilingReceiptInteractor', () => { }); it('should populate filedBy on the receipt of filing', async () => { - await generatePrintableFilingReceiptInteractor(applicationContext, { - docketNumber: mockCase.docketNumber, - documentsFiled: { - hasSecondarySupportingDocuments: true, - hasSupportingDocuments: true, - primaryDocumentId: mockPrimaryDocketEntryId, - secondaryDocument: { docketEntryId: 4 }, - secondaryDocumentFile: { fakeDocument: true }, - secondarySupportingDocuments: [ - { docketEntryId: '3' }, - { docketEntryId: '7' }, - ], - supportingDocuments: [{ docketEntryId: '1' }, { docketEntryId: '2' }], + await generatePrintableFilingReceiptInteractor( + applicationContext, + { + docketNumber: mockCase.docketNumber, + documentsFiled: { + hasSecondarySupportingDocuments: true, + hasSupportingDocuments: true, + primaryDocumentId: mockPrimaryDocketEntryId, + secondaryDocument: { docketEntryId: 4 }, + secondaryDocumentFile: { fakeDocument: true }, + secondarySupportingDocuments: [ + { docketEntryId: '3' }, + { docketEntryId: '7' }, + ], + supportingDocuments: [{ docketEntryId: '1' }, { docketEntryId: '2' }], + }, + fileAcrossConsolidatedGroup: false, }, - fileAcrossConsolidatedGroup: false, - }); + mockDocketClerkUser, + ); const receiptMockCall = applicationContext.getDocumentGenerators().receiptOfFiling.mock @@ -109,22 +114,26 @@ describe('generatePrintableFilingReceiptInteractor', () => { }); it('acquires document information', async () => { - await generatePrintableFilingReceiptInteractor(applicationContext, { - docketNumber: mockCase.docketNumber, - documentsFiled: { - hasSecondarySupportingDocuments: true, - hasSupportingDocuments: true, - primaryDocumentId: mockPrimaryDocketEntryId, - secondaryDocument: { docketEntryId: 4 }, - secondaryDocumentFile: { fakeDocument: true }, - secondarySupportingDocuments: [ - { docketEntryId: '3' }, - { docketEntryId: '7' }, - ], - supportingDocuments: [{ docketEntryId: '1' }, { docketEntryId: '2' }], + await generatePrintableFilingReceiptInteractor( + applicationContext, + { + docketNumber: mockCase.docketNumber, + documentsFiled: { + hasSecondarySupportingDocuments: true, + hasSupportingDocuments: true, + primaryDocumentId: mockPrimaryDocketEntryId, + secondaryDocument: { docketEntryId: 4 }, + secondaryDocumentFile: { fakeDocument: true }, + secondarySupportingDocuments: [ + { docketEntryId: '3' }, + { docketEntryId: '7' }, + ], + supportingDocuments: [{ docketEntryId: '1' }, { docketEntryId: '2' }], + }, + fileAcrossConsolidatedGroup: false, }, - fileAcrossConsolidatedGroup: false, - }); + mockDocketClerkUser, + ); const receiptMockCall = applicationContext.getDocumentGenerators().receiptOfFiling.mock @@ -135,15 +144,19 @@ describe('generatePrintableFilingReceiptInteractor', () => { }); it('formats certificateOfServiceDate', async () => { - await generatePrintableFilingReceiptInteractor(applicationContext, { - docketNumber: mockCase.docketNumber, - documentsFiled: { - certificateOfService: true, - certificateOfServiceDate: '2019-08-25T05:00:00.000Z', - primaryDocumentId: mockPrimaryDocketEntryId, + await generatePrintableFilingReceiptInteractor( + applicationContext, + { + docketNumber: mockCase.docketNumber, + documentsFiled: { + certificateOfService: true, + certificateOfServiceDate: '2019-08-25T05:00:00.000Z', + primaryDocumentId: mockPrimaryDocketEntryId, + }, + fileAcrossConsolidatedGroup: false, }, - fileAcrossConsolidatedGroup: false, - }); + mockDocketClerkUser, + ); const receiptMockCall = applicationContext.getDocumentGenerators().receiptOfFiling.mock @@ -154,22 +167,26 @@ describe('generatePrintableFilingReceiptInteractor', () => { }); it('should call the Receipt of Filing document generator with consolidatedCases array populated when fileAcrossConsolidatedGroup is true', async () => { - await generatePrintableFilingReceiptInteractor(applicationContext, { - docketNumber: mockCase.docketNumber, - documentsFiled: { - hasSecondarySupportingDocuments: true, - hasSupportingDocuments: true, - primaryDocumentId: mockPrimaryDocketEntryId, - secondaryDocument: { docketEntryId: 4 }, - secondaryDocumentFile: { fakeDocument: true }, - secondarySupportingDocuments: [ - { docketEntryId: '3' }, - { docketEntryId: '7' }, - ], - supportingDocuments: [{ docketEntryId: '1' }, { docketEntryId: '2' }], + await generatePrintableFilingReceiptInteractor( + applicationContext, + { + docketNumber: mockCase.docketNumber, + documentsFiled: { + hasSecondarySupportingDocuments: true, + hasSupportingDocuments: true, + primaryDocumentId: mockPrimaryDocketEntryId, + secondaryDocument: { docketEntryId: 4 }, + secondaryDocumentFile: { fakeDocument: true }, + secondarySupportingDocuments: [ + { docketEntryId: '3' }, + { docketEntryId: '7' }, + ], + supportingDocuments: [{ docketEntryId: '1' }, { docketEntryId: '2' }], + }, + fileAcrossConsolidatedGroup: true, }, - fileAcrossConsolidatedGroup: true, - }); + mockDocketClerkUser, + ); const receiptMockCall = applicationContext.getDocumentGenerators().receiptOfFiling.mock @@ -185,22 +202,26 @@ describe('generatePrintableFilingReceiptInteractor', () => { }); it('should call the Receipt of Filing document generator with consolidatedCases array unpopulated (emptyArray) when fileAcrossConsolidatedGroup is true', async () => { - await generatePrintableFilingReceiptInteractor(applicationContext, { - docketNumber: mockCase.docketNumber, - documentsFiled: { - hasSecondarySupportingDocuments: true, - hasSupportingDocuments: true, - primaryDocumentId: mockPrimaryDocketEntryId, - secondaryDocument: { docketEntryId: 4 }, - secondaryDocumentFile: { fakeDocument: true }, - secondarySupportingDocuments: [ - { docketEntryId: '3' }, - { docketEntryId: '7' }, - ], - supportingDocuments: [{ docketEntryId: '1' }, { docketEntryId: '2' }], + await generatePrintableFilingReceiptInteractor( + applicationContext, + { + docketNumber: mockCase.docketNumber, + documentsFiled: { + hasSecondarySupportingDocuments: true, + hasSupportingDocuments: true, + primaryDocumentId: mockPrimaryDocketEntryId, + secondaryDocument: { docketEntryId: 4 }, + secondaryDocumentFile: { fakeDocument: true }, + secondarySupportingDocuments: [ + { docketEntryId: '3' }, + { docketEntryId: '7' }, + ], + supportingDocuments: [{ docketEntryId: '1' }, { docketEntryId: '2' }], + }, + fileAcrossConsolidatedGroup: false, }, - fileAcrossConsolidatedGroup: false, - }); + mockDocketClerkUser, + ); const receiptMockCall = applicationContext.getDocumentGenerators().receiptOfFiling.mock diff --git a/web-api/src/business/useCases/docketEntry/generatePrintableFilingReceiptInteractor.ts b/web-api/src/business/useCases/docketEntry/generatePrintableFilingReceiptInteractor.ts index 659a435097b..c3f09b3d653 100644 --- a/web-api/src/business/useCases/docketEntry/generatePrintableFilingReceiptInteractor.ts +++ b/web-api/src/business/useCases/docketEntry/generatePrintableFilingReceiptInteractor.ts @@ -1,19 +1,22 @@ import { Case } from '../../../../../shared/src/business/entities/cases/Case'; import { DocketEntry } from '../../../../../shared/src/business/entities/DocketEntry'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { getCaseCaptionMeta } from '../../../../../shared/src/business/utilities/getCaseCaptionMeta'; const getDocumentInfo = ({ applicationContext, + authorizedUser, documentData, petitioners, }: { applicationContext: ServerApplicationContext; + authorizedUser: UnknownAuthUser; documentData: any; petitioners?: any[]; }) => { const doc = new DocketEntry(documentData, { - applicationContext, + authorizedUser, petitioners, }); @@ -51,6 +54,7 @@ export const generatePrintableFilingReceiptInteractor = async ( documentsFiled: any; fileAcrossConsolidatedGroup: boolean; }, + authorizedUser: UnknownAuthUser, ) => { const caseRecord = await applicationContext .getPersistenceGateway() @@ -59,7 +63,9 @@ export const generatePrintableFilingReceiptInteractor = async ( docketNumber, }); - let caseEntity = new Case(caseRecord, { applicationContext }).validate(); + let caseEntity = new Case(caseRecord, { + authorizedUser, + }).validate(); if (fileAcrossConsolidatedGroup && !caseRecord.leadDocketNumber) { throw new Error( @@ -80,12 +86,13 @@ export const generatePrintableFilingReceiptInteractor = async ( .sort((a, b) => a.sortableDocketNumber - b.sortableDocketNumber) .map(consolidatedCaseRecord => consolidatedCaseRecord.docketNumber); caseEntity = new Case(leadCase, { - applicationContext, + authorizedUser, }).validate(); } const primaryDocument = getDocumentInfo({ applicationContext, + authorizedUser, documentData: documentsFiled, petitioners: caseRecord.petitioners, }); @@ -101,21 +108,30 @@ export const generatePrintableFilingReceiptInteractor = async ( if (documentsFiled.hasSupportingDocuments) { filingReceiptDocumentParams.supportingDocuments = documentsFiled.supportingDocuments.map(doc => - getDocumentInfo({ applicationContext, documentData: doc }), + getDocumentInfo({ + applicationContext, + authorizedUser, + documentData: doc, + }), ); } if (documentsFiled.secondaryDocumentFile) { filingReceiptDocumentParams.secondaryDocument = getDocumentInfo({ applicationContext, + authorizedUser, documentData: documentsFiled.secondaryDocument, - } as any); + }); } if (documentsFiled.hasSecondarySupportingDocuments) { filingReceiptDocumentParams.secondarySupportingDocuments = documentsFiled.secondarySupportingDocuments.map(doc => - getDocumentInfo({ applicationContext, documentData: doc }), + getDocumentInfo({ + applicationContext, + authorizedUser, + documentData: doc, + }), ); } diff --git a/web-api/src/business/useCases/docketEntry/sealDocketEntryInteractor.test.ts b/web-api/src/business/useCases/docketEntry/sealDocketEntryInteractor.test.ts index 856ecc14dc0..2cdf662d0b7 100644 --- a/web-api/src/business/useCases/docketEntry/sealDocketEntryInteractor.test.ts +++ b/web-api/src/business/useCases/docketEntry/sealDocketEntryInteractor.test.ts @@ -1,79 +1,79 @@ -import { - DOCKET_ENTRY_SEALED_TO_TYPES, - ROLES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { DOCKET_ENTRY_SEALED_TO_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { sealDocketEntryInteractor } from './sealDocketEntryInteractor'; describe('sealDocketEntryInteractor', () => { const answerDocketEntryId = 'e6b81f4d-1e47-423a-8caf-6d2fdc3d3859'; it('should require a value for dockeEntrySealedTo', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - }); - await expect( - sealDocketEntryInteractor(applicationContext, { - docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', - docketEntrySealedTo: undefined, - docketNumber: '101-20', - }), + sealDocketEntryInteractor( + applicationContext, + { + docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', + //@ts-ignore this error is intentional + docketEntrySealedTo: undefined, + docketNumber: '101-20', + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry sealed to is required'); }); it('should only allow docket clerks to seal a docket entry', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - }); - await expect( - sealDocketEntryInteractor(applicationContext, { - docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', - docketEntrySealedTo: DOCKET_ENTRY_SEALED_TO_TYPES.PUBLIC, - docketNumber: '101-20', - }), + sealDocketEntryInteractor( + applicationContext, + { + docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', + docketEntrySealedTo: DOCKET_ENTRY_SEALED_TO_TYPES.PUBLIC, + docketNumber: '101-20', + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should throw an error when the docket entry is not found', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - }); - await expect( - sealDocketEntryInteractor(applicationContext, { - docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', - docketEntrySealedTo: DOCKET_ENTRY_SEALED_TO_TYPES.PUBLIC, - docketNumber: '101-20', - }), + sealDocketEntryInteractor( + applicationContext, + { + docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', + docketEntrySealedTo: DOCKET_ENTRY_SEALED_TO_TYPES.PUBLIC, + docketNumber: '101-20', + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry not found'); }); it('should throw an error when an invalid option is provided for docketEntrySealedTo', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - }); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE); await expect( - sealDocketEntryInteractor(applicationContext, { - docketEntryId: answerDocketEntryId, - docketEntrySealedTo: 'invalid', - docketNumber: '101-20', - }), + sealDocketEntryInteractor( + applicationContext, + { + docketEntryId: answerDocketEntryId, + docketEntrySealedTo: 'invalid', + docketNumber: '101-20', + }, + mockDocketClerkUser, + ), ).rejects.toThrow( 'The DocketEntry entity was invalid. {"sealedTo":"\'sealedTo\' must be one of [External, Public]"}', ); }); it('should mark the docket entry as sealed and save', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - }); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE); @@ -84,6 +84,7 @@ describe('sealDocketEntryInteractor', () => { docketEntrySealedTo: DOCKET_ENTRY_SEALED_TO_TYPES.PUBLIC, docketNumber: MOCK_CASE.docketNumber, }, + mockDocketClerkUser, ); expect(sealedDocketEntry).toBeDefined(); expect(sealedDocketEntry.isSealed).toEqual(true); diff --git a/web-api/src/business/useCases/docketEntry/sealDocketEntryInteractor.ts b/web-api/src/business/useCases/docketEntry/sealDocketEntryInteractor.ts index b531b6ae923..eb9f7c86140 100644 --- a/web-api/src/business/useCases/docketEntry/sealDocketEntryInteractor.ts +++ b/web-api/src/business/useCases/docketEntry/sealDocketEntryInteractor.ts @@ -5,16 +5,8 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; -/** - * seals a given docket entry on a case - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {string} providers.docketEntryId the docket entry id to seal - * @param {string} providers.docketNumber the docket number of the case - * @returns {object} the updated docket entry after it has been sealed - */ export const sealDocketEntryInteractor = async ( applicationContext: ServerApplicationContext, { @@ -26,13 +18,12 @@ export const sealDocketEntryInteractor = async ( docketEntrySealedTo: string; docketNumber: string; }, + authorizedUser: UnknownAuthUser, ) => { if (!docketEntrySealedTo) { throw new Error('Docket entry sealed to is required'); } - const authorizedUser = applicationContext.getCurrentUser(); - const hasPermission = isAuthorized( authorizedUser, ROLE_PERMISSIONS.SEAL_DOCKET_ENTRY, @@ -49,7 +40,7 @@ export const sealDocketEntryInteractor = async ( docketNumber, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); const docketEntryEntity = caseEntity.getDocketEntryById({ docketEntryId, diff --git a/web-api/src/business/useCases/docketEntry/strikeDocketEntryInteractor.test.ts b/web-api/src/business/useCases/docketEntry/strikeDocketEntryInteractor.test.ts index 6072ec48d1d..f8acf7e7e80 100644 --- a/web-api/src/business/useCases/docketEntry/strikeDocketEntryInteractor.test.ts +++ b/web-api/src/business/useCases/docketEntry/strikeDocketEntryInteractor.test.ts @@ -5,7 +5,9 @@ import { PARTY_TYPES, ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { strikeDocketEntryInteractor } from './strikeDocketEntryInteractor'; describe('strikeDocketEntryInteractor', () => { @@ -64,42 +66,40 @@ describe('strikeDocketEntryInteractor', () => { }); it('should throw an error if not authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - strikeDocketEntryInteractor(applicationContext, { - docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', - docketNumber: caseRecord.docketNumber, - }), + strikeDocketEntryInteractor( + applicationContext, + { + docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', + docketNumber: caseRecord.docketNumber, + }, + {} as UnknownAuthUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should throw an error if the docket record is not found on the case', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.docketClerk, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); - await expect( - strikeDocketEntryInteractor(applicationContext, { - docketEntryId: 'does-not-exist', - docketNumber: caseRecord.docketNumber, - }), + strikeDocketEntryInteractor( + applicationContext, + { + docketEntryId: 'does-not-exist', + docketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry not found'); }); it('should call getCaseByDocketNumber, getUserById, and updateDocketEntry', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.docketClerk, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); - - await strikeDocketEntryInteractor(applicationContext, { - docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', - docketNumber: caseRecord.docketNumber, - }); + await strikeDocketEntryInteractor( + applicationContext, + { + docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', + docketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -120,10 +120,14 @@ describe('strikeDocketEntryInteractor', () => { caseRecord.docketEntries[0].isOnDocketRecord = false; await expect( - strikeDocketEntryInteractor(applicationContext, { - docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', - docketNumber: caseRecord.docketNumber, - }), + strikeDocketEntryInteractor( + applicationContext, + { + docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', + docketNumber: caseRecord.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow( 'Cannot strike a document that is not on the docket record.', ); diff --git a/web-api/src/business/useCases/docketEntry/strikeDocketEntryInteractor.ts b/web-api/src/business/useCases/docketEntry/strikeDocketEntryInteractor.ts index 4f3c342446d..c1e94f416b4 100644 --- a/web-api/src/business/useCases/docketEntry/strikeDocketEntryInteractor.ts +++ b/web-api/src/business/useCases/docketEntry/strikeDocketEntryInteractor.ts @@ -5,25 +5,16 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; -/** - * strikes a given docket entry on a case - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {string} providers.docketEntryId the docket entry id to strike - * @param {string} providers.docketNumber the docket number of the case - * @returns {object} the updated case after the docket entry is stricken - */ export const strikeDocketEntryInteractor = async ( applicationContext: ServerApplicationContext, { docketEntryId, docketNumber, }: { docketEntryId: string; docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - const hasPermission = isAuthorized( authorizedUser, ROLE_PERMISSIONS.EDIT_DOCKET_ENTRY, @@ -40,7 +31,7 @@ export const strikeDocketEntryInteractor = async ( docketNumber, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); const docketEntryEntity = caseEntity.getDocketEntryById({ docketEntryId, diff --git a/web-api/src/business/useCases/docketEntry/unsealDocketEntryInteractor.test.ts b/web-api/src/business/useCases/docketEntry/unsealDocketEntryInteractor.test.ts index 5f93eb31c30..2cb6e29fa3b 100644 --- a/web-api/src/business/useCases/docketEntry/unsealDocketEntryInteractor.test.ts +++ b/web-api/src/business/useCases/docketEntry/unsealDocketEntryInteractor.test.ts @@ -1,41 +1,41 @@ import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { unsealDocketEntryInteractor } from './unsealDocketEntryInteractor'; describe('unsealDocketEntryInteractor', () => { const answerDocketEntryId = 'e6b81f4d-1e47-423a-8caf-6d2fdc3d3859'; it('should only allow docket clerks to unseal a docket entry', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - }); - await expect( - unsealDocketEntryInteractor(applicationContext, { - docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', - docketNumber: '101-20', - }), + unsealDocketEntryInteractor( + applicationContext, + { + docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', + docketNumber: '101-20', + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should throw an error when the docket entry is not found', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - }); - await expect( - unsealDocketEntryInteractor(applicationContext, { - docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', - docketNumber: '101-20', - }), + unsealDocketEntryInteractor( + applicationContext, + { + docketEntryId: '8675309b-18d0-43ec-bafb-654e83405411', + docketNumber: '101-20', + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry not found'); }); it('should mark the docket entry as unsealed and save', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - }); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE); @@ -45,6 +45,7 @@ describe('unsealDocketEntryInteractor', () => { docketEntryId: answerDocketEntryId, docketNumber: MOCK_CASE.docketNumber, }, + mockDocketClerkUser, ); expect(unsealedDocketEntry).toBeDefined(); expect(unsealedDocketEntry.isSealed).toEqual(false); diff --git a/web-api/src/business/useCases/docketEntry/unsealDocketEntryInteractor.ts b/web-api/src/business/useCases/docketEntry/unsealDocketEntryInteractor.ts index f61f81a9af5..3023d54006c 100644 --- a/web-api/src/business/useCases/docketEntry/unsealDocketEntryInteractor.ts +++ b/web-api/src/business/useCases/docketEntry/unsealDocketEntryInteractor.ts @@ -5,6 +5,7 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * unseals a given docket entry on a case @@ -21,9 +22,8 @@ export const unsealDocketEntryInteractor = async ( docketEntryId, docketNumber, }: { docketEntryId: string; docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - const hasPermission = isAuthorized( authorizedUser, ROLE_PERMISSIONS.SEAL_DOCKET_ENTRY, @@ -40,7 +40,7 @@ export const unsealDocketEntryInteractor = async ( docketNumber, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); const docketEntryEntity = caseEntity.getDocketEntryById({ docketEntryId, diff --git a/web-api/src/business/useCases/docketEntry/updateCourtIssuedDocketEntryInteractor.test.ts b/web-api/src/business/useCases/docketEntry/updateCourtIssuedDocketEntryInteractor.test.ts index c3c84239beb..b1fd2d76a75 100644 --- a/web-api/src/business/useCases/docketEntry/updateCourtIssuedDocketEntryInteractor.test.ts +++ b/web-api/src/business/useCases/docketEntry/updateCourtIssuedDocketEntryInteractor.test.ts @@ -8,7 +8,9 @@ import { import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; import { ServiceUnavailableError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { updateCourtIssuedDocketEntryInteractor } from './updateCourtIssuedDocketEntryInteractor'; describe('updateCourtIssuedDocketEntryInteractor', () => { @@ -62,33 +64,51 @@ describe('updateCourtIssuedDocketEntryInteractor', () => { beforeEach(() => { mockLock = undefined; - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.docketClerk, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); }); it('should throw an error if not authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - updateCourtIssuedDocketEntryInteractor(applicationContext, { - documentMeta: { - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bc', - docketNumber: caseRecord.docketNumber, - documentType: 'Memorandum in Support', - eventCode: 'MISP', + updateCourtIssuedDocketEntryInteractor( + applicationContext, + { + documentMeta: { + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bc', + docketNumber: caseRecord.docketNumber, + documentType: 'Memorandum in Support', + eventCode: 'MISP', + }, }, - }), + {} as UnknownAuthUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should throw an error if the document is not found on the case', async () => { await expect( - updateCourtIssuedDocketEntryInteractor(applicationContext, { + updateCourtIssuedDocketEntryInteractor( + applicationContext, + { + documentMeta: { + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bc', + docketNumber: caseRecord.docketNumber, + documentType: 'Order', + eventCode: 'O', + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', + }, + }, + mockDocketClerkUser, + ), + ).rejects.toThrow('Document not found'); + }); + + it('should call updateCase and saveWorkItem', async () => { + await updateCourtIssuedDocketEntryInteractor( + applicationContext, + { documentMeta: { - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335bc', + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335ba', docketNumber: caseRecord.docketNumber, documentType: 'Order', eventCode: 'O', @@ -96,22 +116,9 @@ describe('updateCourtIssuedDocketEntryInteractor', () => { signedByUserId: mockUserId, signedJudgeName: 'Dredd', }, - }), - ).rejects.toThrow('Document not found'); - }); - - it('should call updateCase and saveWorkItem', async () => { - await updateCourtIssuedDocketEntryInteractor(applicationContext, { - documentMeta: { - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335ba', - docketNumber: caseRecord.docketNumber, - documentType: 'Order', - eventCode: 'O', - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -122,18 +129,22 @@ describe('updateCourtIssuedDocketEntryInteractor', () => { }); it('should not update non-editable fields on the document', async () => { - await updateCourtIssuedDocketEntryInteractor(applicationContext, { - documentMeta: { - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335ba', - docketNumber: caseRecord.docketNumber, - documentType: 'Order', - eventCode: 'O', - objections: OBJECTIONS_OPTIONS_MAP.NO, - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', + await updateCourtIssuedDocketEntryInteractor( + applicationContext, + { + documentMeta: { + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335ba', + docketNumber: caseRecord.docketNumber, + documentType: 'Order', + eventCode: 'O', + objections: OBJECTIONS_OPTIONS_MAP.NO, + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -148,17 +159,21 @@ describe('updateCourtIssuedDocketEntryInteractor', () => { mockLock = MOCK_LOCK; await expect( - updateCourtIssuedDocketEntryInteractor(applicationContext, { - documentMeta: { - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335ba', - docketNumber: caseRecord.docketNumber, - documentType: 'Order', - eventCode: 'O', - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', + updateCourtIssuedDocketEntryInteractor( + applicationContext, + { + documentMeta: { + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335ba', + docketNumber: caseRecord.docketNumber, + documentType: 'Order', + eventCode: 'O', + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', + }, }, - }), + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -167,17 +182,21 @@ describe('updateCourtIssuedDocketEntryInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await updateCourtIssuedDocketEntryInteractor(applicationContext, { - documentMeta: { - docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335ba', - docketNumber: caseRecord.docketNumber, - documentType: 'Order', - eventCode: 'O', - signedAt: '2019-03-01T21:40:46.415Z', - signedByUserId: mockUserId, - signedJudgeName: 'Dredd', + await updateCourtIssuedDocketEntryInteractor( + applicationContext, + { + documentMeta: { + docketEntryId: 'c54ba5a9-b37b-479d-9201-067ec6e335ba', + docketNumber: caseRecord.docketNumber, + documentType: 'Order', + eventCode: 'O', + signedAt: '2019-03-01T21:40:46.415Z', + signedByUserId: mockUserId, + signedJudgeName: 'Dredd', + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/docketEntry/updateCourtIssuedDocketEntryInteractor.ts b/web-api/src/business/useCases/docketEntry/updateCourtIssuedDocketEntryInteractor.ts index 942ef654892..e4596606c72 100644 --- a/web-api/src/business/useCases/docketEntry/updateCourtIssuedDocketEntryInteractor.ts +++ b/web-api/src/business/useCases/docketEntry/updateCourtIssuedDocketEntryInteractor.ts @@ -6,21 +6,14 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; -/** - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {object} providers.documentMeta document details to go on the record - * @returns {object} the updated case after the documents are added - */ export const updateCourtIssuedDocketEntry = async ( applicationContext: ServerApplicationContext, { documentMeta }: { documentMeta: any }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - const hasPermission = isAuthorized(authorizedUser, ROLE_PERMISSIONS.DOCKET_ENTRY) || isAuthorized(authorizedUser, ROLE_PERMISSIONS.CREATE_ORDER_DOCKET_ENTRY); @@ -38,7 +31,7 @@ export const updateCourtIssuedDocketEntry = async ( docketNumber, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { authorizedUser }); const currentDocketEntry = caseEntity.getDocketEntryById({ docketEntryId, @@ -74,7 +67,7 @@ export const updateCourtIssuedDocketEntry = async ( editState: JSON.stringify(editableFields), isOnDocketRecord: true, }, - { applicationContext }, + { authorizedUser }, ); docketEntryEntity.setFiledBy(user); @@ -102,6 +95,7 @@ export const updateCourtIssuedDocketEntry = async ( }), applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }), ]; diff --git a/web-api/src/business/useCases/docketEntry/updateDocketEntryMetaInteractor.shouldGenerateCoversheetForDocketEntry.test.ts b/web-api/src/business/useCases/docketEntry/updateDocketEntryMetaInteractor.shouldGenerateCoversheetForDocketEntry.test.ts index 2830600ceda..ce3a2233360 100644 --- a/web-api/src/business/useCases/docketEntry/updateDocketEntryMetaInteractor.shouldGenerateCoversheetForDocketEntry.test.ts +++ b/web-api/src/business/useCases/docketEntry/updateDocketEntryMetaInteractor.shouldGenerateCoversheetForDocketEntry.test.ts @@ -1,5 +1,4 @@ import { DocketEntry } from '../../../../../shared/src/business/entities/DocketEntry'; -import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { shouldGenerateCoversheetForDocketEntry } from './updateDocketEntryMetaInteractor'; describe('updateDocketEntryMetaInteractor shouldGenerateCoversheetForDocketEntry', () => { @@ -14,7 +13,7 @@ describe('updateDocketEntryMetaInteractor shouldGenerateCoversheetForDocketEntry judge: 'Buch', userId: '38c36925-c936-44c5-b219-e13039f7d235', }, - { applicationContext }, + { authorizedUser: undefined }, ); let entryRequiresCoverSheet = false; diff --git a/web-api/src/business/useCases/docketEntry/updateDocketEntryMetaInteractor.test.ts b/web-api/src/business/useCases/docketEntry/updateDocketEntryMetaInteractor.test.ts index 87c7ab16acd..dea9d2dd9fd 100644 --- a/web-api/src/business/useCases/docketEntry/updateDocketEntryMetaInteractor.test.ts +++ b/web-api/src/business/useCases/docketEntry/updateDocketEntryMetaInteractor.test.ts @@ -6,9 +6,10 @@ import { UnauthorizedError, } from '@web-api/errors/errors'; import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; -import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; import { getContactPrimary } from '../../../../../shared/src/business/entities/cases/Case'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { updateDocketEntryMetaInteractor } from './updateDocketEntryMetaInteractor'; describe('updateDocketEntryMetaInteractor', () => { @@ -120,9 +121,6 @@ describe('updateDocketEntryMetaInteractor', () => { judge: 'Buch', }, ]; - - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue({ @@ -155,10 +153,14 @@ describe('updateDocketEntryMetaInteractor', () => { mockLock = MOCK_LOCK; await expect( - updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: mockDocketEntries[0], - docketNumber: MOCK_CASE.docketNumber, - }), + updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: mockDocketEntries[0], + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -167,10 +169,14 @@ describe('updateDocketEntryMetaInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: mockDocketEntries[0], - docketNumber: MOCK_CASE.docketNumber, - }); + await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: mockDocketEntries[0], + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -189,13 +195,15 @@ describe('updateDocketEntryMetaInteractor', () => { }); it('should throw an Unauthorized error if the user is not authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: undefined, - docketNumber: MOCK_CASE.docketNumber, - }), + updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: undefined, + docketNumber: MOCK_CASE.docketNumber, + }, + {} as UnknownAuthUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -204,59 +212,83 @@ describe('updateDocketEntryMetaInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(undefined); await expect( - updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: undefined, - docketNumber: '999-99', - }), + updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: undefined, + docketNumber: '999-99', + }, + mockDocketClerkUser, + ), ).rejects.toThrow(NotFoundError); }); it('should throw an error when the docket entry has not been served', async () => { await expect( - updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - docketEntryId: mockDocketEntries[3].docketEntryId, // Order that has not been served + updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + docketEntryId: mockDocketEntries[3].docketEntryId, // Order that has not been served + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }), + mockDocketClerkUser, + ), ).rejects.toThrow('Unable to update unserved docket entry.'); }); it('should throw an error when the docket entry is not found on the case', async () => { await expect( - updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[6], - docketEntryId: 'not-a-guid', + updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[6], + docketEntryId: 'not-a-guid', + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }), + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry with id not-a-guid not found.'); }); it("should not throw an error when the docket entry has not been served and it's unservable", async () => { await expect( - updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: mockDocketEntries[4], // Unservable document - docketNumber: MOCK_CASE.docketNumber, - }), + updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: mockDocketEntries[4], // Unservable document + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).resolves.not.toThrow(); }); it("should not throw an error when the docket entry has not been served and it's a minute entry", async () => { await expect( - updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: mockDocketEntries[7], // Minute entry - docketNumber: MOCK_CASE.docketNumber, - }), + updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: mockDocketEntries[7], // Minute entry + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ), ).resolves.not.toThrow(); }); it('should call the persistence method to load the case by its docket number', async () => { - await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: mockDocketEntries[0], - docketNumber: MOCK_CASE.docketNumber, - }); + await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: mockDocketEntries[0], + docketNumber: MOCK_CASE.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -274,13 +306,17 @@ describe('updateDocketEntryMetaInteractor', () => { servedAt: '2020-01-01T00:01:00.000Z', }; - const result = await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[0], - ...editedFields, + const result = await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[0], + ...editedFields, + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); const updatedDocketEntry = result.docketEntries.find( record => record.index === 1, @@ -289,13 +325,17 @@ describe('updateDocketEntryMetaInteractor', () => { }); it('should update a non-required field to undefined if undefined value is passed in', async () => { - const result = await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[0], - freeText: undefined, + const result = await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[0], + freeText: undefined, + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); const updatedDocketEntry = result.docketEntries.find( record => record.index === 1, @@ -304,13 +344,17 @@ describe('updateDocketEntryMetaInteractor', () => { }); it('should generate a new coversheet for the document if the servedAt field is changed', async () => { - await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[0], - servedAt: '2020-01-01T00:01:00.000Z', + await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[0], + servedAt: '2020-01-01T00:01:00.000Z', + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -318,13 +362,17 @@ describe('updateDocketEntryMetaInteractor', () => { }); it('should NOT generate a new coversheet for the document if the servedAt field metadata formatted as YYYY-MM-DD is equivalent to the strict ISO formatted date on the entity', async () => { - await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[0], - servedAt: '2019-01-01', + await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[0], + servedAt: '2019-01-01', + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -334,15 +382,19 @@ describe('updateDocketEntryMetaInteractor', () => { it('should generate a new coversheet for the document if the filingDate field is changed on a document that requires a coversheet', async () => { mockDocketEntries[3].servedAt = '2012-02-22T02:22:00.000Z'; mockDocketEntries[3].servedParties = [{ name: 'bob evans' }]; - await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[3], // originally an Order - documentType: 'U.S.C.A', - eventCode: 'USCA', // changing to USCA - which DOES require a coversheet - filingDate: '2020-02-22T02:22:00.000Z', + await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[3], // originally an Order + documentType: 'U.S.C.A', + eventCode: 'USCA', // changing to USCA - which DOES require a coversheet + filingDate: '2020-02-22T02:22:00.000Z', + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -350,13 +402,17 @@ describe('updateDocketEntryMetaInteractor', () => { }); it('should generate a new coversheet for the document if the filingDate field is changed on a document that requires a coversheet', async () => { - await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[4], // was already a USCA - which DOES require a coversheet - filingDate: '2012-02-22T02:22:00.000Z', + await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[4], // was already a USCA - which DOES require a coversheet + filingDate: '2012-02-22T02:22:00.000Z', + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -376,13 +432,17 @@ describe('updateDocketEntryMetaInteractor', () => { mockDocketEntries[4].servedParties = [{ name: 'bob evans' }]; expect(mockDocketEntries[4].eventCode).toBe('USCA'); // requires a cover sheet. - await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[4], - eventCode: 'MISC', // does NOT require a cover sheet + await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[4], + eventCode: 'MISC', // does NOT require a cover sheet + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().removeCoversheet, @@ -390,13 +450,17 @@ describe('updateDocketEntryMetaInteractor', () => { }); it('should not generate a coversheet for the document if the filingDate field is changed on a document that does NOT require a coversheet', async () => { - await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[5], // HEAR - which does NOT require a coversheet - filingDate: '2012-02-22T02:22:00.000Z', + await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[5], // HEAR - which does NOT require a coversheet + filingDate: '2012-02-22T02:22:00.000Z', + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -404,13 +468,17 @@ describe('updateDocketEntryMetaInteractor', () => { }); it('should not generate a new coversheet for a court-issued docket entry if the servedAt field is changed', async () => { - await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[1], - servedAt: '2019-01-02T00:01:00.000Z', + await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[1], + servedAt: '2019-01-02T00:01:00.000Z', + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -418,13 +486,17 @@ describe('updateDocketEntryMetaInteractor', () => { }); it('should make a call to update the docketEntryEntity before adding a coversheet when the filingDate field is changed', async () => { - await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[0], - filingDate: '2020-08-01T00:01:00.000Z', + await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[0], + filingDate: '2020-08-01T00:01:00.000Z', + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateDocketEntry.mock @@ -436,13 +508,17 @@ describe('updateDocketEntryMetaInteractor', () => { }); it('should add a new coversheet when filingDate field is changed', async () => { - await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[0], - filingDate: '2020-01-01T00:01:00.000Z', + await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[0], + filingDate: '2020-01-01T00:01:00.000Z', + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor.mock.calls[0][1], @@ -453,14 +529,18 @@ describe('updateDocketEntryMetaInteractor', () => { }); it('should NOT generate a new coversheet for the document if the servedAt and filingDate fields are NOT changed', async () => { - await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[0], - filingDate: mockDocketEntries[0].filingDate, - servedAt: mockDocketEntries[0].servedAt, + await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[0], + filingDate: mockDocketEntries[0].filingDate, + servedAt: mockDocketEntries[0].servedAt, + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -468,13 +548,17 @@ describe('updateDocketEntryMetaInteractor', () => { }); it('should not call addCoversheetInteractor if filingDate field is changed and the docket entry is a minute entry', async () => { - await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[2], // minute entry - filingDate: '2020-01-01T00:01:00.000Z', + await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[2], // minute entry + filingDate: '2020-01-01T00:01:00.000Z', + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -482,13 +566,17 @@ describe('updateDocketEntryMetaInteractor', () => { }); it('should call the updateCase persistence method', async () => { - await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[0], - documentTitle: 'Updated Description', + await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[0], + documentTitle: 'Updated Description', + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -497,28 +585,36 @@ describe('updateDocketEntryMetaInteractor', () => { it('should not throw an error when a null certificate of service date is passed for a docket entry without an associated document', async () => { await expect( - updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[0], - action: 'asdf', - certificateOfServiceDate: null, - documentTitle: 'Request for Place of Trial at Houston, Texas', - eventCode: 'RQT', - filingDate: '2020-02-03T08:06:07.539Z', + updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[0], + action: 'asdf', + certificateOfServiceDate: null, + documentTitle: 'Request for Place of Trial at Houston, Texas', + eventCode: 'RQT', + filingDate: '2020-02-03T08:06:07.539Z', + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }), + mockDocketClerkUser, + ), ).resolves.not.toThrow(); }); it('should update the document pending status and the automatic blocked status of the case when setting pending to true', async () => { - const result = await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[0], - pending: true, + const result = await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[0], + pending: true, + }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); const updatedDocketEntry = result.docketEntries.find( record => record.index === 1, @@ -530,15 +626,19 @@ describe('updateDocketEntryMetaInteractor', () => { }); it('should update the previousDocument', async () => { - const result = await updateDocketEntryMetaInteractor(applicationContext, { - docketEntryMeta: { - ...mockDocketEntries[0], - previousDocument: { - ...mockDocketEntries[1], + const result = await updateDocketEntryMetaInteractor( + applicationContext, + { + docketEntryMeta: { + ...mockDocketEntries[0], + previousDocument: { + ...mockDocketEntries[1], + }, }, + docketNumber: MOCK_CASE.docketNumber, }, - docketNumber: MOCK_CASE.docketNumber, - }); + mockDocketClerkUser, + ); const updatedDocketEntry = result.docketEntries.find( record => record.index === 1, diff --git a/web-api/src/business/useCases/docketEntry/updateDocketEntryMetaInteractor.ts b/web-api/src/business/useCases/docketEntry/updateDocketEntryMetaInteractor.ts index fa633c8222e..453a5ea9e67 100644 --- a/web-api/src/business/useCases/docketEntry/updateDocketEntryMetaInteractor.ts +++ b/web-api/src/business/useCases/docketEntry/updateDocketEntryMetaInteractor.ts @@ -10,28 +10,20 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { createISODateString } from '../../../../../shared/src/business/utilities/DateHandler'; import { getDocumentTitleWithAdditionalInfo } from '../../../../../shared/src/business/utilities/getDocumentTitleWithAdditionalInfo'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; -/** - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {object} providers.docketEntryMeta the docket entry metadata - * @param {object} providers.docketNumber the docket number of the case to be updated - * @returns {object} the updated case after the documents are added - */ export const updateDocketEntryMeta = async ( applicationContext: ServerApplicationContext, { docketEntryMeta, docketNumber, }: { docketEntryMeta: any; docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.EDIT_DOCKET_ENTRY)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.EDIT_DOCKET_ENTRY)) { throw new UnauthorizedError('Unauthorized to update docket entry'); } @@ -46,7 +38,7 @@ export const updateDocketEntryMeta = async ( throw new NotFoundError(`Case ${docketNumber} was not found.`); } - let caseEntity = new Case(caseToUpdate, { applicationContext }); + let caseEntity = new Case(caseToUpdate, { authorizedUser }); const originalDocketEntry: RawDocketEntry = caseEntity.getDocketEntryById({ docketEntryId: docketEntryMeta.docketEntryId, @@ -147,7 +139,7 @@ export const updateDocketEntryMeta = async ( ...originalDocketEntry, ...editableFields, }, - { applicationContext, petitioners: caseEntity.petitioners }, + { authorizedUser, petitioners: caseEntity.petitioners }, ).validate(); caseEntity.updateDocketEntry(docketEntryEntity); @@ -166,11 +158,15 @@ export const updateDocketEntryMeta = async ( const updatedDocketEntry = await applicationContext .getUseCases() - .addCoversheetInteractor(applicationContext, { - docketEntryId: originalDocketEntry.docketEntryId, - docketNumber: caseEntity.docketNumber, - filingDateUpdated, - }); + .addCoversheetInteractor( + applicationContext, + { + docketEntryId: originalDocketEntry.docketEntryId, + docketNumber: caseEntity.docketNumber, + filingDateUpdated, + }, + authorizedUser, + ); caseEntity.updateDocketEntry(updatedDocketEntry); } else if (shouldRemoveExistingCoverSheet) { @@ -189,10 +185,11 @@ export const updateDocketEntryMeta = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); - return new Case(result, { applicationContext }).validate().toRawObject(); + return new Case(result, { authorizedUser }).validate().toRawObject(); }; export const shouldGenerateCoversheetForDocketEntry = ({ diff --git a/web-api/src/business/useCases/document/batchDownloadDocketEntriesInteractor.test.ts b/web-api/src/business/useCases/document/batchDownloadDocketEntriesInteractor.test.ts index dce65802a45..db93a5ee970 100644 --- a/web-api/src/business/useCases/document/batchDownloadDocketEntriesInteractor.test.ts +++ b/web-api/src/business/useCases/document/batchDownloadDocketEntriesInteractor.test.ts @@ -5,13 +5,14 @@ import { STANDING_PRETRIAL_ORDER_ENTRY, } from '@shared/test/mockDocketEntry'; import { MOCK_CASE } from '@shared/test/mockCase'; -import { ROLES } from '@shared/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { batchDownloadDocketEntriesInteractor } from '@web-api/business/useCases/document/batchDownloadDocketEntriesInteractor'; +import { + mockDocketClerkUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; describe('batchDownloadDocketEntriesInteractor', () => { - let user; - const MOCK_URL = 'document_url_containing_id'; const mockClientConnectionId = '987654'; const PETITION_DOCKET_ENTRY = MOCK_DOCUMENTS[0]; @@ -37,18 +38,11 @@ describe('batchDownloadDocketEntriesInteractor', () => { }; beforeEach(() => { - user = { - role: ROLES.docketClerk, - userId: 'abc-123', - }; - requestParams = { clientConnectionId: mockClientConnectionId, docketNumber: MOCK_CASE.docketNumber, documentsSelectedForDownload: mockDocumentsSelectedForDownload, }; - applicationContext.getCurrentUser.mockImplementation(() => user); - applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue({ @@ -68,13 +62,10 @@ describe('batchDownloadDocketEntriesInteractor', () => { }); it('throws an Unauthorized error if the user role is not allowed to access the method', async () => { - user = { - role: ROLES.privatePractitioner, - userId: 'abc-456', - }; await batchDownloadDocketEntriesInteractor( applicationContext, requestParams, + mockPrivatePractitionerUser, ); expect(applicationContext.logger.error).toHaveBeenCalledWith( @@ -90,7 +81,7 @@ describe('batchDownloadDocketEntriesInteractor', () => { action: 'batch_download_error', error: expect.anything(), }, - userId: 'abc-456', + userId: mockPrivatePractitionerUser.userId, }); }); @@ -104,6 +95,7 @@ describe('batchDownloadDocketEntriesInteractor', () => { await batchDownloadDocketEntriesInteractor( applicationContext, requestParams, + mockDocketClerkUser, ); expect(applicationContext.logger.error).toHaveBeenCalledWith( @@ -119,7 +111,7 @@ describe('batchDownloadDocketEntriesInteractor', () => { action: 'batch_download_error', error: expect.anything(), }, - userId: 'abc-123', + userId: mockDocketClerkUser.userId, }); }); @@ -131,6 +123,7 @@ describe('batchDownloadDocketEntriesInteractor', () => { await batchDownloadDocketEntriesInteractor( applicationContext, requestParams, + mockDocketClerkUser, ); expect(applicationContext.logger.error).toHaveBeenCalledWith( @@ -146,7 +139,7 @@ describe('batchDownloadDocketEntriesInteractor', () => { action: 'batch_download_error', error: expect.anything(), }, - userId: 'abc-123', + userId: mockDocketClerkUser.userId, }); }); @@ -154,6 +147,7 @@ describe('batchDownloadDocketEntriesInteractor', () => { await batchDownloadDocketEntriesInteractor( applicationContext, requestParams, + mockDocketClerkUser, ); expect( @@ -189,6 +183,7 @@ describe('batchDownloadDocketEntriesInteractor', () => { await batchDownloadDocketEntriesInteractor( applicationContext, requestParams, + mockDocketClerkUser, ); expect( @@ -227,6 +222,7 @@ describe('batchDownloadDocketEntriesInteractor', () => { await batchDownloadDocketEntriesInteractor( applicationContext, requestParams, + mockDocketClerkUser, ); expect( @@ -238,7 +234,7 @@ describe('batchDownloadDocketEntriesInteractor', () => { action: 'batch_download_ready', url: MOCK_URL, }, - userId: user.userId, + userId: mockDocketClerkUser.userId, }); }); }); diff --git a/web-api/src/business/useCases/document/batchDownloadDocketEntriesInteractor.ts b/web-api/src/business/useCases/document/batchDownloadDocketEntriesInteractor.ts index b4cd2265cfe..74b4f06fd91 100644 --- a/web-api/src/business/useCases/document/batchDownloadDocketEntriesInteractor.ts +++ b/web-api/src/business/useCases/document/batchDownloadDocketEntriesInteractor.ts @@ -7,6 +7,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { generateValidDocketEntryFilename } from '@web-api/business/useCases/trialSessions/batchDownloadTrialSessionInteractor'; export type DownloadDocketEntryRequestType = { @@ -19,14 +20,16 @@ export type DownloadDocketEntryRequestType = { export const batchDownloadDocketEntriesInteractor = async ( applicationContext: ServerApplicationContext, downloadDocketEntryRequestInfo: DownloadDocketEntryRequestType, + authorizedUser: UnknownAuthUser, ) => { try { await batchDownloadDocketEntriesHelper( applicationContext, downloadDocketEntryRequestInfo, + authorizedUser, ); } catch (error: any) { - const { userId } = applicationContext.getCurrentUser(); + const { userId } = authorizedUser; const { clientConnectionId, docketNumber } = downloadDocketEntryRequestInfo; const erMsg = error.message || 'unknown error'; @@ -54,10 +57,14 @@ const batchDownloadDocketEntriesHelper = async ( documentsSelectedForDownload, printableDocketRecordFileId, }: DownloadDocketEntryRequestType, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.BATCH_DOWNLOAD_CASE_DOCUMENTS)) { + if ( + !isAuthorized( + authorizedUser, + ROLE_PERMISSIONS.BATCH_DOWNLOAD_CASE_DOCUMENTS, + ) + ) { throw new UnauthorizedError('Unauthorized'); } @@ -69,7 +76,7 @@ const batchDownloadDocketEntriesHelper = async ( filesCompleted: 0, totalFiles: documentsSelectedForDownload.length, }, - userId: user.userId, + userId: authorizedUser.userId, }); const caseToBatch = await applicationContext @@ -93,7 +100,7 @@ const batchDownloadDocketEntriesHelper = async ( useTempBucket: boolean; }[] = []; - const caseEntity = new Case(caseToBatch, { applicationContext }); + const caseEntity = new Case(caseToBatch, { authorizedUser }); documentsSelectedForDownload.forEach(docketEntryId => { const docInfo = caseEntity.getDocketEntryById({ @@ -138,7 +145,7 @@ const batchDownloadDocketEntriesHelper = async ( filesCompleted: progressData.filesCompleted, totalFiles: progressData.totalFiles, }, - userId: user.userId, + userId: authorizedUser.userId, }); }; @@ -165,6 +172,6 @@ const batchDownloadDocketEntriesHelper = async ( action: 'batch_download_ready', url, }, - userId: user.userId, + userId: authorizedUser.userId, }); }; diff --git a/web-api/src/business/useCases/document/getDocumentContentsForDocketEntryInteractor.test.ts b/web-api/src/business/useCases/document/getDocumentContentsForDocketEntryInteractor.test.ts index 2eff039af1f..636f6e49d5e 100644 --- a/web-api/src/business/useCases/document/getDocumentContentsForDocketEntryInteractor.test.ts +++ b/web-api/src/business/useCases/document/getDocumentContentsForDocketEntryInteractor.test.ts @@ -1,15 +1,16 @@ -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; +import { ROLES } from '@shared/business/entities/EntityConstants'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getDocumentContentsForDocketEntryInteractor } from './getDocumentContentsForDocketEntryInteractor'; +import { + mockDocketClerkUser, + mockJudgeUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getDocumentContentsForDocketEntryInteractor', () => { const mockDocumentContentsId = '599dbad3-4912-4a61-9525-3da245700893'; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Tasha Yar', - role: ROLES.docketClerk, - }); - applicationContext.getPersistenceGateway().getDocument.mockReturnValue( Buffer.from( JSON.stringify({ @@ -21,27 +22,29 @@ describe('getDocumentContentsForDocketEntryInteractor', () => { }); it('should throw an error when the logged in user does not have permission to EDIT_ORDER', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Tasha Yar', + let authorizedUser = { + ...mockPrivatePractitionerUser, role: ROLES.inactivePractitioner, - }); - + } as UnknownAuthUser; await expect( - getDocumentContentsForDocketEntryInteractor(applicationContext, { - documentContentsId: mockDocumentContentsId, - }), + getDocumentContentsForDocketEntryInteractor( + applicationContext, + { + documentContentsId: mockDocumentContentsId, + }, + authorizedUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should allow the logged in internal user with permissions to edit the order', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Test Judge', - role: ROLES.judge, - }); - - await getDocumentContentsForDocketEntryInteractor(applicationContext, { - documentContentsId: mockDocumentContentsId, - }); + await getDocumentContentsForDocketEntryInteractor( + applicationContext, + { + documentContentsId: mockDocumentContentsId, + }, + mockJudgeUser, + ); expect( applicationContext.getPersistenceGateway().getDocument.mock.calls[0][0], @@ -49,9 +52,13 @@ describe('getDocumentContentsForDocketEntryInteractor', () => { }); it('should call applicationContext.getPersistenceGateway().getDocument with documentCntentsId as the key', async () => { - await getDocumentContentsForDocketEntryInteractor(applicationContext, { - documentContentsId: mockDocumentContentsId, - }); + await getDocumentContentsForDocketEntryInteractor( + applicationContext, + { + documentContentsId: mockDocumentContentsId, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getDocument.mock.calls[0][0], @@ -64,6 +71,7 @@ describe('getDocumentContentsForDocketEntryInteractor', () => { { documentContentsId: mockDocumentContentsId, }, + mockDocketClerkUser, ); expect(result).toEqual({ @@ -82,9 +90,13 @@ describe('getDocumentContentsForDocketEntryInteractor', () => { ); await expect( - getDocumentContentsForDocketEntryInteractor(applicationContext, { - documentContentsId: mockDocumentContentsId, - }), + getDocumentContentsForDocketEntryInteractor( + applicationContext, + { + documentContentsId: mockDocumentContentsId, + }, + mockDocketClerkUser, + ), ).rejects.toThrow( `Document contents ${mockDocumentContentsId} could not be found in the S3 bucket.`, ); diff --git a/web-api/src/business/useCases/document/getDocumentContentsForDocketEntryInteractor.ts b/web-api/src/business/useCases/document/getDocumentContentsForDocketEntryInteractor.ts index 1bf76b4c815..57d62c2d67b 100644 --- a/web-api/src/business/useCases/document/getDocumentContentsForDocketEntryInteractor.ts +++ b/web-api/src/business/useCases/document/getDocumentContentsForDocketEntryInteractor.ts @@ -4,22 +4,14 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; -/** - * getDocumentContentsForDocketEntryInteractor - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {object} providers.documentContentsId document contents id - * @returns {string} url for the generated document on the storage client - */ export const getDocumentContentsForDocketEntryInteractor = async ( applicationContext: ServerApplicationContext, { documentContentsId }: { documentContentsId: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.EDIT_ORDER)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.EDIT_ORDER)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/document/getDownloadPolicyUrlInteractor.test.ts b/web-api/src/business/useCases/document/getDownloadPolicyUrlInteractor.test.ts index ea56d337f8d..a346157f5ac 100644 --- a/web-api/src/business/useCases/document/getDownloadPolicyUrlInteractor.test.ts +++ b/web-api/src/business/useCases/document/getDownloadPolicyUrlInteractor.test.ts @@ -5,7 +5,6 @@ import { DOCUMENT_PROCESSING_STATUS_OPTIONS, INITIAL_DOCUMENT_TYPES, NOTICE_OF_CHANGE_CONTACT_INFORMATION_MAP, - ROLES, STIPULATED_DECISION_EVENT_CODE, TRANSCRIPT_EVENT_CODE, } from '../../../../../shared/src/business/entities/EntityConstants'; @@ -23,14 +22,19 @@ import { } from '../../../../../shared/src/business/utilities/DateHandler'; import { casePetitioner, - docketClerkUser, irsPractitionerUser, - irsSuperuserUser, - petitionerUser, - petitionsClerkUser, privatePractitionerUser, } from '../../../../../shared/src/test/mockUsers'; import { cloneDeep } from 'lodash'; +import { + mockAdminUser, + mockDocketClerkUser, + mockIrsPractitionerUser, + mockIrsSuperuser, + mockPetitionerUser, + mockPetitionsClerkUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getDownloadPolicyUrlInteractor', () => { let mockCase; @@ -57,24 +61,19 @@ describe('getDownloadPolicyUrlInteractor', () => { }); it('should throw unauthorized error when the users role is invalid', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.admin, - userId: 'b5724655-1791-4a99-b0f6-f9bbe99c1db5', - }); - await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockAdminUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should throw and error when requested document is a correspondence but the user is not internal', async () => { - applicationContext.getCurrentUser.mockReturnValueOnce({ - role: ROLES.petitioner, - userId: 'b5724655-1791-4a99-b0f6-f9bbe99c1db5', - }); const mockCorrespondenceId = applicationContext.getUniqueId(); mockCase.correspondence = [ { @@ -83,33 +82,41 @@ describe('getDownloadPolicyUrlInteractor', () => { ]; await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: mockCorrespondenceId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: mockCorrespondenceId, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); describe('when the user is a petitioner not associated with case or the consolidated group', () => { - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - }); - it('should throw an unauthorized error', async () => { await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should throw an unauthorized error when the document being viewed is the case confirmation pdf', async () => { await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: `case-${MOCK_CASE.docketNumber}-confirmation.pdf`, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: `case-${MOCK_CASE.docketNumber}-confirmation.pdf`, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -126,10 +133,14 @@ describe('getDownloadPolicyUrlInteractor', () => { }; await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized to view document at this time'); }); @@ -143,10 +154,14 @@ describe('getDownloadPolicyUrlInteractor', () => { servedAt: applicationContext.getUtilities().createISODateString(), }; - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPetitionerUser, + ); expect(url).toEqual('localhost'); }); @@ -161,32 +176,36 @@ describe('getDownloadPolicyUrlInteractor', () => { }; await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized to view document at this time.'); }); it('should throw an Unauthorized error for a petitioner attempting to access an case confirmation pdf for a different case', async () => { await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, //docket number is 101-18 - key: 'case-101-20-confirmation.pdf', - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, //docket number is 101-18 + key: 'case-101-20-confirmation.pdf', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); }); describe('when the user is a petitioner associated with case', () => { - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - }); - beforeEach(() => { mockCase.petitioners = [ { - contactId: petitionerUser.userId, + contactId: mockPetitionerUser.userId, }, ]; }); @@ -202,10 +221,14 @@ describe('getDownloadPolicyUrlInteractor', () => { }; await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized to view document at this time'); }); @@ -221,10 +244,14 @@ describe('getDownloadPolicyUrlInteractor', () => { }; await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized to view document at this time'); }); @@ -240,18 +267,26 @@ describe('getDownloadPolicyUrlInteractor', () => { }; await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized to view document at this time'); }); it('should return the policy url when the doucument requested is an available document', async () => { - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPetitionerUser, + ); expect(url).toEqual('localhost'); }); @@ -267,10 +302,14 @@ describe('getDownloadPolicyUrlInteractor', () => { sealedTo: DOCKET_ENTRY_SEALED_TO_TYPES.PUBLIC, }; - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPetitionerUser, + ); expect(url).toEqual('localhost'); }); @@ -290,19 +329,27 @@ describe('getDownloadPolicyUrlInteractor', () => { sealedTo: DOCKET_ENTRY_SEALED_TO_TYPES.PUBLIC, }; - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPetitionerUser, + ); expect(url).toEqual('localhost'); }); it('should throw a not found error when the document requested is a document that is not on the docket record', async () => { await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: '26258791-7a20-4a53-8e25-cc509b502cf3', - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: '26258791-7a20-4a53-8e25-cc509b502cf3', + }, + mockPetitionerUser, + ), ).rejects.toThrow( 'Docket entry 26258791-7a20-4a53-8e25-cc509b502cf3 was not found.', ); @@ -315,10 +362,14 @@ describe('getDownloadPolicyUrlInteractor', () => { }; await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPetitionerUser, + ), ).rejects.toThrow( `Docket entry ${baseDocketEntry.docketEntryId} does not have an attached file.`, ); @@ -330,10 +381,14 @@ describe('getDownloadPolicyUrlInteractor', () => { .getCaseByDocketNumber.mockReturnValue({ docketEntries: [] }); await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: '123-20', - key: '26258791-7a20-4a53-8e25-cc509b502cf3', - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: '123-20', + key: '26258791-7a20-4a53-8e25-cc509b502cf3', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Case 123-20 was not found.'); }); @@ -346,10 +401,14 @@ describe('getDownloadPolicyUrlInteractor', () => { }; await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized to view document at this time'); }); @@ -362,29 +421,41 @@ describe('getDownloadPolicyUrlInteractor', () => { servedAt: applicationContext.getUtilities().createISODateString(), }; - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPetitionerUser, + ); expect(url).toEqual('localhost'); }); it('should return the policy url when the document requested is a case confirmation pdf', async () => { - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: 'case-101-18-confirmation.pdf', - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: 'case-101-18-confirmation.pdf', + }, + mockPetitionerUser, + ); expect(url).toEqual('localhost'); }); it('should throw an error when the document requested is a STIN', async () => { await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: stinDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: stinDocketEntry.docketEntryId, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized to view document at this time.'); }); @@ -414,10 +485,14 @@ describe('getDownloadPolicyUrlInteractor', () => { userId: '7805d1ab-18d0-43ec-bafb-654e83405416', }); - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: briefDocketEntryId, - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: briefDocketEntryId, + }, + mockPetitionerUser, + ); expect(url).toEqual('localhost'); }); @@ -455,19 +530,20 @@ describe('getDownloadPolicyUrlInteractor', () => { }); await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: briefDocketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: briefDocketEntryId, + }, + mockPetitionerUser, + ), ).rejects.toThrow(); }); }); describe('when the user is a private practitioner not associated with case', () => { beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue( - privatePractitionerUser, - ); applicationContext .getPersistenceGateway() .verifyCaseForUser.mockReturnValue(false); @@ -481,10 +557,14 @@ describe('getDownloadPolicyUrlInteractor', () => { }; await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPrivatePractitionerUser, + ), ).rejects.toThrow('Unauthorized to view document at this time'); }); @@ -500,23 +580,26 @@ describe('getDownloadPolicyUrlInteractor', () => { }; await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPrivatePractitionerUser, + ), ).resolves.toBeDefined(); }); }); describe('when the user is a private practitioner associated with case', () => { - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue( - privatePractitionerUser, - ); - }); - beforeEach(() => { - mockCase.privatePractitioners = [privatePractitionerUser]; + mockCase.privatePractitioners = [ + { + ...privatePractitionerUser, + userId: mockPrivatePractitionerUser.userId, + }, + ]; }); it('should receive the policy url when the document being viewed is a document that has been sealed to the public', async () => { @@ -530,10 +613,14 @@ describe('getDownloadPolicyUrlInteractor', () => { servedAt: applicationContext.getUtilities().createISODateString(), }; - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPrivatePractitionerUser, + ); expect(url).toEqual('localhost'); }); @@ -550,10 +637,14 @@ describe('getDownloadPolicyUrlInteractor', () => { }; await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPrivatePractitionerUser, + ), ).rejects.toThrow('Unauthorized to view document at this time'); }); @@ -566,27 +657,31 @@ describe('getDownloadPolicyUrlInteractor', () => { servedAt: applicationContext.getUtilities().createISODateString(), }); - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPrivatePractitionerUser, + ); expect(url).toEqual('localhost'); }); }); describe('when the user is a petitions clerk', () => { - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - }); - it('should return the policy url when the case has not been served and the requested document is a STIN', async () => { mockCase.docketEntries[0].servedAt = undefined; stinDocketEntry.servedAt = undefined; - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: stinDocketEntry.docketEntryId, - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: stinDocketEntry.docketEntryId, + }, + mockPetitionsClerkUser, + ); expect(url).toEqual('localhost'); }); @@ -595,25 +690,29 @@ describe('getDownloadPolicyUrlInteractor', () => { mockCase.docketEntries[0].servedAt = '2019-08-25T05:00:00.000Z'; await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: stinDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: stinDocketEntry.docketEntryId, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(UNAUTHORIZED_DOCUMENT_MESSAGE); }); }); describe('when the user is a docket clerk', () => { - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - }); - it('should throw an error when the requested document is a STIN', async () => { await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: stinDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: stinDocketEntry.docketEntryId, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(UNAUTHORIZED_DOCUMENT_MESSAGE); }); @@ -625,38 +724,46 @@ describe('getDownloadPolicyUrlInteractor', () => { }, ]; - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: mockCorrespondenceId, - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: mockCorrespondenceId, + }, + mockDocketClerkUser, + ); expect(url).toEqual('localhost'); }); }); describe('when the user is a irs superuser', () => { - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(irsSuperuserUser); - }); - it('should throw an error when the petition document on the case is not served', async () => { mockCase.docketEntries[0].servedAt = undefined; await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockIrsSuperuser, + ), ).rejects.toThrow(UNAUTHORIZED_DOCUMENT_MESSAGE); }); it('should return the policy url when requested document is a petition on a served case', async () => { mockCase.docketEntries[0].servedAt = '2019-08-25T05:00:00.000Z'; - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: petitionDocketEntry.docketEntryId, - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: petitionDocketEntry.docketEntryId, + }, + mockIrsSuperuser, + ); expect(url).toEqual('localhost'); }); @@ -673,10 +780,14 @@ describe('getDownloadPolicyUrlInteractor', () => { servedAt: '2019-03-01T21:40:46.415Z', }); - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: '60814ae9-cd39-454a-9dc7-f5595a39988f', - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: '60814ae9-cd39-454a-9dc7-f5595a39988f', + }, + mockIrsSuperuser, + ); expect(url).toEqual('localhost'); }); @@ -694,10 +805,14 @@ describe('getDownloadPolicyUrlInteractor', () => { servedAt: applicationContext.getUtilities().createISODateString(), }); - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: '60814ae9-cd39-454a-9dc7-f5595a39988f', - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: '60814ae9-cd39-454a-9dc7-f5595a39988f', + }, + mockIrsSuperuser, + ); expect(url).toEqual('localhost'); }); @@ -712,10 +827,14 @@ describe('getDownloadPolicyUrlInteractor', () => { }; await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: '60814ae9-cd39-454a-9dc7-f5595a39988f', - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: '60814ae9-cd39-454a-9dc7-f5595a39988f', + }, + mockIrsSuperuser, + ), ).rejects.toThrow( 'Docket entry 60814ae9-cd39-454a-9dc7-f5595a39988f does not have an attached file.', ); @@ -723,10 +842,14 @@ describe('getDownloadPolicyUrlInteractor', () => { it('throws a not found error if the user role is irsSuperuser and the petition document on the case is served but the document requested is not on the case', async () => { await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: '984fe4c3-7685-4d1e-9ad6-9914785e6dd6', - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: '984fe4c3-7685-4d1e-9ad6-9914785e6dd6', + }, + mockIrsSuperuser, + ), ).rejects.toThrow( 'Docket entry 984fe4c3-7685-4d1e-9ad6-9914785e6dd6 was not found.', ); @@ -740,12 +863,10 @@ describe('getDownloadPolicyUrlInteractor', () => { units: 'hours', }); - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(irsPractitionerUser); - }); - beforeEach(() => { - mockCase.irsPractitioners = [irsPractitionerUser]; + mockCase.irsPractitioners = [ + { ...irsPractitionerUser, userId: mockIrsPractitionerUser.userId }, + ]; }); it('should not throw an error if the user is associated with the case and the document meets age requirements', async () => { @@ -758,10 +879,14 @@ describe('getDownloadPolicyUrlInteractor', () => { isFileAttached: true, }; - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockIrsPractitionerUser, + ); expect(url).toEqual('localhost'); }); @@ -777,10 +902,14 @@ describe('getDownloadPolicyUrlInteractor', () => { }; await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockIrsPractitionerUser, + ), ).rejects.toThrow(UNAUTHORIZED_DOCUMENT_MESSAGE); }); }); @@ -789,39 +918,42 @@ describe('getDownloadPolicyUrlInteractor', () => { const leadMockCase: RawCase = { ...MOCK_CASE, leadDocketNumber: MOCK_CASE.docketNumber, - petitioners: [casePetitioner], + petitioners: [ + { ...casePetitioner, contactId: mockPetitionerUser.userId }, + ], }; leadMockCase.consolidatedCases = [ new ConsolidatedCaseSummary(leadMockCase), ]; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(leadMockCase); }); it('should return the policy url when the document requested is an available document', async () => { - const url = await getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: baseDocketEntry.docketEntryId, - }); + const url = await getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: baseDocketEntry.docketEntryId, + }, + mockPetitionerUser, + ); expect(url).toEqual('localhost'); }); it('should throw an error when the document requested is an available document and the user is not associated with the consolidated group', async () => { - applicationContext.getCurrentUser.mockReturnValueOnce({ - ...petitionerUser, - userId: 'someone-else', - }); - await expect( - getDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - key: `case-${MOCK_CASE.docketNumber}-confirmation.pdf`, - }), + getDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + key: `case-${MOCK_CASE.docketNumber}-confirmation.pdf`, + }, + { ...mockPetitionerUser, userId: 'someone-else' }, + ), ).rejects.toThrow(new UnauthorizedError('Unauthorized')); }); }); diff --git a/web-api/src/business/useCases/document/getDownloadPolicyUrlInteractor.ts b/web-api/src/business/useCases/document/getDownloadPolicyUrlInteractor.ts index 8445071e620..6e52548f99c 100644 --- a/web-api/src/business/useCases/document/getDownloadPolicyUrlInteractor.ts +++ b/web-api/src/business/useCases/document/getDownloadPolicyUrlInteractor.ts @@ -5,17 +5,17 @@ import { NotFoundError, UnauthorizedError } from '@web-api/errors/errors'; import { ROLE_PERMISSIONS, isAuthorized, -} from '../../../../../shared/src/authorization/authorizationClientService'; +} from '@shared/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { User } from '@shared/business/entities/User'; export const getDownloadPolicyUrlInteractor = async ( applicationContext: ServerApplicationContext, { docketNumber, key }: { docketNumber: string; key: string }, + authorizedUser: UnknownAuthUser, ): Promise<{ url: string }> => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.VIEW_DOCUMENTS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.VIEW_DOCUMENTS)) { throw new UnauthorizedError('Unauthorized'); } @@ -30,7 +30,7 @@ export const getDownloadPolicyUrlInteractor = async ( throw new NotFoundError(`Case ${docketNumber} was not found.`); } - const caseEntity = new Case(caseData, { applicationContext }); + const caseEntity = new Case(caseData, { authorizedUser }); const docketEntryEntity = caseEntity.getDocketEntryById({ docketEntryId: key, }); @@ -38,12 +38,12 @@ export const getDownloadPolicyUrlInteractor = async ( if (key.includes('.pdf')) { if ( caseEntity.getCaseConfirmationGeneratedPdfFileName() !== key || - !caseEntity.userHasAccessToCase(user) + !caseEntity.userHasAccessToCase(authorizedUser) ) { throw new UnauthorizedError('Unauthorized'); } } else if (caseEntity.getCorrespondenceById({ correspondenceId: key })) { - if (!User.isInternalUser(user.role)) { + if (!User.isInternalUser(authorizedUser.role)) { throw new UnauthorizedError(UNAUTHORIZED_DOCUMENT_MESSAGE); } } else { @@ -69,7 +69,7 @@ export const getDownloadPolicyUrlInteractor = async ( !DocketEntry.isDownloadable(docketEntryEntity, { isTerminalUser: false, rawCase: caseData, - user, + user: authorizedUser, visibilityChangeDate: documentVisibilityChangeDate, }) ) { diff --git a/web-api/src/business/useCases/document/getUploadPolicyInteractor.test.ts b/web-api/src/business/useCases/document/getUploadPolicyInteractor.test.ts index 5bc0be79ce8..74e6a896444 100644 --- a/web-api/src/business/useCases/document/getUploadPolicyInteractor.test.ts +++ b/web-api/src/business/useCases/document/getUploadPolicyInteractor.test.ts @@ -1,16 +1,20 @@ -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getUploadPolicyInteractor } from './getUploadPolicyInteractor'; +import { + mockAdminUser, + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getUploadPolicyInteractor', () => { it('throw unauthorized error on invalid role', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.admin, - userId: 'petitioner', - }); let error; try { - await getUploadPolicyInteractor(applicationContext, {} as any); + await getUploadPolicyInteractor( + applicationContext, + {} as any, + mockAdminUser, + ); } catch (err) { error = err; } @@ -18,11 +22,6 @@ describe('getUploadPolicyInteractor', () => { }); it('returns the expected policy when the file does not already exist', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - isExternalUser: () => true, - role: ROLES.petitioner, - userId: 'petitioner', - }); applicationContext .getPersistenceGateway() .getUploadPolicy.mockReturnValue('policy'); @@ -30,32 +29,30 @@ describe('getUploadPolicyInteractor', () => { .getPersistenceGateway() .isFileExists.mockReturnValue(false); - const url = await getUploadPolicyInteractor(applicationContext, {} as any); + const url = await getUploadPolicyInteractor( + applicationContext, + {} as any, + mockPetitionerUser, + ); expect(url).toEqual('policy'); }); it('does not check if the file exists if the user is internal', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - isExternalUser: () => false, - role: ROLES.docketClerk, - userId: 'docket', - }); applicationContext .getPersistenceGateway() .getUploadPolicy.mockReturnValue('policy'); - await getUploadPolicyInteractor(applicationContext, {} as any); + await getUploadPolicyInteractor( + applicationContext, + {} as any, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().isFileExists, ).not.toHaveBeenCalled(); }); it('throws an unauthorized exception when file already exists', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - isExternalUser: () => true, - role: ROLES.petitioner, - userId: 'petitioner', - }); applicationContext .getPersistenceGateway() .getUploadPolicy.mockReturnValue('policy'); @@ -65,7 +62,11 @@ describe('getUploadPolicyInteractor', () => { let error; try { - await getUploadPolicyInteractor(applicationContext, {} as any); + await getUploadPolicyInteractor( + applicationContext, + {} as any, + mockPetitionerUser, + ); } catch (err) { error = err; } diff --git a/web-api/src/business/useCases/document/getUploadPolicyInteractor.ts b/web-api/src/business/useCases/document/getUploadPolicyInteractor.ts index 1e8f8f04853..1481015e6cd 100644 --- a/web-api/src/business/useCases/document/getUploadPolicyInteractor.ts +++ b/web-api/src/business/useCases/document/getUploadPolicyInteractor.ts @@ -5,20 +5,20 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { User } from '../../../../../shared/src/business/entities/User'; export const getUploadPolicyInteractor = async ( applicationContext: ServerApplicationContext, { key }: { key: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.UPLOAD_DOCUMENT)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.UPLOAD_DOCUMENT)) { throw new UnauthorizedError('Unauthorized'); } // we don't want external users to be able to overwrite existing s3 files - if (User.isExternalUser(user.role)) { + if (User.isExternalUser(authorizedUser.role)) { const isFileExists = await applicationContext .getPersistenceGateway() .isFileExists({ diff --git a/web-api/src/business/useCases/document/serveExternallyFiledDocumentInteractor.locking.test.ts b/web-api/src/business/useCases/document/serveExternallyFiledDocumentInteractor.locking.test.ts index 77937cff6b2..8af162cb418 100644 --- a/web-api/src/business/useCases/document/serveExternallyFiledDocumentInteractor.locking.test.ts +++ b/web-api/src/business/useCases/document/serveExternallyFiledDocumentInteractor.locking.test.ts @@ -9,7 +9,7 @@ import { handleLockError, serveExternallyFiledDocumentInteractor, } from '../../../../../web-api/src/business/useCases/document/serveExternallyFiledDocumentInteractor'; -import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { testPdfDoc } from '../../../../../shared/src/business/test/getFakeFile'; describe('determineEntitiesToLock', () => { @@ -49,12 +49,22 @@ describe('handleLockError', () => { beforeAll(() => { applicationContext .getPersistenceGateway() - .getUserById.mockReturnValue(docketClerkUser); + .getUserById.mockReturnValue(mockDocketClerkUser); }); - it('should determine who the user is based on applicationContext', async () => { - await handleLockError(applicationContext, { foo: 'bar' }); - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); + it('should determine who the user is based on arguents to handleLockError, not appcontext', async () => { + await handleLockError( + applicationContext, + { foo: 'bar' }, + mockDocketClerkUser, + ); + expect( + applicationContext.getNotificationGateway().sendNotificationToUser, + ).toHaveBeenCalledWith( + expect.objectContaining({ + userId: mockDocketClerkUser.userId, + }), + ); }); it('should send a notification to the user with "retry_async_request" and the originalRequest', async () => { @@ -62,7 +72,11 @@ describe('handleLockError', () => { clientConnectionId: mockClientConnectionId, foo: 'bar', }; - await handleLockError(applicationContext, mockOriginalRequest); + await handleLockError( + applicationContext, + mockOriginalRequest, + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock .calls[0][0].message, @@ -103,8 +117,6 @@ describe('serveExternallyFiledDocumentInteractor', () => { beforeEach(() => { mockLock = undefined; // unlocked - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getUseCaseHelpers() .fileAndServeDocumentOnOneCase.mockImplementation( @@ -119,7 +131,7 @@ describe('serveExternallyFiledDocumentInteractor', () => { applicationContext .getPersistenceGateway() - .getUserById.mockReturnValue(docketClerkUser); + .getUserById.mockReturnValue(mockDocketClerkUser); applicationContext .getPersistenceGateway() @@ -133,7 +145,11 @@ describe('serveExternallyFiledDocumentInteractor', () => { it('should throw a ServiceUnavailableError if a Case is currently locked', async () => { await expect( - serveExternallyFiledDocumentInteractor(applicationContext, mockRequest), + serveExternallyFiledDocumentInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -143,7 +159,11 @@ describe('serveExternallyFiledDocumentInteractor', () => { it('should return a "retry_async_request" notification with the original request', async () => { await expect( - serveExternallyFiledDocumentInteractor(applicationContext, mockRequest), + serveExternallyFiledDocumentInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -156,7 +176,7 @@ describe('serveExternallyFiledDocumentInteractor', () => { originalRequest: mockRequest, requestToRetry: 'serve_externally_filed_document', }, - userId: docketClerkUser.userId, + userId: mockDocketClerkUser.userId, }); expect( @@ -174,6 +194,7 @@ describe('serveExternallyFiledDocumentInteractor', () => { await serveExternallyFiledDocumentInteractor( applicationContext, mockRequest, + mockDocketClerkUser, ); expect( @@ -189,6 +210,7 @@ describe('serveExternallyFiledDocumentInteractor', () => { await serveExternallyFiledDocumentInteractor( applicationContext, mockRequest, + mockDocketClerkUser, ); expect( diff --git a/web-api/src/business/useCases/document/serveExternallyFiledDocumentInteractor.test.ts b/web-api/src/business/useCases/document/serveExternallyFiledDocumentInteractor.test.ts index e7450dce845..1a39eab09cc 100644 --- a/web-api/src/business/useCases/document/serveExternallyFiledDocumentInteractor.test.ts +++ b/web-api/src/business/useCases/document/serveExternallyFiledDocumentInteractor.test.ts @@ -7,7 +7,9 @@ import { applicationContext } from '../../../../../shared/src/business/test/crea import { serveExternallyFiledDocumentInteractor } from './serveExternallyFiledDocumentInteractor'; jest.mock('../addCoverToPdf'); import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('serveExternallyFiledDocumentInteractor', () => { let mockCase; @@ -30,9 +32,6 @@ describe('serveExternallyFiledDocumentInteractor', () => { { docketEntryId: mockDocketEntryId, documentTitle: 'something cool' }, ], }; - - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(mockCase); @@ -55,15 +54,17 @@ describe('serveExternallyFiledDocumentInteractor', () => { }); it('should throw an error when the user is not authorized to serve externally filed documents', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - await expect( - serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: '', - docketNumbers: [], - subjectCaseDocketNumber: '', - }), + serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: '', + docketNumbers: [], + subjectCaseDocketNumber: '', + }, + {} as UnknownAuthUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -71,12 +72,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { const mockNonExistentDocketEntryId = 'd9f645b1-c0b6-4782-a798-091760343573'; await expect( - serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockNonExistentDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: '', - }), + serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockNonExistentDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: '', + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry not found'); }); @@ -94,12 +99,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { }); await expect( - serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: '', - }), + serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: '', + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry has already been served'); }); @@ -117,12 +126,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { }); await expect( - serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: '', - }), + serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: '', + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry is already being served'); expect( @@ -144,12 +157,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { ], }); - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -177,12 +194,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { ], }); - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -206,12 +227,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { ], }); - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -233,12 +258,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { ], }); - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -260,12 +289,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { ], }); - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -287,12 +320,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { ], }); - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -301,12 +338,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { }); it('should set the number of pages in the docket entry as the length of the document plus the coversheet', async () => { - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -328,12 +369,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { ], }); - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -357,12 +402,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { ], }); - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [mockMemberCaseDocketNumber], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [mockMemberCaseDocketNumber], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase, @@ -388,12 +437,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { ], }); - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [mockMemberCaseDocketNumber], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [mockMemberCaseDocketNumber], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase, @@ -418,12 +471,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { ], }); - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -442,12 +499,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { docketNumber: memberCaseDocketNumber, }); - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [memberCaseDocketNumber], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [memberCaseDocketNumber], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().fileAndServeDocumentOnOneCase.mock @@ -463,12 +524,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { it('should call the persistence method to set and unset the pending service status on the subjectCase`s docket entry ONLY', async () => { const memberCaseDocketNumber = '999-16'; - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [memberCaseDocketNumber], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [memberCaseDocketNumber], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -503,12 +568,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { ); await expect( - serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: mockCase.docketNumber, - }), + serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(mockErrorText); expect( @@ -534,12 +603,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { }); it('should call serveDocumentAndGetPaperServicePdf to generate a paper service pdf', async () => { - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: '', - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: '', + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().serveDocumentAndGetPaperServicePdf @@ -550,12 +623,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { }); it('should send a serve_document_complete notification to the user', async () => { - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock @@ -572,12 +649,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { }); it('should send a notification including the DOCUMENT_SERVED_MESSAGES.SELECTED_CASES message when the docket entry was served on more than one case', async () => { - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockDocketEntryId, - docketNumbers: ['102-34'], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockDocketEntryId, + docketNumbers: ['102-34'], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock @@ -586,12 +667,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { }); it('should send a notification including the DOCUMENT_SERVED_MESSAGES.ENTRY_ADDED message when the docket entry was served on exactly one case', async () => { - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock @@ -600,12 +685,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { }); it('should send a notification with a paper service url when at least one of the served cases has paper service parties', async () => { - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock @@ -620,12 +709,16 @@ describe('serveExternallyFiledDocumentInteractor', () => { pdfUrl: undefined, }); - await serveExternallyFiledDocumentInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - docketEntryId: mockDocketEntryId, - docketNumbers: [], - subjectCaseDocketNumber: mockCase.docketNumber, - }); + await serveExternallyFiledDocumentInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + docketEntryId: mockDocketEntryId, + docketNumbers: [], + subjectCaseDocketNumber: mockCase.docketNumber, + }, + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock diff --git a/web-api/src/business/useCases/document/serveExternallyFiledDocumentInteractor.ts b/web-api/src/business/useCases/document/serveExternallyFiledDocumentInteractor.ts index 0fe62a0dbe8..59e15a036e1 100644 --- a/web-api/src/business/useCases/document/serveExternallyFiledDocumentInteractor.ts +++ b/web-api/src/business/useCases/document/serveExternallyFiledDocumentInteractor.ts @@ -11,6 +11,7 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; export const serveExternallyFiledDocument = async ( @@ -26,9 +27,8 @@ export const serveExternallyFiledDocument = async ( docketNumbers: string[]; subjectCaseDocketNumber: string; }, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); - const hasPermission = (isAuthorized(authorizedUser, ROLE_PERMISSIONS.DOCKET_ENTRY) || isAuthorized( @@ -48,7 +48,7 @@ export const serveExternallyFiledDocument = async ( docketNumber: subjectCaseDocketNumber, }); - const subjectCaseEntity = new Case(subjectCase, { applicationContext }); + const subjectCaseEntity = new Case(subjectCase, { authorizedUser }); const originalSubjectDocketEntry = subjectCaseEntity.getDocketEntryById({ docketEntryId, @@ -110,7 +110,7 @@ export const serveExternallyFiledDocument = async ( }); const caseEntity = new Case(rawCaseToUpdate, { - applicationContext, + authorizedUser, }); const isSubjectCase = @@ -133,7 +133,7 @@ export const serveExternallyFiledDocument = async ( numberOfPages: numberOfPages + coversheetLength, processingStatus: DOCUMENT_PROCESSING_STATUS_OPTIONS.COMPLETE, }, - { applicationContext }, + { authorizedUser }, ); return applicationContext @@ -154,13 +154,15 @@ export const serveExternallyFiledDocument = async ( const updatedSubjectDocketEntry = updatedSubjectCaseEntity!.getDocketEntryById({ docketEntryId }); - await applicationContext - .getUseCases() - .addCoversheetInteractor(applicationContext, { + await applicationContext.getUseCases().addCoversheetInteractor( + applicationContext, + { caseEntity: updatedSubjectCaseEntity, docketEntryId: updatedSubjectDocketEntry.docketEntryId, docketNumber: updatedSubjectCaseEntity!.docketNumber, - }); + }, + authorizedUser, + ); paperServiceResult = await applicationContext .getUseCaseHelpers() @@ -219,19 +221,20 @@ export const determineEntitiesToLock = ( export const handleLockError = async ( applicationContext: ServerApplicationContext, originalRequest: any, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - await applicationContext.getNotificationGateway().sendNotificationToUser({ - applicationContext, - clientConnectionId: originalRequest.clientConnectionId, - message: { - action: 'retry_async_request', - originalRequest, - requestToRetry: 'serve_externally_filed_document', - }, - userId: user.userId, - }); + if (authorizedUser?.userId) { + await applicationContext.getNotificationGateway().sendNotificationToUser({ + applicationContext, + clientConnectionId: originalRequest.clientConnectionId, + message: { + action: 'retry_async_request', + originalRequest, + requestToRetry: 'serve_externally_filed_document', + }, + userId: authorizedUser.userId, + }); + } }; export const serveExternallyFiledDocumentInteractor = withLocking( diff --git a/web-api/src/business/useCases/editDocketEntry/completeDocketEntryQCInteractor.needsNewCoversheet.test.ts b/web-api/src/business/useCases/editDocketEntry/completeDocketEntryQCInteractor.needsNewCoversheet.test.ts deleted file mode 100644 index f656e387889..00000000000 --- a/web-api/src/business/useCases/editDocketEntry/completeDocketEntryQCInteractor.needsNewCoversheet.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { DocketEntry } from '../../../../../shared/src/business/entities/DocketEntry'; -import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; -import { needsNewCoversheet } from './completeDocketEntryQCInteractor'; - -describe('completeDocketEntryQCInteractor needsNewCoversheet', () => { - let currentDocketEntry; - let updatedDocketEntry; - beforeEach(() => { - currentDocketEntry = new DocketEntry( - { - certificateOfService: false, - documentTitle: 'fake title', - filedBy: 'petitioner.high', - receivedAt: '2019-08-25T05:00:00.000Z', - }, - { applicationContext }, - ); - - updatedDocketEntry = new DocketEntry( - { - certificateOfService: false, - documentTitle: 'fake title', - filedBy: 'petitioner.high', - receivedAt: '2019-08-25T05:00:00.000Z', - }, - { applicationContext }, - ); - }); - it('should return true when receivedAt is updated', () => { - updatedDocketEntry.receivedAt = '2020-08-26T05:00:00.000Z'; - const result = needsNewCoversheet({ - applicationContext, - currentDocketEntry, - updatedDocketEntry, - }); - expect(result).toEqual(true); - }); - - it('should return false when receivedAt format is different but the date is the same', () => { - currentDocketEntry.receivedAt = '2019-08-25'; - updatedDocketEntry.receivedAt = '2019-08-25T05:00:00.000Z'; - const result = needsNewCoversheet({ - applicationContext, - currentDocketEntry, - updatedDocketEntry, - }); - - expect(result).toEqual(false); - }); - - it('should return true when certificateOfService is updated', () => { - updatedDocketEntry.certificateOfService = true; - const result = needsNewCoversheet({ - applicationContext, - currentDocketEntry, - updatedDocketEntry, - }); - expect(result).toEqual(true); - }); - - it('should return false when filedBy is updated', () => { - updatedDocketEntry.filedBy = 'petitioner.smith'; - const result = needsNewCoversheet({ - applicationContext, - currentDocketEntry, - updatedDocketEntry, - }); - expect(result).toEqual(false); - }); - - it('should return true when documentTitle is updated', () => { - updatedDocketEntry.documentTitle = 'fake title 2'; - const result = needsNewCoversheet({ - applicationContext, - currentDocketEntry, - updatedDocketEntry, - }); - expect(result).toEqual(true); - }); -}); diff --git a/web-api/src/business/useCases/editDocketEntry/completeDocketEntryQCInteractor.test.ts b/web-api/src/business/useCases/editDocketEntry/completeDocketEntryQCInteractor.test.ts deleted file mode 100644 index 8bbd20f389a..00000000000 --- a/web-api/src/business/useCases/editDocketEntry/completeDocketEntryQCInteractor.test.ts +++ /dev/null @@ -1,644 +0,0 @@ -import { - CASE_SERVICES_SUPERVISOR_SECTION, - DOCKET_SECTION, - DOCUMENT_PROCESSING_STATUS_OPTIONS, - SERVICE_INDICATOR_TYPES, - SYSTEM_GENERATED_DOCUMENT_TYPES, -} from '../../../../../shared/src/business/entities/EntityConstants'; -import { MOCK_ACTIVE_LOCK } from '../../../../../shared/src/test/mockLock'; -import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; -import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; -import { - caseServicesSupervisorUser, - docketClerkUser, -} from '../../../../../shared/src/test/mockUsers'; -import { completeDocketEntryQCInteractor } from './completeDocketEntryQCInteractor'; - -describe('completeDocketEntryQCInteractor', () => { - let caseRecord; - - const mockPrimaryId = MOCK_CASE.petitioners[0].contactId; - const mockDocketEntryId = MOCK_CASE.docketEntries[0].docketEntryId; - let mockLock; - - beforeAll(() => { - applicationContext - .getPersistenceGateway() - .getLock.mockImplementation(() => mockLock); - - applicationContext - .getPersistenceGateway() - .getConfigurationItemValue.mockImplementation(() => ({ - name: 'bob', - title: 'clerk of court', - })); - }); - - beforeEach(() => { - mockLock = undefined; - const workItem = { - docketEntry: { - docketEntryId: mockDocketEntryId, - docketNumber: MOCK_CASE.docketNumber, - documentType: 'Answer', - eventCode: 'A', - }, - docketNumber: '45678-18', - section: DOCKET_SECTION, - sentBy: 'Test User', - sentByUserId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - updatedAt: applicationContext.getUtilities().createISODateString(), - workItemId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; - - caseRecord = { - ...MOCK_CASE, - docketEntries: [ - { - ...MOCK_CASE.docketEntries[0], - addToCoversheet: false, - additionalInfo: 'additional info', - additionalInfo2: 'additional info 2', - certificateOfService: true, - certificateOfServiceDate: '2019-08-25T05:00:00.000Z', - documentTitle: 'Answer', - documentType: 'Answer', - eventCode: 'A', - isOnDocketRecord: true, - receivedAt: '2019-08-25T05:00:00.000Z', - servedAt: '2019-08-25T05:00:00.000Z', - servedParties: [{ name: 'Bernard Lowe' }], - workItem, - }, - ], - }; - - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - - applicationContext - .getPersistenceGateway() - .getUserById.mockReturnValue(docketClerkUser); - - applicationContext - .getPersistenceGateway() - .getCaseByDocketNumber.mockReturnValue(caseRecord); - - applicationContext.getChromiumBrowser().newPage.mockReturnValue({ - addStyleTag: () => {}, - pdf: () => { - return 'Hello World'; - }, - setContent: () => {}, - }); - - applicationContext - .getPersistenceGateway() - .getDownloadPolicyUrl.mockReturnValue({ - url: 'www.example.com', - }); - - applicationContext - .getUseCaseHelpers() - .serveDocumentAndGetPaperServicePdf.mockReturnValue({ - pdfUrl: 'www.example.com', - }); - }); - - it('should throw an error if not authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); - - await expect( - completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - leadDocketNumber: caseRecord.docketNumber, - }, - }), - ).rejects.toThrow('Unauthorized'); - }); - - it('adds documents and workitems', async () => { - await expect( - completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - leadDocketNumber: caseRecord.docketNumber, - }, - }), - ).resolves.not.toThrow(); - - expect( - applicationContext.getPersistenceGateway().getCaseByDocketNumber, - ).toHaveBeenCalled(); - expect( - applicationContext.getPersistenceGateway() - .saveWorkItemForDocketClerkFilingExternalDocument, - ).toHaveBeenCalled(); - expect( - applicationContext.getPersistenceGateway() - .saveWorkItemForDocketClerkFilingExternalDocument.mock.calls[0][0] - .workItem, - ).toMatchObject({ leadDocketNumber: caseRecord.docketNumber }); - expect( - applicationContext.getPersistenceGateway().updateCase, - ).toHaveBeenCalled(); - }); - - it('serves the document for electronic-only parties if a notice of docket change is generated', async () => { - const result = await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: caseRecord.docketEntries[0], - }); - - expect( - applicationContext.getPersistenceGateway().getCaseByDocketNumber, - ).toHaveBeenCalled(); - expect( - applicationContext.getPersistenceGateway() - .saveWorkItemForDocketClerkFilingExternalDocument, - ).toHaveBeenCalled(); - expect( - applicationContext.getPersistenceGateway().updateCase, - ).toHaveBeenCalled(); - expect(result.paperServicePdfUrl).toBeUndefined(); - expect(result.paperServiceParties.length).toEqual(0); - }); - - it('should generate a notice of docket change with a new coversheet when additional info fields are added and addToCoversheet is true', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: true, - additionalInfo: '123', - additionalInfo2: 'abc', - certificateOfService: false, - }, - }); - - expect( - applicationContext.getUseCases().addCoversheetInteractor, - ).toHaveBeenCalled(); - expect( - applicationContext.getDocumentGenerators().noticeOfDocketChange.mock - .calls[0][0].data.filingsAndProceedings, - ).toEqual({ - after: 'Answer 123 abc', - before: 'Answer additional info (C/S 08/25/19) additional info 2', - }); - }); - - it('should generate a notice of docket change with the name and title of the clerk of the court', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: true, - additionalInfo: '123', - additionalInfo2: 'abc', - certificateOfService: false, - }, - }); - - expect( - applicationContext.getDocumentGenerators().noticeOfDocketChange.mock - .calls[0][0].data, - ).toMatchObject({ - nameOfClerk: 'bob', - titleOfClerk: 'clerk of court', - }); - }); - - it('should save the notice of docket change on the case', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: true, - additionalInfo: '123', - additionalInfo2: 'abc', - certificateOfService: false, - }, - }); - - const updatedCaseDocketEntries = - applicationContext.getUseCaseHelpers().updateCaseAndAssociations.mock - .calls[0][0].caseToUpdate.docketEntries; - const noticeOfDocketChangeDocketEntry = updatedCaseDocketEntries.find( - d => - d.eventCode === - SYSTEM_GENERATED_DOCUMENT_TYPES.noticeOfDocketChange.eventCode, - ); - - expect(noticeOfDocketChangeDocketEntry.documentTitle).toEqual( - 'Notice of Docket Change for Docket Entry No. 1', - ); - }); - - it('should generate a notice of docket change without a new coversheet when the certificate of service date has been updated', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - certificateOfService: true, - certificateOfServiceDate: '2019-08-06T07:53:09.001Z', - }, - }); - - expect( - applicationContext.getUseCases().addCoversheetInteractor, - ).not.toHaveBeenCalled(); - expect( - applicationContext.getDocumentGenerators().noticeOfDocketChange.mock - .calls[0][0].data.filingsAndProceedings, - ).toEqual({ - after: 'Answer additional info (C/S 08/06/19) additional info 2', - before: 'Answer additional info (C/S 08/25/19) additional info 2', - }); - }); - - it('should generate a notice of docket change without a new coversheet when attachments has been updated', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - attachments: true, - }, - }); - - expect( - applicationContext.getUseCases().addCoversheetInteractor, - ).not.toHaveBeenCalled(); - expect( - applicationContext.getDocumentGenerators().noticeOfDocketChange.mock - .calls[0][0].data.filingsAndProceedings, - ).toEqual({ - after: - 'Answer additional info (C/S 08/25/19) (Attachment(s)) additional info 2', - before: 'Answer additional info (C/S 08/25/19) additional info 2', - }); - }); - - it('should generate a notice of docket change with a new coversheet when additional info fields are removed and addToCoversheet is true', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: true, - additionalInfo: undefined, - additionalInfo2: undefined, - certificateOfService: false, - }, - }); - - expect( - applicationContext.getUseCases().addCoversheetInteractor, - ).toHaveBeenCalled(); - expect( - applicationContext.getDocumentGenerators().noticeOfDocketChange.mock - .calls[0][0].data.filingsAndProceedings, - ).toEqual({ - after: 'Answer', - before: 'Answer additional info (C/S 08/25/19) additional info 2', - }); - }); - - it('should generate a notice of docket change with a new coversheet when documentTitle has changed and addToCoversheeet is false', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: false, - additionalInfo: undefined, - additionalInfo2: undefined, - certificateOfService: false, - documentTitle: 'Something Different', - }, - }); - - expect( - applicationContext.getUseCases().addCoversheetInteractor, - ).toHaveBeenCalled(); - expect( - applicationContext.getDocumentGenerators().noticeOfDocketChange.mock - .calls[0][0].data.filingsAndProceedings, - ).toEqual({ - after: 'Something Different', - before: 'Answer additional info (C/S 08/25/19) additional info 2', - }); - }); - - it('should not generate a new coversheet when the documentTitle has not changed and addToCoversheet is false', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: false, - }, - }); - - expect( - applicationContext.getUseCases().addCoversheetInteractor, - ).not.toHaveBeenCalled(); - expect( - applicationContext.getDocumentGenerators().noticeOfDocketChange, - ).not.toHaveBeenCalled(); - }); - - it('should generate a new coversheet when additionalInfo is changed and addToCoversheet is true', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: true, - additionalInfo: 'additional info', - additionalInfo2: 'additional info 221', - certificateOfService: false, - }, - }); - - expect( - applicationContext.getUseCases().addCoversheetInteractor, - ).toHaveBeenCalled(); - expect( - applicationContext.getDocumentGenerators().noticeOfDocketChange.mock - .calls[0][0].data.filingsAndProceedings, - ).toEqual({ - after: 'Answer additional info additional info 221', - before: 'Answer additional info (C/S 08/25/19) additional info 2', - }); - }); - - it('should generate a new coversheet when additionalInfo is NOT changed and addToCoversheet is true', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - addToCoversheet: true, - additionalInfo: 'additional info', - additionalInfo2: 'additional info', - certificateOfService: false, - }, - }); - - expect( - applicationContext.getUseCases().addCoversheetInteractor, - ).toHaveBeenCalled(); - expect( - applicationContext.getDocumentGenerators().noticeOfDocketChange.mock - .calls[0][0].data.filingsAndProceedings, - ).toEqual({ - after: 'Answer additional info additional info', - before: 'Answer additional info (C/S 08/25/19) additional info 2', - }); - }); - - it('serves the document for parties with paper service if a notice of docket change is generated', async () => { - applicationContext - .getPersistenceGateway() - .getCaseByDocketNumber.mockReturnValue({ - ...caseRecord, - isPaper: true, - mailingDate: '2019-03-01T21:40:46.415Z', - petitioners: [ - { - ...caseRecord.petitioners[0], - serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, - }, - ], - }); - - const mockNumberOfPages = 999; - applicationContext - .getUseCaseHelpers() - .countPagesInDocument.mockImplementation(() => { - return mockNumberOfPages; - }); - - const result = await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - documentTitle: 'Something Else', - documentType: 'Memorandum in Support', - }, - }); - - const noticeOfDocketChange = result.caseDetail.docketEntries.find( - docketEntry => docketEntry.eventCode === 'NODC', - ); - - expect( - applicationContext.getUseCaseHelpers().countPagesInDocument, - ).toHaveBeenCalled(); - - expect(noticeOfDocketChange).toMatchObject({ - isFileAttached: true, - numberOfPages: 999, - processingStatus: DOCUMENT_PROCESSING_STATUS_OPTIONS.COMPLETE, - }); - - expect( - applicationContext.getPersistenceGateway().getCaseByDocketNumber, - ).toHaveBeenCalled(); - expect( - applicationContext.getPersistenceGateway() - .saveWorkItemForDocketClerkFilingExternalDocument, - ).toHaveBeenCalled(); - expect( - applicationContext.getPersistenceGateway().updateCase, - ).toHaveBeenCalled(); - expect(result.paperServicePdfUrl).toEqual('www.example.com'); - expect(result.paperServiceParties.length).toEqual(1); - }); - - it('generates a document for paper service if the document is a Notice of Change of Address and the case has paper service parties', async () => { - applicationContext - .getPersistenceGateway() - .getCaseByDocketNumber.mockReturnValue({ - ...caseRecord, - isPaper: true, - mailingDate: '2019-03-01T21:40:46.415Z', - petitioners: [ - { - ...caseRecord.petitioners[0], - serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, - }, - ], - }); - - const result = await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - documentTitle: 'Notice of Change of Address', - documentType: 'Notice of Change of Address', - }, - }); - - expect( - applicationContext.getPersistenceGateway().getCaseByDocketNumber, - ).toHaveBeenCalled(); - expect( - applicationContext.getPersistenceGateway() - .saveWorkItemForDocketClerkFilingExternalDocument, - ).toHaveBeenCalled(); - expect( - applicationContext.getPersistenceGateway().updateCase, - ).toHaveBeenCalled(); - expect(result.paperServicePdfUrl).toEqual('www.example.com'); - expect(result.paperServiceParties.length).toEqual(1); - }); - - it('does not generate a document for paper service if the document is a Notice of Change of Address and the case has no paper service parties', async () => { - const result = await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - documentTitle: 'Notice of Change of Address', - documentType: 'Notice of Change of Address', - }, - }); - - expect( - applicationContext.getPersistenceGateway().getCaseByDocketNumber, - ).toHaveBeenCalled(); - expect( - applicationContext.getPersistenceGateway() - .saveWorkItemForDocketClerkFilingExternalDocument, - ).toHaveBeenCalled(); - expect( - applicationContext.getPersistenceGateway().updateCase, - ).toHaveBeenCalled(); - expect(result.paperServicePdfUrl).toEqual(undefined); - expect(result.paperServiceParties.length).toEqual(0); - }); - - it('should update only allowed editable fields on a docket entry document', async () => { - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - documentTitle: 'My Edited Document', - documentType: 'Notice of Change of Address', - eventCode: 'NCA', - filedBy: 'Resp.', - filers: [mockPrimaryId], - freeText: 'Some text about this document', - hasOtherFilingParty: true, - isPaper: true, - otherFilingParty: 'Bert Brooks', - scenario: 'Nonstandard H', - secondaryDocument: { - documentType: 'Notice of Change of Address', - eventCode: 'A', - }, - }, - }); - - expect( - applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] - .caseToUpdate.docketEntries[0], - ).toMatchObject({ - documentTitle: 'My Edited Document', - documentType: 'Notice of Change of Address', - eventCode: 'NCA', - freeText: 'Some text about this document', - hasOtherFilingParty: true, - otherFilingParty: 'Bert Brooks', - secondaryDocument: { - documentType: 'Notice of Change of Address', - eventCode: 'A', - }, - }); - }); - - it('updates automaticBlocked on a case and all associated case trial sort mappings if pending is true', async () => { - expect(caseRecord.automaticBlocked).toBeFalsy(); - - const { caseDetail } = await completeDocketEntryQCInteractor( - applicationContext, - { - entryMetadata: { - ...caseRecord.docketEntries[0], - pending: true, - }, - }, - ); - - expect( - applicationContext.getUseCaseHelpers().updateCaseAutomaticBlock, - ).toHaveBeenCalled(); - expect( - applicationContext.getPersistenceGateway() - .deleteCaseTrialSortMappingRecords, - ).toHaveBeenCalled(); - expect(caseDetail.automaticBlocked).toBeTruthy(); - }); - - it('normalizes receivedAt dates to ISO string format', async () => { - const { caseDetail } = await completeDocketEntryQCInteractor( - applicationContext, - { - entryMetadata: { - ...caseRecord.docketEntries[0], - receivedAt: '2021-01-01', // date only - }, - }, - ); - - expect(caseDetail.docketEntries[0].receivedAt).toEqual( - '2021-01-01T05:00:00.000Z', - ); - }); - - it('sets the assigned users section from the selected section when it is defined and the user is a case services user', async () => { - applicationContext.getCurrentUser.mockReturnValue( - caseServicesSupervisorUser, - ); - - await applicationContext - .getPersistenceGateway() - .getUserById.mockReturnValue(caseServicesSupervisorUser); - - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - selectedSection: DOCKET_SECTION, - }, - }); - - const assignedWorkItem = - applicationContext.getPersistenceGateway() - .saveWorkItemForDocketClerkFilingExternalDocument.mock.calls[0][0] - .workItem; - - expect(assignedWorkItem.section).toEqual(DOCKET_SECTION); - }); - - it('sets the section as Case Services when selected section is NOT defined and the user is a case services user', async () => { - applicationContext.getCurrentUser.mockReturnValue( - caseServicesSupervisorUser, - ); - - await applicationContext - .getPersistenceGateway() - .getUserById.mockReturnValue(caseServicesSupervisorUser); - - await completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - selectedSection: undefined, - }, - }); - - const assignedWorkItem = - applicationContext.getPersistenceGateway() - .saveWorkItemForDocketClerkFilingExternalDocument.mock.calls[0][0] - .workItem; - - expect(assignedWorkItem.section).toEqual(CASE_SERVICES_SUPERVISOR_SECTION); - }); - - it('throws the expected error if the lock is already acquired by another process', async () => { - applicationContext.getCurrentUser.mockReturnValue( - caseServicesSupervisorUser, - ); - - mockLock = MOCK_ACTIVE_LOCK; - - await expect(() => - completeDocketEntryQCInteractor(applicationContext, { - entryMetadata: { - ...caseRecord.docketEntries[0], - selectedSection: undefined, - }, - }), - ).rejects.toThrow('The document is currently being updated'); - }); -}); diff --git a/web-api/src/business/useCases/editDocketEntry/completeDocketEntryQCInteractor.ts b/web-api/src/business/useCases/editDocketEntry/completeDocketEntryQCInteractor.ts deleted file mode 100644 index fbf6f6ef1c3..00000000000 --- a/web-api/src/business/useCases/editDocketEntry/completeDocketEntryQCInteractor.ts +++ /dev/null @@ -1,391 +0,0 @@ -import { - CONTACT_CHANGE_DOCUMENT_TYPES, - DOCUMENT_PROCESSING_STATUS_OPTIONS, - DOCUMENT_RELATIONSHIPS, - SYSTEM_GENERATED_DOCUMENT_TYPES, -} from '../../../../../shared/src/business/entities/EntityConstants'; -import { Case } from '../../../../../shared/src/business/entities/cases/Case'; -import { DocketEntry } from '../../../../../shared/src/business/entities/DocketEntry'; -import { - FORMATS, - dateStringsCompared, - formatDateString, -} from '../../../../../shared/src/business/utilities/DateHandler'; -import { InvalidRequest, UnauthorizedError } from '@web-api/errors/errors'; -import { - ROLE_PERMISSIONS, - isAuthorized, -} from '../../../../../shared/src/authorization/authorizationClientService'; -import { ServerApplicationContext } from '@web-api/applicationContext'; -import { User } from '@shared/business/entities/User'; -import { addServedStampToDocument } from '@web-api/business/useCases/courtIssuedDocument/addServedStampToDocument'; -import { aggregatePartiesForService } from '@shared/business/utilities/aggregatePartiesForService'; -import { generateNoticeOfDocketChangePdf } from '@web-api/business/useCaseHelper/noticeOfDocketChange/generateNoticeOfDocketChangePdf'; -import { getCaseCaptionMeta } from '@shared/business/utilities/getCaseCaptionMeta'; -import { getDocumentTitleForNoticeOfChange } from '@shared/business/utilities/getDocumentTitleForNoticeOfChange'; -import { replaceBracketed } from '@shared/business/utilities/replaceBracketed'; -import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; - -const completeDocketEntryQC = async ( - applicationContext: ServerApplicationContext, - { entryMetadata }: { entryMetadata: any }, -) => { - const authorizedUser = applicationContext.getCurrentUser(); - - const { PDFDocument } = await applicationContext.getPdfLib(); - - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.DOCKET_ENTRY)) { - throw new UnauthorizedError('Unauthorized'); - } - - const { - docketEntryId, - docketNumber, - leadDocketNumber, - overridePaperServiceAddress, - selectedSection, - } = entryMetadata; - - const user = await applicationContext - .getPersistenceGateway() - .getUserById({ applicationContext, userId: authorizedUser.userId }); - - const caseToUpdate = await applicationContext - .getPersistenceGateway() - .getCaseByDocketNumber({ - applicationContext, - docketNumber, - }); - - let caseEntity = new Case(caseToUpdate, { applicationContext }); - const { index: docketRecordIndexUpdated } = caseEntity.docketEntries.find( - record => record.docketEntryId === docketEntryId, - ); - - const currentDocketEntry = caseEntity.getDocketEntryById({ - docketEntryId, - }); - - if (currentDocketEntry.workItem.isCompleted()) { - throw new InvalidRequest('The work item was already completed'); - } - - const editableFields = { - addToCoversheet: entryMetadata.addToCoversheet, - additionalInfo: entryMetadata.additionalInfo, - additionalInfo2: entryMetadata.additionalInfo2, - attachments: entryMetadata.attachments, - certificateOfService: entryMetadata.certificateOfService, - certificateOfServiceDate: entryMetadata.certificateOfServiceDate, - documentTitle: entryMetadata.documentTitle, - documentType: entryMetadata.documentType, - eventCode: entryMetadata.eventCode, - filedBy: entryMetadata.filedBy, - filers: entryMetadata.filers, - freeText: entryMetadata.freeText, - freeText2: entryMetadata.freeText2, - hasOtherFilingParty: entryMetadata.hasOtherFilingParty, - isFileAttached: true, - lodged: entryMetadata.lodged, - mailingDate: entryMetadata.mailingDate, - objections: entryMetadata.objections, - ordinalValue: entryMetadata.ordinalValue, - otherFilingParty: entryMetadata.otherFilingParty, - otherIteration: entryMetadata.otherIteration, - partyIrsPractitioner: entryMetadata.partyIrsPractitioner, - pending: entryMetadata.pending, - receivedAt: entryMetadata.receivedAt, - scenario: entryMetadata.scenario, - secondaryDocument: entryMetadata.secondaryDocument, - serviceDate: entryMetadata.serviceDate, - }; - - const updatedDocketEntry = new DocketEntry( - { - ...currentDocketEntry, - ...editableFields, - documentTitle: editableFields.documentTitle, - editState: '{}', - relationship: DOCUMENT_RELATIONSHIPS.PRIMARY, - workItem: { - ...currentDocketEntry.workItem, - leadDocketNumber, - trialDate: caseEntity.trialDate, - trialLocation: caseEntity.trialLocation, - }, - }, - { applicationContext, petitioners: caseToUpdate.petitioners }, - ).validate(); - updatedDocketEntry.setQCed(user); - - let updatedDocumentTitle = getDocumentTitleForNoticeOfChange({ - applicationContext, - docketEntry: updatedDocketEntry, - }); - - let currentDocumentTitle = getDocumentTitleForNoticeOfChange({ - applicationContext, - docketEntry: currentDocketEntry, - }); - - const isNewCoverSheetNeeded = needsNewCoversheet({ - applicationContext, - currentDocketEntry, - updatedDocketEntry, - }); - - const needsNoticeOfDocketChange = - updatedDocketEntry.filedBy !== currentDocketEntry.filedBy || - updatedDocumentTitle !== currentDocumentTitle; - - const { caseCaptionExtension, caseTitle } = getCaseCaptionMeta(caseEntity); - - const { name, title } = await applicationContext - .getPersistenceGateway() - .getConfigurationItemValue({ - applicationContext, - configurationItemKey: - applicationContext.getConstants().CLERK_OF_THE_COURT_CONFIGURATION, - }); - - const docketChangeInfo = { - caseCaptionExtension, - caseTitle, - docketEntryIndex: docketRecordIndexUpdated, - docketNumber: `${caseToUpdate.docketNumber}${ - caseToUpdate.docketNumberSuffix || '' - }`, - filingParties: { - after: updatedDocketEntry.filedBy, - before: currentDocketEntry.filedBy, - }, - filingsAndProceedings: { - after: updatedDocumentTitle, - before: currentDocumentTitle, - }, - nameOfClerk: name, - titleOfClerk: title, - }; - - caseEntity.updateDocketEntry(updatedDocketEntry); - - caseEntity = await applicationContext - .getUseCaseHelpers() - .updateCaseAutomaticBlock({ applicationContext, caseEntity }); - - const workItemToUpdate = updatedDocketEntry.workItem; - - Object.assign(workItemToUpdate, { - docketEntry: { - ...updatedDocketEntry.toRawObject(), - createdAt: updatedDocketEntry.createdAt, - }, - }); - - workItemToUpdate.setAsCompleted({ - message: 'completed', - user, - }); - - const userIsCaseServices = User.isCaseServicesUser({ - section: user.section || '', - }); - - let sectionToAssignTo = - userIsCaseServices && selectedSection ? selectedSection : user.section; - - workItemToUpdate.assignToUser({ - assigneeId: user.userId, - assigneeName: user.name, - section: sectionToAssignTo, - sentBy: user.name, - sentBySection: user.section, - sentByUserId: user.userId, - }); - - await applicationContext - .getPersistenceGateway() - .saveWorkItemForDocketClerkFilingExternalDocument({ - applicationContext, - workItem: workItemToUpdate.validate().toRawObject(), - }); - - let servedParties = aggregatePartiesForService(caseEntity); - let paperServicePdfUrl; - let paperServiceDocumentTitle; - - if ( - overridePaperServiceAddress || - CONTACT_CHANGE_DOCUMENT_TYPES.includes(updatedDocketEntry.documentType) - ) { - if (servedParties.paper.length > 0) { - const pdfData = await applicationContext - .getPersistenceGateway() - .getDocument({ - applicationContext, - key: updatedDocketEntry.docketEntryId, - }); - - const noticeDoc = await PDFDocument.load(pdfData); - - let newPdfDoc = await PDFDocument.create(); - - await applicationContext - .getUseCaseHelpers() - .appendPaperServiceAddressPageToPdf({ - applicationContext, - caseEntity, - newPdfDoc, - noticeDoc, - servedParties, - }); - - const paperServicePdfData = await newPdfDoc.save(); - - const paperServicePdfId = applicationContext.getUniqueId(); - - await applicationContext.getPersistenceGateway().saveDocumentFromLambda({ - applicationContext, - document: paperServicePdfData, - key: paperServicePdfId, - useTempBucket: true, - }); - - const { url } = await applicationContext - .getPersistenceGateway() - .getDownloadPolicyUrl({ - applicationContext, - key: paperServicePdfId, - useTempBucket: true, - }); - - paperServicePdfUrl = url; - paperServiceDocumentTitle = updatedDocketEntry.documentTitle; - } - } else if (needsNoticeOfDocketChange) { - const noticeDocketEntryId = await generateNoticeOfDocketChangePdf({ - applicationContext, - docketChangeInfo, - }); - - let noticeUpdatedDocketEntry = new DocketEntry( - { - ...SYSTEM_GENERATED_DOCUMENT_TYPES.noticeOfDocketChange, - docketEntryId: noticeDocketEntryId, - documentTitle: replaceBracketed( - SYSTEM_GENERATED_DOCUMENT_TYPES.noticeOfDocketChange.documentTitle, - docketChangeInfo.docketEntryIndex, - ), - isFileAttached: true, - isOnDocketRecord: true, - processingStatus: DOCUMENT_PROCESSING_STATUS_OPTIONS.COMPLETE, - }, - { applicationContext, petitioners: caseToUpdate.petitioners }, - ); - - noticeUpdatedDocketEntry.setFiledBy(user); - - noticeUpdatedDocketEntry.numberOfPages = await applicationContext - .getUseCaseHelpers() - .countPagesInDocument({ - applicationContext, - docketEntryId: noticeUpdatedDocketEntry.docketEntryId, - }); - - noticeUpdatedDocketEntry.setAsServed(servedParties.all); - - caseEntity.addDocketEntry(noticeUpdatedDocketEntry); - - const serviceStampDate = formatDateString( - noticeUpdatedDocketEntry.servedAt!, - FORMATS.MMDDYY, - ); - - const pdfData = await applicationContext - .getPersistenceGateway() - .getDocument({ - applicationContext, - key: noticeUpdatedDocketEntry.docketEntryId, - }); - - const newPdfData = await addServedStampToDocument({ - applicationContext, - pdfData, - serviceStampText: `Served ${serviceStampDate}`, - }); - - await applicationContext.getPersistenceGateway().saveDocumentFromLambda({ - applicationContext, - document: newPdfData, - key: noticeUpdatedDocketEntry.docketEntryId, - }); - - const paperServiceResult = await applicationContext - .getUseCaseHelpers() - .serveDocumentAndGetPaperServicePdf({ - applicationContext, - caseEntities: [caseEntity], - docketEntryId: noticeUpdatedDocketEntry.docketEntryId, - }); - - if (servedParties.paper.length > 0) { - paperServicePdfUrl = paperServiceResult && paperServiceResult.pdfUrl; - paperServiceDocumentTitle = noticeUpdatedDocketEntry.documentTitle; - } - } - - await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ - applicationContext, - caseToUpdate: caseEntity, - }); - - if (isNewCoverSheetNeeded) { - await applicationContext - .getUseCases() - .addCoversheetInteractor(applicationContext, { - docketEntryId, - docketNumber: caseEntity.docketNumber, - }); - } - - return { - caseDetail: caseEntity.toRawObject(), - paperServiceDocumentTitle, - paperServiceParties: servedParties.paper, - paperServicePdfUrl, - }; -}; - -export const completeDocketEntryQCInteractor = withLocking( - completeDocketEntryQC, - (_applicationContext: ServerApplicationContext, { entryMetadata }) => ({ - identifiers: [`docket-entry|${entryMetadata.docketEntryId}`], - }), - new InvalidRequest('The document is currently being updated'), -); - -export const needsNewCoversheet = ({ - applicationContext, - currentDocketEntry, - updatedDocketEntry, -}) => { - const receivedAtUpdated = - dateStringsCompared( - currentDocketEntry.receivedAt, - updatedDocketEntry.receivedAt, - ) !== 0; - const certificateOfServiceUpdated = - currentDocketEntry.certificateOfService !== - updatedDocketEntry.certificateOfService; - const documentTitleUpdated = - applicationContext.getUtilities().getDocumentTitleWithAdditionalInfo({ - docketEntry: currentDocketEntry, - }) !== - applicationContext.getUtilities().getDocumentTitleWithAdditionalInfo({ - docketEntry: updatedDocketEntry, - }); - - return ( - receivedAtUpdated || certificateOfServiceUpdated || documentTitleUpdated - ); -}; diff --git a/web-api/src/business/useCases/externalDocument/fileExternalDocumentInteractor.test.ts b/web-api/src/business/useCases/externalDocument/fileExternalDocumentInteractor.test.ts index 879ca7ac375..4738d8b4e96 100644 --- a/web-api/src/business/useCases/externalDocument/fileExternalDocumentInteractor.test.ts +++ b/web-api/src/business/useCases/externalDocument/fileExternalDocumentInteractor.test.ts @@ -11,11 +11,13 @@ import { SIMULTANEOUS_DOCUMENT_EVENT_CODES, } from '@shared/business/entities/EntityConstants'; import { MOCK_LOCK } from '@shared/test/mockLock'; -import { MOCK_USERS, docketClerkUser } from '@shared/test/mockUsers'; import { ServiceUnavailableError } from '@web-api/errors/errors'; -import { User } from '@shared/business/entities/User'; import { applicationContext } from '@shared/business/test/createTestApplicationContext'; import { fileExternalDocumentInteractor } from './fileExternalDocumentInteractor'; +import { + mockDocketClerkUser, + mockIrsPractitionerUser, +} from '@shared/test/mockAuthUsers'; describe('fileExternalDocumentInteractor', () => { const mockDocketEntryId = applicationContext.getUniqueId(); @@ -103,17 +105,9 @@ describe('fileExternalDocumentInteractor', () => { userId: '0e97c6b4-d299-44f5-af99-2ce905d520f2', }; - applicationContext.getCurrentUser.mockReturnValue( - new User({ - name: 'irsPractitioner', - role: ROLES.irsPractitioner, - userId: 'f7d90c05-f6cd-442c-a168-202db587f16f', - }), - ); - applicationContext .getPersistenceGateway() - .getUserById.mockImplementation(({ userId }) => MOCK_USERS[userId]); + .getUserById.mockReturnValue(mockIrsPractitionerUser); applicationContext .getPersistenceGateway() @@ -121,34 +115,40 @@ describe('fileExternalDocumentInteractor', () => { }); it('should throw an error when the user is not authorized to file an external document on a case', async () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - await expect( - fileExternalDocumentInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'Memorandum in Support', - documentType: 'Memorandum in Support', - eventCode: 'A', - filedBy: 'Test Petitioner', - primaryDocumentId: mockDocketEntryId, + fileExternalDocumentInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'Memorandum in Support', + documentType: 'Memorandum in Support', + eventCode: 'A', + filedBy: 'Test Petitioner', + primaryDocumentId: mockDocketEntryId, + }, }, - }), + mockDocketClerkUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should validate docket entry entities before adding them to the case and not call service or persistence methods', async () => { await expect( - fileExternalDocumentInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'Memorandum in Support', - documentType: 'Memorandum in Support', - eventCode: 'XYZ', - filedBy: 'Test Petitioner', - primaryDocumentId: mockDocketEntryId, + fileExternalDocumentInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'Memorandum in Support', + documentType: 'Memorandum in Support', + eventCode: 'XYZ', + filedBy: 'Test Petitioner', + primaryDocumentId: mockDocketEntryId, + }, }, - }), + mockIrsPractitionerUser, + ), ).rejects.toThrow('The DocketEntry entity was invalid.'); expect( @@ -178,6 +178,7 @@ describe('fileExternalDocumentInteractor', () => { primaryDocumentId: mockDocketEntryId, }, }, + mockIrsPractitionerUser, ); expect( @@ -192,7 +193,7 @@ describe('fileExternalDocumentInteractor', () => { expect( applicationContext.getUseCaseHelpers().sendServedPartiesEmails, ).toHaveBeenCalled(); - expect(updatedCase.docketEntries[4].servedAt).toBeDefined(); + expect(updatedCase!.docketEntries[4].servedAt).toBeDefined(); }); it('should add documents and workitems and auto-serve the documents on the parties with an electronic service indicator across consolidated cases', async () => { @@ -295,6 +296,7 @@ describe('fileExternalDocumentInteractor', () => { primaryDocumentId: mockDocketEntryId, }, }, + mockIrsPractitionerUser, ); expect( @@ -312,20 +314,24 @@ describe('fileExternalDocumentInteractor', () => { expect( applicationContext.getUseCaseHelpers().sendServedPartiesEmails, ).toHaveBeenCalledTimes(2); - expect(updatedCase.docketEntries[4].servedAt).toBeDefined(); + expect(updatedCase!.docketEntries[4].servedAt).toBeDefined(); }); it('should use original case caption to create case title when creating work item', async () => { - await fileExternalDocumentInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'Memorandum in Support', - documentType: 'Memorandum in Support', - eventCode: 'A', - filedBy: 'Test Petitioner', - primaryDocumentId: mockDocketEntryId, + await fileExternalDocumentInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'Memorandum in Support', + documentType: 'Memorandum in Support', + eventCode: 'A', + filedBy: 'Test Petitioner', + primaryDocumentId: mockDocketEntryId, + }, }, - }); + mockIrsPractitionerUser, + ); expect( applicationContext.getPersistenceGateway().saveWorkItem.mock.calls[0][0] @@ -377,11 +383,12 @@ describe('fileExternalDocumentInteractor', () => { ], }, }, + mockIrsPractitionerUser, ); expect( applicationContext.getPersistenceGateway().updateCase, ).toHaveBeenCalled(); - expect(updatedCase.docketEntries).toMatchObject([ + expect(updatedCase!.docketEntries).toMatchObject([ {}, // first 4 docs were already on the case {}, {}, @@ -424,6 +431,7 @@ describe('fileExternalDocumentInteractor', () => { primaryDocumentId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }, }, + mockIrsPractitionerUser, ); expect( @@ -438,8 +446,8 @@ describe('fileExternalDocumentInteractor', () => { expect( applicationContext.getUseCaseHelpers().sendServedPartiesEmails, ).not.toHaveBeenCalled(); - expect(updatedCase.docketEntries[3].status).toBeUndefined(); - expect(updatedCase.docketEntries[3].servedAt).toBeUndefined(); + expect(updatedCase!.docketEntries[3].status).toBeUndefined(); + expect(updatedCase!.docketEntries[3].servedAt).toBeUndefined(); }); it('should create a high-priority work item if the case status is calendared', async () => { @@ -447,16 +455,20 @@ describe('fileExternalDocumentInteractor', () => { caseRecord.trialDate = '2019-03-01T21:40:46.415Z'; caseRecord.trialSessionId = 'c54ba5a9-b37b-479d-9201-067ec6e335bc'; - await fileExternalDocumentInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'Simultaneous Memoranda of Law', - documentType: 'Simultaneous Memoranda of Law', - eventCode: 'A', - filedBy: 'Test Petitioner', - primaryDocumentId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + await fileExternalDocumentInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'Simultaneous Memoranda of Law', + documentType: 'Simultaneous Memoranda of Law', + eventCode: 'A', + filedBy: 'Test Petitioner', + primaryDocumentId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, }, - }); + mockIrsPractitionerUser, + ); expect( applicationContext.getPersistenceGateway().saveWorkItem, @@ -471,16 +483,20 @@ describe('fileExternalDocumentInteractor', () => { it('should create a not-high-priority work item if the case status is not calendared', async () => { caseRecord.status = CASE_STATUS_TYPES.new; - await fileExternalDocumentInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'Simultaneous Memoranda of Law', - documentType: 'Simultaneous Memoranda of Law', - eventCode: 'A', - filedBy: 'test Petitioner', - primaryDocumentId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + await fileExternalDocumentInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'Simultaneous Memoranda of Law', + documentType: 'Simultaneous Memoranda of Law', + eventCode: 'A', + filedBy: 'test Petitioner', + primaryDocumentId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, }, - }); + mockIrsPractitionerUser, + ); expect( applicationContext.getPersistenceGateway().saveWorkItem, @@ -493,17 +509,21 @@ describe('fileExternalDocumentInteractor', () => { }); it('should automatically block the case if the document filed is a tracked document', async () => { - await fileExternalDocumentInteractor(applicationContext, { - documentMetadata: { - category: 'Application', - docketNumber: caseRecord.docketNumber, - documentTitle: 'Application for Waiver of Filing Fee', - documentType: 'Application for Waiver of Filing Fee', - eventCode: 'APPW', - filedBy: 'Test Petitioner', - primaryDocumentId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + await fileExternalDocumentInteractor( + applicationContext, + { + documentMetadata: { + category: 'Application', + docketNumber: caseRecord.docketNumber, + documentTitle: 'Application for Waiver of Filing Fee', + documentType: 'Application for Waiver of Filing Fee', + eventCode: 'APPW', + filedBy: 'Test Petitioner', + primaryDocumentId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, }, - }); + mockIrsPractitionerUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -528,17 +548,21 @@ describe('fileExternalDocumentInteractor', () => { }, ]); - await fileExternalDocumentInteractor(applicationContext, { - documentMetadata: { - category: 'Application', - docketNumber: caseRecord.docketNumber, - documentTitle: 'Application for Waiver of Filing Fee', - documentType: 'Application for Waiver of Filing Fee', - eventCode: 'APPW', - filedBy: 'Test Petitioner', - primaryDocumentId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + await fileExternalDocumentInteractor( + applicationContext, + { + documentMetadata: { + category: 'Application', + docketNumber: caseRecord.docketNumber, + documentTitle: 'Application for Waiver of Filing Fee', + documentType: 'Application for Waiver of Filing Fee', + eventCode: 'APPW', + filedBy: 'Test Petitioner', + primaryDocumentId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, }, - }); + mockIrsPractitionerUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -555,16 +579,20 @@ describe('fileExternalDocumentInteractor', () => { }); it('should not sendServedPartiesEmails if docketEntryId is undefined', async () => { - await fileExternalDocumentInteractor(applicationContext, { - documentMetadata: { - docketNumber: caseRecord.docketNumber, - documentTitle: 'Memorandum in Support', - documentType: 'Memorandum in Support', - eventCode: 'XYZ', - filedBy: 'Test Petitioner', - primaryDocumentId: undefined, + await fileExternalDocumentInteractor( + applicationContext, + { + documentMetadata: { + docketNumber: caseRecord.docketNumber, + documentTitle: 'Memorandum in Support', + documentType: 'Memorandum in Support', + eventCode: 'XYZ', + filedBy: 'Test Petitioner', + primaryDocumentId: undefined, + }, }, - }); + mockIrsPractitionerUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -578,17 +606,21 @@ describe('fileExternalDocumentInteractor', () => { mockLock = MOCK_LOCK; await expect( - fileExternalDocumentInteractor(applicationContext, { - documentMetadata: { - category: 'Application', - docketNumber: caseRecord.docketNumber, - documentTitle: 'Application for Waiver of Filing Fee', - documentType: 'Application for Waiver of Filing Fee', - eventCode: 'APPW', - filedBy: 'Test Petitioner', - primaryDocumentId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + fileExternalDocumentInteractor( + applicationContext, + { + documentMetadata: { + category: 'Application', + docketNumber: caseRecord.docketNumber, + documentTitle: 'Application for Waiver of Filing Fee', + documentType: 'Application for Waiver of Filing Fee', + eventCode: 'APPW', + filedBy: 'Test Petitioner', + primaryDocumentId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, }, - }), + mockIrsPractitionerUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -597,17 +629,21 @@ describe('fileExternalDocumentInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await fileExternalDocumentInteractor(applicationContext, { - documentMetadata: { - category: 'Application', - docketNumber: caseRecord.docketNumber, - documentTitle: 'Application for Waiver of Filing Fee', - documentType: 'Application for Waiver of Filing Fee', - eventCode: 'APPW', - filedBy: 'Test Petitioner', - primaryDocumentId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + await fileExternalDocumentInteractor( + applicationContext, + { + documentMetadata: { + category: 'Application', + docketNumber: caseRecord.docketNumber, + documentTitle: 'Application for Waiver of Filing Fee', + documentType: 'Application for Waiver of Filing Fee', + eventCode: 'APPW', + filedBy: 'Test Petitioner', + primaryDocumentId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, }, - }); + mockIrsPractitionerUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/externalDocument/fileExternalDocumentInteractor.ts b/web-api/src/business/useCases/externalDocument/fileExternalDocumentInteractor.ts index c2cfef8e7da..65b1138d811 100644 --- a/web-api/src/business/useCases/externalDocument/fileExternalDocumentInteractor.ts +++ b/web-api/src/business/useCases/externalDocument/fileExternalDocumentInteractor.ts @@ -11,6 +11,7 @@ import { } from '@shared/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { WorkItem } from '@shared/business/entities/WorkItem'; import { aggregatePartiesForService } from '@shared/business/utilities/aggregatePartiesForService'; import { pick } from 'lodash'; @@ -26,9 +27,8 @@ import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; export const fileExternalDocument = async ( applicationContext: ServerApplicationContext, { documentMetadata }: { documentMetadata: any }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.FILE_EXTERNAL_DOCUMENT)) { throw new UnauthorizedError('Unauthorized'); } @@ -47,7 +47,7 @@ export const fileExternalDocument = async ( docketNumber, }); - let currentCaseEntity = new Case(currentCase, { applicationContext }); + let currentCaseEntity = new Case(currentCase, { authorizedUser }); const { consolidatedCasesToFileAcross, @@ -132,7 +132,7 @@ export const fileExternalDocument = async ( docketNumber: individualDocumentMetadata.docketNumber, }); - let caseEntity = new Case(caseToUpdate, { applicationContext }); + let caseEntity = new Case(caseToUpdate, { authorizedUser }); const servedParties = aggregatePartiesForService(caseEntity); @@ -148,7 +148,7 @@ export const fileExternalDocument = async ( relationship, }, { - applicationContext, + authorizedUser, petitioners: currentCaseEntity.petitioners, }, ); @@ -160,30 +160,27 @@ export const fileExternalDocument = async ( const highPriorityWorkItem = caseEntity.status === CASE_STATUS_TYPES.calendared; - const workItem = new WorkItem( - { - assigneeId: null, - assigneeName: null, - associatedJudge: caseToUpdate.associatedJudge, - associatedJudgeId: caseToUpdate.associatedJudgeId, - caseStatus: caseToUpdate.status, - caseTitle: Case.getCaseTitle(caseEntity.caseCaption), - docketEntry: { - ...docketEntryEntity.toRawObject(), - createdAt: docketEntryEntity.createdAt, - }, - docketNumber: caseToUpdate.docketNumber, - docketNumberWithSuffix: caseToUpdate.docketNumberWithSuffix, - highPriority: highPriorityWorkItem, - leadDocketNumber: caseToUpdate.leadDocketNumber, - section: DOCKET_SECTION, - sentBy: user.name, - sentByUserId: user.userId, - trialDate: caseEntity.trialDate, - trialLocation: caseEntity.trialLocation, + const workItem = new WorkItem({ + assigneeId: null, + assigneeName: null, + associatedJudge: caseToUpdate.associatedJudge, + associatedJudgeId: caseToUpdate.associatedJudgeId, + caseStatus: caseToUpdate.status, + caseTitle: Case.getCaseTitle(caseEntity.caseCaption), + docketEntry: { + ...docketEntryEntity.toRawObject(), + createdAt: docketEntryEntity.createdAt, }, - { applicationContext }, - ).validate(); + docketNumber: caseToUpdate.docketNumber, + docketNumberWithSuffix: caseToUpdate.docketNumberWithSuffix, + highPriority: highPriorityWorkItem, + leadDocketNumber: caseToUpdate.leadDocketNumber, + section: DOCKET_SECTION, + sentBy: user.name, + sentByUserId: user.userId, + trialDate: caseEntity.trialDate, + trialLocation: caseEntity.trialLocation, + }).validate(); docketEntryEntity.setWorkItem(workItem); @@ -216,6 +213,7 @@ export const fileExternalDocument = async ( await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); diff --git a/web-api/src/business/useCases/generateDocketRecordPdfInteractor.test.ts b/web-api/src/business/useCases/generateDocketRecordPdfInteractor.test.ts index 85af501b656..2e228f6515c 100644 --- a/web-api/src/business/useCases/generateDocketRecordPdfInteractor.test.ts +++ b/web-api/src/business/useCases/generateDocketRecordPdfInteractor.test.ts @@ -6,13 +6,18 @@ import { } from '../../../../shared/src/business/entities/EntityConstants'; import { MOCK_PRACTITIONER, - docketClerkUser, petitionerUser, - petitionsClerkUser, privatePractitionerUser, } from '../../../../shared/src/test/mockUsers'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; import { generateDocketRecordPdfInteractor } from './generateDocketRecordPdfInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, + mockPetitionsClerkUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; describe('generateDocketRecordPdfInteractor', () => { const mockId = '12345'; @@ -57,7 +62,6 @@ describe('generateDocketRecordPdfInteractor', () => { privatePractitioners: [], }; - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); applicationContext .getPersistenceGateway() .verifyCaseForUser.mockReturnValue(true); @@ -76,10 +80,14 @@ describe('generateDocketRecordPdfInteractor', () => { }); it('Calls docketRecord document generator to build a PDF', async () => { - await generateDocketRecordPdfInteractor(applicationContext, { - docketNumber: caseDetail.docketNumber, - includePartyDetail: true, - }); + await generateDocketRecordPdfInteractor( + applicationContext, + { + docketNumber: caseDetail.docketNumber, + includePartyDetail: true, + }, + mockDocketClerkUser, + ); expect( applicationContext.getDocumentGenerators().docketRecord.mock.calls[0][0] @@ -95,10 +103,14 @@ describe('generateDocketRecordPdfInteractor', () => { caseDetail.privatePractitioners = [mockPractitionerOnCase, {}]; - await generateDocketRecordPdfInteractor(applicationContext, { - docketNumber: caseDetail.docketNumber, - includePartyDetail: true, - }); + await generateDocketRecordPdfInteractor( + applicationContext, + { + docketNumber: caseDetail.docketNumber, + includePartyDetail: true, + }, + mockDocketClerkUser, + ); expect( applicationContext.getDocumentGenerators().docketRecord.mock.calls[0][0] @@ -118,10 +130,14 @@ describe('generateDocketRecordPdfInteractor', () => { caseDetail.privatePractitioners = [mockPractitionerOnCase, {}]; - await generateDocketRecordPdfInteractor(applicationContext, { - docketNumber: caseDetail.docketNumber, - includePartyDetail: true, - }); + await generateDocketRecordPdfInteractor( + applicationContext, + { + docketNumber: caseDetail.docketNumber, + includePartyDetail: true, + }, + mockPractitionerOnCase, + ); expect( applicationContext.getDocumentGenerators().docketRecord.mock.calls[0][0] @@ -132,10 +148,14 @@ describe('generateDocketRecordPdfInteractor', () => { }); it('Returns a file ID and url to the generated file', async () => { - const result = await generateDocketRecordPdfInteractor(applicationContext, { - docketNumber: caseDetail.docketNumber, - includePartyDetail: true, - }); + const result = await generateDocketRecordPdfInteractor( + applicationContext, + { + docketNumber: caseDetail.docketNumber, + includePartyDetail: true, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().saveFileAndGenerateUrl, @@ -144,9 +164,13 @@ describe('generateDocketRecordPdfInteractor', () => { }); it('defaults includePartyDetail to false when a value has not been provided', async () => { - await generateDocketRecordPdfInteractor(applicationContext, { - docketNumber: caseDetail.docketNumber, - } as any); + await generateDocketRecordPdfInteractor( + applicationContext, + { + docketNumber: caseDetail.docketNumber, + } as any, + mockDocketClerkUser, + ); expect( applicationContext.getDocumentGenerators().docketRecord.mock.calls[0][0] @@ -155,7 +179,6 @@ describe('generateDocketRecordPdfInteractor', () => { }); it('throws an Unauthorized error for an unassociated user attempting to view a sealed case', async () => { - applicationContext.getCurrentUser.mockReturnValue(privatePractitionerUser); applicationContext .getPersistenceGateway() .verifyCaseForUser.mockReturnValue(false); @@ -169,14 +192,17 @@ describe('generateDocketRecordPdfInteractor', () => { }); await expect( - generateDocketRecordPdfInteractor(applicationContext, { - docketNumber: caseDetail.docketNumber, - } as any), + generateDocketRecordPdfInteractor( + applicationContext, + { + docketNumber: caseDetail.docketNumber, + } as any, + mockPrivatePractitionerUser, + ), ).rejects.toThrow('Unauthorized to view sealed case.'); }); it('throws an Unauthorized error for a public user attempting to view a sealed case', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); //public user applicationContext .getPersistenceGateway() .verifyCaseForUser.mockReturnValue(false); @@ -188,14 +214,17 @@ describe('generateDocketRecordPdfInteractor', () => { }); await expect( - generateDocketRecordPdfInteractor(applicationContext, { - docketNumber: caseDetail.docketNumber, - } as any), + generateDocketRecordPdfInteractor( + applicationContext, + { + docketNumber: caseDetail.docketNumber, + } as any, + {} as UnknownAuthUser, + ), ).rejects.toThrow('Unauthorized to view sealed case.'); }); it('returns a PDF url for an internal user attempting to view a sealed case', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); applicationContext .getPersistenceGateway() .verifyCaseForUser.mockReturnValue(false); @@ -206,15 +235,18 @@ describe('generateDocketRecordPdfInteractor', () => { sealedDate: '2019-08-25T05:00:00.000Z', }); - const result = await generateDocketRecordPdfInteractor(applicationContext, { - docketNumber: caseDetail.docketNumber, - } as any); + const result = await generateDocketRecordPdfInteractor( + applicationContext, + { + docketNumber: caseDetail.docketNumber, + } as any, + mockPetitionsClerkUser, + ); expect(result).toEqual(mockPdfUrlAndID); }); it('returns a PDF url for an external, associated user attempting to view a sealed case', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); applicationContext .getPersistenceGateway() .verifyCaseForUser.mockReturnValue(true); @@ -225,15 +257,18 @@ describe('generateDocketRecordPdfInteractor', () => { userId: petitionerUser.userId, }); - const result = await generateDocketRecordPdfInteractor(applicationContext, { - docketNumber: caseDetail.docketNumber, - } as any); + const result = await generateDocketRecordPdfInteractor( + applicationContext, + { + docketNumber: caseDetail.docketNumber, + } as any, + mockPetitionerUser, + ); expect(result).toEqual(mockPdfUrlAndID); }); it('returns a PDF url for an external, indirectly associated user attempting to view a sealed case', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); applicationContext .getPersistenceGateway() .verifyCaseForUser.mockReturnValue(false); @@ -244,10 +279,14 @@ describe('generateDocketRecordPdfInteractor', () => { userId: petitionerUser.userId, }); - const result = await generateDocketRecordPdfInteractor(applicationContext, { - docketNumber: caseDetail.docketNumber, - isIndirectlyAssociated: true, - } as any); + const result = await generateDocketRecordPdfInteractor( + applicationContext, + { + docketNumber: caseDetail.docketNumber, + isIndirectlyAssociated: true, + } as any, + mockPetitionerUser, + ); expect(result).toEqual(mockPdfUrlAndID); }); diff --git a/web-api/src/business/useCases/generateDocketRecordPdfInteractor.ts b/web-api/src/business/useCases/generateDocketRecordPdfInteractor.ts index 1cd4be2637c..15035e72d05 100644 --- a/web-api/src/business/useCases/generateDocketRecordPdfInteractor.ts +++ b/web-api/src/business/useCases/generateDocketRecordPdfInteractor.ts @@ -6,18 +6,13 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../../../shared/src/authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { getCaseCaptionMeta } from '../../../../shared/src/business/utilities/getCaseCaptionMeta'; -/** - * generateDocketRecordPdfInteractor - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {string} providers.docketNumber the docket number for the docket record to be generated - * @returns {Uint8Array} docket record pdf - */ export const generateDocketRecordPdfInteractor = async ( - applicationContext, + applicationContext: ServerApplicationContext, { docketNumber, docketRecordSort, @@ -29,14 +24,14 @@ export const generateDocketRecordPdfInteractor = async ( includePartyDetail: boolean; isIndirectlyAssociated?: boolean; }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); const isDirectlyAssociated = await applicationContext .getPersistenceGateway() .verifyCaseForUser({ applicationContext, docketNumber, - userId: user.userId, + userId: authorizedUser?.userId, }); const caseSource = await applicationContext @@ -53,9 +48,9 @@ export const generateDocketRecordPdfInteractor = async ( .isSealedCase(caseSource); if (isSealedCase) { - if (user.userId) { + if (authorizedUser?.userId) { const isAuthorizedToViewSealedCase = isAuthorized( - user, + authorizedUser, ROLE_PERMISSIONS.VIEW_SEALED_CASE, ); @@ -64,7 +59,7 @@ export const generateDocketRecordPdfInteractor = async ( isDirectlyAssociated || isIndirectlyAssociated ) { - caseEntity = new Case(caseSource, { applicationContext }); + caseEntity = new Case(caseSource, { authorizedUser }); } else { // unassociated user viewing sealed case throw new UnauthorizedError('Unauthorized to view sealed case.'); @@ -74,13 +69,14 @@ export const generateDocketRecordPdfInteractor = async ( throw new UnauthorizedError('Unauthorized to view sealed case.'); } } else { - caseEntity = new Case(caseSource, { applicationContext }); + caseEntity = new Case(caseSource, { authorizedUser }); } const formattedCaseDetail = applicationContext .getUtilities() .getFormattedCaseDetail({ applicationContext, + authorizedUser, caseDetail: caseEntity, docketRecordSort, }); @@ -88,10 +84,9 @@ export const generateDocketRecordPdfInteractor = async ( formattedCaseDetail.petitioners.forEach(petitioner => { petitioner.counselDetails = []; - const practitioners = getPractitionersRepresenting( - formattedCaseDetail, - petitioner.contactId, - ); + const practitioners = + getPractitionersRepresenting(formattedCaseDetail, petitioner.contactId) || + []; if (practitioners.length > 0) { practitioners.forEach(practitioner => { diff --git a/web-api/src/business/useCases/judgeActivityReport/getCaseWorksheetsByJudgeInteractor.test.ts b/web-api/src/business/useCases/judgeActivityReport/getCaseWorksheetsByJudgeInteractor.test.ts index 1e063eb575c..3e8884b3db5 100644 --- a/web-api/src/business/useCases/judgeActivityReport/getCaseWorksheetsByJudgeInteractor.test.ts +++ b/web-api/src/business/useCases/judgeActivityReport/getCaseWorksheetsByJudgeInteractor.test.ts @@ -11,7 +11,11 @@ import { import { MOCK_CASE_WORKSHEET } from '@shared/test/mockCaseWorksheet'; import { RawCaseWorksheet } from '@shared/business/entities/caseWorksheet/CaseWorksheet'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; -import { judgeUser, petitionsClerkUser } from '@shared/test/mockUsers'; +import { judgeUser } from '@shared/test/mockUsers'; +import { + mockJudgeUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('getCaseWorksheetsByJudgeInteractor', () => { let mockGetDocketNumbersByStatusAndByJudgeResult: RawCase[] = []; @@ -61,24 +65,26 @@ describe('getCaseWorksheetsByJudgeInteractor', () => { () => mockGetDocketNumbersByStatusAndByJudgeResult, ); - beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(judgeUser); - }); - it('should return an error when the user is not authorized to generate the report', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - await expect( - getCaseWorksheetsByJudgeInteractor(applicationContext, mockValidRequest), + getCaseWorksheetsByJudgeInteractor( + applicationContext, + mockValidRequest, + mockPetitionsClerkUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should return an error when the search parameters are not valid', async () => { await expect( - getCaseWorksheetsByJudgeInteractor(applicationContext, { - judges: [judgeUser.name], - statuses: [undefined as any], - }), + getCaseWorksheetsByJudgeInteractor( + applicationContext, + { + judges: [judgeUser.name], + statuses: [undefined as any], + }, + mockJudgeUser, + ), ).rejects.toThrow(); }); @@ -86,6 +92,7 @@ describe('getCaseWorksheetsByJudgeInteractor', () => { await getCaseWorksheetsByJudgeInteractor( applicationContext, mockValidRequest, + mockJudgeUser, ); expect( @@ -126,6 +133,7 @@ describe('getCaseWorksheetsByJudgeInteractor', () => { const result = await getCaseWorksheetsByJudgeInteractor( applicationContext, mockValidRequest, + mockJudgeUser, ); expect(result.cases).toEqual( @@ -161,6 +169,7 @@ describe('getCaseWorksheetsByJudgeInteractor', () => { const result = await getCaseWorksheetsByJudgeInteractor( applicationContext, mockValidRequest, + mockJudgeUser, ); const actualCases = result.cases.map(aCase => ({ diff --git a/web-api/src/business/useCases/judgeActivityReport/getCaseWorksheetsByJudgeInteractor.ts b/web-api/src/business/useCases/judgeActivityReport/getCaseWorksheetsByJudgeInteractor.ts index e4eda1f885b..38fe6015f59 100644 --- a/web-api/src/business/useCases/judgeActivityReport/getCaseWorksheetsByJudgeInteractor.ts +++ b/web-api/src/business/useCases/judgeActivityReport/getCaseWorksheetsByJudgeInteractor.ts @@ -7,6 +7,7 @@ import { import { RawCaseWorksheet } from '@shared/business/entities/caseWorksheet/CaseWorksheet'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { SubmittedCAVTableFields } from '@web-api/persistence/elasticsearch/getDocketNumbersByStatusAndByJudge'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export type GetCasesByStatusAndByJudgeRequest = { statuses: string[]; @@ -21,11 +22,10 @@ export type GetCasesByStatusAndByJudgeResponse = SubmittedCAVTableFields & { export const getCaseWorksheetsByJudgeInteractor = async ( applicationContext: ServerApplicationContext, params: GetCasesByStatusAndByJudgeRequest, + authorizedUser: UnknownAuthUser, ): Promise<{ cases: GetCasesByStatusAndByJudgeResponse[]; }> => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.JUDGE_ACTIVITY_REPORT)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/judgeActivityReport/getCasesClosedByJudgeInteractor.test.ts b/web-api/src/business/useCases/judgeActivityReport/getCasesClosedByJudgeInteractor.test.ts index 1f802aac235..e0ad59c550b 100644 --- a/web-api/src/business/useCases/judgeActivityReport/getCasesClosedByJudgeInteractor.test.ts +++ b/web-api/src/business/useCases/judgeActivityReport/getCasesClosedByJudgeInteractor.test.ts @@ -9,10 +9,11 @@ import { createEndOfDayISO, createStartOfDayISO, } from '../../../../../shared/src/business/utilities/DateHandler'; +import { judgeUser } from '../../../../../shared/src/test/mockUsers'; import { - judgeUser, - petitionsClerkUser, -} from '../../../../../shared/src/test/mockUsers'; + mockJudgeUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; const mockClosedCases = 3; const mockClosedDismissedCases = 2; @@ -50,8 +51,6 @@ describe('getCasesClosedByJudgeInteractor', () => { }; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(judgeUser); - applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(judgeUser); @@ -62,20 +61,26 @@ describe('getCasesClosedByJudgeInteractor', () => { }); it('should return an error when the user is not authorized to generate the report', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - await expect( - getCasesClosedByJudgeInteractor(applicationContext, mockValidRequest), + getCasesClosedByJudgeInteractor( + applicationContext, + mockValidRequest, + mockPetitionsClerkUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should return an error when the search parameters are not valid', async () => { await expect( - getCasesClosedByJudgeInteractor(applicationContext, { - endDate: 'baddabingbaddaboom', - judges: [judgeUser.name], - startDate: 'yabbadabbadoo', - }), + getCasesClosedByJudgeInteractor( + applicationContext, + { + endDate: 'baddabingbaddaboom', + judges: [judgeUser.name], + startDate: 'yabbadabbadoo', + }, + mockJudgeUser, + ), ).rejects.toThrow(); }); @@ -83,6 +88,7 @@ describe('getCasesClosedByJudgeInteractor', () => { const closedCases = await getCasesClosedByJudgeInteractor( applicationContext, mockValidRequest, + mockJudgeUser, ); expect( diff --git a/web-api/src/business/useCases/judgeActivityReport/getCasesClosedByJudgeInteractor.ts b/web-api/src/business/useCases/judgeActivityReport/getCasesClosedByJudgeInteractor.ts index ca4a257ad00..3afd9e013a9 100644 --- a/web-api/src/business/useCases/judgeActivityReport/getCasesClosedByJudgeInteractor.ts +++ b/web-api/src/business/useCases/judgeActivityReport/getCasesClosedByJudgeInteractor.ts @@ -7,6 +7,7 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export type CasesClosedReturnType = { aggregations: { @@ -19,9 +20,8 @@ export type CasesClosedReturnType = { export const getCasesClosedByJudgeInteractor = async ( applicationContext: ServerApplicationContext, params: JudgeActivityStatisticsRequest, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.JUDGE_ACTIVITY_REPORT)) { throw new UnauthorizedError('Unauthorized'); } @@ -29,7 +29,7 @@ export const getCasesClosedByJudgeInteractor = async ( const searchEntity = new JudgeActivityReportSearch(params); if (!searchEntity.isValid()) { - throw new InvalidRequest(); + throw new InvalidRequest('Invalid search terms'); } return await applicationContext diff --git a/web-api/src/business/useCases/judgeActivityReport/getCountOfCaseDocumentsFiledByJudgesInteractor.test.ts b/web-api/src/business/useCases/judgeActivityReport/getCountOfCaseDocumentsFiledByJudgesInteractor.test.ts index 54e74d5838c..288c0da941d 100644 --- a/web-api/src/business/useCases/judgeActivityReport/getCountOfCaseDocumentsFiledByJudgesInteractor.test.ts +++ b/web-api/src/business/useCases/judgeActivityReport/getCountOfCaseDocumentsFiledByJudgesInteractor.test.ts @@ -1,16 +1,20 @@ import { AggregatedEventCodesType } from '../../../persistence/elasticsearch/fetchEventCodesCountForJudges'; import { - JudgeActivityReportFilters, + GetCountOfCaseDocumentsFiledByJudgesRequest, getCountOfCaseDocumentsFiledByJudgesInteractor, } from './getCountOfCaseDocumentsFiledByJudgesInteractor'; import { OPINION_EVENT_CODES_WITH_BENCH_OPINION } from '../../../../../shared/src/business/entities/EntityConstants'; import { addDocumentTypeToEventCodeAggregation } from './addDocumentTypeToEventCodeAggregation'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; -import { judgeUser, petitionsClerkUser } from '@shared/test/mockUsers'; +import { judgeUser } from '@shared/test/mockUsers'; import { mockCountOfOpinionsIssuedByJudge, mockCountOfOrdersIssuedByJudge, } from '@shared/test/mockSearchResults'; +import { + mockJudgeUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; jest.mock('./addDocumentTypeToEventCodeAggregation'); @@ -18,7 +22,7 @@ describe('getCountOfCaseDocumentsFiledByJudgesInteractor', () => { const mockStartDate = '02/12/2020'; const mockEndDate = '03/21/2020'; const mockJudges = [judgeUser.name]; - const mockValidRequest: JudgeActivityReportFilters = { + const mockValidRequest: GetCountOfCaseDocumentsFiledByJudgesRequest = { documentEventCodes: OPINION_EVENT_CODES_WITH_BENCH_OPINION, endDate: mockEndDate, judges: mockJudges, @@ -26,8 +30,6 @@ describe('getCountOfCaseDocumentsFiledByJudgesInteractor', () => { }; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(judgeUser); - applicationContext .getPersistenceGateway() .fetchEventCodesCountForJudges.mockResolvedValueOnce( @@ -37,23 +39,27 @@ describe('getCountOfCaseDocumentsFiledByJudgesInteractor', () => { }); it('should return an error when the user is not authorized to generate the report', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - await expect( getCountOfCaseDocumentsFiledByJudgesInteractor( applicationContext, mockValidRequest, + mockPetitionsClerkUser, ), ).rejects.toThrow('Unauthorized'); }); it('should return an error when the search parameters are not valid', async () => { await expect( - getCountOfCaseDocumentsFiledByJudgesInteractor(applicationContext, { - endDate: 'baddabingbaddaboom', - judges: [judgeUser.name], - startDate: 'yabbadabbadoo', - }), + getCountOfCaseDocumentsFiledByJudgesInteractor( + applicationContext, + { + documentEventCodes: [], + endDate: 'baddabingbaddaboom', + judges: [judgeUser.name], + startDate: 'yabbadabbadoo', + }, + mockJudgeUser, + ), ).rejects.toThrow(); }); @@ -62,6 +68,7 @@ describe('getCountOfCaseDocumentsFiledByJudgesInteractor', () => { await getCountOfCaseDocumentsFiledByJudgesInteractor( applicationContext, mockValidRequest, + mockJudgeUser, ); expect( diff --git a/web-api/src/business/useCases/judgeActivityReport/getCountOfCaseDocumentsFiledByJudgesInteractor.ts b/web-api/src/business/useCases/judgeActivityReport/getCountOfCaseDocumentsFiledByJudgesInteractor.ts index dffb6b18503..0a054ede523 100644 --- a/web-api/src/business/useCases/judgeActivityReport/getCountOfCaseDocumentsFiledByJudgesInteractor.ts +++ b/web-api/src/business/useCases/judgeActivityReport/getCountOfCaseDocumentsFiledByJudgesInteractor.ts @@ -6,6 +6,7 @@ import { isAuthorized, } from '@shared/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { addDocumentTypeToEventCodeAggregation } from './addDocumentTypeToEventCodeAggregation'; export type JudgeActivityReportFilters = { @@ -30,9 +31,8 @@ export type GetCountOfCaseDocumentsFiledByJudgesRequest = { export const getCountOfCaseDocumentsFiledByJudgesInteractor = async ( applicationContext: ServerApplicationContext, params: GetCountOfCaseDocumentsFiledByJudgesRequest, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.JUDGE_ACTIVITY_REPORT)) { throw new UnauthorizedError('Unauthorized to view Judge Activity Report'); } diff --git a/web-api/src/business/useCases/judgeActivityReport/getTrialSessionsForJudgeActivityReportInteractor.test.ts b/web-api/src/business/useCases/judgeActivityReport/getTrialSessionsForJudgeActivityReportInteractor.test.ts index 0d66cafc723..ef1dccd0722 100644 --- a/web-api/src/business/useCases/judgeActivityReport/getTrialSessionsForJudgeActivityReportInteractor.test.ts +++ b/web-api/src/business/useCases/judgeActivityReport/getTrialSessionsForJudgeActivityReportInteractor.test.ts @@ -2,8 +2,9 @@ import { JudgeActivityStatisticsRequest } from '@web-api/business/useCases/judge import { MOCK_TRIAL_REGULAR } from '@shared/test/mockTrial'; import { SESSION_TYPES } from '@shared/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; -import { docketClerkUser, judgeUser } from '@shared/test/mockUsers'; import { getTrialSessionsForJudgeActivityReportInteractor } from './getTrialSessionsForJudgeActivityReportInteractor'; +import { judgeUser } from '@shared/test/mockUsers'; +import { mockDocketClerkUser, mockJudgeUser } from '@shared/test/mockAuthUsers'; describe('getTrialSessionsForJudgeActivityReportInteractor', () => { const mockJudges = [ @@ -117,20 +118,17 @@ describe('getTrialSessionsForJudgeActivityReportInteractor', () => { }; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(judgeUser); - applicationContext .getPersistenceGateway() .getTrialSessions.mockReturnValue(mockTrialSessionsForAllJudges); }); it('should throw an error when user is unauthorized to retrieve the judge activity report', async () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - await expect( getTrialSessionsForJudgeActivityReportInteractor( applicationContext, mockValidRequest, + mockDocketClerkUser, ), ).rejects.toThrow(); }); @@ -140,6 +138,7 @@ describe('getTrialSessionsForJudgeActivityReportInteractor', () => { getTrialSessionsForJudgeActivityReportInteractor( applicationContext, mockInvalidRequest, + mockJudgeUser, ), ).rejects.toThrow(); }); @@ -148,6 +147,7 @@ describe('getTrialSessionsForJudgeActivityReportInteractor', () => { await getTrialSessionsForJudgeActivityReportInteractor( applicationContext, mockValidRequest, + mockJudgeUser, ); expect( @@ -159,6 +159,7 @@ describe('getTrialSessionsForJudgeActivityReportInteractor', () => { const opinions = await getTrialSessionsForJudgeActivityReportInteractor( applicationContext, mockValidRequest, + mockJudgeUser, ); expect(opinions).toEqual({ @@ -178,6 +179,7 @@ describe('getTrialSessionsForJudgeActivityReportInteractor', () => { const result = await getTrialSessionsForJudgeActivityReportInteractor( applicationContext, request, + mockJudgeUser, ); expect(result).toEqual({ diff --git a/web-api/src/business/useCases/judgeActivityReport/getTrialSessionsForJudgeActivityReportInteractor.ts b/web-api/src/business/useCases/judgeActivityReport/getTrialSessionsForJudgeActivityReportInteractor.ts index d73c7c05047..0cd1f3ada8b 100644 --- a/web-api/src/business/useCases/judgeActivityReport/getTrialSessionsForJudgeActivityReportInteractor.ts +++ b/web-api/src/business/useCases/judgeActivityReport/getTrialSessionsForJudgeActivityReportInteractor.ts @@ -10,6 +10,7 @@ import { SESSION_TYPES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { sum } from 'lodash'; export type TrialSessionTypes = { @@ -28,10 +29,9 @@ export type TrialSessionReturnType = { export const getTrialSessionsForJudgeActivityReportInteractor = async ( applicationContext: ServerApplicationContext, { endDate, judges, startDate }: JudgeActivityStatisticsRequest, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.JUDGE_ACTIVITY_REPORT)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.JUDGE_ACTIVITY_REPORT)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/manualAssociation/associateIrsPractitionerWithCaseInteractor.test.ts b/web-api/src/business/useCases/manualAssociation/associateIrsPractitionerWithCaseInteractor.test.ts index 1477a791851..7db5483f53f 100644 --- a/web-api/src/business/useCases/manualAssociation/associateIrsPractitionerWithCaseInteractor.test.ts +++ b/web-api/src/business/useCases/manualAssociation/associateIrsPractitionerWithCaseInteractor.test.ts @@ -9,6 +9,7 @@ import { import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { associateIrsPractitionerWithCaseInteractor } from './associateIrsPractitionerWithCaseInteractor'; +import { mockAdcUser, mockPetitionerUser } from '@shared/test/mockAuthUsers'; describe('associateIrsPractitionerWithCaseInteractor', () => { let caseRecord = { @@ -36,12 +37,9 @@ describe('associateIrsPractitionerWithCaseInteractor', () => { userId: 'e8577e31-d6d5-4c4a-adc6-520075f3dde5', }; - let mockCurrentUser; let mockUserById; beforeAll(() => { - applicationContext.getCurrentUser.mockImplementation(() => mockCurrentUser); - applicationContext .getPersistenceGateway() .getUserById.mockImplementation(() => mockUserById); @@ -52,24 +50,20 @@ describe('associateIrsPractitionerWithCaseInteractor', () => { }); it('should throw an error when not authorized', async () => { - mockCurrentUser = {}; - await expect( - associateIrsPractitionerWithCaseInteractor(applicationContext, { - docketNumber: caseRecord.docketNumber, - serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + associateIrsPractitionerWithCaseInteractor( + applicationContext, + { + docketNumber: caseRecord.docketNumber, + serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should add mapping for an irsPractitioner', async () => { - mockCurrentUser = { - barNumber: 'BN1234', - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.adc, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; mockUserById = { barNumber: 'BN1234', name: 'Emmett Lathrop "Doc" Brown, Ph.D.', @@ -80,11 +74,15 @@ describe('associateIrsPractitionerWithCaseInteractor', () => { .getPersistenceGateway() .verifyCaseForUser.mockReturnValue(false); - await associateIrsPractitionerWithCaseInteractor(applicationContext, { - docketNumber: caseRecord.docketNumber, - serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + await associateIrsPractitionerWithCaseInteractor( + applicationContext, + { + docketNumber: caseRecord.docketNumber, + serviceIndicator: SERVICE_INDICATOR_TYPES.SI_ELECTRONIC, + userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockAdcUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, diff --git a/web-api/src/business/useCases/manualAssociation/associateIrsPractitionerWithCaseInteractor.ts b/web-api/src/business/useCases/manualAssociation/associateIrsPractitionerWithCaseInteractor.ts index 0efe4a8cd49..c3373c2a721 100644 --- a/web-api/src/business/useCases/manualAssociation/associateIrsPractitionerWithCaseInteractor.ts +++ b/web-api/src/business/useCases/manualAssociation/associateIrsPractitionerWithCaseInteractor.ts @@ -4,6 +4,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { associateIrsPractitionerToCase } from '../../useCaseHelper/caseAssociation/associateIrsPractitionerToCase'; /** @@ -23,11 +24,10 @@ export const associateIrsPractitionerWithCaseInteractor = async ( serviceIndicator, userId, }: { docketNumber: string; serviceIndicator: string; userId: string }, + authorizedUser: UnknownAuthUser, ) => { - const authenticatedUser = applicationContext.getCurrentUser(); - if ( - !isAuthorized(authenticatedUser, ROLE_PERMISSIONS.ASSOCIATE_USER_WITH_CASE) + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.ASSOCIATE_USER_WITH_CASE) ) { throw new UnauthorizedError('Unauthorized'); } @@ -38,6 +38,7 @@ export const associateIrsPractitionerWithCaseInteractor = async ( return await associateIrsPractitionerToCase({ applicationContext, + authorizedUser, docketNumber, serviceIndicator, user, diff --git a/web-api/src/business/useCases/manualAssociation/associatePrivatePractitionerWithCaseInteractor.test.ts b/web-api/src/business/useCases/manualAssociation/associatePrivatePractitionerWithCaseInteractor.test.ts index f3f9068d08b..67fdf72b420 100644 --- a/web-api/src/business/useCases/manualAssociation/associatePrivatePractitionerWithCaseInteractor.test.ts +++ b/web-api/src/business/useCases/manualAssociation/associatePrivatePractitionerWithCaseInteractor.test.ts @@ -5,6 +5,7 @@ import { PARTY_TYPES, ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { associatePrivatePractitionerWithCaseInteractor } from './associatePrivatePractitionerWithCaseInteractor'; @@ -50,19 +51,24 @@ describe('associatePrivatePractitionerWithCaseInteractor', () => { it('should throw an error when not authorized', async () => { await expect( - associatePrivatePractitionerWithCaseInteractor(applicationContext, { - docketNumber: caseRecord.docketNumber, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - } as any), + associatePrivatePractitionerWithCaseInteractor( + applicationContext, + { + docketNumber: caseRecord.docketNumber, + userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + } as any, + {} as UnknownAuthUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should add mapping for a practitioner', async () => { - applicationContext.getCurrentUser.mockReturnValue({ + let mockUser = { + email: 'emmet.brown@example.com', name: 'Emmett Lathrop "Doc" Brown, Ph.D.', role: ROLES.adc, userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + }; applicationContext .getPersistenceGateway() .getUserById.mockImplementation(() => { @@ -81,11 +87,15 @@ describe('associatePrivatePractitionerWithCaseInteractor', () => { .getPersistenceGateway() .verifyCaseForUser.mockReturnValue(false); - await associatePrivatePractitionerWithCaseInteractor(applicationContext, { - docketNumber: caseRecord.docketNumber, - representing: [caseRecord.petitioners[0].contactId], - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - } as any); + await associatePrivatePractitionerWithCaseInteractor( + applicationContext, + { + docketNumber: caseRecord.docketNumber, + representing: [caseRecord.petitioners[0].contactId], + userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + } as any, + mockUser, + ); expect( applicationContext.getUseCaseHelpers().updateCaseAndAssociations, diff --git a/web-api/src/business/useCases/manualAssociation/associatePrivatePractitionerWithCaseInteractor.ts b/web-api/src/business/useCases/manualAssociation/associatePrivatePractitionerWithCaseInteractor.ts index 3eb5b917d14..401a1a4e665 100644 --- a/web-api/src/business/useCases/manualAssociation/associatePrivatePractitionerWithCaseInteractor.ts +++ b/web-api/src/business/useCases/manualAssociation/associatePrivatePractitionerWithCaseInteractor.ts @@ -4,6 +4,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { associatePrivatePractitionerToCase } from '../../useCaseHelper/caseAssociation/associatePrivatePractitionerToCase'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; @@ -30,11 +31,10 @@ export const associatePrivatePractitionerWithCase = async ( serviceIndicator: string; userId: string; }, + authorizedUser: UnknownAuthUser, ) => { - const authenticatedUser = applicationContext.getCurrentUser(); - if ( - !isAuthorized(authenticatedUser, ROLE_PERMISSIONS.ASSOCIATE_USER_WITH_CASE) + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.ASSOCIATE_USER_WITH_CASE) ) { throw new UnauthorizedError('Unauthorized'); } @@ -45,6 +45,7 @@ export const associatePrivatePractitionerWithCase = async ( return await associatePrivatePractitionerToCase({ applicationContext, + authorizedUser, docketNumber, representing, serviceIndicator, diff --git a/web-api/src/business/useCases/messages/completeMessageInteractor.test.ts b/web-api/src/business/useCases/messages/completeMessageInteractor.test.ts index 278ef028afd..143625fdb65 100644 --- a/web-api/src/business/useCases/messages/completeMessageInteractor.test.ts +++ b/web-api/src/business/useCases/messages/completeMessageInteractor.test.ts @@ -9,6 +9,10 @@ import { applicationContext } from '../../../../../shared/src/business/test/crea import { completeMessageInteractor } from './completeMessageInteractor'; import { getMessageThreadByParentId } from '@web-api/persistence/postgres/messages/getMessageThreadByParentId'; import { markMessageThreadRepliedTo } from '@web-api/persistence/postgres/messages/markMessageThreadRepliedTo'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { updateMessage } from '@web-api/persistence/postgres/messages/updateMessage'; describe('completeMessageInteractor', () => { @@ -56,10 +60,6 @@ describe('completeMessageInteractor', () => { const PARENT_MESSAGE_ID_2 = '4782edfe-618b-4315-9619-675403246bce'; beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'b9fcabc8-3c83-4cbf-9f4a-d2ecbdc591e1', - }); applicationContext.getPersistenceGateway().getUserById.mockReturnValue({ name: 'Test Petitionsclerk', role: ROLES.petitionsClerk, @@ -74,28 +74,31 @@ describe('completeMessageInteractor', () => { }); it('should throw unauthorized for a user without MESSAGES permission', async () => { - applicationContext.getCurrentUser.mockReturnValueOnce({ - role: ROLES.petitioner, - userId: '9bd0308c-2b06-4589-b36e-242398bea31b', - }); - await expect( - completeMessageInteractor(applicationContext, { - messages: [{ messageBody: 'hi', parentMessageId: '123' }], - }), + completeMessageInteractor( + applicationContext, + { + messages: [{ messageBody: 'hi', parentMessageId: '123' }], + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); it('should call persistence methods to mark the thread as replied to and complete the most recent messages', async () => { - await completeMessageInteractor(applicationContext, { - messages: [ - { - messageBody: 'the completed message', - parentMessageId: PARENT_MESSAGE_ID_1, - }, - { messageBody: 'hi', parentMessageId: PARENT_MESSAGE_ID_2 }, - ], - }); + await completeMessageInteractor( + applicationContext, + { + messages: [ + { + messageBody: 'the completed message', + parentMessageId: PARENT_MESSAGE_ID_1, + }, + { messageBody: 'hi', parentMessageId: PARENT_MESSAGE_ID_2 }, + ], + }, + mockPetitionsClerkUser, + ); expect(markMessageThreadRepliedTo).toHaveBeenCalledTimes(2); expect( @@ -126,14 +129,18 @@ describe('completeMessageInteractor', () => { }); it('should send a success message to the user', async () => { - await completeMessageInteractor(applicationContext, { - messages: [ - { - messageBody: 'the completed message', - parentMessageId: PARENT_MESSAGE_ID_1, - }, - ], - }); + await completeMessageInteractor( + applicationContext, + { + messages: [ + { + messageBody: 'the completed message', + parentMessageId: PARENT_MESSAGE_ID_1, + }, + ], + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock .calls[0][0].message, diff --git a/web-api/src/business/useCases/messages/completeMessageInteractor.ts b/web-api/src/business/useCases/messages/completeMessageInteractor.ts index 91b43736456..b62aa888b52 100644 --- a/web-api/src/business/useCases/messages/completeMessageInteractor.ts +++ b/web-api/src/business/useCases/messages/completeMessageInteractor.ts @@ -5,6 +5,7 @@ import { } from '@shared/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { getMessageThreadByParentId } from '@web-api/persistence/postgres/messages/getMessageThreadByParentId'; import { markMessageThreadRepliedTo } from '@web-api/persistence/postgres/messages/markMessageThreadRepliedTo'; import { orderBy } from 'lodash'; @@ -15,9 +16,8 @@ export const completeMessageInteractor = async ( { messages, }: { messages: { messageBody: string; parentMessageId: string }[] }, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.SEND_RECEIVE_MESSAGES)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/messages/createMessageInteractor.test.ts b/web-api/src/business/useCases/messages/createMessageInteractor.test.ts index 10b6606ebfb..ab95f2aa35c 100644 --- a/web-api/src/business/useCases/messages/createMessageInteractor.test.ts +++ b/web-api/src/business/useCases/messages/createMessageInteractor.test.ts @@ -11,23 +11,26 @@ import { createMessageInteractor } from './createMessageInteractor'; import { createMessage as createMessageMock } from '@web-api/persistence/postgres/messages/createMessage'; const createMessage = createMessageMock as jest.Mock; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('createMessageInteractor', () => { it('throws unauthorized for a user without MESSAGES permission', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '9bd0308c-2b06-4589-b36e-242398bea31b', - }); - await expect( - createMessageInteractor(applicationContext, { - attachments: [], - docketNumber: '101-20', - message: 'hello world', - subject: 'what is up', - toSection: DOCKET_SECTION, - toUserId: 'abc', - }), + createMessageInteractor( + applicationContext, + { + attachments: [], + docketNumber: '101-20', + message: 'hello world', + subject: 'what is up', + toSection: DOCKET_SECTION, + toUserId: 'abc', + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -49,10 +52,6 @@ describe('createMessageInteractor', () => { toSection: PETITIONS_SECTION, toUserId: 'b427ca37-0df1-48ac-94bb-47aed073d6f7', }; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'b9fcabc8-3c83-4cbf-9f4a-d2ecbdc591e1', - }); applicationContext .getPersistenceGateway() .getUserById.mockReturnValueOnce({ @@ -76,10 +75,14 @@ describe('createMessageInteractor', () => { status: CASE_STATUS_TYPES.generalDocket, }); - await createMessageInteractor(applicationContext, { - ...messageData, - attachments: mockAttachments, - }); + await createMessageInteractor( + applicationContext, + { + ...messageData, + attachments: mockAttachments, + }, + mockPetitionsClerkUser, + ); expect(createMessage).toHaveBeenCalled(); expect(createMessage.mock.calls[0][0].message).toMatchObject({ diff --git a/web-api/src/business/useCases/messages/createMessageInteractor.ts b/web-api/src/business/useCases/messages/createMessageInteractor.ts index cbf143b01a1..68296df7985 100644 --- a/web-api/src/business/useCases/messages/createMessageInteractor.ts +++ b/web-api/src/business/useCases/messages/createMessageInteractor.ts @@ -9,6 +9,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { createMessage } from '@web-api/persistence/postgres/messages/createMessage'; export type MessageType = { @@ -40,9 +41,8 @@ export const createMessageInteractor = async ( toSection, toUserId, }: MessageWithMetaData, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.SEND_RECEIVE_MESSAGES)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/messages/forwardMessageInteractor.test.ts b/web-api/src/business/useCases/messages/forwardMessageInteractor.test.ts index b44bf1dd0d2..a1b30268ca7 100644 --- a/web-api/src/business/useCases/messages/forwardMessageInteractor.test.ts +++ b/web-api/src/business/useCases/messages/forwardMessageInteractor.test.ts @@ -1,10 +1,11 @@ jest.mock('./replyToMessageInteractor'); import { forwardMessageInteractor } from './forwardMessageInteractor'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { replyToMessage } from './replyToMessageInteractor'; describe('forwardMessageInteractor', () => { it('should call the replyToMessageInteractor with the given params', async () => { - await forwardMessageInteractor({} as any, {} as any); + await forwardMessageInteractor({} as any, {} as any, mockDocketClerkUser); expect(replyToMessage).toHaveBeenCalled(); }); diff --git a/web-api/src/business/useCases/messages/forwardMessageInteractor.ts b/web-api/src/business/useCases/messages/forwardMessageInteractor.ts index 6be7b0e8d88..45e85f8802e 100644 --- a/web-api/src/business/useCases/messages/forwardMessageInteractor.ts +++ b/web-api/src/business/useCases/messages/forwardMessageInteractor.ts @@ -1,6 +1,7 @@ import { RawMessage } from '@shared/business/entities/Message'; import { ReplyMessageType } from '@web-api/business/useCases/messages/createMessageInteractor'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { replyToMessage } from './replyToMessageInteractor'; export const forwardMessageInteractor = async ( @@ -14,14 +15,19 @@ export const forwardMessageInteractor = async ( toSection, toUserId, }: ReplyMessageType, + authorizedUser: UnknownAuthUser, ): Promise => { - return await replyToMessage(applicationContext, { - attachments, - docketNumber, - message, - parentMessageId, - subject, - toSection, - toUserId, - }); + return await replyToMessage( + applicationContext, + { + attachments, + docketNumber, + message, + parentMessageId, + subject, + toSection, + toUserId, + }, + authorizedUser, + ); }; diff --git a/web-api/src/business/useCases/messages/getCompletedMessagesForSectionInteractor.test.ts b/web-api/src/business/useCases/messages/getCompletedMessagesForSectionInteractor.test.ts index 9edf8b895b1..bc86eb9ff3b 100644 --- a/web-api/src/business/useCases/messages/getCompletedMessagesForSectionInteractor.test.ts +++ b/web-api/src/business/useCases/messages/getCompletedMessagesForSectionInteractor.test.ts @@ -9,19 +9,22 @@ import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getCompletedMessagesForSectionInteractor } from './getCompletedMessagesForSectionInteractor'; import { getCompletedSectionInboxMessages } from '@web-api/persistence/postgres/messages/getCompletedSectionInboxMessages'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { omit } from 'lodash'; describe('getCompletedMessagesForSectionInteractor', () => { it('throws unauthorized for a user without MESSAGES permission', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '9bd0308c-2b06-4589-b36e-242398bea31b', - }); - await expect( - getCompletedMessagesForSectionInteractor(applicationContext, { - section: DOCKET_SECTION, - }), + getCompletedMessagesForSectionInteractor( + applicationContext, + { + section: DOCKET_SECTION, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -66,6 +69,7 @@ describe('getCompletedMessagesForSectionInteractor', () => { { section: DOCKET_SECTION, }, + mockPetitionsClerkUser, ); expect(getCompletedSectionInboxMessages).toHaveBeenCalled(); diff --git a/web-api/src/business/useCases/messages/getCompletedMessagesForSectionInteractor.ts b/web-api/src/business/useCases/messages/getCompletedMessagesForSectionInteractor.ts index a0fe2982f44..e1eb53f4555 100644 --- a/web-api/src/business/useCases/messages/getCompletedMessagesForSectionInteractor.ts +++ b/web-api/src/business/useCases/messages/getCompletedMessagesForSectionInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { getCompletedSectionInboxMessages } from '@web-api/persistence/postgres/messages/getCompletedSectionInboxMessages'; /** @@ -18,9 +19,8 @@ import { getCompletedSectionInboxMessages } from '@web-api/persistence/postgres/ export const getCompletedMessagesForSectionInteractor = async ( applicationContext: ServerApplicationContext, { section }: { section }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.VIEW_MESSAGES)) { throw new UnauthorizedError('Unauthorized'); } @@ -29,7 +29,5 @@ export const getCompletedMessagesForSectionInteractor = async ( section, }); - return MessageResult.validateRawCollection(messages, { - applicationContext, - }); + return MessageResult.validateRawCollection(messages); }; diff --git a/web-api/src/business/useCases/messages/getCompletedMessagesForUserInteractor.test.ts b/web-api/src/business/useCases/messages/getCompletedMessagesForUserInteractor.test.ts index ea2fdd78def..fc527339e38 100644 --- a/web-api/src/business/useCases/messages/getCompletedMessagesForUserInteractor.test.ts +++ b/web-api/src/business/useCases/messages/getCompletedMessagesForUserInteractor.test.ts @@ -8,19 +8,22 @@ import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getCompletedMessagesForUserInteractor } from './getCompletedMessagesForUserInteractor'; import { getCompletedUserInboxMessages } from '@web-api/persistence/postgres/messages/getCompletedUserInboxMessages'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { omit } from 'lodash'; describe('getCompletedMessagesForUserInteractor', () => { it('throws unauthorized for a user without MESSAGES permission', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '9bd0308c-2b06-4589-b36e-242398bea31b', - }); - await expect( - getCompletedMessagesForUserInteractor(applicationContext, { - userId: 'abc', - }), + getCompletedMessagesForUserInteractor( + applicationContext, + { + userId: 'abc', + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -64,6 +67,7 @@ describe('getCompletedMessagesForUserInteractor', () => { { userId: messageData.completedByUserId, }, + mockPetitionsClerkUser, ); expect(getCompletedUserInboxMessages).toHaveBeenCalled(); diff --git a/web-api/src/business/useCases/messages/getCompletedMessagesForUserInteractor.ts b/web-api/src/business/useCases/messages/getCompletedMessagesForUserInteractor.ts index b630e4381ef..0221a5cfd6b 100644 --- a/web-api/src/business/useCases/messages/getCompletedMessagesForUserInteractor.ts +++ b/web-api/src/business/useCases/messages/getCompletedMessagesForUserInteractor.ts @@ -5,22 +5,14 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { getCompletedUserInboxMessages } from '@web-api/persistence/postgres/messages/getCompletedUserInboxMessages'; -/** - * getCompletedMessagesForUserInteractor - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {string} providers.userId the user to get the inbox messages - * @returns {object} the messages in the user inbox - */ export const getCompletedMessagesForUserInteractor = async ( applicationContext: ServerApplicationContext, { userId }: { userId: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.VIEW_MESSAGES)) { throw new UnauthorizedError('Unauthorized'); } @@ -29,7 +21,5 @@ export const getCompletedMessagesForUserInteractor = async ( userId, }); - return MessageResult.validateRawCollection(messages, { - applicationContext, - }); + return MessageResult.validateRawCollection(messages); }; diff --git a/web-api/src/business/useCases/messages/getInboxMessagesForSectionInteractor.test.ts b/web-api/src/business/useCases/messages/getInboxMessagesForSectionInteractor.test.ts index 0a13661419c..d72a7fd6fb6 100644 --- a/web-api/src/business/useCases/messages/getInboxMessagesForSectionInteractor.test.ts +++ b/web-api/src/business/useCases/messages/getInboxMessagesForSectionInteractor.test.ts @@ -3,25 +3,27 @@ import { CASE_STATUS_TYPES, DOCKET_SECTION, PETITIONS_SECTION, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getInboxMessagesForSectionInteractor } from './getInboxMessagesForSectionInteractor'; import { getSectionInboxMessages } from '@web-api/persistence/postgres/messages/getSectionInboxMessages'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { omit } from 'lodash'; describe('getInboxMessagesForSectionInteractor', () => { it('throws unauthorized for a user without MESSAGES permission', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '9bd0308c-2b06-4589-b36e-242398bea31b', - }); - await expect( - getInboxMessagesForSectionInteractor(applicationContext, { - section: DOCKET_SECTION, - }), + getInboxMessagesForSectionInteractor( + applicationContext, + { + section: DOCKET_SECTION, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -50,10 +52,7 @@ describe('getInboxMessagesForSectionInteractor', () => { trialDate: '2028-03-01T21:40:46.415Z', trialLocation: 'El Paso, Texas', }; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'b9fcabc8-3c83-4cbf-9f4a-d2ecbdc591e1', - }); + (getSectionInboxMessages as jest.Mock).mockReturnValue([messageData]); const returnedMessages = await getInboxMessagesForSectionInteractor( @@ -61,6 +60,7 @@ describe('getInboxMessagesForSectionInteractor', () => { { section: DOCKET_SECTION, }, + mockPetitionsClerkUser, ); expect(getSectionInboxMessages).toHaveBeenCalled(); diff --git a/web-api/src/business/useCases/messages/getInboxMessagesForSectionInteractor.ts b/web-api/src/business/useCases/messages/getInboxMessagesForSectionInteractor.ts index ba1f6d38570..7600bf57d8c 100644 --- a/web-api/src/business/useCases/messages/getInboxMessagesForSectionInteractor.ts +++ b/web-api/src/business/useCases/messages/getInboxMessagesForSectionInteractor.ts @@ -5,22 +5,14 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { getSectionInboxMessages } from '@web-api/persistence/postgres/messages/getSectionInboxMessages'; -/** - * getInboxMessagesForSectionInteractor - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {string} providers.section the section to get the inbox messages - * @returns {object} the messages in the section inbox - */ export const getInboxMessagesForSectionInteractor = async ( applicationContext: ServerApplicationContext, { section }: { section: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.VIEW_MESSAGES)) { throw new UnauthorizedError('Unauthorized'); } @@ -30,7 +22,5 @@ export const getInboxMessagesForSectionInteractor = async ( section, }); - return MessageResult.validateRawCollection(messages, { - applicationContext, - }); + return MessageResult.validateRawCollection(messages); }; diff --git a/web-api/src/business/useCases/messages/getInboxMessagesForUserInteractor.test.ts b/web-api/src/business/useCases/messages/getInboxMessagesForUserInteractor.test.ts index e554bcb10e7..b3c5ca0fafe 100644 --- a/web-api/src/business/useCases/messages/getInboxMessagesForUserInteractor.test.ts +++ b/web-api/src/business/useCases/messages/getInboxMessagesForUserInteractor.test.ts @@ -2,25 +2,27 @@ import '@web-api/persistence/postgres/messages/mocks.jest'; import { CASE_STATUS_TYPES, PETITIONS_SECTION, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getInboxMessagesForUserInteractor } from './getInboxMessagesForUserInteractor'; import { getUserInboxMessages } from '@web-api/persistence/postgres/messages/getUserInboxMessages'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { omit } from 'lodash'; describe('getInboxMessagesForUserInteractor', () => { it('throws unauthorized for a user without MESSAGES permission', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '9bd0308c-2b06-4589-b36e-242398bea31b', - }); - await expect( - getInboxMessagesForUserInteractor(applicationContext, { - userId: 'bob', - }), + getInboxMessagesForUserInteractor( + applicationContext, + { + userId: 'bob', + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -49,10 +51,7 @@ describe('getInboxMessagesForUserInteractor', () => { trialDate: '2028-03-01T21:40:46.415Z', trialLocation: 'El Paso, Texas', }; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'b9fcabc8-3c83-4cbf-9f4a-d2ecbdc591e1', - }); + (getUserInboxMessages as jest.Mock).mockReturnValue([messageData]); const returnedMessages = await getInboxMessagesForUserInteractor( @@ -60,6 +59,7 @@ describe('getInboxMessagesForUserInteractor', () => { { userId: 'bob', }, + mockPetitionsClerkUser, ); expect(getUserInboxMessages).toHaveBeenCalled(); diff --git a/web-api/src/business/useCases/messages/getInboxMessagesForUserInteractor.ts b/web-api/src/business/useCases/messages/getInboxMessagesForUserInteractor.ts index 650636ec931..c61d0bc1d78 100644 --- a/web-api/src/business/useCases/messages/getInboxMessagesForUserInteractor.ts +++ b/web-api/src/business/useCases/messages/getInboxMessagesForUserInteractor.ts @@ -5,22 +5,14 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { getUserInboxMessages } from '@web-api/persistence/postgres/messages/getUserInboxMessages'; -/** - * getInboxMessagesForUserInteractor - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {string} providers.userId the user to get the inbox messages - * @returns {object} the messages in the user inbox - */ export const getInboxMessagesForUserInteractor = async ( applicationContext: ServerApplicationContext, { userId }: { userId: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.VIEW_MESSAGES)) { throw new UnauthorizedError('Unauthorized'); } @@ -30,7 +22,5 @@ export const getInboxMessagesForUserInteractor = async ( userId, }); - return MessageResult.validateRawCollection(messages, { - applicationContext, - }); + return MessageResult.validateRawCollection(messages); }; diff --git a/web-api/src/business/useCases/messages/getMessageThreadInteractor.test.ts b/web-api/src/business/useCases/messages/getMessageThreadInteractor.test.ts index 7633c98742a..0746501628e 100644 --- a/web-api/src/business/useCases/messages/getMessageThreadInteractor.test.ts +++ b/web-api/src/business/useCases/messages/getMessageThreadInteractor.test.ts @@ -2,24 +2,26 @@ import '@web-api/persistence/postgres/messages/mocks.jest'; import { CASE_STATUS_TYPES, PETITIONS_SECTION, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getMessageThreadByParentId } from '@web-api/persistence/postgres/messages/getMessageThreadByParentId'; import { getMessageThreadInteractor } from './getMessageThreadInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('getMessageThreadInteractor', () => { it('throws unauthorized for a user without MESSAGES permission', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '9bd0308c-2b06-4589-b36e-242398bea31b', - }); - await expect( - getMessageThreadInteractor(applicationContext, { - parentMessageId: 'abc', - }), + getMessageThreadInteractor( + applicationContext, + { + parentMessageId: 'abc', + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -44,10 +46,7 @@ describe('getMessageThreadInteractor', () => { toSection: PETITIONS_SECTION, toUserId: 'b427ca37-0df1-48ac-94bb-47aed073d6f7', }; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'b9fcabc8-3c83-4cbf-9f4a-d2ecbdc591e1', - }); + (getMessageThreadByParentId as jest.Mock).mockReturnValue([mockMessage]); const returnedMessage = await getMessageThreadInteractor( @@ -55,6 +54,7 @@ describe('getMessageThreadInteractor', () => { { parentMessageId: 'abc', }, + mockPetitionsClerkUser, ); expect(getMessageThreadByParentId).toHaveBeenCalled(); diff --git a/web-api/src/business/useCases/messages/getMessageThreadInteractor.ts b/web-api/src/business/useCases/messages/getMessageThreadInteractor.ts index fb28d53bf15..2896504c5cd 100644 --- a/web-api/src/business/useCases/messages/getMessageThreadInteractor.ts +++ b/web-api/src/business/useCases/messages/getMessageThreadInteractor.ts @@ -5,22 +5,14 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { getMessageThreadByParentId } from '@web-api/persistence/postgres/messages/getMessageThreadByParentId'; -/** - * gets a message thread by parent id - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {string} providers.parentMessageId the id of the parent message for the thread - * @returns {object} the message - */ export const getMessageThreadInteractor = async ( applicationContext: ServerApplicationContext, { parentMessageId }: { parentMessageId: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.VIEW_MESSAGES)) { throw new UnauthorizedError('Unauthorized'); } @@ -29,7 +21,5 @@ export const getMessageThreadInteractor = async ( parentMessageId, }); - return Message.validateRawCollection(messages, { - applicationContext, - }); + return Message.validateRawCollection(messages); }; diff --git a/web-api/src/business/useCases/messages/getMessagesForCaseInteractor.test.ts b/web-api/src/business/useCases/messages/getMessagesForCaseInteractor.test.ts index b192e324649..231af43d0fe 100644 --- a/web-api/src/business/useCases/messages/getMessagesForCaseInteractor.test.ts +++ b/web-api/src/business/useCases/messages/getMessagesForCaseInteractor.test.ts @@ -2,24 +2,26 @@ import '@web-api/persistence/postgres/messages/mocks.jest'; import { CASE_STATUS_TYPES, PETITIONS_SECTION, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getMessagesByDocketNumber } from '@web-api/persistence/postgres/messages/getMessagesByDocketNumber'; import { getMessagesForCaseInteractor } from './getMessagesForCaseInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('getMessagesForCaseInteractor', () => { it('throws unauthorized for a user without MESSAGES permission', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '9bd0308c-2b06-4589-b36e-242398bea31b', - }); - await expect( - getMessagesForCaseInteractor(applicationContext, { - docketNumber: '101-20', - }), + getMessagesForCaseInteractor( + applicationContext, + { + docketNumber: '101-20', + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -43,10 +45,7 @@ describe('getMessagesForCaseInteractor', () => { toSection: PETITIONS_SECTION, toUserId: 'b427ca37-0df1-48ac-94bb-47aed073d6f7', }; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'b9fcabc8-3c83-4cbf-9f4a-d2ecbdc591e1', - }); + (getMessagesByDocketNumber as jest.Mock).mockReturnValue([mockMessage]); const returnedMessage = await getMessagesForCaseInteractor( @@ -54,6 +53,7 @@ describe('getMessagesForCaseInteractor', () => { { docketNumber: mockMessage.docketNumber, }, + mockPetitionsClerkUser, ); expect(getMessagesByDocketNumber).toHaveBeenCalled(); diff --git a/web-api/src/business/useCases/messages/getMessagesForCaseInteractor.ts b/web-api/src/business/useCases/messages/getMessagesForCaseInteractor.ts index dd914d6aaa0..662508222ba 100644 --- a/web-api/src/business/useCases/messages/getMessagesForCaseInteractor.ts +++ b/web-api/src/business/useCases/messages/getMessagesForCaseInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { getMessagesByDocketNumber } from '@web-api/persistence/postgres/messages/getMessagesByDocketNumber'; /** @@ -18,9 +19,8 @@ import { getMessagesByDocketNumber } from '@web-api/persistence/postgres/message export const getMessagesForCaseInteractor = async ( applicationContext: ServerApplicationContext, { docketNumber }: { docketNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.VIEW_MESSAGES)) { throw new UnauthorizedError('Unauthorized'); } @@ -30,7 +30,5 @@ export const getMessagesForCaseInteractor = async ( docketNumber, }); - return Message.validateRawCollection(messages, { - applicationContext, - }); + return Message.validateRawCollection(messages); }; diff --git a/web-api/src/business/useCases/messages/getOutboxMessagesForSectionInteractor.test.ts b/web-api/src/business/useCases/messages/getOutboxMessagesForSectionInteractor.test.ts index 835740023b5..007014cd6d3 100644 --- a/web-api/src/business/useCases/messages/getOutboxMessagesForSectionInteractor.test.ts +++ b/web-api/src/business/useCases/messages/getOutboxMessagesForSectionInteractor.test.ts @@ -3,25 +3,27 @@ import { CASE_STATUS_TYPES, DOCKET_SECTION, PETITIONS_SECTION, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getOutboxMessagesForSectionInteractor } from './getOutboxMessagesForSectionInteractor'; import { getSectionOutboxMessages } from '@web-api/persistence/postgres/messages/getSectionOutboxMessages'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { omit } from 'lodash'; describe('getOutboxMessagesForSectionInteractor', () => { it('throws unauthorized for a user without MESSAGES permission', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '9bd0308c-2b06-4589-b36e-242398bea31b', - }); - await expect( - getOutboxMessagesForSectionInteractor(applicationContext, { - section: DOCKET_SECTION, - }), + getOutboxMessagesForSectionInteractor( + applicationContext, + { + section: DOCKET_SECTION, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -50,10 +52,7 @@ describe('getOutboxMessagesForSectionInteractor', () => { trialDate: '2028-03-01T21:40:46.415Z', trialLocation: 'El Paso, Texas', }; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'b9fcabc8-3c83-4cbf-9f4a-d2ecbdc591e1', - }); + (getSectionOutboxMessages as jest.Mock).mockReturnValue([messageData]); const returnedMessages = await getOutboxMessagesForSectionInteractor( @@ -61,6 +60,7 @@ describe('getOutboxMessagesForSectionInteractor', () => { { section: DOCKET_SECTION, }, + mockPetitionsClerkUser, ); expect(getSectionOutboxMessages).toHaveBeenCalled(); diff --git a/web-api/src/business/useCases/messages/getOutboxMessagesForSectionInteractor.ts b/web-api/src/business/useCases/messages/getOutboxMessagesForSectionInteractor.ts index 6c334be0309..2c86b666a1b 100644 --- a/web-api/src/business/useCases/messages/getOutboxMessagesForSectionInteractor.ts +++ b/web-api/src/business/useCases/messages/getOutboxMessagesForSectionInteractor.ts @@ -5,22 +5,14 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { getSectionOutboxMessages } from '@web-api/persistence/postgres/messages/getSectionOutboxMessages'; -/** - * getOutboxMessagesForSectionInteractor - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {string} providers.section the section to get the outbox messages - * @returns {object} the messages in the section outbox - */ export const getOutboxMessagesForSectionInteractor = async ( applicationContext: ServerApplicationContext, { section }: { section: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.VIEW_MESSAGES)) { throw new UnauthorizedError('Unauthorized'); } @@ -30,7 +22,5 @@ export const getOutboxMessagesForSectionInteractor = async ( section, }); - return MessageResult.validateRawCollection(messages, { - applicationContext, - }); + return MessageResult.validateRawCollection(messages); }; diff --git a/web-api/src/business/useCases/messages/getOutboxMessagesForUserInteractor.test.ts b/web-api/src/business/useCases/messages/getOutboxMessagesForUserInteractor.test.ts index bd7ced63834..752bcd45607 100644 --- a/web-api/src/business/useCases/messages/getOutboxMessagesForUserInteractor.test.ts +++ b/web-api/src/business/useCases/messages/getOutboxMessagesForUserInteractor.test.ts @@ -2,25 +2,27 @@ import '@web-api/persistence/postgres/messages/mocks.jest'; import { CASE_STATUS_TYPES, PETITIONS_SECTION, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getOutboxMessagesForUserInteractor } from './getOutboxMessagesForUserInteractor'; import { getUserOutboxMessages } from '@web-api/persistence/postgres/messages/getUserOutboxMessages'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { omit } from 'lodash'; describe('getOutboxMessagesForUserInteractor', () => { it('throws unauthorized for a user without MESSAGES permission', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '9bd0308c-2b06-4589-b36e-242398bea31b', - }); - await expect( - getOutboxMessagesForUserInteractor(applicationContext, { - userId: 'bob', - }), + getOutboxMessagesForUserInteractor( + applicationContext, + { + userId: 'bob', + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -49,10 +51,7 @@ describe('getOutboxMessagesForUserInteractor', () => { trialDate: '2028-03-01T21:40:46.415Z', trialLocation: 'El Paso, Texas', }; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'b9fcabc8-3c83-4cbf-9f4a-d2ecbdc591e1', - }); + (getUserOutboxMessages as jest.Mock).mockReturnValue([messageData]); const returnedMessages = await getOutboxMessagesForUserInteractor( @@ -60,6 +59,7 @@ describe('getOutboxMessagesForUserInteractor', () => { { userId: 'b9fcabc8-3c83-4cbf-9f4a-d2ecbdc591e1', }, + mockPetitionsClerkUser, ); expect(getUserOutboxMessages).toHaveBeenCalled(); diff --git a/web-api/src/business/useCases/messages/getOutboxMessagesForUserInteractor.ts b/web-api/src/business/useCases/messages/getOutboxMessagesForUserInteractor.ts index 9db65515742..f0f7e38f347 100644 --- a/web-api/src/business/useCases/messages/getOutboxMessagesForUserInteractor.ts +++ b/web-api/src/business/useCases/messages/getOutboxMessagesForUserInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { getUserOutboxMessages } from '@web-api/persistence/postgres/messages/getUserOutboxMessages'; /** @@ -18,9 +19,8 @@ import { getUserOutboxMessages } from '@web-api/persistence/postgres/messages/ge export const getOutboxMessagesForUserInteractor = async ( applicationContext: ServerApplicationContext, { userId }: { userId: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.VIEW_MESSAGES)) { throw new UnauthorizedError('Unauthorized'); } @@ -29,7 +29,5 @@ export const getOutboxMessagesForUserInteractor = async ( userId, }); - return MessageResult.validateRawCollection(messages, { - applicationContext, - }); + return MessageResult.validateRawCollection(messages); }; diff --git a/web-api/src/business/useCases/messages/replyToMessageInteractor.test.ts b/web-api/src/business/useCases/messages/replyToMessageInteractor.test.ts index ecf5ba9af52..373dcd15980 100644 --- a/web-api/src/business/useCases/messages/replyToMessageInteractor.test.ts +++ b/web-api/src/business/useCases/messages/replyToMessageInteractor.test.ts @@ -8,6 +8,10 @@ import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { createMessage as createMessageMock } from '@web-api/persistence/postgres/messages/createMessage'; import { markMessageThreadRepliedTo as markMessageThreadRepliedToMock } from '@web-api/persistence/postgres/messages/markMessageThreadRepliedTo'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { replyToMessageInteractor } from './replyToMessageInteractor'; const createMessage = createMessageMock as jest.Mock; @@ -24,21 +28,20 @@ describe('replyToMessageInteractor', () => { ]; it('throws unauthorized for a user without MESSAGES permission', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '9bd0308c-2b06-4589-b36e-242398bea31b', - }); - await expect( - replyToMessageInteractor(applicationContext, { - attachments: mockAttachments, - docketNumber: '101-20', - message: "How's it going?", - parentMessageId: '62ea7e6e-8101-4e4b-9bbd-932b149c86c3', - subject: 'Hey!', - toSection: PETITIONS_SECTION, - toUserId: 'b427ca37-0df1-48ac-94bb-47aed073d6f7', - }), + replyToMessageInteractor( + applicationContext, + { + attachments: mockAttachments, + docketNumber: '101-20', + message: "How's it going?", + parentMessageId: '62ea7e6e-8101-4e4b-9bbd-932b149c86c3', + subject: 'Hey!', + toSection: PETITIONS_SECTION, + toUserId: 'b427ca37-0df1-48ac-94bb-47aed073d6f7', + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -51,10 +54,6 @@ describe('replyToMessageInteractor', () => { toSection: PETITIONS_SECTION, toUserId: 'b427ca37-0df1-48ac-94bb-47aed073d6f7', }; - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'b9fcabc8-3c83-4cbf-9f4a-d2ecbdc591e1', - }); applicationContext .getPersistenceGateway() .getUserById.mockReturnValueOnce({ @@ -79,10 +78,14 @@ describe('replyToMessageInteractor', () => { status: CASE_STATUS_TYPES.generalDocket, }); - await replyToMessageInteractor(applicationContext, { - ...messageData, - attachments: mockAttachments, - }); + await replyToMessageInteractor( + applicationContext, + { + ...messageData, + attachments: mockAttachments, + }, + mockPetitionsClerkUser, + ); expect(createMessage).toHaveBeenCalled(); expect((createMessage as jest.Mock).mock.calls[0][0].message).toMatchObject( diff --git a/web-api/src/business/useCases/messages/replyToMessageInteractor.ts b/web-api/src/business/useCases/messages/replyToMessageInteractor.ts index 4e148493079..3f7dad8e6a5 100644 --- a/web-api/src/business/useCases/messages/replyToMessageInteractor.ts +++ b/web-api/src/business/useCases/messages/replyToMessageInteractor.ts @@ -10,6 +10,7 @@ import { import { ReplyMessageType } from '@web-api/business/useCases/messages/createMessageInteractor'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { createMessage } from '@web-api/persistence/postgres/messages/createMessage'; import { markMessageThreadRepliedTo } from '@web-api/persistence/postgres/messages/markMessageThreadRepliedTo'; @@ -24,9 +25,8 @@ export const replyToMessage = async ( toSection, toUserId, }: ReplyMessageType, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.SEND_RECEIVE_MESSAGES)) { throw new UnauthorizedError('Unauthorized'); } @@ -85,14 +85,19 @@ export const replyToMessageInteractor = ( toSection, toUserId, }: ReplyMessageType, + authorizedUser: UnknownAuthUser, ): Promise => { - return replyToMessage(applicationContext, { - attachments, - docketNumber, - message, - parentMessageId, - subject, - toSection, - toUserId, - }); + return replyToMessage( + applicationContext, + { + attachments, + docketNumber, + message, + parentMessageId, + subject, + toSection, + toUserId, + }, + authorizedUser, + ); }; diff --git a/web-api/src/business/useCases/messages/setMessageAsReadInteractor.test.ts b/web-api/src/business/useCases/messages/setMessageAsReadInteractor.test.ts index a36722551fd..39318b66f47 100644 --- a/web-api/src/business/useCases/messages/setMessageAsReadInteractor.test.ts +++ b/web-api/src/business/useCases/messages/setMessageAsReadInteractor.test.ts @@ -1,35 +1,36 @@ import '@web-api/persistence/postgres/messages/mocks.jest'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { setMessageAsRead } from '@web-api/persistence/postgres/messages/setMessageAsRead'; import { setMessageAsReadInteractor } from './setMessageAsReadInteractor'; describe('setMessageAsReadInteractor', () => { it('returns an authorization error if the user does not have the necessary permission', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: 'petitioner', - }); - await expect( - setMessageAsReadInteractor(applicationContext, { - docketNumber: '123-45', - messageId: '123', - }), + setMessageAsReadInteractor( + applicationContext, + { + docketNumber: '123-45', + messageId: '123', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); expect(setMessageAsRead).not.toHaveBeenCalled(); }); it('calls the persistence method for marking a message as read for the given messageId', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'petitionsClerk', - }); - - await setMessageAsReadInteractor(applicationContext, { - docketNumber: '123-45', - messageId: '123', - }); + await setMessageAsReadInteractor( + applicationContext, + { + docketNumber: '123-45', + messageId: '123', + }, + mockPetitionsClerkUser, + ); expect(setMessageAsRead).toHaveBeenCalledWith({ messageId: '123', diff --git a/web-api/src/business/useCases/messages/setMessageAsReadInteractor.ts b/web-api/src/business/useCases/messages/setMessageAsReadInteractor.ts index 37f83f84cd9..faf5e069e0a 100644 --- a/web-api/src/business/useCases/messages/setMessageAsReadInteractor.ts +++ b/web-api/src/business/useCases/messages/setMessageAsReadInteractor.ts @@ -4,6 +4,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { setMessageAsRead } from '@web-api/persistence/postgres/messages/setMessageAsRead'; /** @@ -19,10 +20,9 @@ export const setMessageAsReadInteractor = async ( applicationContext: ServerApplicationContext, // eslint-disable-next-line @typescript-eslint/no-unused-vars { docketNumber, messageId }: { docketNumber: string; messageId: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.GET_READ_MESSAGES)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.GET_READ_MESSAGES)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/notifications/onConnectInteractor.test.ts b/web-api/src/business/useCases/notifications/onConnectInteractor.test.ts index 359e34eb7e9..d3041ec1cb8 100644 --- a/web-api/src/business/useCases/notifications/onConnectInteractor.test.ts +++ b/web-api/src/business/useCases/notifications/onConnectInteractor.test.ts @@ -1,22 +1,25 @@ import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { onConnectInteractor } from './onConnectInteractor'; -import { petitionerUser } from '@shared/test/mockUsers'; describe('onConnectInteractor', () => { const mockClientConnectionId = '03c1ee1e-c24a-480d-9ffc-683c8c417df7'; const mockConnectionId = '7f926304-e167-45e7-8601-e320298aaed3'; const mockEndpoint = 'www.example.com'; - beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - }); - it('should save the user connection', async () => { - await onConnectInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - connectionId: mockConnectionId, - endpoint: mockEndpoint, - }); + await onConnectInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + connectionId: mockConnectionId, + endpoint: mockEndpoint, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveUserConnection, @@ -24,13 +27,15 @@ describe('onConnectInteractor', () => { }); it('should NOT save the user connection when the current user is undefined', async () => { - applicationContext.getCurrentUser.mockReturnValue(undefined); - - await onConnectInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - connectionId: mockConnectionId, - endpoint: mockEndpoint, - }); + await onConnectInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + connectionId: mockConnectionId, + endpoint: mockEndpoint, + }, + undefined, + ); expect( applicationContext.getPersistenceGateway().saveUserConnection, @@ -39,11 +44,15 @@ describe('onConnectInteractor', () => { it('should add https protocol to the endpoint when the endpoint does not have a protocol', async () => { let endpoint = 'somedomain.hello.org'; - await onConnectInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - connectionId: mockConnectionId, - endpoint, - }); + await onConnectInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + connectionId: mockConnectionId, + endpoint, + }, + mockPetitionerUser, + ); expect( applicationContext.getPersistenceGateway().saveUserConnection, @@ -52,17 +61,21 @@ describe('onConnectInteractor', () => { clientConnectionId: mockClientConnectionId, connectionId: mockConnectionId, endpoint: 'https://' + endpoint, - userId: petitionerUser.userId, + userId: mockPetitionerUser.userId, }); }); it('should not add https protocol when endpoint already has a protocol', async () => { let endpoint = 'https://somedomain.hello.org'; - await onConnectInteractor(applicationContext, { - clientConnectionId: mockClientConnectionId, - connectionId: mockConnectionId, - endpoint, - }); + await onConnectInteractor( + applicationContext, + { + clientConnectionId: mockClientConnectionId, + connectionId: mockConnectionId, + endpoint, + }, + mockPetitionerUser, + ); expect( applicationContext.getPersistenceGateway().saveUserConnection, @@ -71,7 +84,7 @@ describe('onConnectInteractor', () => { clientConnectionId: mockClientConnectionId, connectionId: mockConnectionId, endpoint, - userId: petitionerUser.userId, + userId: mockPetitionerUser.userId, }); }); }); diff --git a/web-api/src/business/useCases/notifications/onConnectInteractor.ts b/web-api/src/business/useCases/notifications/onConnectInteractor.ts index 1f0dbf3d4c6..30f755b6bac 100644 --- a/web-api/src/business/useCases/notifications/onConnectInteractor.ts +++ b/web-api/src/business/useCases/notifications/onConnectInteractor.ts @@ -1,4 +1,5 @@ import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const onConnectInteractor = async ( applicationContext: ServerApplicationContext, @@ -7,8 +8,8 @@ export const onConnectInteractor = async ( connectionId, endpoint, }: { clientConnectionId: string; connectionId: string; endpoint: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); if (!authorizedUser) { // silence local development errors return; diff --git a/web-api/src/business/useCases/pendingItems/exportPendingReportInteractor.test.ts b/web-api/src/business/useCases/pendingItems/exportPendingReportInteractor.test.ts index bce8b791efc..d7b76fb4737 100644 --- a/web-api/src/business/useCases/pendingItems/exportPendingReportInteractor.test.ts +++ b/web-api/src/business/useCases/pendingItems/exportPendingReportInteractor.test.ts @@ -1,14 +1,15 @@ import { CASE_STATUS_TYPES, DOCKET_NUMBER_SUFFIXES, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { exportPendingReportInteractor } from '@web-api/business/useCases/pendingItems/exportPendingReportInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('exportPendingReportInteractor', () => { - let mockUser; - const judge = 'Colvin'; const mockFoundDocuments = [ @@ -97,32 +98,26 @@ describe('exportPendingReportInteractor', () => { }); }); - beforeEach(() => { - mockUser = { - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }; - - applicationContext.getCurrentUser.mockImplementation(() => mockUser); - }); - it('should throw an unauthorized error when the user does not have access', async () => { - mockUser = { - role: ROLES.petitioner, - userId: 'petitioner', - }; - await expect( - exportPendingReportInteractor(applicationContext, { - judge: 'Colvin', - }), + exportPendingReportInteractor( + applicationContext, + { + judge: 'Colvin', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should call fetchPendingItems from persistence and return a csv string of the results', async () => { - const results = await exportPendingReportInteractor(applicationContext, { - judge, - }); + const results = await exportPendingReportInteractor( + applicationContext, + { + judge, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().fetchPendingItems, diff --git a/web-api/src/business/useCases/pendingItems/exportPendingReportInteractor.ts b/web-api/src/business/useCases/pendingItems/exportPendingReportInteractor.ts index e8dde7bccaa..776ebf9f55f 100644 --- a/web-api/src/business/useCases/pendingItems/exportPendingReportInteractor.ts +++ b/web-api/src/business/useCases/pendingItems/exportPendingReportInteractor.ts @@ -4,14 +4,14 @@ import { } from '@shared/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { stringify } from 'csv-stringify/sync'; export const exportPendingReportInteractor = async ( applicationContext: ServerApplicationContext, { judge }: { judge?: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.PENDING_ITEMS)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/pendingItems/fetchPendingItemsInteractor.test.ts b/web-api/src/business/useCases/pendingItems/fetchPendingItemsInteractor.test.ts index 4c0a0b3b7e0..95233f9379c 100644 --- a/web-api/src/business/useCases/pendingItems/fetchPendingItemsInteractor.test.ts +++ b/web-api/src/business/useCases/pendingItems/fetchPendingItemsInteractor.test.ts @@ -1,37 +1,32 @@ -import { ROLES } from '@shared/business/entities/EntityConstants'; import { applicationContext } from '@shared/business/test/createTestApplicationContext'; import { fetchPendingItemsInteractor } from '@web-api/business/useCases/pendingItems/fetchPendingItemsInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('fetchPendingItemsInteractor', () => { - let mockUser; - - beforeEach(() => { - mockUser = { - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }; - - applicationContext.getCurrentUser.mockImplementation(() => mockUser); - }); - it('should throw an unauthorized error when the user does not have access to blocked cases', async () => { - mockUser = { - role: ROLES.petitioner, - userId: 'petitioner', - }; - await expect( - fetchPendingItemsInteractor(applicationContext, { - judge: 'Judge Colvin', - } as any), + fetchPendingItemsInteractor( + applicationContext, + { + judge: 'Judge Colvin', + } as any, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should throw an error when the judge is not defined', async () => { await expect( - fetchPendingItemsInteractor(applicationContext, { - judge: undefined, - } as any), + fetchPendingItemsInteractor( + applicationContext, + { + judge: undefined, + } as any, + mockPetitionsClerkUser, + ), ).rejects.toThrow('judge is required'); }); @@ -43,9 +38,13 @@ describe('fetchPendingItemsInteractor', () => { { docketEntryId: 'abc', docketNumber: '201-20', pending: true }, ]); - const results = await fetchPendingItemsInteractor(applicationContext, { - judge: 'Judge Colvin', - } as any); + const results = await fetchPendingItemsInteractor( + applicationContext, + { + judge: 'Judge Colvin', + } as any, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().fetchPendingItems, diff --git a/web-api/src/business/useCases/pendingItems/fetchPendingItemsInteractor.ts b/web-api/src/business/useCases/pendingItems/fetchPendingItemsInteractor.ts index 3e01fbe537f..17727473c33 100644 --- a/web-api/src/business/useCases/pendingItems/fetchPendingItemsInteractor.ts +++ b/web-api/src/business/useCases/pendingItems/fetchPendingItemsInteractor.ts @@ -4,6 +4,7 @@ import { } from '@shared/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const pendingItemCaseSource = [ 'associatedJudge', @@ -34,12 +35,11 @@ export type PendingItem = Pick< export const fetchPendingItemsInteractor = async ( applicationContext: ServerApplicationContext, { judge, page }: { judge: string; page: number }, + authorizedUser: UnknownAuthUser, ): Promise<{ foundDocuments: PendingItem[]; total: number; }> => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.PENDING_ITEMS)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/pendingItems/generatePrintablePendingReportInteractor.test.ts b/web-api/src/business/useCases/pendingItems/generatePrintablePendingReportInteractor.test.ts index c2285814984..64fe99c25a5 100644 --- a/web-api/src/business/useCases/pendingItems/generatePrintablePendingReportInteractor.test.ts +++ b/web-api/src/business/useCases/pendingItems/generatePrintablePendingReportInteractor.test.ts @@ -1,14 +1,13 @@ -import { - DOCKET_NUMBER_SUFFIXES, - ROLES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { DOCKET_NUMBER_SUFFIXES } from '../../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { generatePrintablePendingReportInteractor } from './generatePrintablePendingReportInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('generatePrintablePendingReportInteractor', () => { - let mockUser; - const mockFoundDocuments = [ { associatedJudge: 'Judge Judgey', @@ -87,13 +86,6 @@ describe('generatePrintablePendingReportInteractor', () => { }); beforeEach(() => { - mockUser = { - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }; - - applicationContext.getCurrentUser.mockImplementation(() => mockUser); - applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE); @@ -104,15 +96,14 @@ describe('generatePrintablePendingReportInteractor', () => { }); it('should throw an unauthorized error when the user does not have access', async () => { - mockUser = { - role: ROLES.petitioner, - userId: 'petitioner', - }; - await expect( - generatePrintablePendingReportInteractor(applicationContext, { - judge: 'Colvin', - } as any), + generatePrintablePendingReportInteractor( + applicationContext, + { + judge: 'Colvin', + } as any, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -120,6 +111,7 @@ describe('generatePrintablePendingReportInteractor', () => { const results = await generatePrintablePendingReportInteractor( applicationContext, {} as any, + mockPetitionsClerkUser, ); expect( @@ -135,6 +127,7 @@ describe('generatePrintablePendingReportInteractor', () => { await generatePrintablePendingReportInteractor( applicationContext, {} as any, + mockPetitionsClerkUser, ); const { pendingItems } = @@ -223,6 +216,7 @@ describe('generatePrintablePendingReportInteractor', () => { await generatePrintablePendingReportInteractor( applicationContext, {} as any, + mockPetitionsClerkUser, ); const { subtitle } = @@ -232,9 +226,13 @@ describe('generatePrintablePendingReportInteractor', () => { }); it('should generate a subtitle with the judge name if a judge filter is applied', async () => { - await generatePrintablePendingReportInteractor(applicationContext, { - judge: 'Colvin', - } as any); + await generatePrintablePendingReportInteractor( + applicationContext, + { + judge: 'Colvin', + } as any, + mockPetitionsClerkUser, + ); const { subtitle } = applicationContext.getDocumentGenerators().pendingReport.mock.calls[0][0] @@ -243,9 +241,13 @@ describe('generatePrintablePendingReportInteractor', () => { }); it('should get case information from persistence and generate a subtitle with the docket number if a docketNumber is present', async () => { - await generatePrintablePendingReportInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - } as any); + await generatePrintablePendingReportInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + } as any, + mockPetitionsClerkUser, + ); const { subtitle } = applicationContext.getDocumentGenerators().pendingReport.mock.calls[0][0] @@ -257,9 +259,13 @@ describe('generatePrintablePendingReportInteractor', () => { it('should generate a subtitle with the docket number suffix if present', async () => { MOCK_CASE.docketNumberWithSuffix = `${MOCK_CASE.docketNumber}${DOCKET_NUMBER_SUFFIXES.WHISTLEBLOWER}`; - await generatePrintablePendingReportInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - } as any); + await generatePrintablePendingReportInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + } as any, + mockPetitionsClerkUser, + ); const { subtitle } = applicationContext.getDocumentGenerators().pendingReport.mock.calls[0][0] @@ -271,6 +277,7 @@ describe('generatePrintablePendingReportInteractor', () => { await generatePrintablePendingReportInteractor( applicationContext, {} as any, + mockPetitionsClerkUser, ); expect( @@ -282,6 +289,7 @@ describe('generatePrintablePendingReportInteractor', () => { await generatePrintablePendingReportInteractor( applicationContext, {} as any, + mockPetitionsClerkUser, ); expect( @@ -293,6 +301,7 @@ describe('generatePrintablePendingReportInteractor', () => { const results = await generatePrintablePendingReportInteractor( applicationContext, {} as any, + mockPetitionsClerkUser, ); expect( diff --git a/web-api/src/business/useCases/pendingItems/generatePrintablePendingReportInteractor.ts b/web-api/src/business/useCases/pendingItems/generatePrintablePendingReportInteractor.ts index 884efdf3d1b..4b082ad1fad 100644 --- a/web-api/src/business/useCases/pendingItems/generatePrintablePendingReportInteractor.ts +++ b/web-api/src/business/useCases/pendingItems/generatePrintablePendingReportInteractor.ts @@ -4,13 +4,13 @@ import { } from '@shared/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const generatePrintablePendingReportInteractor = async ( applicationContext: ServerApplicationContext, { docketNumber, judge }: { docketNumber?: string; judge?: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.PENDING_ITEMS)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/pendingMotion/deleteDocketEntryWorksheetInteractor.test.ts b/web-api/src/business/useCases/pendingMotion/deleteDocketEntryWorksheetInteractor.test.ts index 599a8f45daa..fff4681e1eb 100644 --- a/web-api/src/business/useCases/pendingMotion/deleteDocketEntryWorksheetInteractor.test.ts +++ b/web-api/src/business/useCases/pendingMotion/deleteDocketEntryWorksheetInteractor.test.ts @@ -1,7 +1,10 @@ import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { deleteDocketEntryWorksheetInteractor } from '@web-api/business/useCases/pendingMotion/deleteDocketEntryWorksheetInteractor'; -import { docketClerkUser } from '@shared/test/mockUsers'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('deleteDocketEntryWorksheetInteractor', () => { const TEST_DOCKET_ENTRY_ID = 'TEST_DOCKET_ENTRY_ID'; @@ -10,16 +13,14 @@ describe('deleteDocketEntryWorksheetInteractor', () => { applicationContext .getPersistenceGateway() .deleteDocketEntryWorksheetRecord.mockReturnValue(null); - - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); }); it('should throw an Unauthorized Error when user does not have permission', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); await expect( deleteDocketEntryWorksheetInteractor( applicationContext, TEST_DOCKET_ENTRY_ID, + mockPetitionerUser, ), ).rejects.toThrow(UnauthorizedError); }); @@ -28,6 +29,7 @@ describe('deleteDocketEntryWorksheetInteractor', () => { await deleteDocketEntryWorksheetInteractor( applicationContext, TEST_DOCKET_ENTRY_ID, + mockDocketClerkUser, ); const { calls } = diff --git a/web-api/src/business/useCases/pendingMotion/deleteDocketEntryWorksheetInteractor.ts b/web-api/src/business/useCases/pendingMotion/deleteDocketEntryWorksheetInteractor.ts index baaab5dc060..86565baeadb 100644 --- a/web-api/src/business/useCases/pendingMotion/deleteDocketEntryWorksheetInteractor.ts +++ b/web-api/src/business/useCases/pendingMotion/deleteDocketEntryWorksheetInteractor.ts @@ -4,12 +4,13 @@ import { } from '@shared/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const deleteDocketEntryWorksheetInteractor = async ( applicationContext: ServerApplicationContext, docketEntryId: string, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); if ( !isAuthorized( authorizedUser, diff --git a/web-api/src/business/useCases/pendingMotion/getPendingMotionDocketEntriesForCurrentJudgeInteractor.test.ts b/web-api/src/business/useCases/pendingMotion/getPendingMotionDocketEntriesForCurrentJudgeInteractor.test.ts index e75c040595a..aa52bc33a61 100644 --- a/web-api/src/business/useCases/pendingMotion/getPendingMotionDocketEntriesForCurrentJudgeInteractor.test.ts +++ b/web-api/src/business/useCases/pendingMotion/getPendingMotionDocketEntriesForCurrentJudgeInteractor.test.ts @@ -5,7 +5,10 @@ import { import { RawDocketEntryWorksheet } from '@shared/business/entities/docketEntryWorksheet/DocketEntryWorksheet'; import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; -import { judgeColvin, petitionsClerkUser } from '@shared/test/mockUsers'; +import { + mockJudgeUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; jest.mock('@shared/business/utilities/DateHandler', () => { const originalModule = jest.requireActual( @@ -33,8 +36,6 @@ describe('getPendingMotionDocketEntriesForCurrentJudgeInteractor', () => { const CASE_BY_DOCKET_NUMBER: { [key: string]: any } = {}; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(judgeColvin); - applicationContext .getPersistenceGateway() .getAllPendingMotionDocketEntriesForJudge.mockReturnValue( @@ -73,14 +74,13 @@ describe('getPendingMotionDocketEntriesForCurrentJudgeInteractor', () => { }); it('should throw an error when the user does not have access to the case worksheet feature', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - await expect( getPendingMotionDocketEntriesForCurrentJudgeInteractor( applicationContext, { judgeIds: ['judgeId'], }, + mockPetitionsClerkUser, ), ).rejects.toThrow(UnauthorizedError); }); @@ -121,6 +121,7 @@ describe('getPendingMotionDocketEntriesForCurrentJudgeInteractor', () => { { judgeIds: ['judgeId'], }, + mockJudgeUser, ); expect( @@ -212,6 +213,7 @@ describe('getPendingMotionDocketEntriesForCurrentJudgeInteractor', () => { { judgeIds: ['judgeId'], }, + mockJudgeUser, ); expect(results.docketEntries.length).toEqual(1); diff --git a/web-api/src/business/useCases/pendingMotion/getPendingMotionDocketEntriesForCurrentJudgeInteractor.ts b/web-api/src/business/useCases/pendingMotion/getPendingMotionDocketEntriesForCurrentJudgeInteractor.ts index 183cd116d2e..9a10036c9fb 100644 --- a/web-api/src/business/useCases/pendingMotion/getPendingMotionDocketEntriesForCurrentJudgeInteractor.ts +++ b/web-api/src/business/useCases/pendingMotion/getPendingMotionDocketEntriesForCurrentJudgeInteractor.ts @@ -6,6 +6,7 @@ import { import { RawDocketEntryWorksheet } from '@shared/business/entities/docketEntryWorksheet/DocketEntryWorksheet'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { calculateDifferenceInDays, prepareDateFromString, @@ -34,11 +35,11 @@ export type FormattedPendingMotionWithWorksheet = FormattedPendingMotion & { export const getPendingMotionDocketEntriesForCurrentJudgeInteractor = async ( applicationContext: ServerApplicationContext, params: { judgeIds: string[] }, + authorizedUser: UnknownAuthUser, ): Promise<{ docketEntries: FormattedPendingMotionWithWorksheet[]; }> => { const { judgeIds } = params; - const authorizedUser = applicationContext.getCurrentUser(); if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.PENDING_MOTIONS_TABLE)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/pendingMotion/updateDocketEntryWorksheetInteractor.test.ts b/web-api/src/business/useCases/pendingMotion/updateDocketEntryWorksheetInteractor.test.ts index 1bf68de488a..b0406ec2ae8 100644 --- a/web-api/src/business/useCases/pendingMotion/updateDocketEntryWorksheetInteractor.test.ts +++ b/web-api/src/business/useCases/pendingMotion/updateDocketEntryWorksheetInteractor.test.ts @@ -1,7 +1,10 @@ import { InvalidEntityError, UnauthorizedError } from '@web-api/errors/errors'; import { RawDocketEntryWorksheet } from '@shared/business/entities/docketEntryWorksheet/DocketEntryWorksheet'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; -import { judgeColvin, petitionsClerkUser } from '@shared/test/mockUsers'; +import { + mockJudgeUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { updateDocketEntryWorksheetInteractor } from '@web-api/business/useCases/pendingMotion/updateDocketEntryWorksheetInteractor'; describe('updateDocketEntryWorksheetInteractor', () => { @@ -16,8 +19,6 @@ describe('updateDocketEntryWorksheetInteractor', () => { }; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(judgeColvin); - applicationContext .getUseCaseHelpers() .getJudgeForUserHelper.mockReturnValue({ userId: TEST_JUDGE_USER_ID }); @@ -28,20 +29,26 @@ describe('updateDocketEntryWorksheetInteractor', () => { }); it('should throw an error when the user does not have access to the case worksheet feature', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - await expect( - updateDocketEntryWorksheetInteractor(applicationContext, { - worksheet: VALID_WORKSHEET, - }), + updateDocketEntryWorksheetInteractor( + applicationContext, + { + worksheet: VALID_WORKSHEET, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(UnauthorizedError); }); it('should throw an error when the provided worksheet fails validation', async () => { await expect( - updateDocketEntryWorksheetInteractor(applicationContext, { - worksheet: { ...VALID_WORKSHEET, docketEntryId: 'NOT A UUID' }, - }), + updateDocketEntryWorksheetInteractor( + applicationContext, + { + worksheet: { ...VALID_WORKSHEET, docketEntryId: 'NOT A UUID' }, + }, + mockJudgeUser, + ), ).rejects.toThrow(InvalidEntityError); }); @@ -51,6 +58,7 @@ describe('updateDocketEntryWorksheetInteractor', () => { { worksheet: VALID_WORKSHEET, }, + mockJudgeUser, ); const updateDocketEntryWorksheetCallCount = diff --git a/web-api/src/business/useCases/pendingMotion/updateDocketEntryWorksheetInteractor.ts b/web-api/src/business/useCases/pendingMotion/updateDocketEntryWorksheetInteractor.ts index e1cc06183f3..211e58d1616 100644 --- a/web-api/src/business/useCases/pendingMotion/updateDocketEntryWorksheetInteractor.ts +++ b/web-api/src/business/useCases/pendingMotion/updateDocketEntryWorksheetInteractor.ts @@ -8,6 +8,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const updateDocketEntryWorksheetInteractor = async ( applicationContext: ServerApplicationContext, @@ -16,16 +17,15 @@ export const updateDocketEntryWorksheetInteractor = async ( }: { worksheet: RawDocketEntryWorksheet; }, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.DOCKET_ENTRY_WORKSHEET)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.DOCKET_ENTRY_WORKSHEET)) { throw new UnauthorizedError('Unauthorized'); } const judgeUser = await applicationContext .getUseCaseHelpers() - .getJudgeForUserHelper(applicationContext, { user }); + .getJudgeForUserHelper(applicationContext, { user: authorizedUser }); const docketEntryWorksheetEntity = new DocketEntryWorksheet( worksheet, diff --git a/web-api/src/business/useCases/polling/startPollingForResultsInteractor.test.ts b/web-api/src/business/useCases/polling/startPollingForResultsInteractor.test.ts index d56acd02b26..9bea5e1f5b3 100644 --- a/web-api/src/business/useCases/polling/startPollingForResultsInteractor.test.ts +++ b/web-api/src/business/useCases/polling/startPollingForResultsInteractor.test.ts @@ -1,4 +1,6 @@ +import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { startPollingForResultsInteractor } from '@web-api/business/useCases/polling/startPollingForResultsInteractor'; describe('startPollingForResultsInteractor', () => { @@ -13,22 +15,22 @@ describe('startPollingForResultsInteractor', () => { totalNumberOfChunks: 1, }, ]; - const TEST_USER_ID = 'TEST_USER_ID'; - const TEST_USER = { - userId: TEST_USER_ID, - }; + const TEST_USER_ID = mockDocketClerkUser.userId; beforeEach(() => { - applicationContext.getCurrentUser = jest.fn().mockReturnValue(TEST_USER); applicationContext.getPersistenceGateway().getRequestResults = jest .fn() .mockResolvedValue(MOCKED_RESULTS); }); it('should load poll response', async () => { - const results = await startPollingForResultsInteractor(applicationContext, { - requestId: TEST_REQUEST_ID, - }); + const results = await startPollingForResultsInteractor( + applicationContext, + { + requestId: TEST_REQUEST_ID, + }, + mockDocketClerkUser, + ); const getRequestResultsCalls = applicationContext.getPersistenceGateway().getRequestResults.mock.calls; @@ -47,9 +49,13 @@ describe('startPollingForResultsInteractor', () => { .fn() .mockResolvedValue([]); - const results = await startPollingForResultsInteractor(applicationContext, { - requestId: TEST_REQUEST_ID, - }); + const results = await startPollingForResultsInteractor( + applicationContext, + { + requestId: TEST_REQUEST_ID, + }, + mockDocketClerkUser, + ); const getRequestResultsCalls = applicationContext.getPersistenceGateway().getRequestResults.mock.calls; @@ -61,6 +67,26 @@ describe('startPollingForResultsInteractor', () => { expect(results).toEqual(undefined); }); + it('should throw an error when the user is not an auth user', async () => { + applicationContext.getPersistenceGateway().getRequestResults = jest + .fn() + .mockResolvedValue([]); + + await expect( + startPollingForResultsInteractor( + applicationContext, + { + requestId: TEST_REQUEST_ID, + }, + undefined, + ), + ).rejects.toThrow( + new UnauthorizedError( + 'User attempting to poll for results is not an auth user', + ), + ); + }); + it('should returned undefined if all the records are not yet saved in the database', async () => { applicationContext.getPersistenceGateway().getRequestResults = jest .fn() @@ -74,9 +100,13 @@ describe('startPollingForResultsInteractor', () => { }, ]); - const results = await startPollingForResultsInteractor(applicationContext, { - requestId: TEST_REQUEST_ID, - }); + const results = await startPollingForResultsInteractor( + applicationContext, + { + requestId: TEST_REQUEST_ID, + }, + mockDocketClerkUser, + ); const getRequestResultsCalls = applicationContext.getPersistenceGateway().getRequestResults.mock.calls; diff --git a/web-api/src/business/useCases/polling/startPollingForResultsInteractor.ts b/web-api/src/business/useCases/polling/startPollingForResultsInteractor.ts index 8dc2d7e23b8..9c8c788c161 100644 --- a/web-api/src/business/useCases/polling/startPollingForResultsInteractor.ts +++ b/web-api/src/business/useCases/polling/startPollingForResultsInteractor.ts @@ -1,17 +1,27 @@ import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnauthorizedError } from '@web-api/errors/errors'; +import { + UnknownAuthUser, + isAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; export const startPollingForResultsInteractor = async ( applicationContext: ServerApplicationContext, { requestId }: { requestId: string }, + authorizedUser: UnknownAuthUser, ): Promise<{ response: any } | undefined> => { - const user = applicationContext.getCurrentUser(); + if (!isAuthUser(authorizedUser)) { + throw new UnauthorizedError( + 'User attempting to poll for results is not an auth user', + ); + } const records = await applicationContext .getPersistenceGateway() .getRequestResults({ applicationContext, requestId, - userId: user.userId, + userId: authorizedUser.userId, }); if (records.length === 0) return undefined; diff --git a/web-api/src/business/useCases/practitioner/createPractitionerDocumentInteractor.test.ts b/web-api/src/business/useCases/practitioner/createPractitionerDocumentInteractor.test.ts index 347051ed778..8327a7faf52 100644 --- a/web-api/src/business/useCases/practitioner/createPractitionerDocumentInteractor.test.ts +++ b/web-api/src/business/useCases/practitioner/createPractitionerDocumentInteractor.test.ts @@ -1,11 +1,13 @@ import { InvalidEntityError, UnauthorizedError } from '@web-api/errors/errors'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { createPractitionerDocumentInteractor } from './createPractitionerDocumentInteractor'; +import { + mockAdmissionsClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; jest.mock('@web-api/business/useCases/user/generateChangeOfAddress'); describe('updatePractitionerUserInteractor', () => { - let testUser; const mockDocumentMetadata = { categoryName: 'Application', categoryType: 'Application', @@ -15,35 +17,29 @@ describe('updatePractitionerUserInteractor', () => { practitionerDocumentFileId: '07044afe-641b-4d75-a84f-0698870b7650', } as any; - beforeEach(() => { - testUser = { - role: ROLES.admissionsClerk, - userId: 'admissionsclerk', - }; - - applicationContext.getCurrentUser.mockImplementation(() => testUser); - }); - it('should throw an unauthorized error when the user does not have permission to update the practitioner user', async () => { - testUser = { - role: ROLES.petitioner, - userId: 'petitioner', - }; - await expect( - createPractitionerDocumentInteractor(applicationContext, { - barNumber: 'pt1234', - documentMetadata: mockDocumentMetadata, - }), + createPractitionerDocumentInteractor( + applicationContext, + { + barNumber: 'pt1234', + documentMetadata: mockDocumentMetadata, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); it('should throw a validation error if the practitioner document has the wrong type', async () => { await expect( - createPractitionerDocumentInteractor(applicationContext, { - barNumber: 'pt1234', - documentMetadata: { ...mockDocumentMetadata, categoryType: 'GG' }, - }), + createPractitionerDocumentInteractor( + applicationContext, + { + barNumber: 'pt1234', + documentMetadata: { ...mockDocumentMetadata, categoryType: 'GG' }, + }, + mockAdmissionsClerkUser, + ), ).rejects.toThrow(InvalidEntityError); }); @@ -54,6 +50,7 @@ describe('updatePractitionerUserInteractor', () => { barNumber: 'pt1234', documentMetadata: mockDocumentMetadata, }, + mockAdmissionsClerkUser, ); expect(results).toMatchObject({ ...mockDocumentMetadata }); }); diff --git a/web-api/src/business/useCases/practitioner/createPractitionerDocumentInteractor.ts b/web-api/src/business/useCases/practitioner/createPractitionerDocumentInteractor.ts index 7a41567b1a7..f0799eceb66 100644 --- a/web-api/src/business/useCases/practitioner/createPractitionerDocumentInteractor.ts +++ b/web-api/src/business/useCases/practitioner/createPractitionerDocumentInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * createPractitionerDocumentInteractor @@ -30,11 +31,10 @@ export const createPractitionerDocumentInteractor = async ( fileName: string; }; }, + authorizedUser: UnknownAuthUser, ) => { - const requestUser = applicationContext.getCurrentUser(); - if ( - !isAuthorized(requestUser, ROLE_PERMISSIONS.UPLOAD_PRACTITIONER_DOCUMENT) + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.UPLOAD_PRACTITIONER_DOCUMENT) ) { throw new UnauthorizedError('Unauthorized for creating practitioner user'); } diff --git a/web-api/src/business/useCases/practitioner/createPractitionerUserInteractor.test.ts b/web-api/src/business/useCases/practitioner/createPractitionerUserInteractor.test.ts index e67b01f28de..7d9cd3b5e59 100644 --- a/web-api/src/business/useCases/practitioner/createPractitionerUserInteractor.test.ts +++ b/web-api/src/business/useCases/practitioner/createPractitionerUserInteractor.test.ts @@ -4,9 +4,12 @@ import { } from '../../../../../shared/src/business/entities/EntityConstants'; import { RawPractitioner } from '@shared/business/entities/Practitioner'; import { UnauthorizedError } from '@web-api/errors/errors'; -import { admissionsClerkUser, petitionerUser } from '@shared/test/mockUsers'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { createPractitionerUserInteractor } from './createPractitionerUserInteractor'; +import { + mockAdmissionsClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('createPractitionerUserInteractor', () => { const mockUser: RawPractitioner = { @@ -28,19 +31,20 @@ describe('createPractitionerUserInteractor', () => { }; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(admissionsClerkUser); applicationContext .getPersistenceGateway() .createOrUpdatePractitionerUser.mockResolvedValue(mockUser); }); it('should throw an error when the user is unauthorized to create a practitioner user', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - await expect( - createPractitionerUserInteractor(applicationContext, { - user: mockUser, - }), + createPractitionerUserInteractor( + applicationContext, + { + user: mockUser, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -50,6 +54,7 @@ describe('createPractitionerUserInteractor', () => { { user: mockUser, }, + mockAdmissionsClerkUser, ); expect(barNumber).toEqual(mockUser.barNumber); @@ -58,12 +63,16 @@ describe('createPractitionerUserInteractor', () => { it('should set practitioner.pendingEmail to practitioner.email and set practitioner.email to undefined', async () => { const mockEmail = 'testing@example.com'; - await createPractitionerUserInteractor(applicationContext, { - user: { - ...mockUser, - email: mockEmail, + await createPractitionerUserInteractor( + applicationContext, + { + user: { + ...mockUser, + email: mockEmail, + }, }, - }); + mockAdmissionsClerkUser, + ); const mockUserCall = applicationContext.getPersistenceGateway().createOrUpdatePractitionerUser diff --git a/web-api/src/business/useCases/practitioner/createPractitionerUserInteractor.ts b/web-api/src/business/useCases/practitioner/createPractitionerUserInteractor.ts index 42bda73d028..12877296336 100644 --- a/web-api/src/business/useCases/practitioner/createPractitionerUserInteractor.ts +++ b/web-api/src/business/useCases/practitioner/createPractitionerUserInteractor.ts @@ -5,15 +5,17 @@ import { import { RawPractitioner } from '../../../../../shared/src/business/entities/Practitioner'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { createPractitionerUser } from '../../../../../shared/src/business/utilities/createPractitionerUser'; export const createPractitionerUserInteractor = async ( applicationContext: ServerApplicationContext, { user }: { user: RawPractitioner }, + authorizedUser: UnknownAuthUser, ): Promise<{ barNumber: string }> => { - const requestUser = applicationContext.getCurrentUser(); - - if (!isAuthorized(requestUser, ROLE_PERMISSIONS.ADD_EDIT_PRACTITIONER_USER)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.ADD_EDIT_PRACTITIONER_USER) + ) { throw new UnauthorizedError('Unauthorized for creating practitioner user'); } diff --git a/web-api/src/business/useCases/practitioner/deletePractitionerDocumentInteractor.test.ts b/web-api/src/business/useCases/practitioner/deletePractitionerDocumentInteractor.test.ts index 47642352804..41a3d0d9f87 100644 --- a/web-api/src/business/useCases/practitioner/deletePractitionerDocumentInteractor.test.ts +++ b/web-api/src/business/useCases/practitioner/deletePractitionerDocumentInteractor.test.ts @@ -1,40 +1,37 @@ -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { deletePractitionerDocumentInteractor } from './deletePractitionerDocumentInteractor'; +import { + mockAdmissionsClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('deletePractitionerDocumentInteractor', () => { - const testUser = { - role: ROLES.admissionsClerk, - userId: 'admissionsclerk', - }; const practitionerDocumentFileId = '3da3e303-5da9-4b8b-99a5-d4b65c449619'; const barNumber = 'PT76543'; - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(testUser); - }); - it('should throw an unauthorized error when the user does not have permission to update practitioner documents', async () => { - const testPetitionerUser = { - role: ROLES.petitioner, - userId: 'petitioner', - }; - applicationContext.getCurrentUser.mockReturnValueOnce(testPetitionerUser); - await expect( - deletePractitionerDocumentInteractor(applicationContext, { - barNumber, - practitionerDocumentFileId, - }), + deletePractitionerDocumentInteractor( + applicationContext, + { + barNumber, + practitionerDocumentFileId, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); it('should delete the practitioner document from persistence', async () => { - await deletePractitionerDocumentInteractor(applicationContext, { - barNumber, - practitionerDocumentFileId, - }); + await deletePractitionerDocumentInteractor( + applicationContext, + { + barNumber, + practitionerDocumentFileId, + }, + mockAdmissionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().deleteDocumentFile.mock .calls[0][0], @@ -44,10 +41,14 @@ describe('deletePractitionerDocumentInteractor', () => { }); it('should delete the practitioner document from the DB', async () => { - await deletePractitionerDocumentInteractor(applicationContext, { - barNumber, - practitionerDocumentFileId, - }); + await deletePractitionerDocumentInteractor( + applicationContext, + { + barNumber, + practitionerDocumentFileId, + }, + mockAdmissionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().deletePractitionerDocument.mock .calls[0][0], diff --git a/web-api/src/business/useCases/practitioner/deletePractitionerDocumentInteractor.ts b/web-api/src/business/useCases/practitioner/deletePractitionerDocumentInteractor.ts index 662d9508a4c..a77dd2e1ba1 100644 --- a/web-api/src/business/useCases/practitioner/deletePractitionerDocumentInteractor.ts +++ b/web-api/src/business/useCases/practitioner/deletePractitionerDocumentInteractor.ts @@ -4,6 +4,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * deletePractitionerDocumentInteractor @@ -22,11 +23,10 @@ export const deletePractitionerDocumentInteractor = async ( barNumber: string; practitionerDocumentFileId: string; }, + authorizedUser: UnknownAuthUser, ) => { - const requestUser = applicationContext.getCurrentUser(); - if ( - !isAuthorized(requestUser, ROLE_PERMISSIONS.UPLOAD_PRACTITIONER_DOCUMENT) + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.UPLOAD_PRACTITIONER_DOCUMENT) ) { throw new UnauthorizedError( 'Unauthorized for deleting practitioner documents', diff --git a/web-api/src/business/useCases/practitioner/editPractitionerDocumentInteractor.test.ts b/web-api/src/business/useCases/practitioner/editPractitionerDocumentInteractor.test.ts index ac036f4974a..c217a71ec0c 100644 --- a/web-api/src/business/useCases/practitioner/editPractitionerDocumentInteractor.test.ts +++ b/web-api/src/business/useCases/practitioner/editPractitionerDocumentInteractor.test.ts @@ -1,13 +1,12 @@ import { InvalidEntityError, UnauthorizedError } from '@web-api/errors/errors'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { editPractitionerDocumentInteractor } from './editPractitionerDocumentInteractor'; +import { + mockAdmissionsClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('editPractitionerDocumentInteractor', () => { - const testUser = { - role: ROLES.admissionsClerk, - userId: 'admissionsclerk', - }; const barNumber = 'PT4785'; const mockDocumentMetadata = { categoryName: 'Application', @@ -18,40 +17,42 @@ describe('editPractitionerDocumentInteractor', () => { practitionerDocumentFileId: 'ad69486a-2489-4eb1-bee6-bdb6cc0257b4', } as any; - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(testUser); - }); - it('should throw an unauthorized error when the user does not have permission to update the practitioner user', async () => { - const testPetitionerUser = { - role: ROLES.petitioner, - userId: 'petitioner', - }; - applicationContext.getCurrentUser.mockReturnValueOnce(testPetitionerUser); - await expect( - editPractitionerDocumentInteractor(applicationContext, { - barNumber, - documentMetadata: mockDocumentMetadata, - }), + editPractitionerDocumentInteractor( + applicationContext, + { + barNumber, + documentMetadata: mockDocumentMetadata, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); it('should throw a validation error if the practitioner document has the wrong type', async () => { await expect( - editPractitionerDocumentInteractor(applicationContext, { - barNumber, - documentMetadata: { ...mockDocumentMetadata, categoryType: 'GG' }, - }), + editPractitionerDocumentInteractor( + applicationContext, + { + barNumber, + documentMetadata: { ...mockDocumentMetadata, categoryType: 'GG' }, + }, + mockAdmissionsClerkUser, + ), ).rejects.toThrow(InvalidEntityError); }); it('should throw a validation error if the practitioner document is missing information', async () => { await expect( - editPractitionerDocumentInteractor(applicationContext, { - barNumber, - documentMetadata: { ...mockDocumentMetadata, fileName: undefined }, - }), + editPractitionerDocumentInteractor( + applicationContext, + { + barNumber, + documentMetadata: { ...mockDocumentMetadata, fileName: undefined }, + }, + mockAdmissionsClerkUser, + ), ).rejects.toThrow(InvalidEntityError); }); @@ -62,6 +63,7 @@ describe('editPractitionerDocumentInteractor', () => { barNumber, documentMetadata: mockDocumentMetadata, }, + mockAdmissionsClerkUser, ); expect(results).toMatchObject({ ...mockDocumentMetadata }); }); diff --git a/web-api/src/business/useCases/practitioner/editPractitionerDocumentInteractor.ts b/web-api/src/business/useCases/practitioner/editPractitionerDocumentInteractor.ts index 7cce99ab64e..9ec5ba628b9 100644 --- a/web-api/src/business/useCases/practitioner/editPractitionerDocumentInteractor.ts +++ b/web-api/src/business/useCases/practitioner/editPractitionerDocumentInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * editPractitionerDocumentInteractor @@ -31,11 +32,10 @@ export const editPractitionerDocumentInteractor = async ( uploadDate: string; }; }, + authorizedUser: UnknownAuthUser, ) => { - const requestUser = applicationContext.getCurrentUser(); - if ( - !isAuthorized(requestUser, ROLE_PERMISSIONS.UPLOAD_PRACTITIONER_DOCUMENT) + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.UPLOAD_PRACTITIONER_DOCUMENT) ) { throw new UnauthorizedError('Unauthorized for creating practitioner user'); } diff --git a/web-api/src/business/useCases/practitioner/getPractitionerByBarNumberInteractor.test.ts b/web-api/src/business/useCases/practitioner/getPractitionerByBarNumberInteractor.test.ts index c08a8eb6097..68eced0490b 100644 --- a/web-api/src/business/useCases/practitioner/getPractitionerByBarNumberInteractor.test.ts +++ b/web-api/src/business/useCases/practitioner/getPractitionerByBarNumberInteractor.test.ts @@ -2,36 +2,28 @@ import { ROLES, SERVICE_INDICATOR_TYPES, } from '../../../../../shared/src/business/entities/EntityConstants'; -import { User } from '../../../../../shared/src/business/entities/User'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getPractitionerByBarNumberInteractor } from './getPractitionerByBarNumberInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('getPractitionerByBarNumberInteractor', () => { describe('Logged in User', () => { it('throws an unauthorized error if the request user does not have the MANAGE_PRACTITIONER_USERS permissions', async () => { - applicationContext.getCurrentUser.mockReturnValue( - new User({ - name: 'Test Petitioner', - role: ROLES.petitioner, - userId: '1005d1ab-18d0-43ec-bafb-654e83405416', - }), - ); - await expect( - getPractitionerByBarNumberInteractor(applicationContext, { - barNumber: 'BN0000', - }), + getPractitionerByBarNumberInteractor( + applicationContext, + { + barNumber: 'BN0000', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized for getting attorney user'); }); it('calls the persistence method to get a private practitioner with the given bar number', async () => { - applicationContext.getCurrentUser.mockReturnValue( - new User({ - name: 'Test Petitionsclerk', - role: ROLES.petitionsClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }), - ); applicationContext .getPersistenceGateway() .getPractitionerByBarNumber.mockReturnValue({ @@ -58,6 +50,7 @@ describe('getPractitionerByBarNumberInteractor', () => { { barNumber: 'PP1234', }, + mockPetitionsClerkUser, ); expect(practitioner).toEqual({ @@ -89,13 +82,6 @@ describe('getPractitionerByBarNumberInteractor', () => { }); it('calls the persistence method to get an IRS practitioner with the given bar number', async () => { - applicationContext.getCurrentUser.mockReturnValue( - new User({ - name: 'Test Petitionsclerk', - role: ROLES.petitionsClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }), - ); applicationContext .getPersistenceGateway() .getPractitionerByBarNumber.mockReturnValue({ @@ -120,6 +106,7 @@ describe('getPractitionerByBarNumberInteractor', () => { { barNumber: 'PI5678', }, + mockPetitionsClerkUser, ); expect(practitioner).toEqual({ @@ -149,13 +136,6 @@ describe('getPractitionerByBarNumberInteractor', () => { }); it('throws a not found error if no practitioner is found with the given bar number', async () => { - applicationContext.getCurrentUser.mockReturnValue( - new User({ - name: 'Test Petitionsclerk', - role: ROLES.petitionsClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }), - ); applicationContext .getPersistenceGateway() .getPractitionerByBarNumber.mockReturnValue(undefined); @@ -165,6 +145,7 @@ describe('getPractitionerByBarNumberInteractor', () => { { barNumber: 'BN0000', }, + mockPetitionsClerkUser, ); expect(practitioner).toBeUndefined(); @@ -173,8 +154,6 @@ describe('getPractitionerByBarNumberInteractor', () => { describe('Public User', () => { beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(undefined); - applicationContext .getPersistenceGateway() .getPractitionerByBarNumber.mockReturnValue({ @@ -197,26 +176,24 @@ describe('getPractitionerByBarNumberInteractor', () => { }); it('should not throw an error when a public user access interactor', async () => { - applicationContext.getCurrentUser.mockReturnValue(undefined); - const results = await getPractitionerByBarNumberInteractor( applicationContext, { barNumber: 'BN0000', }, + undefined, ); expect(results).toBeDefined(); }); it('should return an array with Practitioner result', async () => { - applicationContext.getCurrentUser.mockReturnValue(undefined); - const results = await getPractitionerByBarNumberInteractor( applicationContext, { barNumber: 'BN0000', }, + undefined, ); expect(results).toEqual([ diff --git a/web-api/src/business/useCases/practitioner/getPractitionerByBarNumberInteractor.ts b/web-api/src/business/useCases/practitioner/getPractitionerByBarNumberInteractor.ts index c0b39a1d720..1c4a920d2a4 100644 --- a/web-api/src/business/useCases/practitioner/getPractitionerByBarNumberInteractor.ts +++ b/web-api/src/business/useCases/practitioner/getPractitionerByBarNumberInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * getPractitionerByBarNumberInteractor @@ -17,13 +18,13 @@ import { UnauthorizedError } from '@web-api/errors/errors'; export const getPractitionerByBarNumberInteractor = async ( applicationContext: ServerApplicationContext, { barNumber }: { barNumber: string }, + authorizedUser: UnknownAuthUser, ) => { - const requestUser = applicationContext.getCurrentUser(); - const isLoggedInUser = !!requestUser?.userId; + const isLoggedInUser = !!authorizedUser?.userId; if ( isLoggedInUser && - !isAuthorized(requestUser, ROLE_PERMISSIONS.MANAGE_PRACTITIONER_USERS) + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.MANAGE_PRACTITIONER_USERS) ) { throw new UnauthorizedError('Unauthorized for getting attorney user'); } diff --git a/web-api/src/business/useCases/practitioner/getPractitionerDocumentDownloadUrlInteractor.test.ts b/web-api/src/business/useCases/practitioner/getPractitionerDocumentDownloadUrlInteractor.test.ts index 22b4a42c4b4..1b420312181 100644 --- a/web-api/src/business/useCases/practitioner/getPractitionerDocumentDownloadUrlInteractor.test.ts +++ b/web-api/src/business/useCases/practitioner/getPractitionerDocumentDownloadUrlInteractor.test.ts @@ -1,10 +1,12 @@ -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getPractitionerDocumentDownloadUrlInteractor } from './getPractitionerDocumentDownloadUrlInteractor'; +import { + mockAdmissionsClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getPractitionerDocumentDownloadUrlInteractor', () => { - let testUser; const mockDocumentMetadata = { categoryName: 'Application', categoryType: 'Application', @@ -25,30 +27,20 @@ describe('getPractitionerDocumentDownloadUrlInteractor', () => { }); it('should throw an unauthorized error when the user does not have permission to download the practitioner documentation file', async () => { - testUser = { - role: ROLES.petitioner, - userId: 'petitioner', - }; - - applicationContext.getCurrentUser.mockImplementation(() => testUser); - await expect( - getPractitionerDocumentDownloadUrlInteractor(applicationContext, { - barNumber: mockPractitioner.barNumber, - practitionerDocumentFileId: - mockDocumentMetadata.practitionerDocumentFileId, - }), + getPractitionerDocumentDownloadUrlInteractor( + applicationContext, + { + barNumber: mockPractitioner.barNumber, + practitionerDocumentFileId: + mockDocumentMetadata.practitionerDocumentFileId, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); it('should not throw an unauthorized error when the user has permission to download the practitioner documentation file', async () => { - testUser = { - role: ROLES.admissionsClerk, - userId: 'admissionsclerk', - }; - - applicationContext.getCurrentUser.mockImplementation(() => testUser); - const results = await getPractitionerDocumentDownloadUrlInteractor( applicationContext, { @@ -56,6 +48,7 @@ describe('getPractitionerDocumentDownloadUrlInteractor', () => { practitionerDocumentFileId: mockDocumentMetadata.practitionerDocumentFileId, }, + mockAdmissionsClerkUser, ); expect(results).toMatchObject({ url: expect.any(String), diff --git a/web-api/src/business/useCases/practitioner/getPractitionerDocumentDownloadUrlInteractor.ts b/web-api/src/business/useCases/practitioner/getPractitionerDocumentDownloadUrlInteractor.ts index e9bcf09ec7b..77f15ac7e51 100644 --- a/web-api/src/business/useCases/practitioner/getPractitionerDocumentDownloadUrlInteractor.ts +++ b/web-api/src/business/useCases/practitioner/getPractitionerDocumentDownloadUrlInteractor.ts @@ -4,6 +4,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * @@ -21,10 +22,11 @@ export const getPractitionerDocumentDownloadUrlInteractor = async ( barNumber: string; practitionerDocumentFileId: string; }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.UPLOAD_PRACTITIONER_DOCUMENT)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.UPLOAD_PRACTITIONER_DOCUMENT) + ) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/practitioner/getPractitionerDocumentInteractor.test.ts b/web-api/src/business/useCases/practitioner/getPractitionerDocumentInteractor.test.ts index 0c100a87866..87a6726bfed 100644 --- a/web-api/src/business/useCases/practitioner/getPractitionerDocumentInteractor.test.ts +++ b/web-api/src/business/useCases/practitioner/getPractitionerDocumentInteractor.test.ts @@ -1,16 +1,13 @@ -import { - PRACTITIONER_DOCUMENT_TYPES_MAP, - ROLES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { PRACTITIONER_DOCUMENT_TYPES_MAP } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getPractitionerDocumentInteractor } from './getPractitionerDocumentInteractor'; +import { + mockAdmissionsClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getPractitionerDocumentInteractor', () => { - const testUser = { - role: ROLES.admissionsClerk, - userId: 'admissionsclerk', - }; const barNumber = 'PT4785'; const practitionerDocumentFileId = '14c373ff-3335-400d-8b39-3e4053072512'; const practitionerDocument = { @@ -20,24 +17,21 @@ describe('getPractitionerDocumentInteractor', () => { }; beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(testUser); applicationContext .getPersistenceGateway() .getPractitionerDocumentByFileId.mockReturnValue(practitionerDocument); }); it('should throw an unauthorized error when the user does not have permission to update the practitioner user', async () => { - const testPetitionerUser = { - role: ROLES.petitioner, - userId: 'petitioner', - }; - applicationContext.getCurrentUser.mockReturnValueOnce(testPetitionerUser); - await expect( - getPractitionerDocumentInteractor(applicationContext, { - barNumber, - practitionerDocumentFileId, - }), + getPractitionerDocumentInteractor( + applicationContext, + { + barNumber, + practitionerDocumentFileId, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -48,6 +42,7 @@ describe('getPractitionerDocumentInteractor', () => { barNumber, practitionerDocumentFileId, }, + mockAdmissionsClerkUser, ); expect( diff --git a/web-api/src/business/useCases/practitioner/getPractitionerDocumentInteractor.ts b/web-api/src/business/useCases/practitioner/getPractitionerDocumentInteractor.ts index 02ebaaef34f..2ad52fe141f 100644 --- a/web-api/src/business/useCases/practitioner/getPractitionerDocumentInteractor.ts +++ b/web-api/src/business/useCases/practitioner/getPractitionerDocumentInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * @@ -23,10 +24,11 @@ export const getPractitionerDocumentInteractor = async ( barNumber: string; practitionerDocumentFileId: string; }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.UPLOAD_PRACTITIONER_DOCUMENT)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.UPLOAD_PRACTITIONER_DOCUMENT) + ) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/practitioner/getPractitionerDocumentsInteractor.test.ts b/web-api/src/business/useCases/practitioner/getPractitionerDocumentsInteractor.test.ts index e36dbadbbe7..ce363ebce23 100644 --- a/web-api/src/business/useCases/practitioner/getPractitionerDocumentsInteractor.test.ts +++ b/web-api/src/business/useCases/practitioner/getPractitionerDocumentsInteractor.test.ts @@ -1,34 +1,24 @@ -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getPractitionerDocumentsInteractor } from './getPractitionerDocumentsInteractor'; +import { + mockAdmissionsClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getPractitionersDocumentsInteractor', () => { - beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'admissionsClerk', - }); - }); - it('throws an unauthorized error exception when user is not an admissions clerk', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: 'petitioner', - }); - await expect( - getPractitionerDocumentsInteractor(applicationContext, { - barNumber: 'PT1234', - }), + getPractitionerDocumentsInteractor( + applicationContext, + { + barNumber: 'PT1234', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized for getting practitioner documents'); }); it('returns and validates the documents returned from persistence', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.admissionsClerk, - userId: 'bob', - }); - applicationContext .getPersistenceGateway() .getPractitionerDocuments.mockResolvedValue([ @@ -47,6 +37,7 @@ describe('getPractitionersDocumentsInteractor', () => { { barNumber: 'PT1234', }, + mockAdmissionsClerkUser, ); expect(documents.length).toEqual(1); diff --git a/web-api/src/business/useCases/practitioner/getPractitionerDocumentsInteractor.ts b/web-api/src/business/useCases/practitioner/getPractitionerDocumentsInteractor.ts index d632a9b8ddd..c40e6616a34 100644 --- a/web-api/src/business/useCases/practitioner/getPractitionerDocumentsInteractor.ts +++ b/web-api/src/business/useCases/practitioner/getPractitionerDocumentsInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * getPractitionerDocumentsInteractor @@ -21,11 +22,10 @@ export const getPractitionerDocumentsInteractor = async ( }: { barNumber: string; }, + authorizedUser: UnknownAuthUser, ) => { - const requestUser = applicationContext.getCurrentUser(); - if ( - !isAuthorized(requestUser, ROLE_PERMISSIONS.UPLOAD_PRACTITIONER_DOCUMENT) + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.UPLOAD_PRACTITIONER_DOCUMENT) ) { throw new UnauthorizedError( 'Unauthorized for getting practitioner documents', diff --git a/web-api/src/business/useCases/practitioner/getPractitionersByNameInteractor.test.ts b/web-api/src/business/useCases/practitioner/getPractitionersByNameInteractor.test.ts index ce19ea02ee5..eff6fdb8899 100644 --- a/web-api/src/business/useCases/practitioner/getPractitionersByNameInteractor.test.ts +++ b/web-api/src/business/useCases/practitioner/getPractitionersByNameInteractor.test.ts @@ -1,26 +1,19 @@ import { ROLES } from '@shared/business/entities/EntityConstants'; import { applicationContext } from '@shared/business/test/createTestApplicationContext'; import { getPractitionersByNameInteractor } from './getPractitionersByNameInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('getPractitionersByNameInteractor', () => { describe('Logged in User', () => { - beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'petitionsClerk', - }); - }); - it('returns an unauthorized error on petitioner user role', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: 'petitioner', - }); - await expect( getPractitionersByNameInteractor( applicationContext, {} as { name: string; searchAfter: string }, + mockPetitionerUser, ), ).rejects.toThrow('Unauthorized for searching practitioners'); }); @@ -30,6 +23,7 @@ describe('getPractitionersByNameInteractor', () => { getPractitionersByNameInteractor( applicationContext, {} as { name: string; searchAfter: string }, + mockPetitionsClerkUser, ), ).rejects.toThrow('Name must be provided to search'); }); @@ -64,6 +58,7 @@ describe('getPractitionersByNameInteractor', () => { name: 'Test Practitioner', searchAfter: undefined as unknown as string, }, + mockPetitionsClerkUser, ); expect(results).toMatchObject({ @@ -89,8 +84,6 @@ describe('getPractitionersByNameInteractor', () => { describe('Public User', () => { beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(undefined); - applicationContext .getPersistenceGateway() .getPractitionersByName.mockReturnValue({ @@ -124,6 +117,7 @@ describe('getPractitionersByNameInteractor', () => { name: 'Test Practitioner', searchAfter: undefined as unknown as string, }, + mockPetitionsClerkUser, ); expect(results).toBeDefined(); @@ -136,6 +130,7 @@ describe('getPractitionersByNameInteractor', () => { name: 'Test Practitioner', searchAfter: undefined as unknown as string, }, + undefined, ); expect(results).toMatchObject({ diff --git a/web-api/src/business/useCases/practitioner/getPractitionersByNameInteractor.ts b/web-api/src/business/useCases/practitioner/getPractitionersByNameInteractor.ts index 96306f21023..36fd3bf93d2 100644 --- a/web-api/src/business/useCases/practitioner/getPractitionersByNameInteractor.ts +++ b/web-api/src/business/useCases/practitioner/getPractitionersByNameInteractor.ts @@ -4,6 +4,7 @@ import { } from '@shared/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export type PractitionersByName = { searchResults: { @@ -26,13 +27,13 @@ export type PractitionersByName = { export const getPractitionersByNameInteractor = async ( applicationContext: ServerApplicationContext, { name, searchAfter }: { name: string; searchAfter: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const authenticatedUser = applicationContext.getCurrentUser(); - const isLoggedInUser = !!authenticatedUser?.userId; + const isLoggedInUser = !!authorizedUser?.userId; if ( isLoggedInUser && - !isAuthorized(authenticatedUser, ROLE_PERMISSIONS.MANAGE_PRACTITIONER_USERS) + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.MANAGE_PRACTITIONER_USERS) ) { throw new UnauthorizedError('Unauthorized for searching practitioners'); } diff --git a/web-api/src/business/useCases/practitioner/updatePractitionerUserInteractor.locking.test.ts b/web-api/src/business/useCases/practitioner/updatePractitionerUserInteractor.locking.test.ts index 47c4d0627ca..06af9bf8b69 100644 --- a/web-api/src/business/useCases/practitioner/updatePractitionerUserInteractor.locking.test.ts +++ b/web-api/src/business/useCases/practitioner/updatePractitionerUserInteractor.locking.test.ts @@ -12,6 +12,7 @@ import { handleLockError, updatePractitionerUserInteractor, } from './updatePractitionerUserInteractor'; +import { mockAdmissionsClerkUser } from '@shared/test/mockAuthUsers'; describe('determineEntitiesToLock', () => { const mockPractitioner: RawPractitioner = MOCK_PRACTITIONER; @@ -55,17 +56,16 @@ describe('handleLockError', () => { .getUserById.mockReturnValue(admissionsClerkUser); }); - it('should determine who the user is based on applicationContext', async () => { - await handleLockError(applicationContext, { foo: 'bar' }); - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); - }); - it('should send a notification to the user with "retry_async_request" and the originalRequest', async () => { const mockOriginalRequest = { clientConnectionId: mockClientConnectionId, foo: 'bar', }; - await handleLockError(applicationContext, mockOriginalRequest); + await handleLockError( + applicationContext, + mockOriginalRequest, + mockAdmissionsClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock .calls[0][0].message, @@ -101,7 +101,6 @@ describe('updatePractitionerUserInteractor', () => { beforeEach(() => { mockLock = undefined; // unlocked - applicationContext.getCurrentUser.mockReturnValue(admissionsClerkUser); applicationContext .getPersistenceGateway() @@ -119,7 +118,11 @@ describe('updatePractitionerUserInteractor', () => { it('should throw a ServiceUnavailableError if a Case is currently locked', async () => { await expect( - updatePractitionerUserInteractor(applicationContext, mockRequest), + updatePractitionerUserInteractor( + applicationContext, + mockRequest, + mockAdmissionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -129,7 +132,11 @@ describe('updatePractitionerUserInteractor', () => { it('should return a "retry_async_request" notification with the original request', async () => { await expect( - updatePractitionerUserInteractor(applicationContext, mockRequest), + updatePractitionerUserInteractor( + applicationContext, + mockRequest, + mockAdmissionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -141,7 +148,7 @@ describe('updatePractitionerUserInteractor', () => { originalRequest: mockRequest, requestToRetry: 'update_practitioner_user', }, - userId: admissionsClerkUser.userId, + userId: mockAdmissionsClerkUser.userId, }); expect( @@ -156,7 +163,11 @@ describe('updatePractitionerUserInteractor', () => { }); it('should acquire a lock that lasts for 15 minutes', async () => { - await updatePractitionerUserInteractor(applicationContext, mockRequest); + await updatePractitionerUserInteractor( + applicationContext, + mockRequest, + mockAdmissionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -167,7 +178,11 @@ describe('updatePractitionerUserInteractor', () => { }); }); it('should remove the lock', async () => { - await updatePractitionerUserInteractor(applicationContext, mockRequest); + await updatePractitionerUserInteractor( + applicationContext, + mockRequest, + mockAdmissionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().removeLock, diff --git a/web-api/src/business/useCases/practitioner/updatePractitionerUserInteractor.test.ts b/web-api/src/business/useCases/practitioner/updatePractitionerUserInteractor.test.ts index 6b606ea066d..a9b29981577 100644 --- a/web-api/src/business/useCases/practitioner/updatePractitionerUserInteractor.test.ts +++ b/web-api/src/business/useCases/practitioner/updatePractitionerUserInteractor.test.ts @@ -1,29 +1,24 @@ import { MOCK_PRACTITIONER } from '../../../../../shared/src/test/mockUsers'; import { NotFoundError, UnauthorizedError } from '@web-api/errors/errors'; -import { - ROLES, - SERVICE_INDICATOR_TYPES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { SERVICE_INDICATOR_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { generateChangeOfAddress } from '@web-api/business/useCases/user/generateChangeOfAddress'; +import { + mockAdmissionsClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { updatePractitionerUserInteractor } from './updatePractitionerUserInteractor'; jest.mock('@web-api/business/useCases/user/generateChangeOfAddress'); describe('updatePractitionerUserInteractor', () => { - let testUser; let mockPractitioner = MOCK_PRACTITIONER; beforeEach(() => { - testUser = { - role: ROLES.admissionsClerk, - userId: 'admissionsclerk', - }; mockPractitioner = { ...MOCK_PRACTITIONER }; applicationContext .getPersistenceGateway() .getDocketNumbersByUser.mockReturnValue(['123-23']); - applicationContext.getCurrentUser.mockImplementation(() => testUser); applicationContext .getPersistenceGateway() .getPractitionerByBarNumber.mockImplementation(() => mockPractitioner); @@ -39,16 +34,15 @@ describe('updatePractitionerUserInteractor', () => { }); it('should throw an unauthorized error when the user does not have permission to update the practitioner user', async () => { - testUser = { - role: ROLES.petitioner, - userId: 'petitioner', - }; - await expect( - updatePractitionerUserInteractor(applicationContext, { - barNumber: 'pt101', - user: mockPractitioner, - }), + updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'pt101', + user: mockPractitioner, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -58,16 +52,20 @@ describe('updatePractitionerUserInteractor', () => { .getPractitionerByBarNumber.mockResolvedValue(undefined); await expect( - updatePractitionerUserInteractor(applicationContext, { - barNumber: 'AB1111', - bypassDocketEntry: false, - user: { - ...mockPractitioner, + updatePractitionerUserInteractor( + applicationContext, + { barNumber: 'AB1111', - updatedEmail: 'bc@example.com', - userId: '9ea9732c-9751-4159-9619-bd27556eb9bc', + bypassDocketEntry: false, + user: { + ...mockPractitioner, + barNumber: 'AB1111', + updatedEmail: 'bc@example.com', + userId: '9ea9732c-9751-4159-9619-bd27556eb9bc', + }, }, - }), + mockAdmissionsClerkUser, + ), ).rejects.toThrow(NotFoundError); }); @@ -80,16 +78,20 @@ describe('updatePractitionerUserInteractor', () => { }); await expect( - updatePractitionerUserInteractor(applicationContext, { - barNumber: 'AB1111', - bypassDocketEntry: false, - user: { - ...mockPractitioner, + updatePractitionerUserInteractor( + applicationContext, + { barNumber: 'AB1111', - updatedEmail: 'bc@example.com', - userId: '9ea9732c-9751-4159-9619-bd27556eb9bc', + bypassDocketEntry: false, + user: { + ...mockPractitioner, + barNumber: 'AB1111', + updatedEmail: 'bc@example.com', + userId: '9ea9732c-9751-4159-9619-bd27556eb9bc', + }, }, - }), + mockAdmissionsClerkUser, + ), ).rejects.toThrow('Bar number does not match user data.'); }); @@ -100,15 +102,19 @@ describe('updatePractitionerUserInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await updatePractitionerUserInteractor(applicationContext, { - barNumber: 'AB1111', - user: { - ...mockPractitioner, - barNumber: 'AB2222', - confirmEmail: 'bc@example.com', - updatedEmail: 'bc@example.com', + await updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'AB1111', + user: { + ...mockPractitioner, + barNumber: 'AB2222', + confirmEmail: 'bc@example.com', + updatedEmail: 'bc@example.com', + }, }, - }); + mockAdmissionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createNewPractitionerUser.mock @@ -119,15 +125,19 @@ describe('updatePractitionerUserInteractor', () => { }); it('updates the practitioner user and does NOT override a bar number or email when the original user had an email', async () => { - await updatePractitionerUserInteractor(applicationContext, { - barNumber: 'AB1111', - user: { - ...mockPractitioner, - barNumber: 'AB2222', - confirmEmail: 'bc@example.com', - updatedEmail: 'bc@example.com', + await updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'AB1111', + user: { + ...mockPractitioner, + barNumber: 'AB2222', + confirmEmail: 'bc@example.com', + updatedEmail: 'bc@example.com', + }, }, - }); + mockAdmissionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().updatePractitionerUser, @@ -142,15 +152,19 @@ describe('updatePractitionerUserInteractor', () => { mockPractitioner.email = undefined; mockPractitioner.pendingEmail = 'pendingEmail@example.com'; - await updatePractitionerUserInteractor(applicationContext, { - barNumber: 'AB1111', - user: { - ...mockPractitioner, - barNumber: 'AB2222', - confirmEmail: 'bc@example.com', - updatedEmail: 'bc@example.com', + await updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'AB1111', + user: { + ...mockPractitioner, + barNumber: 'AB2222', + confirmEmail: 'bc@example.com', + updatedEmail: 'bc@example.com', + }, }, - }); + mockAdmissionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().updatePractitionerUser, @@ -169,14 +183,18 @@ describe('updatePractitionerUserInteractor', () => { email: undefined, }); - await updatePractitionerUserInteractor(applicationContext, { - barNumber: 'AB1111', - user: { - ...mockPractitioner, - confirmEmail: 'admissionsclerk@example.com', - updatedEmail: 'admissionsclerk@example.com', + await updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'AB1111', + user: { + ...mockPractitioner, + confirmEmail: 'admissionsclerk@example.com', + updatedEmail: 'admissionsclerk@example.com', + }, }, - }); + mockAdmissionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createNewPractitionerUser, @@ -195,14 +213,18 @@ describe('updatePractitionerUserInteractor', () => { email: undefined, }); - await updatePractitionerUserInteractor(applicationContext, { - barNumber: 'AB1111', - user: { - ...mockPractitioner, - email: undefined, - firstName: 'Donna', + await updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'AB1111', + user: { + ...mockPractitioner, + email: undefined, + firstName: 'Donna', + }, }, - }); + mockAdmissionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateUserRecords.mock @@ -219,16 +241,15 @@ describe('updatePractitionerUserInteractor', () => { describe('updating email', () => { it('should throw unauthorized error when the logged in user does not have permission to manage emails', async () => { - testUser = { - role: ROLES.petitioner, - userId: 'f7d90c05-f6cd-442c-a168-202db587f16f', - }; - await expect( - updatePractitionerUserInteractor(applicationContext, { - barNumber: 'pt101', - user: mockPractitioner, - }), + updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'pt101', + user: mockPractitioner, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized for updating practitioner user'); }); @@ -238,26 +259,34 @@ describe('updatePractitionerUserInteractor', () => { .isEmailAvailable.mockReturnValue(false); await expect( - updatePractitionerUserInteractor(applicationContext, { - barNumber: 'pt101', - user: { - ...mockPractitioner, - confirmEmail: 'exists@example.com', - updatedEmail: 'exists@example.com', + updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'pt101', + user: { + ...mockPractitioner, + confirmEmail: 'exists@example.com', + updatedEmail: 'exists@example.com', + }, }, - }), + mockAdmissionsClerkUser, + ), ).rejects.toThrow('Email is not available'); }); it('should update the user with the new user.updatedEmail value', async () => { - await updatePractitionerUserInteractor(applicationContext, { - barNumber: 'pt101', - user: { - ...mockPractitioner, - confirmEmail: 'free-email-to-use@example.com', - updatedEmail: 'free-email-to-use@example.com', + await updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'pt101', + user: { + ...mockPractitioner, + confirmEmail: 'free-email-to-use@example.com', + updatedEmail: 'free-email-to-use@example.com', + }, }, - }); + mockAdmissionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().updatePractitionerUser.mock @@ -269,14 +298,18 @@ describe('updatePractitionerUserInteractor', () => { }); it("should send the verification email when the user's email is being changed", async () => { - await updatePractitionerUserInteractor(applicationContext, { - barNumber: 'pt101', - user: { - ...mockPractitioner, - confirmEmail: 'free-email-to-use@example.com', - updatedEmail: 'free-email-to-use@example.com', + await updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'pt101', + user: { + ...mockPractitioner, + confirmEmail: 'free-email-to-use@example.com', + updatedEmail: 'free-email-to-use@example.com', + }, }, - }); + mockAdmissionsClerkUser, + ); expect( applicationContext.getUseCaseHelpers().sendEmailVerificationLink.mock @@ -289,14 +322,18 @@ describe('updatePractitionerUserInteractor', () => { it("should NOT send the verification email when the user's email is being added for the first time", async () => { mockPractitioner.email = undefined; - await updatePractitionerUserInteractor(applicationContext, { - barNumber: 'pt101', - user: { - ...mockPractitioner, - confirmEmail: 'free-email-to-use@example.com', - updatedEmail: 'free-email-to-use@example.com', + await updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'pt101', + user: { + ...mockPractitioner, + confirmEmail: 'free-email-to-use@example.com', + updatedEmail: 'free-email-to-use@example.com', + }, }, - }); + mockAdmissionsClerkUser, + ); expect( applicationContext.getUseCaseHelpers().sendEmailVerificationLink, @@ -304,72 +341,92 @@ describe('updatePractitionerUserInteractor', () => { }); it('should NOT call generateChangeOfAddress if ONLY the email is being updated', async () => { - await updatePractitionerUserInteractor(applicationContext, { - barNumber: 'pt101', - user: { - ...mockPractitioner, - confirmEmail: 'free-email-to-use@example.com', - updatedEmail: 'free-email-to-use@example.com', + await updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'pt101', + user: { + ...mockPractitioner, + confirmEmail: 'free-email-to-use@example.com', + updatedEmail: 'free-email-to-use@example.com', + }, }, - }); + mockAdmissionsClerkUser, + ); expect(generateChangeOfAddress).not.toHaveBeenCalled(); }); it('should NOT call generateChangeOfAddress if ONLY the notes are being updated', async () => { - await updatePractitionerUserInteractor(applicationContext, { - barNumber: 'pt101', - user: { - ...mockPractitioner, - practitionerNotes: 'wow, real good notes', + await updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'pt101', + user: { + ...mockPractitioner, + practitionerNotes: 'wow, real good notes', + }, }, - }); + mockAdmissionsClerkUser, + ); expect(generateChangeOfAddress).not.toHaveBeenCalled(); }); it('should NOT call generateChangeOfAddress if ONLY the notes and email are being updated', async () => { - await updatePractitionerUserInteractor(applicationContext, { - barNumber: 'pt101', - user: { - ...mockPractitioner, - confirmEmail: 'free-email-to-use@example.com', - practitionerNotes: 'wow, real good notes', - updatedEmail: 'free-email-to-use@example.com', + await updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'pt101', + user: { + ...mockPractitioner, + confirmEmail: 'free-email-to-use@example.com', + practitionerNotes: 'wow, real good notes', + updatedEmail: 'free-email-to-use@example.com', + }, }, - }); + mockAdmissionsClerkUser, + ); expect(generateChangeOfAddress).not.toHaveBeenCalled(); }); it('should call generateChangeOfAddress if the email is being updated along with the address1', async () => { - await updatePractitionerUserInteractor(applicationContext, { - barNumber: 'pt101', - user: { - ...mockPractitioner, - confirmEmail: 'free-email-to-use@example.com', - contact: { - ...mockPractitioner.contact!, - address1: 'yeahhhhh', + await updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'pt101', + user: { + ...mockPractitioner, + confirmEmail: 'free-email-to-use@example.com', + contact: { + ...mockPractitioner.contact!, + address1: 'yeahhhhh', + }, + updatedEmail: 'free-email-to-use@example.com', }, - updatedEmail: 'free-email-to-use@example.com', }, - }); + mockAdmissionsClerkUser, + ); expect(generateChangeOfAddress).toHaveBeenCalled(); }); it('should call generateChangeOfAddress if the email is being updated along with the practitioner name', async () => { - await updatePractitionerUserInteractor(applicationContext, { - barNumber: 'pt101', - user: { - ...mockPractitioner, - confirmEmail: 'free-email-to-use@example.com', - firstName: 'Helen', - lastName: 'Hunt', - updatedEmail: 'free-email-to-use@example.com', + await updatePractitionerUserInteractor( + applicationContext, + { + barNumber: 'pt101', + user: { + ...mockPractitioner, + confirmEmail: 'free-email-to-use@example.com', + firstName: 'Helen', + lastName: 'Hunt', + updatedEmail: 'free-email-to-use@example.com', + }, }, - }); + mockAdmissionsClerkUser, + ); expect(generateChangeOfAddress).toHaveBeenCalled(); }); diff --git a/web-api/src/business/useCases/practitioner/updatePractitionerUserInteractor.ts b/web-api/src/business/useCases/practitioner/updatePractitionerUserInteractor.ts index 5c330b1e317..d8e80f6e031 100644 --- a/web-api/src/business/useCases/practitioner/updatePractitionerUserInteractor.ts +++ b/web-api/src/business/useCases/practitioner/updatePractitionerUserInteractor.ts @@ -8,6 +8,7 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { generateChangeOfAddress } from '../user/generateChangeOfAddress'; import { omit, union } from 'lodash'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; @@ -19,12 +20,14 @@ export const updatePractitionerUser = async ( bypassDocketEntry = false, user, }: { barNumber: string; bypassDocketEntry?: boolean; user: RawPractitioner }, + authorizedUser: UnknownAuthUser, ): Promise => { - const requestUser = applicationContext.getCurrentUser(); - if ( - !isAuthorized(requestUser, ROLE_PERMISSIONS.ADD_EDIT_PRACTITIONER_USER) || - !isAuthorized(requestUser, ROLE_PERMISSIONS.EMAIL_MANAGEMENT) + !isAuthorized( + authorizedUser, + ROLE_PERMISSIONS.ADD_EDIT_PRACTITIONER_USER, + ) || + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.EMAIL_MANAGEMENT) ) { throw new UnauthorizedError('Unauthorized for updating practitioner user'); } @@ -95,7 +98,7 @@ export const updatePractitionerUser = async ( message: { action: 'admin_contact_initial_update_complete', }, - userId: requestUser.userId, + userId: authorizedUser.userId, }); if (userHasAccount && userIsUpdatingEmail) { @@ -125,10 +128,11 @@ export const updatePractitionerUser = async ( if (combinedDiffKeys.length > propertiesNotRequiringChangeOfAddress.length) { await generateChangeOfAddress({ applicationContext, + authorizedUser, bypassDocketEntry, contactInfo: validatedUserData.contact, firmName: validatedUserData.firmName, - requestUserId: requestUser.userId, + requestUserId: authorizedUser.userId, updatedEmail: validatedUserData.email, updatedName: validatedUserData.name, user: oldUser, @@ -140,7 +144,7 @@ export const updatePractitionerUser = async ( message: { action: 'admin_contact_full_update_complete', }, - userId: requestUser.userId, + userId: authorizedUser.userId, }); } }; @@ -203,19 +207,20 @@ const getUpdatedFieldNames = ({ export const handleLockError = async ( applicationContext: ServerApplicationContext, originalRequest: any, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - await applicationContext.getNotificationGateway().sendNotificationToUser({ - applicationContext, - clientConnectionId: originalRequest.clientConnectionId, - message: { - action: 'retry_async_request', - originalRequest, - requestToRetry: 'update_practitioner_user', - }, - userId: user.userId, - }); + if (authorizedUser?.userId) { + await applicationContext.getNotificationGateway().sendNotificationToUser({ + applicationContext, + clientConnectionId: originalRequest.clientConnectionId, + message: { + action: 'retry_async_request', + originalRequest, + requestToRetry: 'update_practitioner_user', + }, + userId: authorizedUser?.userId, + }); + } }; export const determineEntitiesToLock = async ( diff --git a/web-api/src/business/useCases/public/getCaseForPublicDocketSearchInteractor.ts b/web-api/src/business/useCases/public/getCaseForPublicDocketSearchInteractor.ts index a4942cf199a..7b7e4c54f4c 100644 --- a/web-api/src/business/useCases/public/getCaseForPublicDocketSearchInteractor.ts +++ b/web-api/src/business/useCases/public/getCaseForPublicDocketSearchInteractor.ts @@ -39,7 +39,7 @@ export const getCaseForPublicDocketSearchInteractor = async ( throw error; } else { caseDetailRaw = new PublicCase(caseRecord, { - applicationContext, + authorizedUser: undefined, }) .validate() .toRawObject(); diff --git a/web-api/src/business/useCases/public/getJudgesForPublicSearchInteractor.ts b/web-api/src/business/useCases/public/getJudgesForPublicSearchInteractor.ts index a9a6fa83029..ea0f136186b 100644 --- a/web-api/src/business/useCases/public/getJudgesForPublicSearchInteractor.ts +++ b/web-api/src/business/useCases/public/getJudgesForPublicSearchInteractor.ts @@ -18,5 +18,5 @@ export const getJudgesForPublicSearchInteractor = async ( section: ROLES.judge, }); - return PublicUser.validateRawCollection(rawJudges, { applicationContext }); + return PublicUser.validateRawCollection(rawJudges); }; diff --git a/web-api/src/business/useCases/public/getPublicCaseInteractor.ts b/web-api/src/business/useCases/public/getPublicCaseInteractor.ts index 7ed3f47aadb..3cd11196916 100644 --- a/web-api/src/business/useCases/public/getPublicCaseInteractor.ts +++ b/web-api/src/business/useCases/public/getPublicCaseInteractor.ts @@ -28,5 +28,5 @@ export const getPublicCaseInteractor = async ( throw error; } - return formatPublicCase({ applicationContext, rawCaseRecord }); + return formatPublicCase({ rawCaseRecord }); }; diff --git a/web-api/src/business/useCases/public/getPublicDownloadPolicyUrlInteractor.test.ts b/web-api/src/business/useCases/public/getPublicDownloadPolicyUrlInteractor.test.ts index 6b37ac4543a..bd602a0d170 100644 --- a/web-api/src/business/useCases/public/getPublicDownloadPolicyUrlInteractor.test.ts +++ b/web-api/src/business/useCases/public/getPublicDownloadPolicyUrlInteractor.test.ts @@ -7,6 +7,7 @@ import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { cloneDeep } from 'lodash'; import { getPublicDownloadPolicyUrlInteractor } from './getPublicDownloadPolicyUrlInteractor'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('getPublicDownloadPolicyUrlInteractor', () => { let mockCase; @@ -27,11 +28,15 @@ describe('getPublicDownloadPolicyUrlInteractor', () => { jest.spyOn(DocketEntry, 'isPublic').mockReturnValueOnce(false); await expect( - getPublicDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: '123-20', - isTerminalUser: false, - key: '9de27a7d-7c6b-434b-803b-7655f82d5e07', - }), + getPublicDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: '123-20', + isTerminalUser: false, + key: '9de27a7d-7c6b-434b-803b-7655f82d5e07', + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Unauthorized to access private document'); }); @@ -43,6 +48,7 @@ describe('getPublicDownloadPolicyUrlInteractor', () => { isTerminalUser: true, key: '9de27a7d-7c6b-434b-803b-7655f82d5e07', }, + mockDocketClerkUser, ); expect( @@ -60,10 +66,14 @@ describe('getPublicDownloadPolicyUrlInteractor', () => { .getCaseByDocketNumber.mockReturnValue({ docketEntries: [] }); await expect( - getPublicDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: '123-20', - key: '9de27a7d-7c6b-434b-803b-7655f82d5e07', - } as any), + getPublicDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: '123-20', + key: '9de27a7d-7c6b-434b-803b-7655f82d5e07', + } as any, + mockDocketClerkUser, + ), ).rejects.toThrow('Case 123-20 was not found.'); }); @@ -86,14 +96,18 @@ describe('getPublicDownloadPolicyUrlInteractor', () => { isOnDocketRecord: true, servedAt: '2019-03-01T21:40:46.415Z', }, - { applicationContext }, + { authorizedUser: undefined }, ), ); await expect( - getPublicDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: '123-20', - key: '5a3ea70f-c539-4118-81a3-0be94be3b4f1', - } as any), + getPublicDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: '123-20', + key: '5a3ea70f-c539-4118-81a3-0be94be3b4f1', + } as any, + mockDocketClerkUser, + ), ).rejects.toThrow('Unauthorized to access documents in a sealed case'); }); @@ -117,7 +131,7 @@ describe('getPublicDownloadPolicyUrlInteractor', () => { processingStatus: DOCUMENT_PROCESSING_STATUS_OPTIONS.COMPLETE, servedAt: '2019-03-01T21:40:46.415Z', }, - { applicationContext }, + { authorizedUser: undefined }, ), ); const result = await getPublicDownloadPolicyUrlInteractor( @@ -126,6 +140,7 @@ describe('getPublicDownloadPolicyUrlInteractor', () => { docketNumber: '123-20', key: '83813a24-7687-418e-a186-c416b4bb0ad4', } as any, + mockDocketClerkUser, ); expect(result).toEqual({ url: 'localhost' }); }); @@ -143,7 +158,7 @@ describe('getPublicDownloadPolicyUrlInteractor', () => { processingStatus: DOCUMENT_PROCESSING_STATUS_OPTIONS.COMPLETE, servedAt: '2019-03-01T21:40:46.415Z', }, - { applicationContext }, + { authorizedUser: undefined }, ), ); @@ -153,16 +168,21 @@ describe('getPublicDownloadPolicyUrlInteractor', () => { docketNumber: '123-20', key: '8008b288-8b6b-48e3-8239-599266b13b8b', } as any, + mockDocketClerkUser, ); expect(result).toEqual({ url: 'localhost' }); }); it('should throw a not found error for a document that is not found on the case', async () => { await expect( - getPublicDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: '123-20', - key: 'b907f4e5-4d4d-44b3-bcfd-224a6f31d889', - } as any), + getPublicDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: '123-20', + key: 'b907f4e5-4d4d-44b3-bcfd-224a6f31d889', + } as any, + mockDocketClerkUser, + ), ).rejects.toThrow( 'Docket entry b907f4e5-4d4d-44b3-bcfd-224a6f31d889 was not found.', ); @@ -180,15 +200,19 @@ describe('getPublicDownloadPolicyUrlInteractor', () => { eventCode: 'RQT', isFileAttached: false, }, - { applicationContext }, + { authorizedUser: undefined }, ), ); await expect( - getPublicDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: '123-20', - key: '8205c4bc-879f-4648-a3ba-9280384c4c00', - } as any), + getPublicDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: '123-20', + key: '8205c4bc-879f-4648-a3ba-9280384c4c00', + } as any, + mockDocketClerkUser, + ), ).rejects.toThrow( 'Docket entry 8205c4bc-879f-4648-a3ba-9280384c4c00 does not have an attached file.', ); @@ -209,15 +233,19 @@ describe('getPublicDownloadPolicyUrlInteractor', () => { isSealed: true, sealedTo: DOCKET_ENTRY_SEALED_TO_TYPES.PUBLIC, }, - { applicationContext }, + { authorizedUser: undefined }, ), ); await expect( - getPublicDownloadPolicyUrlInteractor(applicationContext, { - docketNumber: '123-20', - key: '8205c4bc-879f-4648-a3ba-9280384c4c00', - } as any), + getPublicDownloadPolicyUrlInteractor( + applicationContext, + { + docketNumber: '123-20', + key: '8205c4bc-879f-4648-a3ba-9280384c4c00', + } as any, + mockDocketClerkUser, + ), ).rejects.toThrow('Docket entry has been sealed.'); }); }); diff --git a/web-api/src/business/useCases/public/getPublicDownloadPolicyUrlInteractor.ts b/web-api/src/business/useCases/public/getPublicDownloadPolicyUrlInteractor.ts index e363565e5ef..1178821ca82 100644 --- a/web-api/src/business/useCases/public/getPublicDownloadPolicyUrlInteractor.ts +++ b/web-api/src/business/useCases/public/getPublicDownloadPolicyUrlInteractor.ts @@ -9,6 +9,7 @@ import { import { DocketEntry } from '@shared/business/entities/DocketEntry'; import { NotFoundError, UnauthorizedError } from '@web-api/errors/errors'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const getPublicDownloadPolicyUrlInteractor = async ( applicationContext: ServerApplicationContext, @@ -17,6 +18,7 @@ export const getPublicDownloadPolicyUrlInteractor = async ( isTerminalUser, key, }: { docketNumber: string; isTerminalUser: boolean; key: string }, + authorizdeUser: UnknownAuthUser, ): Promise<{ url: string }> => { const caseToCheck: any = await applicationContext .getPersistenceGateway() @@ -29,7 +31,7 @@ export const getPublicDownloadPolicyUrlInteractor = async ( throw new NotFoundError(`Case ${docketNumber} was not found.`); } - const caseEntity = new Case(caseToCheck, { applicationContext }); + const caseEntity = new Case(caseToCheck, { authorizedUser: authorizdeUser }); const docketEntryEntity = caseEntity.getDocketEntryById({ docketEntryId: key, @@ -72,7 +74,6 @@ export const getPublicDownloadPolicyUrlInteractor = async ( isTerminalUser, rawCase: caseToCheck, user: { - name: '', role: ROLES.petitioner, userId: '', }, diff --git a/web-api/src/business/useCases/public/opinionPublicSearchInteractor.ts b/web-api/src/business/useCases/public/opinionPublicSearchInteractor.ts index ba4a91a7efd..10ece9c7aee 100644 --- a/web-api/src/business/useCases/public/opinionPublicSearchInteractor.ts +++ b/web-api/src/business/useCases/public/opinionPublicSearchInteractor.ts @@ -60,7 +60,5 @@ export const opinionPublicSearchInteractor = async ( const filteredResults = results.slice(0, MAX_SEARCH_RESULTS); - return PublicDocumentSearchResult.validateRawCollection(filteredResults, { - applicationContext, - }); + return PublicDocumentSearchResult.validateRawCollection(filteredResults); }; diff --git a/web-api/src/business/useCases/public/orderPublicSearchInteractor.ts b/web-api/src/business/useCases/public/orderPublicSearchInteractor.ts index 57270e18f34..62dba1059d5 100644 --- a/web-api/src/business/useCases/public/orderPublicSearchInteractor.ts +++ b/web-api/src/business/useCases/public/orderPublicSearchInteractor.ts @@ -61,7 +61,5 @@ export const orderPublicSearchInteractor = async ( const slicedResults = results.slice(0, MAX_SEARCH_RESULTS); - return PublicDocumentSearchResult.validateRawCollection(slicedResults, { - applicationContext, - }); + return PublicDocumentSearchResult.validateRawCollection(slicedResults); }; diff --git a/web-api/src/business/useCases/reports/coldCaseReportInteractor.test.ts b/web-api/src/business/useCases/reports/coldCaseReportInteractor.test.ts index a54b487baaa..8561e3e1903 100644 --- a/web-api/src/business/useCases/reports/coldCaseReportInteractor.test.ts +++ b/web-api/src/business/useCases/reports/coldCaseReportInteractor.test.ts @@ -1,7 +1,10 @@ import { ColdCaseEntry } from './coldCaseReportInteractor'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { coldCaseReportInteractor } from './coldCaseReportInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('coldCaseReportInteractor', () => { const mockColdCases: ColdCaseEntry[] = [ @@ -23,23 +26,16 @@ describe('coldCaseReportInteractor', () => { }); it('should throw an unauthorized error when the user does not have access', async () => { - applicationContext.getCurrentUser.mockImplementation(() => ({ - role: ROLES.petitioner, - userId: 'petitioner', - })); - - await expect(coldCaseReportInteractor(applicationContext)).rejects.toThrow( - 'Unauthorized', - ); + await expect( + coldCaseReportInteractor(applicationContext, mockPetitionerUser), + ).rejects.toThrow('Unauthorized'); }); it('should return the expected mocked data', async () => { - applicationContext.getCurrentUser.mockImplementation(() => ({ - role: ROLES.docketClerk, - userId: 'docketclerk', - })); - - const coldCases = await coldCaseReportInteractor(applicationContext); + const coldCases = await coldCaseReportInteractor( + applicationContext, + mockDocketClerkUser, + ); expect(coldCases).toEqual(mockColdCases); }); diff --git a/web-api/src/business/useCases/reports/coldCaseReportInteractor.ts b/web-api/src/business/useCases/reports/coldCaseReportInteractor.ts index efe812b0974..25280457cea 100644 --- a/web-api/src/business/useCases/reports/coldCaseReportInteractor.ts +++ b/web-api/src/business/useCases/reports/coldCaseReportInteractor.ts @@ -4,6 +4,7 @@ import { } from '@shared/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export type ColdCaseEntry = { createdAt: string; @@ -17,10 +18,9 @@ export type ColdCaseEntry = { export const coldCaseReportInteractor = async ( applicationContext: ServerApplicationContext, + authorizedUser: UnknownAuthUser, ): Promise => { - const requestUser = applicationContext.getCurrentUser(); - - if (!isAuthorized(requestUser, ROLE_PERMISSIONS.COLD_CASE_REPORT)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.COLD_CASE_REPORT)) { throw new UnauthorizedError( 'Unauthorized for viewing the cold case report data', ); diff --git a/web-api/src/business/useCases/serveCaseToIrs/generateDraftDocument.ts b/web-api/src/business/useCases/serveCaseToIrs/generateDraftDocument.ts index 8427a8c2ea9..12603dfbb5b 100644 --- a/web-api/src/business/useCases/serveCaseToIrs/generateDraftDocument.ts +++ b/web-api/src/business/useCases/serveCaseToIrs/generateDraftDocument.ts @@ -1,3 +1,4 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { Case } from '@shared/business/entities/cases/Case'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { replaceBracketed } from '../../../../../shared/src/business/utilities/replaceBracketed'; @@ -12,6 +13,7 @@ import { replaceBracketed } from '../../../../../shared/src/business/utilities/r */ export const generateDraftDocument = async ({ applicationContext, + authorizedUser, caseEntity, document, replacements, @@ -20,6 +22,7 @@ export const generateDraftDocument = async ({ caseEntity: Case; document: any; replacements: string[]; + authorizedUser: AuthUser; }) => { const content = replaceBracketed(document.content, ...replacements); @@ -27,6 +30,7 @@ export const generateDraftDocument = async ({ .getUseCaseHelpers() .addDocketEntryForSystemGeneratedOrder({ applicationContext, + authorizedUser, caseEntity, systemGeneratedDocument: { ...document, diff --git a/web-api/src/business/useCases/serveCaseToIrs/serveCaseToIrsInteractor.addDocketEntryForPaymentStatus.test.ts b/web-api/src/business/useCases/serveCaseToIrs/serveCaseToIrsInteractor.addDocketEntryForPaymentStatus.test.ts index c43873cdf06..770c2cc569a 100644 --- a/web-api/src/business/useCases/serveCaseToIrs/serveCaseToIrsInteractor.addDocketEntryForPaymentStatus.test.ts +++ b/web-api/src/business/useCases/serveCaseToIrs/serveCaseToIrsInteractor.addDocketEntryForPaymentStatus.test.ts @@ -2,14 +2,13 @@ import { Case } from '../../../../../shared/src/business/entities/cases/Case'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { PAYMENT_STATUS } from '../../../../../shared/src/business/entities/EntityConstants'; import { addDocketEntryForPaymentStatus } from './serveCaseToIrsInteractor'; -import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('addDocketEntryForPaymentStatus', () => { - let user; - - beforeEach(() => { - user = applicationContext.getCurrentUser(); - }); + let user = mockPetitionerUser; it('adds a docketRecord for a paid petition payment', async () => { const caseEntity = new Case( @@ -18,10 +17,9 @@ describe('addDocketEntryForPaymentStatus', () => { petitionPaymentDate: 'Today', petitionPaymentStatus: PAYMENT_STATUS.PAID, }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); await addDocketEntryForPaymentStatus({ - applicationContext, caseEntity, user, }); @@ -43,10 +41,9 @@ describe('addDocketEntryForPaymentStatus', () => { petitionPaymentWaivedDate: 'Today', petitioners: undefined, }, - { applicationContext }, + { authorizedUser: mockPetitionsClerkUser }, ); await addDocketEntryForPaymentStatus({ - applicationContext, caseEntity, user, }); diff --git a/web-api/src/business/useCases/serveCaseToIrs/serveCaseToIrsInteractor.test.ts b/web-api/src/business/useCases/serveCaseToIrs/serveCaseToIrsInteractor.test.ts index b9462bf5169..3f38263efdd 100644 --- a/web-api/src/business/useCases/serveCaseToIrs/serveCaseToIrsInteractor.test.ts +++ b/web-api/src/business/useCases/serveCaseToIrs/serveCaseToIrsInteractor.test.ts @@ -30,14 +30,14 @@ import { UnauthorizedError, } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; -import { - docketClerkUser, - petitionsClerkUser, -} from '../../../../../shared/src/test/mockUsers'; import { getFakeFile, testPdfDoc, } from '../../../../../shared/src/business/test/getFakeFile'; +import { + mockDocketClerkUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { serveCaseToIrsInteractor } from './serveCaseToIrsInteractor'; describe('serveCaseToIrsInteractor', () => { @@ -108,8 +108,6 @@ describe('serveCaseToIrsInteractor', () => { mockCase.docketEntries[0].workItem = { ...MOCK_WORK_ITEM }; applicationContext.getPersistenceGateway().updateWorkItem = jest.fn(); - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - applicationContext.getStorageClient.mockReturnValue({ getObject: getObjectMock, upload: (params, cb) => { @@ -137,9 +135,11 @@ describe('serveCaseToIrsInteractor', () => { }); it('should throw unauthorized error when user is unauthorized', async () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser, ).toHaveBeenCalledWith({ @@ -167,7 +167,11 @@ describe('serveCaseToIrsInteractor', () => { mailingDate: 'some day', }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -192,7 +196,11 @@ describe('serveCaseToIrsInteractor', () => { mailingDate: 'some day', }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -202,7 +210,11 @@ describe('serveCaseToIrsInteractor', () => { it('should replace coversheet on the served petition if the case is not paper', async () => { mockCase = { ...MOCK_CASE }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -217,7 +229,11 @@ describe('serveCaseToIrsInteractor', () => { it('should preserve original case caption and docket number on the coversheet if the case is not paper', async () => { mockCase = { ...MOCK_CASE }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getUseCases().addCoversheetInteractor, @@ -255,7 +271,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getUtilities().getAddressPhoneDiff, @@ -285,7 +305,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getUtilities().getAddressPhoneDiff, ).toHaveBeenCalled(); @@ -318,7 +342,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getUtilities().getAddressPhoneDiff, @@ -375,7 +403,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getDocumentGenerators().noticeOfReceiptOfPetition, @@ -409,7 +441,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getDocumentGenerators().noticeOfReceiptOfPetition.mock @@ -453,7 +489,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getDocumentGenerators().noticeOfReceiptOfPetition.mock @@ -496,7 +536,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getDocumentGenerators().noticeOfReceiptOfPetition.mock @@ -525,7 +569,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().isFileExists, @@ -553,7 +601,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect(addDocketEntrySpy.mock.calls[0][0].documentTitle).toEqual( 'Filing Fee Waived', @@ -574,7 +626,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect(addDocketEntrySpy.mock.calls[0][0].documentTitle).toEqual( 'Filing Fee Paid', @@ -596,7 +652,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().isFileExists, @@ -632,7 +692,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().isFileExists, @@ -672,7 +736,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().isFileExists, @@ -719,7 +787,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getDocumentGenerators().noticeOfReceiptOfPetition, @@ -772,7 +844,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getDocumentGenerators().noticeOfReceiptOfPetition, @@ -802,7 +878,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getDocumentGenerators().noticeOfReceiptOfPetition, @@ -844,7 +924,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getDocumentGenerators().noticeOfReceiptOfPetition, @@ -862,7 +946,11 @@ describe('serveCaseToIrsInteractor', () => { isPaper: false, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getUseCaseHelpers().updateCaseAndAssociations.mock @@ -876,7 +964,11 @@ describe('serveCaseToIrsInteractor', () => { isPaper: false, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getDocumentGenerators().noticeOfReceiptOfPetition, @@ -890,7 +982,11 @@ describe('serveCaseToIrsInteractor', () => { orderForFilingFee: false, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getUseCaseHelpers() @@ -910,7 +1006,11 @@ describe('serveCaseToIrsInteractor', () => { orderForAmendedPetition: false, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getUseCaseHelpers() @@ -927,6 +1027,7 @@ describe('serveCaseToIrsInteractor', () => { const result = await serveCaseToIrsInteractor( applicationContext, mockParams, + mockPetitionsClerkUser, ); expect(result).toBeUndefined(); @@ -939,7 +1040,11 @@ describe('serveCaseToIrsInteractor', () => { mailingDate: 'some day', }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser, @@ -961,7 +1066,11 @@ describe('serveCaseToIrsInteractor', () => { mailingDate: 'some day', }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); const updatedCase = applicationContext.getUseCaseHelpers().updateCaseAndAssociations.mock @@ -1026,7 +1135,11 @@ describe('serveCaseToIrsInteractor', () => { .mockReturnValueOnce(mockCaseWithServedDocketEntries) .mockReturnValueOnce(mockCaseWithServedDocketEntries); - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -1067,7 +1180,11 @@ describe('serveCaseToIrsInteractor', () => { }; const MOCK_NOTR_ID = 'ea10afeb-f189-4657-a862-c607a091beaa'; applicationContext.getUniqueId.mockReturnValue(MOCK_NOTR_ID); - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getUseCaseHelpers().sendServedPartiesEmails.mock .calls[0][0].docketEntryId, @@ -1108,7 +1225,11 @@ describe('serveCaseToIrsInteractor', () => { mailingDate: 'some day', }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getUtilities().serveCaseDocument, @@ -1121,7 +1242,11 @@ describe('serveCaseToIrsInteractor', () => { noticeOfAttachments: true, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect(applicationContext.getDocumentGenerators().order).toHaveBeenCalled(); expect( @@ -1135,7 +1260,11 @@ describe('serveCaseToIrsInteractor', () => { orderDesignatingPlaceOfTrial: true, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( await applicationContext.getUseCaseHelpers() @@ -1190,7 +1319,11 @@ describe('serveCaseToIrsInteractor', () => { orderToShowCause: true, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect(applicationContext.getDocumentGenerators().order).toHaveBeenCalled(); expect( @@ -1204,7 +1337,11 @@ describe('serveCaseToIrsInteractor', () => { orderToShowCause: true, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( await applicationContext.getUseCaseHelpers() @@ -1250,7 +1387,11 @@ describe('serveCaseToIrsInteractor', () => { orderForAmendedPetition: true, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( await applicationContext.getUseCaseHelpers() @@ -1288,7 +1429,11 @@ describe('serveCaseToIrsInteractor', () => { orderForAmendedPetitionAndFilingFee: true, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( await applicationContext.getUseCaseHelpers() @@ -1341,7 +1486,11 @@ describe('serveCaseToIrsInteractor', () => { orderToShowCause: true, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( await applicationContext.getUseCaseHelpers() @@ -1358,7 +1507,11 @@ describe('serveCaseToIrsInteractor', () => { orderForFilingFee: true, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect(applicationContext.getDocumentGenerators().order).toHaveBeenCalled(); expect( @@ -1390,7 +1543,11 @@ describe('serveCaseToIrsInteractor', () => { mockLock = MOCK_LOCK; await expect( - serveCaseToIrsInteractor(applicationContext, mockParams), + serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -1399,7 +1556,11 @@ describe('serveCaseToIrsInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -1418,7 +1579,11 @@ describe('serveCaseToIrsInteractor', () => { }); it('should generate a notice of receipt of petition with the name and title of the clerk of the court', async () => { - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getDocumentGenerators().noticeOfReceiptOfPetition.mock .calls[0][0].data, @@ -1453,7 +1618,11 @@ describe('serveCaseToIrsInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }; - await serveCaseToIrsInteractor(applicationContext, mockParams); + await serveCaseToIrsInteractor( + applicationContext, + mockParams, + mockPetitionsClerkUser, + ); expect( applicationContext.getDocumentGenerators().noticeOfReceiptOfPetition.mock diff --git a/web-api/src/business/useCases/serveCaseToIrs/serveCaseToIrsInteractor.ts b/web-api/src/business/useCases/serveCaseToIrs/serveCaseToIrsInteractor.ts index d50fe757604..5862ae35f66 100644 --- a/web-api/src/business/useCases/serveCaseToIrs/serveCaseToIrsInteractor.ts +++ b/web-api/src/business/useCases/serveCaseToIrs/serveCaseToIrsInteractor.ts @@ -1,4 +1,8 @@ /* eslint-disable complexity */ +import { + AuthUser, + UnknownAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; import { Case } from '../../../../../shared/src/business/entities/cases/Case'; import { DocketEntry } from '../../../../../shared/src/business/entities/DocketEntry'; import { @@ -29,11 +33,7 @@ import { getClinicLetterKey } from '../../../../../shared/src/business/utilities import { random, remove } from 'lodash'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; -export const addDocketEntryForPaymentStatus = ({ - applicationContext, - caseEntity, - user, -}) => { +export const addDocketEntryForPaymentStatus = ({ caseEntity, user }) => { if (caseEntity.petitionPaymentStatus === PAYMENT_STATUS.PAID) { const paymentStatusDocketEntry = new DocketEntry( { @@ -45,7 +45,7 @@ export const addDocketEntryForPaymentStatus = ({ isOnDocketRecord: true, processingStatus: 'complete', }, - { applicationContext }, + { authorizedUser: user }, ); paymentStatusDocketEntry.setFiledBy(user); @@ -62,7 +62,7 @@ export const addDocketEntryForPaymentStatus = ({ isOnDocketRecord: true, processingStatus: 'complete', }, - { applicationContext }, + { authorizedUser: user }, ); petitionPaymentStatusDocketEntry.setFiledBy(user); @@ -336,7 +336,10 @@ const generateNoticeOfReceipt = async ({ isFileAttached: true, isOnDocketRecord: true, }, - { applicationContext, petitioners: caseEntity.petitioners }, + { + authorizedUser: userServingPetition, + petitioners: caseEntity.petitioners, + }, ); notrDocketEntry.setFiledBy(userServingPetition); @@ -412,20 +415,29 @@ const shouldIncludeClinicLetter = ( const createCoversheetsForServedEntries = async ({ applicationContext, + authorizedUser, caseEntity, +}: { + applicationContext: ServerApplicationContext; + caseEntity: Case; + authorizedUser: AuthUser; }) => { return await Promise.all( caseEntity.docketEntries.map(async doc => { if (doc.isFileAttached && !doc.isDraft) { const updatedDocketEntry = await applicationContext .getUseCases() - .addCoversheetInteractor(applicationContext, { - caseEntity, - docketEntryId: doc.docketEntryId, - docketNumber: caseEntity.docketNumber, - replaceCoversheet: !caseEntity.isPaper, - useInitialData: !caseEntity.isPaper, - }); + .addCoversheetInteractor( + applicationContext, + { + caseEntity, + docketEntryId: doc.docketEntryId, + docketNumber: caseEntity.docketNumber, + replaceCoversheet: !caseEntity.isPaper, + useInitialData: !caseEntity.isPaper, + }, + authorizedUser, + ); caseEntity.updateDocketEntry(updatedDocketEntry); } @@ -469,12 +481,13 @@ export const serveCaseToIrs = async ( clientConnectionId, docketNumber, }: { clientConnectionId: string; docketNumber: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); try { - if (!isAuthorized(user, ROLE_PERMISSIONS.SERVE_PETITION)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.SERVE_PETITION)) { throw new UnauthorizedError('Unauthorized'); } + const caseToBatch = await applicationContext .getPersistenceGateway() .getCaseByDocketNumber({ @@ -482,7 +495,7 @@ export const serveCaseToIrs = async ( docketNumber, }); - let caseEntity = new Case(caseToBatch, { applicationContext }); + let caseEntity = new Case(caseToBatch, { authorizedUser }); caseEntity.markAsSentToIRS(); @@ -499,14 +512,13 @@ export const serveCaseToIrs = async ( } addDocketEntryForPaymentStatus({ - applicationContext, caseEntity, - user, + user: authorizedUser, }); caseEntity - .updateCaseCaptionDocketRecord({ applicationContext }) - .updateDocketNumberRecord({ applicationContext }) + .updateCaseCaptionDocketRecord({ authorizedUser }) + .updateDocketNumberRecord({ authorizedUser }) .validate(); const generatedDocuments: Promise[] = []; @@ -519,6 +531,7 @@ export const serveCaseToIrs = async ( .getUseCaseHelpers() .addDocketEntryForSystemGeneratedOrder({ applicationContext, + authorizedUser, caseEntity, systemGeneratedDocument: noticeOfAttachmentsInNatureOfEvidence, }), @@ -540,6 +553,7 @@ export const serveCaseToIrs = async ( generatedDocuments.push( generateDraftDocument({ applicationContext, + authorizedUser, caseEntity, document: orderDesignatingPlaceOfTrial, replacements: [ @@ -561,6 +575,7 @@ export const serveCaseToIrs = async ( generatedDocuments.push( generateDraftDocument({ applicationContext, + authorizedUser, caseEntity, document: orderForFilingFee, replacements: [todayPlus30, todayPlus30], @@ -575,6 +590,7 @@ export const serveCaseToIrs = async ( generatedDocuments.push( generateDraftDocument({ applicationContext, + authorizedUser, caseEntity, document: orderForAmendedPetitionAndFilingFee, replacements: [formattedFiledDate, todayPlus30, todayPlus30], @@ -593,6 +609,7 @@ export const serveCaseToIrs = async ( generatedDocuments.push( generateDraftDocument({ applicationContext, + authorizedUser, caseEntity, document: orderForAmendedPetition, replacements: [formattedFiledDate, todayPlus60, todayPlus60], @@ -607,6 +624,7 @@ export const serveCaseToIrs = async ( generatedDocuments.push( generateDraftDocument({ applicationContext, + authorizedUser, caseEntity, document: orderPetitionersToShowCause, replacements: [formattedFiledDate, todayPlus60], @@ -619,22 +637,24 @@ export const serveCaseToIrs = async ( await createPetitionWorkItems({ applicationContext, caseEntity, - user, + user: authorizedUser, }); await createCoversheetsForServedEntries({ applicationContext, + authorizedUser, caseEntity, }); const urlToReturn = await generateNoticeOfReceipt({ applicationContext, caseEntity, - userServingPetition: user, + userServingPetition: authorizedUser, }); await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); @@ -645,7 +665,7 @@ export const serveCaseToIrs = async ( action: 'serve_to_irs_complete', pdfUrl: urlToReturn, }, - userId: user.userId, + userId: authorizedUser.userId, }); } catch (err) { applicationContext.logger.error('Error serving case to IRS', { @@ -658,7 +678,7 @@ export const serveCaseToIrs = async ( message: { action: 'serve_to_irs_error', }, - userId: user.userId, + userId: authorizedUser?.userId || '', }); } }; diff --git a/web-api/src/business/useCases/trialSession/generatePrintableTrialSessionCopyReportInteractor.test.ts b/web-api/src/business/useCases/trialSession/generatePrintableTrialSessionCopyReportInteractor.test.ts index bcf10204b05..1cce24a3e13 100644 --- a/web-api/src/business/useCases/trialSession/generatePrintableTrialSessionCopyReportInteractor.test.ts +++ b/web-api/src/business/useCases/trialSession/generatePrintableTrialSessionCopyReportInteractor.test.ts @@ -1,22 +1,17 @@ import { Case } from '@shared/business/entities/cases/Case'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_TRIAL_REGULAR } from '../../../../../shared/src/test/mockTrial'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { generatePrintableTrialSessionCopyReportInteractor } from './generatePrintableTrialSessionCopyReportInteractor'; +import { + mockPetitionerUser, + mockTrialClerkUser, +} from '@shared/test/mockAuthUsers'; describe('generatePrintableTrialSessionCopyReportInteractor', () => { - let mockUser; let mockTrialSession; beforeEach(() => { - mockUser = { - role: ROLES.trialClerk, - userId: 'trialclerk', - }; - - applicationContext.getCurrentUser.mockImplementation(() => mockUser); - applicationContext .getPersistenceGateway() .getDownloadPolicyUrl.mockReturnValue({ url: 'https://example.com' }); @@ -31,32 +26,33 @@ describe('generatePrintableTrialSessionCopyReportInteractor', () => { }); it('should throw an error when the user is not authorized to generate a printable trial session report', async () => { - mockUser = { - role: ROLES.petitioner, - userId: 'petitioner', - }; - await expect( - generatePrintableTrialSessionCopyReportInteractor(applicationContext, { - filters: { - aBasisReached: true, - continued: true, - dismissed: true, - recall: true, - rule122: true, - setForTrial: true, - settled: true, - showAll: true, - statusUnassigned: true, - takenUnderAdvisement: true, + generatePrintableTrialSessionCopyReportInteractor( + applicationContext, + { + filters: { + aBasisReached: true, + continued: true, + dismissed: true, + recall: true, + rule122: true, + setForTrial: true, + settled: true, + showAll: true, + statusUnassigned: true, + takenUnderAdvisement: true, + }, + formattedCases: [ + new Case(MOCK_CASE, { authorizedUser: mockTrialClerkUser }), + ], + formattedTrialSession: mockTrialSession, + sessionNotes: 'session notes', + showCaseNotes: true, + sort: 'docket', + userHeading: 'Yggdrasil - Session Copy', }, - formattedCases: [new Case(MOCK_CASE, { applicationContext })], - formattedTrialSession: mockTrialSession, - sessionNotes: 'session notes', - showCaseNotes: true, - sort: 'docket', - userHeading: 'Yggdrasil - Session Copy', - }), + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -76,13 +72,16 @@ describe('generatePrintableTrialSessionCopyReportInteractor', () => { statusUnassigned: true, takenUnderAdvisement: true, }, - formattedCases: [new Case(MOCK_CASE, { applicationContext })], + formattedCases: [ + new Case(MOCK_CASE, { authorizedUser: mockTrialClerkUser }), + ], formattedTrialSession: mockTrialSession, sessionNotes: 'session notes', showCaseNotes: true, sort: 'docket', userHeading: 'Yggdrasil - Session Copy', }, + mockTrialClerkUser, ); expect( @@ -103,7 +102,9 @@ describe('generatePrintableTrialSessionCopyReportInteractor', () => { statusUnassigned: true, takenUnderAdvisement: true, }, - formattedCases: [new Case(MOCK_CASE, { applicationContext })], + formattedCases: [ + new Case(MOCK_CASE, { authorizedUser: mockTrialClerkUser }), + ], formattedTrialSession: mockTrialSession, sessionNotes: 'session notes', showCaseNotes: true, @@ -129,13 +130,16 @@ describe('generatePrintableTrialSessionCopyReportInteractor', () => { statusUnassigned: true, takenUnderAdvisement: true, }, - formattedCases: [new Case(MOCK_CASE, { applicationContext })], + formattedCases: [ + new Case(MOCK_CASE, { authorizedUser: mockTrialClerkUser }), + ], formattedTrialSession: mockTrialSession, sessionNotes: 'session notes', showCaseNotes: true, sort: 'docket', userHeading: 'Yggdrasil - Session Copy', }, + mockTrialClerkUser, ); expect( @@ -159,13 +163,16 @@ describe('generatePrintableTrialSessionCopyReportInteractor', () => { statusUnassigned: true, takenUnderAdvisement: true, }, - formattedCases: [new Case(MOCK_CASE, { applicationContext })], + formattedCases: [ + new Case(MOCK_CASE, { authorizedUser: mockTrialClerkUser }), + ], formattedTrialSession: mockTrialSession, sessionNotes: 'session notes', showCaseNotes: true, sort: 'docket', userHeading: 'Yggdrasil - Session Copy', }, + mockTrialClerkUser, ); expect( diff --git a/web-api/src/business/useCases/trialSession/generatePrintableTrialSessionCopyReportInteractor.ts b/web-api/src/business/useCases/trialSession/generatePrintableTrialSessionCopyReportInteractor.ts index f71f7edb7f1..4d3dd92f2f5 100644 --- a/web-api/src/business/useCases/trialSession/generatePrintableTrialSessionCopyReportInteractor.ts +++ b/web-api/src/business/useCases/trialSession/generatePrintableTrialSessionCopyReportInteractor.ts @@ -6,6 +6,7 @@ import { import { RawTrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const generatePrintableTrialSessionCopyReportInteractor = async ( applicationContext: ServerApplicationContext, @@ -26,8 +27,8 @@ export const generatePrintableTrialSessionCopyReportInteractor = async ( sort: string; userHeading: string; }, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); if ( !isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSION_WORKING_COPY) ) { diff --git a/web-api/src/business/useCases/trialSessions/addCaseToTrialSessionInteractor.test.ts b/web-api/src/business/useCases/trialSessions/addCaseToTrialSessionInteractor.test.ts index d62f6affe38..5aaaf103c6a 100644 --- a/web-api/src/business/useCases/trialSessions/addCaseToTrialSessionInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/addCaseToTrialSessionInteractor.test.ts @@ -2,7 +2,6 @@ import '@web-api/persistence/postgres/messages/mocks.jest'; import { CASE_STATUS_TYPES, CHIEF_JUDGE, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; @@ -10,9 +9,12 @@ import { MOCK_TRIAL_REMOTE } from '../../../../../shared/src/test/mockTrial'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { addCaseToTrialSessionInteractor } from './addCaseToTrialSessionInteractor'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('addCaseToTrialSessionInteractor', () => { - let mockCurrentUser; let mockTrialSession; let mockCase; let mockLock; @@ -21,7 +23,6 @@ describe('addCaseToTrialSessionInteractor', () => { applicationContext .getPersistenceGateway() .getLock.mockImplementation(() => mockLock); - applicationContext.getCurrentUser.mockImplementation(() => mockCurrentUser); applicationContext .getPersistenceGateway() .getTrialSessionById.mockImplementation(() => mockTrialSession); @@ -32,26 +33,21 @@ describe('addCaseToTrialSessionInteractor', () => { beforeEach(() => { mockLock = undefined; - mockCurrentUser = { - role: ROLES.petitionsClerk, - userId: '8675309b-18d0-43ec-bafb-654e83405411', - }; mockTrialSession = MOCK_TRIAL_REMOTE; mockCase = MOCK_CASE; }); it('throws an Unauthorized error if the user role is not allowed to access the method', async () => { - mockCurrentUser = { - role: ROLES.petitioner, - userId: '8675309b-18d0-43ec-bafb-654e83405411', - }; - await expect( - addCaseToTrialSessionInteractor(applicationContext, { - calendarNotes: 'testing', - docketNumber: mockCase.docketNumber, - trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, - }), + addCaseToTrialSessionInteractor( + applicationContext, + { + calendarNotes: 'testing', + docketNumber: mockCase.docketNumber, + trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -62,11 +58,15 @@ describe('addCaseToTrialSessionInteractor', () => { }; await expect( - addCaseToTrialSessionInteractor(applicationContext, { - calendarNotes: 'testing', - docketNumber: mockCase.docketNumber, - trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, - }), + addCaseToTrialSessionInteractor( + applicationContext, + { + calendarNotes: 'testing', + docketNumber: mockCase.docketNumber, + trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('The case is already calendared'); }); @@ -78,11 +78,15 @@ describe('addCaseToTrialSessionInteractor', () => { }; await expect( - addCaseToTrialSessionInteractor(applicationContext, { - calendarNotes: 'testing', - docketNumber: MOCK_CASE.docketNumber, - trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, - }), + addCaseToTrialSessionInteractor( + applicationContext, + { + calendarNotes: 'testing', + docketNumber: MOCK_CASE.docketNumber, + trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('The case is already part of this trial session.'); }); @@ -100,6 +104,7 @@ describe('addCaseToTrialSessionInteractor', () => { docketNumber: MOCK_CASE.docketNumber, trialSessionId: mockTrialSession.trialSessionId, }, + mockPetitionsClerkUser, ); expect(latestCase).toMatchObject({ @@ -119,11 +124,15 @@ describe('addCaseToTrialSessionInteractor', () => { isCalendared: true, }; - await addCaseToTrialSessionInteractor(applicationContext, { - calendarNotes: 'Test', - docketNumber: MOCK_CASE.docketNumber, - trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, - }); + await addCaseToTrialSessionInteractor( + applicationContext, + { + calendarNotes: 'Test', + docketNumber: MOCK_CASE.docketNumber, + trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, + }, + mockPetitionsClerkUser, + ); const caseWithCalendarNotes = applicationContext .getPersistenceGateway() @@ -140,11 +149,15 @@ describe('addCaseToTrialSessionInteractor', () => { isCalendared: true, }; - await addCaseToTrialSessionInteractor(applicationContext, { - calendarNotes: 'testing', - docketNumber: MOCK_CASE.docketNumber, - trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, - }); + await addCaseToTrialSessionInteractor( + applicationContext, + { + calendarNotes: 'testing', + docketNumber: MOCK_CASE.docketNumber, + trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().setPriorityOnAllWorkItems.mock @@ -162,11 +175,15 @@ describe('addCaseToTrialSessionInteractor', () => { isCalendared: false, }; - await addCaseToTrialSessionInteractor(applicationContext, { - calendarNotes: 'testing', - docketNumber: MOCK_CASE.docketNumber, - trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, - }); + await addCaseToTrialSessionInteractor( + applicationContext, + { + calendarNotes: 'testing', + docketNumber: MOCK_CASE.docketNumber, + trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().setPriorityOnAllWorkItems, @@ -177,11 +194,15 @@ describe('addCaseToTrialSessionInteractor', () => { mockLock = MOCK_LOCK; await expect( - addCaseToTrialSessionInteractor(applicationContext, { - calendarNotes: 'testing', - docketNumber: MOCK_CASE.docketNumber, - trialSessionId: mockTrialSession.trialSessionId, - }), + addCaseToTrialSessionInteractor( + applicationContext, + { + calendarNotes: 'testing', + docketNumber: MOCK_CASE.docketNumber, + trialSessionId: mockTrialSession.trialSessionId, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -190,11 +211,15 @@ describe('addCaseToTrialSessionInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await addCaseToTrialSessionInteractor(applicationContext, { - calendarNotes: 'testing', - docketNumber: MOCK_CASE.docketNumber, - trialSessionId: mockTrialSession.trialSessionId, - }); + await addCaseToTrialSessionInteractor( + applicationContext, + { + calendarNotes: 'testing', + docketNumber: MOCK_CASE.docketNumber, + trialSessionId: mockTrialSession.trialSessionId, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/trialSessions/addCaseToTrialSessionInteractor.ts b/web-api/src/business/useCases/trialSessions/addCaseToTrialSessionInteractor.ts index ba495414abf..fc8d136fa9c 100644 --- a/web-api/src/business/useCases/trialSessions/addCaseToTrialSessionInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/addCaseToTrialSessionInteractor.ts @@ -7,6 +7,7 @@ import { import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -29,10 +30,11 @@ export const addCaseToTrialSession = async ( docketNumber: string; trialSessionId: string; }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.ADD_CASE_TO_TRIAL_SESSION)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.ADD_CASE_TO_TRIAL_SESSION) + ) { throw new UnauthorizedError('Unauthorized'); } @@ -54,11 +56,9 @@ export const addCaseToTrialSession = async ( docketNumber, }); - const caseEntity = new Case(caseDetails, { applicationContext }); + const caseEntity = new Case(caseDetails, { authorizedUser }); - const trialSessionEntity = new TrialSession(trialSession, { - applicationContext, - }); + const trialSessionEntity = new TrialSession(trialSession); if (caseEntity.isCalendared()) { throw new Error('The case is already calendared'); @@ -94,6 +94,7 @@ export const addCaseToTrialSession = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); @@ -102,7 +103,7 @@ export const addCaseToTrialSession = async ( trialSessionToUpdate: trialSessionEntity.validate().toRawObject(), }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const addCaseToTrialSessionInteractor = withLocking( diff --git a/web-api/src/business/useCases/trialSessions/batchDownloadTrialSessionInteractor.test.ts b/web-api/src/business/useCases/trialSessions/batchDownloadTrialSessionInteractor.test.ts index 0a0bc57de52..348994d1de3 100644 --- a/web-api/src/business/useCases/trialSessions/batchDownloadTrialSessionInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/batchDownloadTrialSessionInteractor.test.ts @@ -1,16 +1,13 @@ -import { - CASE_STATUS_TYPES, - ROLES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { CASE_STATUS_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { batchDownloadTrialSessionInteractor, generateValidDocketEntryFilename, } from './batchDownloadTrialSessionInteractor'; +import { mockJudgeUser, mockPetitionerUser } from '@shared/test/mockAuthUsers'; describe('batchDownloadTrialSessionInteractor', () => { - let user; let mockCase; beforeEach(() => { @@ -48,11 +45,6 @@ describe('batchDownloadTrialSessionInteractor', () => { }, ]; - user = { - role: ROLES.judge, - userId: 'abc-123', - }; - applicationContext.getCurrentUser.mockImplementation(() => user); applicationContext .getPersistenceGateway() .getCalendaredCasesForTrialSession.mockReturnValue([ @@ -115,9 +107,13 @@ describe('batchDownloadTrialSessionInteractor', () => { }); it('skips DocketEntry that are not in docketrecord or have documents in S3', async () => { - await batchDownloadTrialSessionInteractor(applicationContext, { - trialSessionId: '123', - }); + await batchDownloadTrialSessionInteractor( + applicationContext, + { + trialSessionId: '123', + }, + mockJudgeUser, + ); expect( applicationContext.getPersistenceGateway().zipDocuments, @@ -150,9 +146,13 @@ describe('batchDownloadTrialSessionInteractor', () => { .getPersistenceGateway() .isFileExists.mockResolvedValue(false); - await batchDownloadTrialSessionInteractor(applicationContext, { - trialSessionId: '123', - }); + await batchDownloadTrialSessionInteractor( + applicationContext, + { + trialSessionId: '123', + }, + mockJudgeUser, + ); const errorCall = applicationContext.getNotificationGateway().sendNotificationToUser.mock @@ -164,14 +164,13 @@ describe('batchDownloadTrialSessionInteractor', () => { }); it('throws an Unauthorized error if the user role is not allowed to access the method', async () => { - user = { - role: ROLES.petitioner, - userId: 'abc-123', - }; - - await batchDownloadTrialSessionInteractor(applicationContext, { - trialSessionId: '123', - }); + await batchDownloadTrialSessionInteractor( + applicationContext, + { + trialSessionId: '123', + }, + mockPetitionerUser, + ); expect(applicationContext.logger.error).toHaveBeenCalledWith( 'Error when batch downloading trial session with id 123 - Unauthorized', @@ -185,7 +184,7 @@ describe('batchDownloadTrialSessionInteractor', () => { action: 'batch_download_error', error: expect.anything(), }, - userId: 'abc-123', + userId: mockPetitionerUser.userId, }); }); @@ -194,9 +193,13 @@ describe('batchDownloadTrialSessionInteractor', () => { .getPersistenceGateway() .getCalendaredCasesForTrialSession.mockRejectedValueOnce(new Error()); - await batchDownloadTrialSessionInteractor(applicationContext, { - trialSessionId: '123', - }); + await batchDownloadTrialSessionInteractor( + applicationContext, + { + trialSessionId: '123', + }, + mockJudgeUser, + ); expect(applicationContext.logger.error).toHaveBeenCalledWith( 'Error when batch downloading trial session with id 123 - unknown error', @@ -210,7 +213,7 @@ describe('batchDownloadTrialSessionInteractor', () => { action: 'batch_download_error', error: expect.anything(), }, - userId: 'abc-123', + userId: mockJudgeUser.userId, }); }); @@ -220,9 +223,13 @@ describe('batchDownloadTrialSessionInteractor', () => { .getPersistenceGateway() .getTrialSessionById.mockResolvedValue(false); - await batchDownloadTrialSessionInteractor(applicationContext, { - trialSessionId: mockTrialSessionId, - }); + await batchDownloadTrialSessionInteractor( + applicationContext, + { + trialSessionId: mockTrialSessionId, + }, + mockJudgeUser, + ); expect(applicationContext.logger.error).toHaveBeenCalledWith( `Error when batch downloading trial session with id ${mockTrialSessionId} - Trial session ${mockTrialSessionId} was not found.`, @@ -236,14 +243,18 @@ describe('batchDownloadTrialSessionInteractor', () => { action: 'batch_download_error', error: expect.anything(), }, - userId: 'abc-123', + userId: mockJudgeUser.userId, }); }); it('calls persistence functions to fetch trial sessions and associated cases and then zips their associated documents', async () => { - await batchDownloadTrialSessionInteractor(applicationContext, { - trialSessionId: '123', - }); + await batchDownloadTrialSessionInteractor( + applicationContext, + { + trialSessionId: '123', + }, + mockJudgeUser, + ); expect( applicationContext.getPersistenceGateway().getTrialSessionById, @@ -267,9 +278,13 @@ describe('batchDownloadTrialSessionInteractor', () => { }, ]); - await batchDownloadTrialSessionInteractor(applicationContext, { - trialSessionId: '123', - }); + await batchDownloadTrialSessionInteractor( + applicationContext, + { + trialSessionId: '123', + }, + mockJudgeUser, + ); expect( applicationContext.getPersistenceGateway().getTrialSessionById, @@ -297,9 +312,13 @@ describe('batchDownloadTrialSessionInteractor', () => { }, ]); - await batchDownloadTrialSessionInteractor(applicationContext, { - trialSessionId: '123', - }); + await batchDownloadTrialSessionInteractor( + applicationContext, + { + trialSessionId: '123', + }, + mockJudgeUser, + ); expect( applicationContext.getPersistenceGateway().getTrialSessionById, diff --git a/web-api/src/business/useCases/trialSessions/batchDownloadTrialSessionInteractor.ts b/web-api/src/business/useCases/trialSessions/batchDownloadTrialSessionInteractor.ts index 28254f4ab29..c1f05e3795a 100644 --- a/web-api/src/business/useCases/trialSessions/batchDownloadTrialSessionInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/batchDownloadTrialSessionInteractor.ts @@ -14,43 +14,52 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { padStart } from 'lodash'; import sanitize from 'sanitize-filename'; export const batchDownloadTrialSessionInteractor = async ( applicationContext: ServerApplicationContext, { trialSessionId }: { trialSessionId: string }, + authorizedUser: UnknownAuthUser, ): Promise => { try { - await batchDownloadTrialSessionInteractorHelper(applicationContext, { - trialSessionId, - }); + await batchDownloadTrialSessionInteractorHelper( + applicationContext, + { + trialSessionId, + }, + authorizedUser, + ); } catch (error: any) { - const { userId } = applicationContext.getCurrentUser(); + const userId = authorizedUser?.userId; const erMsg = error.message || 'unknown error'; applicationContext.logger.error( `Error when batch downloading trial session with id ${trialSessionId} - ${erMsg}`, { error }, ); - await applicationContext.getNotificationGateway().sendNotificationToUser({ - applicationContext, - message: { - action: 'batch_download_error', - error, - }, - userId, - }); + if (userId) { + await applicationContext.getNotificationGateway().sendNotificationToUser({ + applicationContext, + message: { + action: 'batch_download_error', + error, + }, + userId, + }); + } } }; const batchDownloadTrialSessionInteractorHelper = async ( applicationContext: ServerApplicationContext, { trialSessionId }: { trialSessionId: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.BATCH_DOWNLOAD_TRIAL_SESSION)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.BATCH_DOWNLOAD_TRIAL_SESSION) + ) { throw new UnauthorizedError('Unauthorized'); } @@ -129,7 +138,7 @@ const batchDownloadTrialSessionInteractorHelper = async ( filesCompleted: numberOfDocketRecordsGenerated, totalFiles: numberOfDocketRecordsToGenerate, }, - userId: user.userId, + userId: authorizedUser.userId, }); }; @@ -138,10 +147,14 @@ const batchDownloadTrialSessionInteractorHelper = async ( for (const sessionCase of batchableSessionCases) { const result = await applicationContext .getUseCases() - .generateDocketRecordPdfInteractor(applicationContext, { - docketNumber: sessionCase.docketNumber, - includePartyDetail: true, - }); + .generateDocketRecordPdfInteractor( + applicationContext, + { + docketNumber: sessionCase.docketNumber, + includePartyDetail: true, + }, + authorizedUser, + ); await onDocketRecordCreation({ docketNumber: sessionCase.docketNumber }); @@ -160,7 +173,7 @@ const batchDownloadTrialSessionInteractorHelper = async ( filesCompleted: progressData.filesCompleted, totalFiles: progressData.totalFiles, }, - userId: user.userId, + userId: authorizedUser.userId, }); }; @@ -171,7 +184,7 @@ const batchDownloadTrialSessionInteractorHelper = async ( filesCompleted: 0, totalFiles: documentsToZip.length, }, - userId: user.userId, + userId: authorizedUser.userId, }); const trialDate = formatDateString( @@ -206,7 +219,7 @@ const batchDownloadTrialSessionInteractorHelper = async ( action: 'batch_download_ready', url, }, - userId: user.userId, + userId: authorizedUser.userId, }); }; diff --git a/web-api/src/business/useCases/trialSessions/closeTrialSessionInteractor.test.ts b/web-api/src/business/useCases/trialSessions/closeTrialSessionInteractor.test.ts index 2f1988f6005..18ee1b5517f 100644 --- a/web-api/src/business/useCases/trialSessions/closeTrialSessionInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/closeTrialSessionInteractor.test.ts @@ -1,16 +1,17 @@ import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_TRIAL_REGULAR } from '../../../../../shared/src/test/mockTrial'; import { - ROLES, TRIAL_SESSION_PROCEEDING_TYPES, TRIAL_SESSION_SCOPE_TYPES, } from '../../../../../shared/src/business/entities/EntityConstants'; -import { User } from '../../../../../shared/src/business/entities/User'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { closeTrialSessionInteractor } from './closeTrialSessionInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('closeTrialSessionInteractor', () => { - let user; let mockTrialSession; const FUTURE_DATE = '2090-11-25T15:00:00.000Z'; @@ -20,7 +21,6 @@ describe('closeTrialSessionInteractor', () => { mockTrialSession = MOCK_TRIAL_REGULAR; applicationContext.environment.stage = 'local'; - applicationContext.getCurrentUser.mockImplementation(() => user); applicationContext .getPersistenceGateway() @@ -28,43 +28,34 @@ describe('closeTrialSessionInteractor', () => { }); it('throws error if user is unauthorized', async () => { - user = { - role: ROLES.petitioner, - userId: 'petitioner', - }; - await expect( - closeTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + closeTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('throws an exception when it fails to find a trial session', async () => { - user = new User({ - name: 'Docket Clerk', - role: ROLES.docketClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - mockTrialSession = null; await expect( - closeTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + closeTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ), ).rejects.toThrow( 'Trial session c54ba5a9-b37b-479d-9201-067ec6e335bb was not found.', ); }); it('throws error when trial session is not standalone remote', async () => { - user = new User({ - name: 'Docket Clerk', - role: ROLES.docketClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - mockTrialSession = { ...MOCK_TRIAL_REGULAR, sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased, @@ -72,21 +63,19 @@ describe('closeTrialSessionInteractor', () => { }; await expect( - closeTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + closeTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ), ).rejects.toThrow( 'Only standalone remote trial sessions can be closed manually', ); }); it('throws error when trial session start date is in the future', async () => { - user = new User({ - name: 'Docket Clerk', - role: ROLES.docketClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - mockTrialSession = { ...MOCK_TRIAL_REGULAR, sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, @@ -94,21 +83,19 @@ describe('closeTrialSessionInteractor', () => { }; await expect( - closeTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + closeTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ), ).rejects.toThrow( 'Trial session cannot be closed until after its start date', ); }); it('throws an error when there are active cases on the trial session', async () => { - user = new User({ - name: 'Docket Clerk', - role: ROLES.docketClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - mockTrialSession = { ...MOCK_TRIAL_REGULAR, caseOrder: [ @@ -119,19 +106,17 @@ describe('closeTrialSessionInteractor', () => { }; await expect( - closeTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + closeTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Trial session cannot be closed with open cases'); }); it('does not throw an error when there are no cases on the trial session', async () => { - user = new User({ - name: 'Docket Clerk', - role: ROLES.docketClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - mockTrialSession = { ...MOCK_TRIAL_REGULAR, caseOrder: undefined, @@ -140,19 +125,17 @@ describe('closeTrialSessionInteractor', () => { }; await expect( - closeTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + closeTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ), ).rejects.not.toThrow('Trial session cannot be closed with open cases'); }); it('should not close the trial session and throws an error instead', async () => { - user = new User({ - name: 'Docket Clerk', - role: ROLES.docketClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - mockTrialSession = { ...MOCK_TRIAL_REGULAR, caseOrder: [ @@ -164,19 +147,17 @@ describe('closeTrialSessionInteractor', () => { }; await expect( - closeTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + closeTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Trial session cannot be closed with open cases'); }); it('closes the trial session and invokes expected persistence methods', async () => { - user = new User({ - name: 'Docket Clerk', - role: ROLES.docketClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - mockTrialSession = { ...MOCK_TRIAL_REGULAR, caseOrder: [ @@ -198,9 +179,13 @@ describe('closeTrialSessionInteractor', () => { startDate: PAST_DATE, }; - await closeTrialSessionInteractor(applicationContext, { - trialSessionId: mockTrialSession.trialSessionId, - }); + await closeTrialSessionInteractor( + applicationContext, + { + trialSessionId: mockTrialSession.trialSessionId, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateTrialSession.mock diff --git a/web-api/src/business/useCases/trialSessions/closeTrialSessionInteractor.ts b/web-api/src/business/useCases/trialSessions/closeTrialSessionInteractor.ts index 6dab1c698a2..8351ea79c0c 100644 --- a/web-api/src/business/useCases/trialSessions/closeTrialSessionInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/closeTrialSessionInteractor.ts @@ -7,6 +7,7 @@ import { ServerApplicationContext } from '@web-api/applicationContext'; import { TRIAL_SESSION_SCOPE_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; import { TrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { isEmpty, isEqual } from 'lodash'; /** @@ -19,9 +20,9 @@ import { isEmpty, isEqual } from 'lodash'; export const closeTrialSessionInteractor = async ( applicationContext: ServerApplicationContext, { trialSessionId }: { trialSessionId: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } @@ -62,9 +63,7 @@ export const closeTrialSessionInteractor = async ( throw new Error('Trial session cannot be closed with open cases'); } - const trialSessionEntity = new TrialSession(trialSession, { - applicationContext, - }); + const trialSessionEntity = new TrialSession(trialSession); trialSessionEntity.setAsClosed(); diff --git a/web-api/src/business/useCases/trialSessions/createTrialSessionInteractor.test.ts b/web-api/src/business/useCases/trialSessions/createTrialSessionInteractor.test.ts index dec590dd09a..610c0a33d67 100644 --- a/web-api/src/business/useCases/trialSessions/createTrialSessionInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/createTrialSessionInteractor.test.ts @@ -1,11 +1,8 @@ -import { - ROLES, - TRIAL_SESSION_SCOPE_TYPES, -} from '../../../../../shared/src/business/entities/EntityConstants'; import { RawTrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; -import { User } from '../../../../../shared/src/business/entities/User'; +import { TRIAL_SESSION_SCOPE_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { createTrialSessionInteractor } from './createTrialSessionInteractor'; +import { mockDocketClerkUser, mockJudgeUser } from '@shared/test/mockAuthUsers'; const MOCK_TRIAL = { maxCases: 100, @@ -17,17 +14,8 @@ const MOCK_TRIAL = { }; describe('createTrialSessionInteractor', () => { - let user; - beforeEach(() => { - user = new User({ - name: 'Docket Clerk', - role: ROLES.docketClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - applicationContext.environment.stage = 'local'; - applicationContext.getCurrentUser.mockImplementation(() => user); applicationContext .getUseCaseHelpers() @@ -37,15 +25,14 @@ describe('createTrialSessionInteractor', () => { }); it('should throw an error when user is unauthorized', async () => { - user = new User({ - role: ROLES.judge, - userId: 'judge', - }); - await expect( - createTrialSessionInteractor(applicationContext, { - trialSession: MOCK_TRIAL as RawTrialSession, - }), + createTrialSessionInteractor( + applicationContext, + { + trialSession: MOCK_TRIAL as RawTrialSession, + }, + mockJudgeUser, + ), ).rejects.toThrow(); }); @@ -57,16 +44,24 @@ describe('createTrialSessionInteractor', () => { }); await expect( - createTrialSessionInteractor(applicationContext, { - trialSession: MOCK_TRIAL as RawTrialSession, - }), + createTrialSessionInteractor( + applicationContext, + { + trialSession: MOCK_TRIAL as RawTrialSession, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(''); }); it('should successfully create a trial session', async () => { - await createTrialSessionInteractor(applicationContext, { - trialSession: MOCK_TRIAL as RawTrialSession, - }); + await createTrialSessionInteractor( + applicationContext, + { + trialSession: MOCK_TRIAL as RawTrialSession, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().createTrialSessionAndWorkingCopy, @@ -74,47 +69,63 @@ describe('createTrialSessionInteractor', () => { }); it('should set the trial session as calendared when it is a Motion/Hearing session type', async () => { - const result = await createTrialSessionInteractor(applicationContext, { - trialSession: { - ...MOCK_TRIAL, - sessionType: 'Motion/Hearing', - } as RawTrialSession, - }); + const result = await createTrialSessionInteractor( + applicationContext, + { + trialSession: { + ...MOCK_TRIAL, + sessionType: 'Motion/Hearing', + } as RawTrialSession, + }, + mockDocketClerkUser, + ); expect(result.isCalendared).toEqual(true); }); it(`should set the trial session as calendared when the sessionScope is ${TRIAL_SESSION_SCOPE_TYPES.standaloneRemote}`, async () => { - const result = await createTrialSessionInteractor(applicationContext, { - trialSession: { - ...MOCK_TRIAL, - sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, - sessionType: 'Something Else', - } as RawTrialSession, - }); + const result = await createTrialSessionInteractor( + applicationContext, + { + trialSession: { + ...MOCK_TRIAL, + sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote, + sessionType: 'Something Else', + } as RawTrialSession, + }, + mockDocketClerkUser, + ); expect(result.isCalendared).toEqual(true); }); it('should set the trial session as calendared when it is a Special session type', async () => { - const result = await createTrialSessionInteractor(applicationContext, { - trialSession: { - ...MOCK_TRIAL, - sessionType: 'Special', - } as RawTrialSession, - }); + const result = await createTrialSessionInteractor( + applicationContext, + { + trialSession: { + ...MOCK_TRIAL, + sessionType: 'Special', + } as RawTrialSession, + }, + mockDocketClerkUser, + ); expect(result.isCalendared).toEqual(true); }); it('should associate swing trial sessions when the current trial session has a swing session', async () => { - await createTrialSessionInteractor(applicationContext, { - trialSession: { - ...MOCK_TRIAL, - swingSession: true, - swingSessionId: '1234', - } as RawTrialSession, - }); + await createTrialSessionInteractor( + applicationContext, + { + trialSession: { + ...MOCK_TRIAL, + swingSession: true, + swingSessionId: '1234', + } as RawTrialSession, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().associateSwingTrialSessions, @@ -126,9 +137,13 @@ describe('createTrialSessionInteractor', () => { }); it('shoud not set the trial session as calendared when it is a Regular session type', async () => { - const result = await createTrialSessionInteractor(applicationContext, { - trialSession: MOCK_TRIAL as RawTrialSession, - }); + const result = await createTrialSessionInteractor( + applicationContext, + { + trialSession: MOCK_TRIAL as RawTrialSession, + }, + mockDocketClerkUser, + ); expect(result.isCalendared).toEqual(false); }); diff --git a/web-api/src/business/useCases/trialSessions/createTrialSessionInteractor.ts b/web-api/src/business/useCases/trialSessions/createTrialSessionInteractor.ts index c39900d3af7..3f41171500c 100644 --- a/web-api/src/business/useCases/trialSessions/createTrialSessionInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/createTrialSessionInteractor.ts @@ -8,28 +8,18 @@ import { } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; -/** - * createTrialSessionInteractor - * - * @param {object} applicationContext the application context - * @param {object} providers the providers object - * @param {object} providers.trialSession the trial session data - * @returns {object} the created trial session - */ export const createTrialSessionInteractor = async ( applicationContext: ServerApplicationContext, { trialSession }: { trialSession: RawTrialSession }, -) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.CREATE_TRIAL_SESSION)) { + authorizedUser: UnknownAuthUser, +): Promise => { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CREATE_TRIAL_SESSION)) { throw new UnauthorizedError('Unauthorized'); } - const trialSessionToAdd = new TrialSession(trialSession, { - applicationContext, - }); + const trialSessionToAdd = new TrialSession(trialSession); if ( ['Motion/Hearing', 'Special'].includes(trialSessionToAdd.sessionType) || @@ -39,12 +29,14 @@ export const createTrialSessionInteractor = async ( } if (trialSessionToAdd.swingSession && trialSessionToAdd.swingSessionId) { - await applicationContext - .getUseCaseHelpers() - .associateSwingTrialSessions(applicationContext, { + await applicationContext.getUseCaseHelpers().associateSwingTrialSessions( + applicationContext, + { swingSessionId: trialSessionToAdd.swingSessionId, trialSessionEntity: trialSessionToAdd, - }); + }, + authorizedUser, + ); } return await applicationContext diff --git a/web-api/src/business/useCases/trialSessions/deleteTrialSessionInteractor.test.ts b/web-api/src/business/useCases/trialSessions/deleteTrialSessionInteractor.test.ts index 5d55caca262..b52d8079b4a 100644 --- a/web-api/src/business/useCases/trialSessions/deleteTrialSessionInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/deleteTrialSessionInteractor.test.ts @@ -2,11 +2,13 @@ import '@web-api/persistence/postgres/messages/mocks.jest'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; import { MOCK_TRIAL_REGULAR } from '../../../../../shared/src/test/mockTrial'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { ServiceUnavailableError } from '@web-api/errors/errors'; -import { User } from '../../../../../shared/src/business/entities/User'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { deleteTrialSessionInteractor } from './deleteTrialSessionInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('deleteTrialSessionInteractor', () => { let mockTrialSession; @@ -26,25 +28,17 @@ describe('deleteTrialSessionInteractor', () => { mockTrialSession = MOCK_TRIAL_REGULAR; applicationContext.environment.stage = 'local'; - applicationContext.getCurrentUser.mockReturnValue( - new User({ - name: 'Docket Clerk', - role: ROLES.docketClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }), - ); }); it('throws error if user is unauthorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: 'petitioner', - }); - await expect( - deleteTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + deleteTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -52,9 +46,13 @@ describe('deleteTrialSessionInteractor', () => { mockTrialSession = null; await expect( - deleteTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + deleteTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ), ).rejects.toThrow( 'Trial session c54ba5a9-b37b-479d-9201-067ec6e335bb was not found.', ); @@ -66,9 +64,13 @@ describe('deleteTrialSessionInteractor', () => { }; await expect( - deleteTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + deleteTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Trial session cannot be updated after its start date'); }); @@ -80,9 +82,13 @@ describe('deleteTrialSessionInteractor', () => { }; await expect( - deleteTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + deleteTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Trial session cannot be deleted after it is calendared'); }); @@ -96,9 +102,13 @@ describe('deleteTrialSessionInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE); - await deleteTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + await deleteTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().deleteTrialSessionWorkingCopy, @@ -126,9 +136,13 @@ describe('deleteTrialSessionInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE); - await deleteTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + await deleteTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().deleteTrialSessionWorkingCopy, @@ -148,9 +162,13 @@ describe('deleteTrialSessionInteractor', () => { preferredTrialCity: null, }); - await deleteTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + await deleteTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -171,9 +189,13 @@ describe('deleteTrialSessionInteractor', () => { mockLock = MOCK_LOCK; await expect( - deleteTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + deleteTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -191,9 +213,13 @@ describe('deleteTrialSessionInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE); - await deleteTrialSessionInteractor(applicationContext, { - trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + await deleteTrialSessionInteractor( + applicationContext, + { + trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, ).toHaveBeenCalledTimes(mockTrialSession.caseOrder.length); diff --git a/web-api/src/business/useCases/trialSessions/deleteTrialSessionInteractor.ts b/web-api/src/business/useCases/trialSessions/deleteTrialSessionInteractor.ts index dd0ebf0526a..500b17a7412 100644 --- a/web-api/src/business/useCases/trialSessions/deleteTrialSessionInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/deleteTrialSessionInteractor.ts @@ -6,6 +6,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { acquireLock } from '@web-api/business/useCaseHelper/acquireLock'; /** @@ -18,10 +19,9 @@ import { acquireLock } from '@web-api/business/useCaseHelper/acquireLock'; export const deleteTrialSessionInteractor = async ( applicationContext: ServerApplicationContext, { trialSessionId }: { trialSessionId: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } @@ -36,9 +36,7 @@ export const deleteTrialSessionInteractor = async ( throw new NotFoundError(`Trial session ${trialSessionId} was not found.`); } - const trialSessionEntity = new TrialSession(trialSession, { - applicationContext, - }); + const trialSessionEntity = new TrialSession(trialSession); if ( trialSessionEntity.startDate < @@ -58,6 +56,7 @@ export const deleteTrialSessionInteractor = async ( await acquireLock({ applicationContext, + authorizedUser, identifiers: docketNumbers?.map(item => `case|${item}`), }); @@ -69,7 +68,7 @@ export const deleteTrialSessionInteractor = async ( docketNumber: order.docketNumber, }); - const caseEntity = new Case(myCase, { applicationContext }); + const caseEntity = new Case(myCase, { authorizedUser }); caseEntity.removeFromTrial({}); @@ -85,6 +84,7 @@ export const deleteTrialSessionInteractor = async ( await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); } diff --git a/web-api/src/business/useCases/trialSessions/dismissNOTTReminderForTrialInteractor.test.ts b/web-api/src/business/useCases/trialSessions/dismissNOTTReminderForTrialInteractor.test.ts index 8b2047e3466..45c1dd4367f 100644 --- a/web-api/src/business/useCases/trialSessions/dismissNOTTReminderForTrialInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/dismissNOTTReminderForTrialInteractor.test.ts @@ -2,33 +2,37 @@ import { MOCK_TRIAL_REGULAR } from '../../../../../shared/src/test/mockTrial'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { dismissNOTTReminderForTrialInteractor } from './dismissNOTTReminderForTrialInteractor'; import { - docketClerkUser, - petitionsClerkUser, -} from '../../../../../shared/src/test/mockUsers'; + mockDocketClerkUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('dismissNOTTReminderForTrialInteractor', () => { beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - applicationContext .getPersistenceGateway() .getTrialSessionById.mockReturnValue(MOCK_TRIAL_REGULAR); }); it('should throw an error when the user is unauthorized to dismiss NOTT alerts', async () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - await expect( - dismissNOTTReminderForTrialInteractor(applicationContext, { - trialSessionId: MOCK_TRIAL_REGULAR.trialSessionId!, - }), + dismissNOTTReminderForTrialInteractor( + applicationContext, + { + trialSessionId: MOCK_TRIAL_REGULAR.trialSessionId!, + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Unauthorized to dismiss NOTT reminder'); }); it('should update the trial session with a flag indicating that the NOTT filing reminder has been dismissed', async () => { - await dismissNOTTReminderForTrialInteractor(applicationContext, { - trialSessionId: MOCK_TRIAL_REGULAR.trialSessionId!, - }); + await dismissNOTTReminderForTrialInteractor( + applicationContext, + { + trialSessionId: MOCK_TRIAL_REGULAR.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateTrialSession.mock diff --git a/web-api/src/business/useCases/trialSessions/dismissNOTTReminderForTrialInteractor.ts b/web-api/src/business/useCases/trialSessions/dismissNOTTReminderForTrialInteractor.ts index f0195403c09..6c6672042f0 100644 --- a/web-api/src/business/useCases/trialSessions/dismissNOTTReminderForTrialInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/dismissNOTTReminderForTrialInteractor.ts @@ -6,6 +6,7 @@ import { import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '../../../../../shared/src/business/entities/authUser/AuthUser'; /** * dismissNOTTReminderForTrialInteractor @@ -16,10 +17,9 @@ import { UnauthorizedError } from '@web-api/errors/errors'; export const dismissNOTTReminderForTrialInteractor = async ( applicationContext: ServerApplicationContext, { trialSessionId }: { trialSessionId: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.DISMISS_NOTT_REMINDER)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.DISMISS_NOTT_REMINDER)) { throw new UnauthorizedError('Unauthorized to dismiss NOTT reminder'); } @@ -34,12 +34,10 @@ export const dismissNOTTReminderForTrialInteractor = async ( throw new NotFoundError(`Trial session ${trialSessionId} was not found.`); } - const updatedTrialSessionEntity: TrialSession = new TrialSession( - { ...currentTrialSession, dismissedAlertForNOTT: true }, - { - applicationContext, - }, - ); + const updatedTrialSessionEntity: TrialSession = new TrialSession({ + ...currentTrialSession, + dismissedAlertForNOTT: true, + }); await applicationContext.getPersistenceGateway().updateTrialSession({ applicationContext, diff --git a/web-api/src/business/useCases/trialSessions/generateNoticeOfChangeOfTrialJudgeInteractor.ts b/web-api/src/business/useCases/trialSessions/generateNoticeOfChangeOfTrialJudgeInteractor.ts index c6f1f421cdb..edb13973837 100644 --- a/web-api/src/business/useCases/trialSessions/generateNoticeOfChangeOfTrialJudgeInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/generateNoticeOfChangeOfTrialJudgeInteractor.ts @@ -18,7 +18,7 @@ export const generateNoticeOfChangeOfTrialJudgeInteractor = async ( docketNumber: string; trialSessionInformation: RawTrialSession; }, -): Promise => { +): Promise => { const formattedStartDate = formatDateString( trialSessionInformation.startDate, FORMATS.MONTH_DAY_YEAR_WITH_DAY_OF_WEEK, diff --git a/web-api/src/business/useCases/trialSessions/generateNoticeOfChangeToRemoteProceedingInteractor.ts b/web-api/src/business/useCases/trialSessions/generateNoticeOfChangeToRemoteProceedingInteractor.ts index 3d9158136f4..26e9c185d7a 100644 --- a/web-api/src/business/useCases/trialSessions/generateNoticeOfChangeToRemoteProceedingInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/generateNoticeOfChangeToRemoteProceedingInteractor.ts @@ -21,7 +21,7 @@ export const generateNoticeOfChangeToRemoteProceedingInteractor = async ( docketNumber, trialSessionInformation, }: { docketNumber; trialSessionInformation: TrialSessionInformationType }, -): Promise => { +): Promise => { const formattedStartDate = formatDateString( trialSessionInformation.startDate, FORMATS.MONTH_DAY_YEAR_WITH_DAY_OF_WEEK, diff --git a/web-api/src/business/useCases/trialSessions/generateNoticeOfTrialIssuedInteractor.ts b/web-api/src/business/useCases/trialSessions/generateNoticeOfTrialIssuedInteractor.ts index 363c0d92f24..45470dc97bc 100644 --- a/web-api/src/business/useCases/trialSessions/generateNoticeOfTrialIssuedInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/generateNoticeOfTrialIssuedInteractor.ts @@ -22,7 +22,7 @@ export const generateNoticeOfTrialIssuedInteractor = async ( docketNumber, trialSessionId, }: { docketNumber: string; trialSessionId: string }, -): Promise => { +): Promise => { const trialSession = await applicationContext .getPersistenceGateway() .getTrialSessionById({ diff --git a/web-api/src/business/useCases/trialSessions/generateNoticesForCaseTrialSessionCalendarInteractor.ts b/web-api/src/business/useCases/trialSessions/generateNoticesForCaseTrialSessionCalendarInteractor.ts index 3dd9dab755d..c59aec7fb61 100644 --- a/web-api/src/business/useCases/trialSessions/generateNoticesForCaseTrialSessionCalendarInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/generateNoticesForCaseTrialSessionCalendarInteractor.ts @@ -127,8 +127,16 @@ const setNoticeForCase = async ({ trialSession, trialSessionEntity, user, +}: { + applicationContext: ServerApplicationContext; + caseRecord: any; + docketNumber: any; + jobId: any; + trialSession: any; + trialSessionEntity: any; + user: any; }) => { - const caseEntity = new Case(caseRecord, { applicationContext }); + const caseEntity = new Case(caseRecord, { authorizedUser: undefined }); const { procedureType } = caseRecord; let noticeOfTrialIssued = await applicationContext @@ -199,7 +207,7 @@ const setNoticeForCase = async ({ signedAt: applicationContext.getUtilities().createISODateString(), // The signature is in the template of the document being generated trialLocation: trialSessionEntity.trialLocation, }, - { applicationContext }, + { authorizedUser: undefined }, ); noticeOfTrialDocketEntry.setFiledBy(user); @@ -267,7 +275,7 @@ const setNoticeForCase = async ({ judge: trialSessionEntity.judge.name, processingStatus: DOCUMENT_PROCESSING_STATUS_OPTIONS.COMPLETE, }, - { applicationContext }, + { authorizedUser: undefined }, ); standingPretrialDocketEntry.setFiledBy(user); @@ -306,6 +314,7 @@ const setNoticeForCase = async ({ await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser: undefined, caseToUpdate: caseEntity, }); @@ -365,9 +374,7 @@ export const generateNoticesForCaseTrialSessionCalendarInteractor = async ( status: 'processing', }); - const trialSessionEntity = new TrialSession(trialSession, { - applicationContext, - }); + const trialSessionEntity = new TrialSession(trialSession); const caseRecord = await applicationContext .getPersistenceGateway() diff --git a/web-api/src/business/useCases/trialSessions/generatePrintableTrialSessionCopyReportInteractor.ts b/web-api/src/business/useCases/trialSessions/generatePrintableTrialSessionCopyReportInteractor.ts index f71f7edb7f1..4d3dd92f2f5 100644 --- a/web-api/src/business/useCases/trialSessions/generatePrintableTrialSessionCopyReportInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/generatePrintableTrialSessionCopyReportInteractor.ts @@ -6,6 +6,7 @@ import { import { RawTrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const generatePrintableTrialSessionCopyReportInteractor = async ( applicationContext: ServerApplicationContext, @@ -26,8 +27,8 @@ export const generatePrintableTrialSessionCopyReportInteractor = async ( sort: string; userHeading: string; }, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); if ( !isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSION_WORKING_COPY) ) { diff --git a/web-api/src/business/useCases/trialSessions/generateTrialSessionPaperServicePdfInteractor.test.ts b/web-api/src/business/useCases/trialSessions/generateTrialSessionPaperServicePdfInteractor.test.ts index 9ad28673ca8..89ce5e6802a 100644 --- a/web-api/src/business/useCases/trialSessions/generateTrialSessionPaperServicePdfInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/generateTrialSessionPaperServicePdfInteractor.test.ts @@ -1,7 +1,10 @@ import { MOCK_TRIAL_INPERSON } from '@shared/test/mockTrial'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { generateTrialSessionPaperServicePdfInteractor } from './generateTrialSessionPaperServicePdfInteractor'; -import { petitionerUser, petitionsClerkUser } from '@shared/test/mockUsers'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { testPdfDoc } from '../../../../../shared/src/business/test/getFakeFile'; describe('generateTrialSessionPaperServicePdfInteractor', () => { @@ -9,8 +12,6 @@ describe('generateTrialSessionPaperServicePdfInteractor', () => { const mockFileId = '46f3244d-aaca-48c8-a7c1-de561d000c90'; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - applicationContext .getPersistenceGateway() .getDocument.mockResolvedValue(testPdfDoc); @@ -24,13 +25,15 @@ describe('generateTrialSessionPaperServicePdfInteractor', () => { }); it('should return an unauthorized error when the user does not have the TRIAL_SESSIONS permission', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); // Petitioners do not have permission to manage trial sessions - await expect( - generateTrialSessionPaperServicePdfInteractor(applicationContext, { - trialNoticePdfsKeys: ['1234-56'], - trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, - }), + generateTrialSessionPaperServicePdfInteractor( + applicationContext, + { + trialNoticePdfsKeys: ['1234-56'], + trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -40,10 +43,14 @@ describe('generateTrialSessionPaperServicePdfInteractor', () => { .getPersistenceGateway() .getTrialSessionById.mockResolvedValue(MOCK_TRIAL_INPERSON); - await generateTrialSessionPaperServicePdfInteractor(applicationContext, { - trialNoticePdfsKeys: mockTrialNoticePdfsKeys, - trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, - }); + await generateTrialSessionPaperServicePdfInteractor( + applicationContext, + { + trialNoticePdfsKeys: mockTrialNoticePdfsKeys, + trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getDocument, @@ -70,10 +77,14 @@ describe('generateTrialSessionPaperServicePdfInteractor', () => { }); it('should send a notification to the user when combining the paper service documents is complete', async () => { - await generateTrialSessionPaperServicePdfInteractor(applicationContext, { - trialNoticePdfsKeys: ['123-56'], - trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, - }); + await generateTrialSessionPaperServicePdfInteractor( + applicationContext, + { + trialNoticePdfsKeys: ['123-56'], + trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock .calls[2][0], diff --git a/web-api/src/business/useCases/trialSessions/generateTrialSessionPaperServicePdfInteractor.ts b/web-api/src/business/useCases/trialSessions/generateTrialSessionPaperServicePdfInteractor.ts index 5f8817c7ebf..a05d1bfcd20 100644 --- a/web-api/src/business/useCases/trialSessions/generateTrialSessionPaperServicePdfInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/generateTrialSessionPaperServicePdfInteractor.ts @@ -6,6 +6,7 @@ import { import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialSession } from '@shared/business/entities/trialSessions/TrialSession'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const generateTrialSessionPaperServicePdfInteractor = async ( applicationContext: ServerApplicationContext, @@ -18,10 +19,9 @@ export const generateTrialSessionPaperServicePdfInteractor = async ( trialSessionId: string; clientConnectionId: string; }, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } @@ -35,7 +35,7 @@ export const generateTrialSessionPaperServicePdfInteractor = async ( action: 'paper_service_started', totalPdfs: trialNoticePdfsKeys.length, }, - userId: user.userId, + userId: authorizedUser.userId, }); let pdfsAppended = 0; @@ -65,7 +65,7 @@ export const generateTrialSessionPaperServicePdfInteractor = async ( action: 'paper_service_updated', pdfsAppended, }, - userId: user.userId, + userId: authorizedUser.userId, }); } @@ -92,9 +92,7 @@ export const generateTrialSessionPaperServicePdfInteractor = async ( throw new NotFoundError(`Trial session ${trialSessionId} was not found.`); } - const trialSessionEntity = new TrialSession(trialSession, { - applicationContext, - }); + const trialSessionEntity = new TrialSession(trialSession); trialSessionEntity.addPaperServicePdf(fileId, 'Initial Calendaring'); @@ -117,6 +115,6 @@ export const generateTrialSessionPaperServicePdfInteractor = async ( hasPaper: true, pdfUrl, }, - userId: user.userId, + userId: authorizedUser.userId, }); }; diff --git a/web-api/src/business/useCases/trialSessions/getCalendaredCasesForTrialSessionInteractor.test.ts b/web-api/src/business/useCases/trialSessions/getCalendaredCasesForTrialSessionInteractor.test.ts index 6802e75469c..d5cb3acf4f7 100644 --- a/web-api/src/business/useCases/trialSessions/getCalendaredCasesForTrialSessionInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/getCalendaredCasesForTrialSessionInteractor.test.ts @@ -1,48 +1,41 @@ import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; -import { - PARTIES_CODES, - PARTY_TYPES, - ROLES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { PARTIES_CODES } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; -import { User } from '../../../../../shared/src/business/entities/User'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getCalendaredCasesForTrialSessionInteractor } from './getCalendaredCasesForTrialSessionInteractor'; - -const user = new User({ - name: 'Docket Clerk', - role: ROLES.docketClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', -}); +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getCalendaredCasesForTrialSessionInteractor', () => { beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(user); applicationContext .getPersistenceGateway() .getCalendaredCasesForTrialSession.mockReturnValue([MOCK_CASE]); }); it('throws an exception when the user is unauthorized', async () => { - const unAuthedUser = new User({ - name: PARTY_TYPES.petitioner, - role: ROLES.petitioner, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - applicationContext.getCurrentUser.mockReturnValueOnce(unAuthedUser); - await expect( - getCalendaredCasesForTrialSessionInteractor(applicationContext, { - trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }), + getCalendaredCasesForTrialSessionInteractor( + applicationContext, + { + trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); it('should find the cases for a trial session successfully', async () => { await expect( - getCalendaredCasesForTrialSessionInteractor(applicationContext, { - trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }), + getCalendaredCasesForTrialSessionInteractor( + applicationContext, + { + trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', + }, + mockDocketClerkUser, + ), ).resolves.not.toThrow(); }); @@ -74,6 +67,7 @@ describe('getCalendaredCasesForTrialSessionInteractor', () => { { trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', }, + mockDocketClerkUser, ); expect(cases[0].PMTServedPartiesCode).toEqual(PARTIES_CODES.PETITIONER); @@ -89,6 +83,7 @@ describe('getCalendaredCasesForTrialSessionInteractor', () => { { trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', }, + mockDocketClerkUser, ); removedFields.forEach(field => { diff --git a/web-api/src/business/useCases/trialSessions/getCalendaredCasesForTrialSessionInteractor.ts b/web-api/src/business/useCases/trialSessions/getCalendaredCasesForTrialSessionInteractor.ts index 933209df281..f694430ee72 100644 --- a/web-api/src/business/useCases/trialSessions/getCalendaredCasesForTrialSessionInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/getCalendaredCasesForTrialSessionInteractor.ts @@ -5,13 +5,14 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const getCalendaredCasesForTrialSessionInteractor = async ( applicationContext: ServerApplicationContext, { trialSessionId }: { trialSessionId: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/trialSessions/getEligibleCasesForTrialSessionInteractor.test.ts b/web-api/src/business/useCases/trialSessions/getEligibleCasesForTrialSessionInteractor.test.ts index 32e4f90a035..429b3c6e3ef 100644 --- a/web-api/src/business/useCases/trialSessions/getEligibleCasesForTrialSessionInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/getEligibleCasesForTrialSessionInteractor.test.ts @@ -3,17 +3,16 @@ import { MOCK_ELIGIBLE_CASE, MOCK_ELIGIBLE_CASE_WITH_PRACTITIONERS, } from '../../../../../shared/src/test/mockCase'; -import { - ROLES, - TRIAL_SESSION_PROCEEDING_TYPES, -} from '../../../../../shared/src/business/entities/EntityConstants'; -import { User } from '../../../../../shared/src/business/entities/User'; +import { TRIAL_SESSION_PROCEEDING_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { cloneDeep } from 'lodash'; import { getEligibleCasesForTrialSessionInteractor } from './getEligibleCasesForTrialSessionInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getEligibleCasesForTrialSessionInteractor', () => { - let mockCurrentUser; let mockTrial; const MOCK_TRIAL = { @@ -32,15 +31,8 @@ describe('getEligibleCasesForTrialSessionInteractor', () => { }; beforeEach(() => { - mockCurrentUser = new User({ - name: 'Docket Clerk', - role: ROLES.docketClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - mockTrial = MOCK_TRIAL; - applicationContext.getCurrentUser.mockImplementation(() => mockCurrentUser); applicationContext .getPersistenceGateway() .getTrialSessionById.mockImplementation(() => mockTrial); @@ -55,27 +47,37 @@ describe('getEligibleCasesForTrialSessionInteractor', () => { }); it('throws an exception when it fails to find the cases for a trial session', async () => { - mockCurrentUser = {}; - await expect( - getEligibleCasesForTrialSessionInteractor(applicationContext, { - trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }), + getEligibleCasesForTrialSessionInteractor( + applicationContext, + { + trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', + }, + mockPetitionerUser, + ), ).rejects.toThrow(); }); it('should find the cases for a trial session successfully', async () => { await expect( - getEligibleCasesForTrialSessionInteractor(applicationContext, { - trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }), + getEligibleCasesForTrialSessionInteractor( + applicationContext, + { + trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', + }, + mockDocketClerkUser, + ), ).resolves.not.toThrow(); }); it('should call getEligibleCasesForTrialSession with correct limit', async () => { - await getEligibleCasesForTrialSessionInteractor(applicationContext, { - trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); + await getEligibleCasesForTrialSessionInteractor( + applicationContext, + { + trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getEligibleCasesForTrialSession @@ -111,6 +113,7 @@ describe('getEligibleCasesForTrialSessionInteractor', () => { { trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', }, + mockDocketClerkUser, ); } catch (e) { error = e; diff --git a/web-api/src/business/useCases/trialSessions/getEligibleCasesForTrialSessionInteractor.ts b/web-api/src/business/useCases/trialSessions/getEligibleCasesForTrialSessionInteractor.ts index 04fc22a9f04..687bb4f4566 100644 --- a/web-api/src/business/useCases/trialSessions/getEligibleCasesForTrialSessionInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/getEligibleCasesForTrialSessionInteractor.ts @@ -11,6 +11,7 @@ import { } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { TRIAL_SESSION_ELIGIBLE_CASES_BUFFER } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * get eligible cases for trial session @@ -23,10 +24,9 @@ import { UnauthorizedError } from '@web-api/errors/errors'; export const getEligibleCasesForTrialSessionInteractor = async ( applicationContext: ServerApplicationContext, { trialSessionId }: { trialSessionId: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } @@ -53,9 +53,7 @@ export const getEligibleCasesForTrialSessionInteractor = async ( }); } - const trialSessionEntity = new TrialSession(trialSession, { - applicationContext, - }); + const trialSessionEntity = new TrialSession(trialSession); trialSessionEntity.validate(); diff --git a/web-api/src/business/useCases/trialSessions/getTrialSessionDetailsInteractor.test.ts b/web-api/src/business/useCases/trialSessions/getTrialSessionDetailsInteractor.test.ts index 051bf63e734..9d80a54ea29 100644 --- a/web-api/src/business/useCases/trialSessions/getTrialSessionDetailsInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/getTrialSessionDetailsInteractor.test.ts @@ -1,10 +1,11 @@ -import { - ROLES, - TRIAL_SESSION_PROCEEDING_TYPES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { TRIAL_SESSION_PROCEEDING_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getTrialSessionDetailsInteractor } from './getTrialSessionDetailsInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { omit } from 'lodash'; describe('Get trial session details', () => { @@ -19,23 +20,19 @@ describe('Get trial session details', () => { trialSessionId: '208a959f-9526-4db5-b262-e58c476a4604', }; - beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }); - }); - it('throws error if user is unauthorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({}); applicationContext .getPersistenceGateway() .getTrialSessionById.mockReturnValue({}); await expect( - getTrialSessionDetailsInteractor(applicationContext, { - trialSessionId: MOCK_TRIAL_SESSION.trialSessionId, - }), + getTrialSessionDetailsInteractor( + applicationContext, + { + trialSessionId: MOCK_TRIAL_SESSION.trialSessionId, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -47,9 +44,13 @@ describe('Get trial session details', () => { ); await expect( - getTrialSessionDetailsInteractor(applicationContext, { - trialSessionId: MOCK_TRIAL_SESSION.trialSessionId, - }), + getTrialSessionDetailsInteractor( + applicationContext, + { + trialSessionId: MOCK_TRIAL_SESSION.trialSessionId, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('The TrialSession entity was invalid'); }); @@ -59,9 +60,13 @@ describe('Get trial session details', () => { .getTrialSessionById.mockResolvedValue(null); await expect( - getTrialSessionDetailsInteractor(applicationContext, { - trialSessionId: MOCK_TRIAL_SESSION.trialSessionId, - }), + getTrialSessionDetailsInteractor( + applicationContext, + { + trialSessionId: MOCK_TRIAL_SESSION.trialSessionId, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow( 'Trial session 208a959f-9526-4db5-b262-e58c476a4604 was not found.', ); @@ -72,9 +77,13 @@ describe('Get trial session details', () => { .getPersistenceGateway() .getTrialSessionById.mockResolvedValue(MOCK_TRIAL_SESSION); - const result = await getTrialSessionDetailsInteractor(applicationContext, { - trialSessionId: MOCK_TRIAL_SESSION.trialSessionId, - }); + const result = await getTrialSessionDetailsInteractor( + applicationContext, + { + trialSessionId: MOCK_TRIAL_SESSION.trialSessionId, + }, + mockPetitionsClerkUser, + ); expect(result).toMatchObject(MOCK_TRIAL_SESSION); }); }); diff --git a/web-api/src/business/useCases/trialSessions/getTrialSessionDetailsInteractor.ts b/web-api/src/business/useCases/trialSessions/getTrialSessionDetailsInteractor.ts index 36ede96b20b..650b8abcdde 100644 --- a/web-api/src/business/useCases/trialSessions/getTrialSessionDetailsInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/getTrialSessionDetailsInteractor.ts @@ -8,13 +8,14 @@ import { TrialSession, } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const getTrialSessionDetailsInteractor = async ( applicationContext: ServerApplicationContext, { trialSessionId }: { trialSessionId: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } @@ -29,9 +30,7 @@ export const getTrialSessionDetailsInteractor = async ( throw new NotFoundError(`Trial session ${trialSessionId} was not found.`); } - const trialSessionEntity = new TrialSession(trialSessionDetails, { - applicationContext, - }).validate(); + const trialSessionEntity = new TrialSession(trialSessionDetails).validate(); return trialSessionEntity.toRawObject(); }; diff --git a/web-api/src/business/useCases/trialSessions/getTrialSessionWorkingCopyInteractor.test.ts b/web-api/src/business/useCases/trialSessions/getTrialSessionWorkingCopyInteractor.test.ts index 028351c2ac7..dea89042fad 100644 --- a/web-api/src/business/useCases/trialSessions/getTrialSessionWorkingCopyInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/getTrialSessionWorkingCopyInteractor.test.ts @@ -2,6 +2,12 @@ import { ROLES } from '../../../../../shared/src/business/entities/EntityConstan import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getTrialSessionWorkingCopyInteractor } from './getTrialSessionWorkingCopyInteractor'; +import { + mockChambersUser, + mockJudgeUser, + mockPetitionerUser, + mockTrialClerkUser, +} from '@shared/test/mockAuthUsers'; import { omit } from 'lodash'; const MOCK_WORKING_COPY = { @@ -39,7 +45,6 @@ describe('Get trial session working copy', () => { trialLocation: 'Birmingham, Alabama', }); - applicationContext.getCurrentUser.mockImplementation(() => user); applicationContext.getPersistenceGateway().getUserById.mockReturnValue({ ...user, section: 'colvinsChambers', @@ -58,15 +63,14 @@ describe('Get trial session working copy', () => { }); it('throws error if user is unauthorized', async () => { - user = { - role: 'unauthorizedRole', - userId: 'unauthorizedUser', - }; - await expect( - getTrialSessionWorkingCopyInteractor(applicationContext, { - trialSessionId: MOCK_WORKING_COPY.trialSessionId, - }), + getTrialSessionWorkingCopyInteractor( + applicationContext, + { + trialSessionId: MOCK_WORKING_COPY.trialSessionId, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -78,9 +82,13 @@ describe('Get trial session working copy', () => { ); await expect( - getTrialSessionWorkingCopyInteractor(applicationContext, { - trialSessionId: MOCK_WORKING_COPY.trialSessionId, - }), + getTrialSessionWorkingCopyInteractor( + applicationContext, + { + trialSessionId: MOCK_WORKING_COPY.trialSessionId, + }, + mockJudgeUser, + ), ).rejects.toThrow('The TrialSessionWorkingCopy entity was invalid'); }); @@ -90,12 +98,14 @@ describe('Get trial session working copy', () => { { trialSessionId: MOCK_WORKING_COPY.trialSessionId, }, + mockJudgeUser, ); expect(result).toMatchObject(MOCK_WORKING_COPY); }); it('does not return data if none is returned from persistence', async () => { user = { + ...mockJudgeUser, name: 'judge who cannot create working copy', role: ROLES.judge, userId: 'something else', @@ -108,17 +118,18 @@ describe('Get trial session working copy', () => { .getJudgeInSectionHelper.mockReturnValue(null); await expect( - getTrialSessionWorkingCopyInteractor(applicationContext, { - trialSessionId: MOCK_WORKING_COPY.trialSessionId, - }), + getTrialSessionWorkingCopyInteractor( + applicationContext, + { + trialSessionId: MOCK_WORKING_COPY.trialSessionId, + }, + mockJudgeUser, + ), ).rejects.toThrow('Trial session working copy not found'); }); it('correctly returns data from persistence for a trial clerk user', async () => { - user = { - role: ROLES.trialClerk, - userId: 'a9ae05ba-d48a-43a6-9981-ee536a7601be', - }; + user = mockTrialClerkUser; applicationContext .getUseCaseHelpers() .getJudgeInSectionHelper.mockImplementation(() => {}); @@ -128,12 +139,13 @@ describe('Get trial session working copy', () => { { trialSessionId: MOCK_WORKING_COPY.trialSessionId, }, + user, ); expect( applicationContext.getPersistenceGateway().getTrialSessionWorkingCopy.mock .calls[0][0], ).toMatchObject({ - userId: 'a9ae05ba-d48a-43a6-9981-ee536a7601be', + userId: mockTrialClerkUser.userId, }); expect(result).toMatchObject(MOCK_WORKING_COPY); }); @@ -185,15 +197,15 @@ describe('Get trial session working copy', () => { trialClerk: undefined, trialLocation: 'Birmingham, Alabama', }); - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.judge, - userId: 'd7d90c05-f6cd-442c-a168-202db587f16f', - }); const result = await getTrialSessionWorkingCopyInteractor( applicationContext, { trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }, + { + ...mockJudgeUser, + userId: 'd7d90c05-f6cd-442c-a168-202db587f16f', + }, ); expect( applicationContext.getPersistenceGateway().getTrialSessionById, @@ -212,15 +224,16 @@ describe('Get trial session working copy', () => { applicationContext .getUseCaseHelpers() .getJudgeInSectionHelper.mockReturnValueOnce(undefined); - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.trialClerk, - userId: 'ffd90c05-f6cd-442c-a168-202db587f16f', - }); + const result = await getTrialSessionWorkingCopyInteractor( applicationContext, { trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }, + { + ...mockTrialClerkUser, + userId: 'ffd90c05-f6cd-442c-a168-202db587f16f', + }, ); expect( applicationContext.getPersistenceGateway().getTrialSessionById, @@ -236,15 +249,16 @@ describe('Get trial session working copy', () => { }); it('for current user who is a chambers user whose associated judge is on this trial session', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.chambers, - userId: 'ffd90c05-f6cd-442c-a168-202db587f16f', - }); const result = await getTrialSessionWorkingCopyInteractor( applicationContext, { trialSessionId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }, + { + ...mockChambersUser, + role: ROLES.chambers, + userId: 'ffd90c05-f6cd-442c-a168-202db587f16f', + }, ); expect( applicationContext.getPersistenceGateway().getTrialSessionById, diff --git a/web-api/src/business/useCases/trialSessions/getTrialSessionWorkingCopyInteractor.ts b/web-api/src/business/useCases/trialSessions/getTrialSessionWorkingCopyInteractor.ts index edeb3ec3b49..b448ba5c306 100644 --- a/web-api/src/business/useCases/trialSessions/getTrialSessionWorkingCopyInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/getTrialSessionWorkingCopyInteractor.ts @@ -6,6 +6,7 @@ import { import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { TrialSessionWorkingCopy } from '../../../../../shared/src/business/entities/trialSessions/TrialSessionWorkingCopy'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { User } from '../../../../../shared/src/business/entities/User'; /** @@ -19,16 +20,17 @@ import { User } from '../../../../../shared/src/business/entities/User'; export const getTrialSessionWorkingCopyInteractor = async ( applicationContext: ServerApplicationContext, { trialSessionId }: { trialSessionId: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSION_WORKING_COPY)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSION_WORKING_COPY) + ) { throw new UnauthorizedError('Unauthorized'); } const rawUser = await applicationContext.getPersistenceGateway().getUserById({ applicationContext, - userId: user.userId, + userId: authorizedUser?.userId || '', }); const userEntity = new User(rawUser); @@ -39,7 +41,8 @@ export const getTrialSessionWorkingCopyInteractor = async ( section: userEntity.section, }); - const chambersUserId = (judgeUser && judgeUser.userId) || user.userId; + const chambersUserId = + (judgeUser && judgeUser.userId) || authorizedUser?.userId || ''; let trialSessionWorkingCopyEntity, validRawTrialSessionWorkingCopyEntity; @@ -70,9 +73,7 @@ export const getTrialSessionWorkingCopyInteractor = async ( throw new NotFoundError(`Trial session ${trialSessionId} was not found.`); } - const trialSessionEntity = new TrialSession(trialSessionDetails, { - applicationContext, - }); + const trialSessionEntity = new TrialSession(trialSessionDetails); const canCreateWorkingCopy = (trialSessionEntity.trialClerk && diff --git a/web-api/src/business/useCases/trialSessions/getTrialSessionsForJudgeInteractor.test.ts b/web-api/src/business/useCases/trialSessions/getTrialSessionsForJudgeInteractor.test.ts index b9f3939a7b6..40b82c14228 100644 --- a/web-api/src/business/useCases/trialSessions/getTrialSessionsForJudgeInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/getTrialSessionsForJudgeInteractor.test.ts @@ -1,6 +1,9 @@ -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getTrialSessionsForJudgeInteractor } from './getTrialSessionsForJudgeInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; const MOCK_TRIAL_SESSION = { maxCases: 100, @@ -21,17 +24,15 @@ describe('getTrialSessionsForJudgeInteractor', () => { ); await expect( - getTrialSessionsForJudgeInteractor(applicationContext, JUDGE_ID), + getTrialSessionsForJudgeInteractor( + applicationContext, + JUDGE_ID, + mockPetitionerUser, + ), ).rejects.toThrow(); }); it('should only return trial sessions associated with the judgeId', async () => { - applicationContext.getCurrentUser.mockImplementation(() => { - return { - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }; - }); applicationContext .getPersistenceGateway() .getTrialSessions.mockResolvedValue([ @@ -47,6 +48,7 @@ describe('getTrialSessionsForJudgeInteractor', () => { const trialSessions = await getTrialSessionsForJudgeInteractor( applicationContext, JUDGE_ID, + mockPetitionsClerkUser, ); expect(trialSessions.length).toEqual(1); diff --git a/web-api/src/business/useCases/trialSessions/getTrialSessionsForJudgeInteractor.ts b/web-api/src/business/useCases/trialSessions/getTrialSessionsForJudgeInteractor.ts index 02b23af92e7..8e9d11cde39 100644 --- a/web-api/src/business/useCases/trialSessions/getTrialSessionsForJudgeInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/getTrialSessionsForJudgeInteractor.ts @@ -6,6 +6,7 @@ import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { TrialSessionInfoDTO } from '../../../../../shared/src/business/dto/trialSessions/TrialSessionInfoDTO'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * getTrialSessionsForJudgeInteractor @@ -16,10 +17,9 @@ import { UnauthorizedError } from '@web-api/errors/errors'; export const getTrialSessionsForJudgeInteractor = async ( applicationContext: ServerApplicationContext, judgeId: string, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } @@ -35,9 +35,6 @@ export const getTrialSessionsForJudgeInteractor = async ( const validatedSessions = TrialSession.validateRawCollection( judgeSessions as any, - { - applicationContext, - }, ); return validatedSessions.map( diff --git a/web-api/src/business/useCases/trialSessions/getTrialSessionsInteractor.test.ts b/web-api/src/business/useCases/trialSessions/getTrialSessionsInteractor.test.ts index a1754bdeb8b..60e283bdd13 100644 --- a/web-api/src/business/useCases/trialSessions/getTrialSessionsInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/getTrialSessionsInteractor.test.ts @@ -6,22 +6,16 @@ import { TrialSessionInfoDTO } from '../../../../../shared/src/business/dto/tria import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getTrialSessionsInteractor } from './getTrialSessionsInteractor'; -import { omit } from 'lodash'; import { - petitionerUser, - petitionsClerkUser, -} from '../../../../../shared/src/test/mockUsers'; + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; +import { omit } from 'lodash'; describe('getTrialSessionsInteractor', () => { - beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - }); - it('should throw an unauthorized error when the user does not have permission to view trial sessions', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - await expect( - getTrialSessionsInteractor(applicationContext), + getTrialSessionsInteractor(applicationContext, mockPetitionerUser), ).rejects.toThrow(new UnauthorizedError('Unauthorized')); }); @@ -33,7 +27,7 @@ describe('getTrialSessionsInteractor', () => { ]); await expect( - getTrialSessionsInteractor(applicationContext), + getTrialSessionsInteractor(applicationContext, mockPetitionsClerkUser), ).rejects.toThrow('The TrialSession entity was invalid.'); }); @@ -45,8 +39,10 @@ describe('getTrialSessionsInteractor', () => { MOCK_TRIAL_REGULAR, ]); - const trialSessionDTOs = - await getTrialSessionsInteractor(applicationContext); + const trialSessionDTOs = await getTrialSessionsInteractor( + applicationContext, + mockPetitionsClerkUser, + ); trialSessionDTOs.forEach(trialSessionDTO => { expect(trialSessionDTO instanceof TrialSessionInfoDTO).toBe(true); diff --git a/web-api/src/business/useCases/trialSessions/getTrialSessionsInteractor.ts b/web-api/src/business/useCases/trialSessions/getTrialSessionsInteractor.ts index dc6b65c63ff..854d6a181f6 100644 --- a/web-api/src/business/useCases/trialSessions/getTrialSessionsInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/getTrialSessionsInteractor.ts @@ -6,13 +6,13 @@ import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { TrialSessionInfoDTO } from '../../../../../shared/src/business/dto/trialSessions/TrialSessionInfoDTO'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const getTrialSessionsInteractor = async ( applicationContext: ServerApplicationContext, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } @@ -22,9 +22,7 @@ export const getTrialSessionsInteractor = async ( applicationContext, }); - const validatedSessions = TrialSession.validateRawCollection(trialSessions, { - applicationContext, - }); + const validatedSessions = TrialSession.validateRawCollection(trialSessions); return validatedSessions.map( trialSession => new TrialSessionInfoDTO(trialSession), diff --git a/web-api/src/business/useCases/trialSessions/removeCaseFromTrialInteractor.test.ts b/web-api/src/business/useCases/trialSessions/removeCaseFromTrialInteractor.test.ts index 34dbf5fb055..892e92e595c 100644 --- a/web-api/src/business/useCases/trialSessions/removeCaseFromTrialInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/removeCaseFromTrialInteractor.test.ts @@ -14,14 +14,13 @@ import { import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { cloneDeep } from 'lodash'; import { - petitionerUser, - petitionsClerkUser, -} from '../../../../../shared/src/test/mockUsers'; + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { removeCaseFromTrialInteractor } from './removeCaseFromTrialInteractor'; describe('removeCaseFromTrialInteractor', () => { let mockLock; - let mockUser; let mockTrialSession: RawTrialSession; beforeAll(() => { @@ -32,10 +31,7 @@ describe('removeCaseFromTrialInteractor', () => { beforeEach(() => { mockLock = undefined; - mockUser = petitionsClerkUser; mockTrialSession = cloneDeep(MOCK_TRIAL_INPERSON); - - applicationContext.getCurrentUser.mockImplementation(() => mockUser); applicationContext .getPersistenceGateway() .getTrialSessionById.mockResolvedValue(mockTrialSession); @@ -57,30 +53,37 @@ describe('removeCaseFromTrialInteractor', () => { }); it('should throw an error when the user is unauthorized to remove a case from a trial session', async () => { - mockUser = petitionerUser; await expect( - removeCaseFromTrialInteractor(applicationContext, { - associatedJudge: '123', - associatedJudgeId: '67f246a0-8803-4aef-bbd2-687ef57e3e3f', - caseStatus: 'new', - disposition: 'because', - docketNumber: MOCK_CASE.docketNumber, - trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, - }), + removeCaseFromTrialInteractor( + applicationContext, + { + associatedJudge: '123', + associatedJudgeId: '67f246a0-8803-4aef-bbd2-687ef57e3e3f', + caseStatus: 'new', + disposition: 'because', + docketNumber: MOCK_CASE.docketNumber, + trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); it('calls getTrialSessionById, updateTrialSession, getCaseByDocketNumber, and updateCase persistence methods with correct parameters for a calendared session', async () => { mockTrialSession.isCalendared = true; - await removeCaseFromTrialInteractor(applicationContext, { - associatedJudge: '123', - associatedJudgeId: '67f246a0-8803-4aef-bbd2-687ef57e3e3f', - caseStatus: CASE_STATUS_TYPES.generalDocketReadyForTrial, - disposition: 'because', - docketNumber: MOCK_CASE.docketNumber, - trialSessionId: mockTrialSession.trialSessionId!, - }); + await removeCaseFromTrialInteractor( + applicationContext, + { + associatedJudge: '123', + associatedJudgeId: '67f246a0-8803-4aef-bbd2-687ef57e3e3f', + caseStatus: CASE_STATUS_TYPES.generalDocketReadyForTrial, + disposition: 'because', + docketNumber: MOCK_CASE.docketNumber, + trialSessionId: mockTrialSession.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getTrialSessionById, @@ -140,14 +143,18 @@ describe('removeCaseFromTrialInteractor', () => { it('calls getTrialSessionById, updateTrialSession, getCaseByDocketNumber, updateCaseAutomaticBlock, and updateCase persistence methods with correct parameters for a not calendared session', async () => { mockTrialSession.isCalendared = false; - await removeCaseFromTrialInteractor(applicationContext, { - associatedJudge: '123', - associatedJudgeId: '67f246a0-8803-4aef-bbd2-687ef57e3e3f', - caseStatus: CASE_STATUS_TYPES.generalDocketReadyForTrial, - disposition: 'because', - docketNumber: MOCK_CASE.docketNumber, - trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, - }); + await removeCaseFromTrialInteractor( + applicationContext, + { + associatedJudge: '123', + associatedJudgeId: '67f246a0-8803-4aef-bbd2-687ef57e3e3f', + caseStatus: CASE_STATUS_TYPES.generalDocketReadyForTrial, + disposition: 'because', + docketNumber: MOCK_CASE.docketNumber, + trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getTrialSessionById.mock @@ -188,14 +195,18 @@ describe('removeCaseFromTrialInteractor', () => { it('updates work items to be not high priority', async () => { mockTrialSession.isCalendared = true; - await removeCaseFromTrialInteractor(applicationContext, { - associatedJudge: '123', - associatedJudgeId: '67f246a0-8803-4aef-bbd2-687ef57e3e3f', - caseStatus: 'New', - disposition: 'because', - docketNumber: MOCK_CASE.docketNumber, - trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, - }); + await removeCaseFromTrialInteractor( + applicationContext, + { + associatedJudge: '123', + associatedJudgeId: '67f246a0-8803-4aef-bbd2-687ef57e3e3f', + caseStatus: 'New', + disposition: 'because', + docketNumber: MOCK_CASE.docketNumber, + trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().setPriorityOnAllWorkItems, @@ -223,14 +234,18 @@ describe('removeCaseFromTrialInteractor', () => { trialSessionId: '959c4338-0fac-42eb-b0eb-d53b8d0195cc', }); - await removeCaseFromTrialInteractor(applicationContext, { - associatedJudge: '123', - associatedJudgeId: '67f246a0-8803-4aef-bbd2-687ef57e3e3f', - caseStatus: 'New', - disposition: 'because', - docketNumber: MOCK_CASE.docketNumber, - trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, - }); + await removeCaseFromTrialInteractor( + applicationContext, + { + associatedJudge: '123', + associatedJudgeId: '67f246a0-8803-4aef-bbd2-687ef57e3e3f', + caseStatus: 'New', + disposition: 'because', + docketNumber: MOCK_CASE.docketNumber, + trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -252,14 +267,18 @@ describe('removeCaseFromTrialInteractor', () => { trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId, }); - await removeCaseFromTrialInteractor(applicationContext, { - associatedJudge: '123', - associatedJudgeId: '67f246a0-8803-4aef-bbd2-687ef57e3e3f', - caseStatus: 'New', - disposition: 'because', - docketNumber: MOCK_CASE.docketNumber, - trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, - }); + await removeCaseFromTrialInteractor( + applicationContext, + { + associatedJudge: '123', + associatedJudgeId: '67f246a0-8803-4aef-bbd2-687ef57e3e3f', + caseStatus: 'New', + disposition: 'because', + docketNumber: MOCK_CASE.docketNumber, + trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getTrialSessionById, @@ -307,14 +326,18 @@ describe('removeCaseFromTrialInteractor', () => { it('sets the associatedJudge and caseStatus when provided', async () => { mockTrialSession.isCalendared = true; - const result = await removeCaseFromTrialInteractor(applicationContext, { - associatedJudge: 'Judge Dredd', - associatedJudgeId: 'e5eaf0ac-6a1f-4a5d-a44d-d59f199b7ab5', - caseStatus: CASE_STATUS_TYPES.cav, - disposition: 'because', - docketNumber: MOCK_CASE.docketNumber, - trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, - }); + const result = await removeCaseFromTrialInteractor( + applicationContext, + { + associatedJudge: 'Judge Dredd', + associatedJudgeId: 'e5eaf0ac-6a1f-4a5d-a44d-d59f199b7ab5', + caseStatus: CASE_STATUS_TYPES.cav, + disposition: 'because', + docketNumber: MOCK_CASE.docketNumber, + trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect(result.associatedJudge).toEqual('Judge Dredd'); expect(result.associatedJudgeId).toEqual( @@ -327,14 +350,18 @@ describe('removeCaseFromTrialInteractor', () => { mockLock = MOCK_LOCK; await expect( - removeCaseFromTrialInteractor(applicationContext, { - associatedJudge: 'Judge Dredd', - associatedJudgeId: 'e5eaf0ac-6a1f-4a5d-a44d-d59f199b7ab5', - caseStatus: CASE_STATUS_TYPES.cav, - disposition: 'because', - docketNumber: MOCK_CASE.docketNumber, - trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, - }), + removeCaseFromTrialInteractor( + applicationContext, + { + associatedJudge: 'Judge Dredd', + associatedJudgeId: 'e5eaf0ac-6a1f-4a5d-a44d-d59f199b7ab5', + caseStatus: CASE_STATUS_TYPES.cav, + disposition: 'because', + docketNumber: MOCK_CASE.docketNumber, + trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -343,14 +370,18 @@ describe('removeCaseFromTrialInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await removeCaseFromTrialInteractor(applicationContext, { - associatedJudge: 'Judge Dredd', - associatedJudgeId: 'e5eaf0ac-6a1f-4a5d-a44d-d59f199b7ab5', - caseStatus: CASE_STATUS_TYPES.cav, - disposition: 'because', - docketNumber: MOCK_CASE.docketNumber, - trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, - }); + await removeCaseFromTrialInteractor( + applicationContext, + { + associatedJudge: 'Judge Dredd', + associatedJudgeId: 'e5eaf0ac-6a1f-4a5d-a44d-d59f199b7ab5', + caseStatus: CASE_STATUS_TYPES.cav, + disposition: 'because', + docketNumber: MOCK_CASE.docketNumber, + trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/trialSessions/removeCaseFromTrialInteractor.ts b/web-api/src/business/useCases/trialSessions/removeCaseFromTrialInteractor.ts index f160d5aa3f4..d73832eea21 100644 --- a/web-api/src/business/useCases/trialSessions/removeCaseFromTrialInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/removeCaseFromTrialInteractor.ts @@ -7,6 +7,7 @@ import { import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; export const removeCaseFromTrial = async ( @@ -26,10 +27,9 @@ export const removeCaseFromTrial = async ( docketNumber: string; trialSessionId: string; }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } @@ -44,9 +44,7 @@ export const removeCaseFromTrial = async ( throw new NotFoundError(`Trial session ${trialSessionId} was not found.`); } - const trialSessionEntity = new TrialSession(trialSession, { - applicationContext, - }); + const trialSessionEntity = new TrialSession(trialSession); if (trialSessionEntity.isCalendared) { trialSessionEntity.removeCaseFromCalendar({ disposition, docketNumber }); @@ -66,13 +64,13 @@ export const removeCaseFromTrial = async ( docketNumber, }); - const caseEntity = new Case(myCase, { applicationContext }); + const caseEntity = new Case(myCase, { authorizedUser }); if (!caseEntity.isHearing(trialSessionId)) { caseEntity.removeFromTrial({ associatedJudge, associatedJudgeId, - changedBy: user.name, + changedBy: authorizedUser?.name, updatedCaseStatus: caseStatus, }); @@ -103,10 +101,11 @@ export const removeCaseFromTrial = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); - return new Case(updatedCase, { applicationContext }).validate().toRawObject(); + return new Case(updatedCase, { authorizedUser }).validate().toRawObject(); }; export const removeCaseFromTrialInteractor = withLocking( diff --git a/web-api/src/business/useCases/trialSessions/runTrialSessionPlanningReportInteractor.test.ts b/web-api/src/business/useCases/trialSessions/runTrialSessionPlanningReportInteractor.test.ts index af846e9ff3a..13d8d55ebe1 100644 --- a/web-api/src/business/useCases/trialSessions/runTrialSessionPlanningReportInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/runTrialSessionPlanningReportInteractor.test.ts @@ -1,20 +1,15 @@ -import { - ROLES, - TRIAL_CITIES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { TRIAL_CITIES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { runTrialSessionPlanningReportInteractor } from './runTrialSessionPlanningReportInteractor'; describe('run trial session planning report', () => { const mockPdfUrl = 'www.example.com'; - let user; beforeEach(() => { - user = { - role: ROLES.petitionsClerk, - userId: 'petitionsClerk', - }; - applicationContext.getCurrentUser.mockImplementation(() => user); applicationContext .getUseCaseHelpers() .saveFileAndGenerateUrl.mockReturnValue(mockPdfUrl); @@ -30,20 +25,19 @@ describe('run trial session planning report', () => { }); it('throws error if user is unauthorized', async () => { - user = { - role: ROLES.petitioner, - userId: 'petitioner', - }; - applicationContext .getPersistenceGateway() .getEligibleCasesForTrialCity.mockReturnValue([]); await expect( - runTrialSessionPlanningReportInteractor(applicationContext, { - term: 'winter', - year: '2020', - }), + runTrialSessionPlanningReportInteractor( + applicationContext, + { + term: 'winter', + year: '2020', + }, + mockPetitionerUser, + ), ).rejects.toThrow(); }); @@ -114,6 +108,7 @@ describe('run trial session planning report', () => { term: 'winter', year: '2020', }, + mockPetitionsClerkUser, ); expect( @@ -149,10 +144,14 @@ describe('run trial session planning report', () => { }); it('sorts trial locations by city', async () => { - await runTrialSessionPlanningReportInteractor(applicationContext, { - term: 'winter', - year: '2020', - }); + await runTrialSessionPlanningReportInteractor( + applicationContext, + { + term: 'winter', + year: '2020', + }, + mockPetitionsClerkUser, + ); const actualtrialLocationData = applicationContext.getDocumentGenerators().trialSessionPlanningReport.mock @@ -171,10 +170,14 @@ describe('run trial session planning report', () => { describe('previous terms', () => { it('returns previous terms when the term is winter', async () => { - await runTrialSessionPlanningReportInteractor(applicationContext, { - term: 'winter', - year: '2020', - }); + await runTrialSessionPlanningReportInteractor( + applicationContext, + { + term: 'winter', + year: '2020', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getDocumentGenerators().trialSessionPlanningReport @@ -187,10 +190,14 @@ describe('run trial session planning report', () => { }); it('returns previous terms when the term is fall', async () => { - await runTrialSessionPlanningReportInteractor(applicationContext, { - term: 'fall', - year: '2020', - }); + await runTrialSessionPlanningReportInteractor( + applicationContext, + { + term: 'fall', + year: '2020', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getDocumentGenerators().trialSessionPlanningReport @@ -203,10 +210,14 @@ describe('run trial session planning report', () => { }); it('returns previous terms when the term is spring', async () => { - await runTrialSessionPlanningReportInteractor(applicationContext, { - term: 'spring', - year: '2020', - }); + await runTrialSessionPlanningReportInteractor( + applicationContext, + { + term: 'spring', + year: '2020', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getDocumentGenerators().trialSessionPlanningReport diff --git a/web-api/src/business/useCases/trialSessions/runTrialSessionPlanningReportInteractor.ts b/web-api/src/business/useCases/trialSessions/runTrialSessionPlanningReportInteractor.ts index 609359d258c..272fd2764dc 100644 --- a/web-api/src/business/useCases/trialSessions/runTrialSessionPlanningReportInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/runTrialSessionPlanningReportInteractor.ts @@ -10,6 +10,7 @@ import { } from '../../../../../shared/src/business/entities/EntityConstants'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { capitalize, invert } from 'lodash'; export type PreviousTerm = { @@ -30,13 +31,12 @@ export type TrialLocationData = { export const runTrialSessionPlanningReportInteractor = async ( applicationContext: ServerApplicationContext, { term, year }: { term: string; year: string }, + authorizedUser: UnknownAuthUser, ): Promise<{ fileId: string; url: string; }> => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/trialSessions/saveCalendarNoteInteractor.test.ts b/web-api/src/business/useCases/trialSessions/saveCalendarNoteInteractor.test.ts index 2b5159c5ddb..2657f798d5e 100644 --- a/web-api/src/business/useCases/trialSessions/saveCalendarNoteInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/saveCalendarNoteInteractor.test.ts @@ -2,15 +2,15 @@ import { MOCK_CASE, MOCK_CASE_WITH_TRIAL_SESSION, } from '../../../../../shared/src/test/mockCase'; -import { - ROLES, - TRIAL_SESSION_PROCEEDING_TYPES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { TRIAL_SESSION_PROCEEDING_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { saveCalendarNoteInteractor } from './saveCalendarNoteInteractor'; describe('saveCalendarNotes', () => { - let mockCurrentUser; let mockTrialSession; let mockCase; @@ -27,16 +27,10 @@ describe('saveCalendarNotes', () => { }; beforeEach(() => { - mockCurrentUser = { - role: ROLES.docketClerk, - userId: '8675309b-18d0-43ec-bafb-654e83405411', - }; - mockTrialSession = { ...MOCK_TRIAL }; mockCase = { ...MOCK_CASE }; - applicationContext.getCurrentUser.mockImplementation(() => mockCurrentUser); applicationContext .getPersistenceGateway() .getTrialSessionById.mockImplementation(() => mockTrialSession); @@ -46,19 +40,19 @@ describe('saveCalendarNotes', () => { }); it('throws an Unauthorized error if the user role is not allowed to access the method', async () => { - mockCurrentUser = { - role: ROLES.petitioner, - userId: '8675309b-18d0-43ec-bafb-654e83405411', - }; const mockTrialSessionId = '8675309b-18d0-43ec-bafb-654e83405411'; mockCase.trialSessionId = mockTrialSessionId; await expect( - saveCalendarNoteInteractor(applicationContext, { - calendarNote: 'testing', - docketNumber: mockCase.docketNumber, - trialSessionId: mockTrialSessionId, - }), + saveCalendarNoteInteractor( + applicationContext, + { + calendarNote: 'testing', + docketNumber: mockCase.docketNumber, + trialSessionId: mockTrialSessionId, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -71,11 +65,15 @@ describe('saveCalendarNotes', () => { '8675309b-18d0-43ec-bafb-654e83405411', ); - await saveCalendarNoteInteractor(applicationContext, { - calendarNote: 'whatever', - docketNumber: mockCase.docketNumber, - trialSessionId: MOCK_CASE_WITH_TRIAL_SESSION.trialSessionId, - }); + await saveCalendarNoteInteractor( + applicationContext, + { + calendarNote: 'whatever', + docketNumber: mockCase.docketNumber, + trialSessionId: MOCK_CASE_WITH_TRIAL_SESSION.trialSessionId, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getTrialSessionById, @@ -102,11 +100,15 @@ describe('saveCalendarNotes', () => { mockCase.trialSessionId = mockTrialSession.trialSessionId; - const result = await saveCalendarNoteInteractor(applicationContext, { - calendarNote: 'this is a calendarNote', - docketNumber: mockCase.docketNumber, - trialSessionId: mockTrialSession.trialSessionId, - }); + const result = await saveCalendarNoteInteractor( + applicationContext, + { + calendarNote: 'this is a calendarNote', + docketNumber: mockCase.docketNumber, + trialSessionId: mockTrialSession.trialSessionId, + }, + mockDocketClerkUser, + ); expect(result.trialSessionId).toEqual(mockTrialSession.trialSessionId); expect( @@ -130,11 +132,15 @@ describe('saveCalendarNotes', () => { }); it('does not update the case hearing record if the given trial session is not a hearing on the case', async () => { - await saveCalendarNoteInteractor(applicationContext, { - calendarNote: 'this is a calendarNote', - docketNumber: mockCase.docketNumber, - trialSessionId: mockTrialSession.trialSessionId, - }); + await saveCalendarNoteInteractor( + applicationContext, + { + calendarNote: 'this is a calendarNote', + docketNumber: mockCase.docketNumber, + trialSessionId: mockTrialSession.trialSessionId, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -166,11 +172,15 @@ describe('saveCalendarNotes', () => { trialSessionId: '8885309b-18d0-43ec-bafb-654e83405412', }; - await saveCalendarNoteInteractor(applicationContext, { - calendarNote: 'just updating the hearing note', - docketNumber: mockCase.docketNumber, - trialSessionId: '9995309b-18d0-43ec-bafb-654e83405412', - }); + await saveCalendarNoteInteractor( + applicationContext, + { + calendarNote: 'just updating the hearing note', + docketNumber: mockCase.docketNumber, + trialSessionId: '9995309b-18d0-43ec-bafb-654e83405412', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -202,11 +212,15 @@ describe('saveCalendarNotes', () => { trialSessionId: '8885309b-18d0-43ec-bafb-654e83405412', }; - await saveCalendarNoteInteractor(applicationContext, { - calendarNote: 'just updating the hearing note', - docketNumber: mockCase.docketNumber, - trialSessionId: '9995309b-18d0-43ec-bafb-654e83405412', - }); + await saveCalendarNoteInteractor( + applicationContext, + { + calendarNote: 'just updating the hearing note', + docketNumber: mockCase.docketNumber, + trialSessionId: '9995309b-18d0-43ec-bafb-654e83405412', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, diff --git a/web-api/src/business/useCases/trialSessions/saveCalendarNoteInteractor.ts b/web-api/src/business/useCases/trialSessions/saveCalendarNoteInteractor.ts index 9d753ae31e6..43ffaefd900 100644 --- a/web-api/src/business/useCases/trialSessions/saveCalendarNoteInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/saveCalendarNoteInteractor.ts @@ -6,6 +6,7 @@ import { import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * saveCalendarNoteInteractor @@ -24,9 +25,11 @@ export const saveCalendarNoteInteractor = async ( docketNumber, trialSessionId, }: { calendarNote: string; docketNumber: string; trialSessionId: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - if (!isAuthorized(user, ROLE_PERMISSIONS.ADD_CASE_TO_TRIAL_SESSION)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.ADD_CASE_TO_TRIAL_SESSION) + ) { throw new UnauthorizedError('Unauthorized'); } @@ -47,9 +50,7 @@ export const saveCalendarNoteInteractor = async ( } }); - const rawTrialSessionEntity = new TrialSession(trialSession, { - applicationContext, - }) + const rawTrialSessionEntity = new TrialSession(trialSession) .validate() .toRawObject(); diff --git a/web-api/src/business/useCases/trialSessions/serveThirtyDayNoticeInteractor.test.ts b/web-api/src/business/useCases/trialSessions/serveThirtyDayNoticeInteractor.test.ts index de397ca0c09..577038ea772 100644 --- a/web-api/src/business/useCases/trialSessions/serveThirtyDayNoticeInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/serveThirtyDayNoticeInteractor.test.ts @@ -11,9 +11,9 @@ import { ThirtyDayNoticeOfTrialRequiredInfo } from '../../../../../shared/src/bu import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { cloneDeep } from 'lodash'; import { - docketClerkUser, - petitionsClerkUser, -} from '../../../../../shared/src/test/mockUsers'; + mockDocketClerkUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { serveThirtyDayNoticeInteractor } from './serveThirtyDayNoticeInteractor'; import { testPdfDoc } from '../../../../../shared/src/business/test/getFakeFile'; @@ -34,8 +34,6 @@ describe('serveThirtyDayNoticeInteractor', () => { title: 'clerk of court', })); - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - applicationContext.getUtilities().formatNow.mockReturnValue('02/23/2023'); applicationContext @@ -44,22 +42,28 @@ describe('serveThirtyDayNoticeInteractor', () => { }); it('should throw an unauthorized error when the user is not authorized to serve 30 day notices', async () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - await expect( - serveThirtyDayNoticeInteractor(applicationContext, { - clientConnectionId: TEST_CLIENT_CONNECTION_ID, - trialSessionId: trialSession.trialSessionId!, - }), + serveThirtyDayNoticeInteractor( + applicationContext, + { + clientConnectionId: TEST_CLIENT_CONNECTION_ID, + trialSessionId: trialSession.trialSessionId!, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(new UnauthorizedError('Unauthorized')); }); it('should throw an invalid request error when no trial session id is provided', async () => { await expect( - serveThirtyDayNoticeInteractor(applicationContext, { - clientConnectionId: TEST_CLIENT_CONNECTION_ID, - trialSessionId: undefined as any, - }), + serveThirtyDayNoticeInteractor( + applicationContext, + { + clientConnectionId: TEST_CLIENT_CONNECTION_ID, + trialSessionId: undefined as any, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(new InvalidRequest('No trial Session Id provided')); }); @@ -108,10 +112,14 @@ describe('serveThirtyDayNoticeInteractor', () => { ) .mockResolvedValueOnce(caseWithProSePetitioner); - await serveThirtyDayNoticeInteractor(applicationContext, { - clientConnectionId: TEST_CLIENT_CONNECTION_ID, - trialSessionId: trialSession.trialSessionId!, - }); + await serveThirtyDayNoticeInteractor( + applicationContext, + { + clientConnectionId: TEST_CLIENT_CONNECTION_ID, + trialSessionId: trialSession.trialSessionId!, + }, + mockPetitionsClerkUser, + ); const expectedThirtyDayNoticeInfo: ThirtyDayNoticeOfTrialRequiredInfo = { caseCaptionExtension: expect.anything(), @@ -146,25 +154,28 @@ describe('serveThirtyDayNoticeInteractor', () => { ).toHaveBeenCalledTimes(1); expect( applicationContext.getUseCaseHelpers().createAndServeNoticeDocketEntry, - ).toHaveBeenCalledWith(expect.anything(), { - additionalDocketEntryInfo: { - date: expect.anything(), - trialLocation: expect.anything(), - }, - caseEntity: expect.anything(), - documentInfo: { - documentTitle: `30 Day Notice of Trial on ${formatDateString( - trialSession.startDate, - FORMATS.MMDDYYYY_DASHED, - )} at ${trialSession.trialLocation}`, - documentType: '30-Day Notice of Trial', - eventCode: 'NOTT', + ).toHaveBeenCalledWith( + expect.anything(), + { + additionalDocketEntryInfo: { + date: expect.anything(), + trialLocation: expect.anything(), + }, + caseEntity: expect.anything(), + documentInfo: { + documentTitle: `30 Day Notice of Trial on ${formatDateString( + trialSession.startDate, + FORMATS.MMDDYYYY_DASHED, + )} at ${trialSession.trialLocation}`, + documentType: '30-Day Notice of Trial', + eventCode: 'NOTT', + }, + newPdfDoc: expect.anything(), + noticePdf: expect.anything(), + onlyProSePetitioners: true, }, - newPdfDoc: expect.anything(), - noticePdf: expect.anything(), - onlyProSePetitioners: true, - user: petitionsClerkUser, - }); + mockPetitionsClerkUser, + ); }); it('should notify the user after processing each case in the trial session', async () => { @@ -175,10 +186,14 @@ describe('serveThirtyDayNoticeInteractor', () => { 'thirty_day_notice_paper_service_complete', ]; - await serveThirtyDayNoticeInteractor(applicationContext, { - clientConnectionId: TEST_CLIENT_CONNECTION_ID, - trialSessionId: trialSession.trialSessionId!, - }); + await serveThirtyDayNoticeInteractor( + applicationContext, + { + clientConnectionId: TEST_CLIENT_CONNECTION_ID, + trialSessionId: trialSession.trialSessionId!, + }, + mockPetitionsClerkUser, + ); const actualNotificationOrder = applicationContext .getNotificationGateway() @@ -196,10 +211,14 @@ describe('serveThirtyDayNoticeInteractor', () => { }, ]; - await serveThirtyDayNoticeInteractor(applicationContext, { - clientConnectionId: TEST_CLIENT_CONNECTION_ID, - trialSessionId: trialSession.trialSessionId!, - }); + await serveThirtyDayNoticeInteractor( + applicationContext, + { + clientConnectionId: TEST_CLIENT_CONNECTION_ID, + trialSessionId: trialSession.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getUseCaseHelpers().saveFileAndGenerateUrl, @@ -232,7 +251,7 @@ describe('serveThirtyDayNoticeInteractor', () => { hasPaper: true, pdfUrl: mockPdfUrl, }, - userId: petitionsClerkUser.userId, + userId: mockPetitionsClerkUser.userId, }); }); @@ -246,10 +265,14 @@ describe('serveThirtyDayNoticeInteractor', () => { }, ]; - await serveThirtyDayNoticeInteractor(applicationContext, { - clientConnectionId: TEST_CLIENT_CONNECTION_ID, - trialSessionId: trialSession.trialSessionId!, - }); + await serveThirtyDayNoticeInteractor( + applicationContext, + { + clientConnectionId: TEST_CLIENT_CONNECTION_ID, + trialSessionId: trialSession.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser, @@ -260,7 +283,7 @@ describe('serveThirtyDayNoticeInteractor', () => { action: 'thirty_day_notice_paper_service_complete', pdfUrl: undefined, }, - userId: petitionsClerkUser.userId, + userId: mockPetitionsClerkUser.userId, }); }); @@ -272,10 +295,14 @@ describe('serveThirtyDayNoticeInteractor', () => { .getPersistenceGateway() .getDocument.mockResolvedValue(testPdfDoc); - await serveThirtyDayNoticeInteractor(applicationContext, { - clientConnectionId: TEST_CLIENT_CONNECTION_ID, - trialSessionId: trialSession.trialSessionId!, - }); + await serveThirtyDayNoticeInteractor( + applicationContext, + { + clientConnectionId: TEST_CLIENT_CONNECTION_ID, + trialSessionId: trialSession.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getUtilities().combineTwoPdfs, @@ -290,10 +317,14 @@ describe('serveThirtyDayNoticeInteractor', () => { .getPersistenceGateway() .getDocument.mockResolvedValue(testPdfDoc); - await serveThirtyDayNoticeInteractor(applicationContext, { - clientConnectionId: TEST_CLIENT_CONNECTION_ID, - trialSessionId: trialSession.trialSessionId!, - }); + await serveThirtyDayNoticeInteractor( + applicationContext, + { + clientConnectionId: TEST_CLIENT_CONNECTION_ID, + trialSessionId: trialSession.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getUtilities().combineTwoPdfs, @@ -335,10 +366,14 @@ describe('serveThirtyDayNoticeInteractor', () => { }, ]; - await serveThirtyDayNoticeInteractor(applicationContext, { - clientConnectionId: TEST_CLIENT_CONNECTION_ID, - trialSessionId: trialSession.trialSessionId!, - }); + await serveThirtyDayNoticeInteractor( + applicationContext, + { + clientConnectionId: TEST_CLIENT_CONNECTION_ID, + trialSessionId: trialSession.trialSessionId!, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getDocumentGenerators().thirtyDayNoticeOfTrial, diff --git a/web-api/src/business/useCases/trialSessions/serveThirtyDayNoticeInteractor.ts b/web-api/src/business/useCases/trialSessions/serveThirtyDayNoticeInteractor.ts index d1ef54fe170..0fab5738c16 100644 --- a/web-api/src/business/useCases/trialSessions/serveThirtyDayNoticeInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/serveThirtyDayNoticeInteractor.ts @@ -18,6 +18,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { getCaseCaptionMeta } from '../../../../../shared/src/business/utilities/getCaseCaptionMeta'; import { getClinicLetterKey } from '../../../../../shared/src/business/utilities/getClinicLetterKey'; import { replaceBracketed } from '../../../../../shared/src/business/utilities/replaceBracketed'; @@ -31,10 +32,9 @@ export const serveThirtyDayNoticeInteractor = async ( trialSessionId: string; clientConnectionId: string; }, + authorizedUser: UnknownAuthUser, ): Promise => { - const currentUser = applicationContext.getCurrentUser(); - - if (!isAuthorized(currentUser, ROLE_PERMISSIONS.DISMISS_NOTT_REMINDER)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.DISMISS_NOTT_REMINDER)) { throw new UnauthorizedError('Unauthorized'); } @@ -69,14 +69,12 @@ export const serveThirtyDayNoticeInteractor = async ( action: 'thirty_day_notice_paper_service_complete', pdfUrl: undefined, }, - userId: currentUser.userId, + userId: authorizedUser.userId, }); return; } - const trialSessionEntity = new TrialSession(trialSession, { - applicationContext, - }); + const trialSessionEntity = new TrialSession(trialSession); const { PDFDocument } = await applicationContext.getPdfLib(); const paperServicePdf = await PDFDocument.create(); @@ -91,7 +89,7 @@ export const serveThirtyDayNoticeInteractor = async ( action: 'paper_service_started', totalPdfs: trialSession.caseOrder.length, }, - userId: currentUser.userId, + userId: authorizedUser.userId, }); let pdfsAppended: number = 0; @@ -106,7 +104,7 @@ export const serveThirtyDayNoticeInteractor = async ( docketNumber: aCase.docketNumber, }); - const caseEntity = new Case(rawCase, { applicationContext }); + const caseEntity = new Case(rawCase, { authorizedUser }); let clinicLetter; const clinicLetterKey = getClinicLetterKey({ @@ -177,32 +175,36 @@ export const serveThirtyDayNoticeInteractor = async ( await applicationContext .getUseCaseHelpers() - .createAndServeNoticeDocketEntry(applicationContext, { - additionalDocketEntryInfo: { - date: trialSession.startDate, - trialLocation: trialSession.trialLocation, - }, - caseEntity, - documentInfo: { - documentTitle: replaceBracketed( - thirtyDayNoticeDocumentInfo!.documentTitle, - formatDateString( - trialSession.startDate, - FORMATS.MMDDYYYY_DASHED, + .createAndServeNoticeDocketEntry( + applicationContext, + { + additionalDocketEntryInfo: { + date: trialSession.startDate, + trialLocation: trialSession.trialLocation, + }, + caseEntity, + documentInfo: { + documentTitle: replaceBracketed( + thirtyDayNoticeDocumentInfo!.documentTitle, + formatDateString( + trialSession.startDate, + FORMATS.MMDDYYYY_DASHED, + ), + trialSession.trialLocation!, ), - trialSession.trialLocation!, - ), - documentType: thirtyDayNoticeDocumentInfo!.documentType, - eventCode: thirtyDayNoticeDocumentInfo!.eventCode, + documentType: thirtyDayNoticeDocumentInfo!.documentType, + eventCode: thirtyDayNoticeDocumentInfo!.eventCode, + }, + newPdfDoc: paperServicePdf, + noticePdf, + onlyProSePetitioners: true, }, - newPdfDoc: paperServicePdf, - noticePdf, - onlyProSePetitioners: true, - user: currentUser, - }); + authorizedUser, + ); await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); @@ -221,7 +223,7 @@ export const serveThirtyDayNoticeInteractor = async ( action: 'paper_service_updated', pdfsAppended, }, - userId: currentUser.userId, + userId: authorizedUser.userId, }); } }); @@ -266,6 +268,6 @@ export const serveThirtyDayNoticeInteractor = async ( hasPaper: hasPaperService, pdfUrl, }, - userId: currentUser.userId, + userId: authorizedUser.userId, }); }; diff --git a/web-api/src/business/useCases/trialSessions/setForHearingInteractor.test.ts b/web-api/src/business/useCases/trialSessions/setForHearingInteractor.test.ts index dbff4458c6b..7d79136b3a7 100644 --- a/web-api/src/business/useCases/trialSessions/setForHearingInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/setForHearingInteractor.test.ts @@ -3,26 +3,22 @@ import { MOCK_CASE_WITH_TRIAL_SESSION, } from '../../../../../shared/src/test/mockCase'; import { MOCK_TRIAL_REMOTE } from '../../../../../shared/src/test/mockTrial'; -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { setForHearingInteractor } from './setForHearingInteractor'; describe('setForHearingInteractor', () => { - let mockCurrentUser; let mockTrialSession; let mockCase; beforeEach(() => { - mockCurrentUser = { - role: ROLES.docketClerk, - userId: '8675309b-18d0-43ec-bafb-654e83405411', - }; - mockTrialSession = MOCK_TRIAL_REMOTE; mockCase = MOCK_CASE; - applicationContext.getCurrentUser.mockImplementation(() => mockCurrentUser); applicationContext .getPersistenceGateway() .getTrialSessionById.mockImplementation(() => mockTrialSession); @@ -32,17 +28,16 @@ describe('setForHearingInteractor', () => { }); it('throws an Unauthorized error if the user role is not allowed to access the method', async () => { - mockCurrentUser = { - role: ROLES.petitioner, - userId: '8675309b-18d0-43ec-bafb-654e83405411', - }; - await expect( - setForHearingInteractor(applicationContext, { - calendarNotes: 'testing', - docketNumber: mockCase.docketNumber, - trialSessionId: '8675309b-18d0-43ec-bafb-654e83405411', - }), + setForHearingInteractor( + applicationContext, + { + calendarNotes: 'testing', + docketNumber: mockCase.docketNumber, + trialSessionId: '8675309b-18d0-43ec-bafb-654e83405411', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -52,11 +47,15 @@ describe('setForHearingInteractor', () => { }; await expect( - setForHearingInteractor(applicationContext, { - calendarNotes: 'testing', - docketNumber: mockCase.docketNumber, - trialSessionId: MOCK_CASE_WITH_TRIAL_SESSION.trialSessionId, - }), + setForHearingInteractor( + applicationContext, + { + calendarNotes: 'testing', + docketNumber: mockCase.docketNumber, + trialSessionId: MOCK_CASE_WITH_TRIAL_SESSION.trialSessionId, + }, + mockDocketClerkUser, + ), ).rejects.toThrow('That Hearing is already assigned to the Case'); }); @@ -69,11 +68,15 @@ describe('setForHearingInteractor', () => { }; await expect( - setForHearingInteractor(applicationContext, { - calendarNotes: 'testing', - docketNumber: mockCase.docketNumber, - trialSessionId: MOCK_CASE_WITH_TRIAL_SESSION.trialSessionId, - }), + setForHearingInteractor( + applicationContext, + { + calendarNotes: 'testing', + docketNumber: mockCase.docketNumber, + trialSessionId: MOCK_CASE_WITH_TRIAL_SESSION.trialSessionId, + }, + mockDocketClerkUser, + ), ).rejects.toThrow('That Hearing is already assigned to the Case'); }); @@ -83,11 +86,15 @@ describe('setForHearingInteractor', () => { hearings: [], }; - await setForHearingInteractor(applicationContext, { - calendarNotes: 'testing', - docketNumber: mockCase.docketNumber, - trialSessionId: MOCK_CASE_WITH_TRIAL_SESSION.trialSessionId, - }); + await setForHearingInteractor( + applicationContext, + { + calendarNotes: 'testing', + docketNumber: mockCase.docketNumber, + trialSessionId: MOCK_CASE_WITH_TRIAL_SESSION.trialSessionId, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().addCaseToHearing, @@ -99,11 +106,15 @@ describe('setForHearingInteractor', () => { ...MOCK_CASE_WITH_TRIAL_SESSION, }; - await setForHearingInteractor(applicationContext, { - calendarNotes: 'testing', - docketNumber: mockCase.docketNumber, - trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, - }); + await setForHearingInteractor( + applicationContext, + { + calendarNotes: 'testing', + docketNumber: mockCase.docketNumber, + trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().addCaseToHearing, @@ -127,11 +138,15 @@ describe('setForHearingInteractor', () => { ...MOCK_CASE_WITH_TRIAL_SESSION, }; - await setForHearingInteractor(applicationContext, { - calendarNotes: 'this is a calendarNote', - docketNumber: mockCase.docketNumber, - trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, - }); + await setForHearingInteractor( + applicationContext, + { + calendarNotes: 'this is a calendarNote', + docketNumber: mockCase.docketNumber, + trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId!, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().addCaseToHearing, diff --git a/web-api/src/business/useCases/trialSessions/setForHearingInteractor.ts b/web-api/src/business/useCases/trialSessions/setForHearingInteractor.ts index e4b6876acae..e2f2ea1a933 100644 --- a/web-api/src/business/useCases/trialSessions/setForHearingInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/setForHearingInteractor.ts @@ -7,6 +7,7 @@ import { import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * setForHearingInteractor @@ -25,10 +26,9 @@ export const setForHearingInteractor = async ( docketNumber, trialSessionId, }: { calendarNotes: string; docketNumber: string; trialSessionId: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.SET_FOR_HEARING)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.SET_FOR_HEARING)) { throw new UnauthorizedError('Unauthorized'); } @@ -50,11 +50,9 @@ export const setForHearingInteractor = async ( docketNumber, }); - const caseEntity = new Case(caseDetails, { applicationContext }); + const caseEntity = new Case(caseDetails, { authorizedUser }); - const trialSessionEntity = new TrialSession(trialSession, { - applicationContext, - }); + const trialSessionEntity = new TrialSession(trialSession); const existingTrialSessionIds = []; if (caseEntity.trialSessionId) { diff --git a/web-api/src/business/useCases/trialSessions/setNoticesForCalendaredTrialSessionInteractor.locking.test.ts b/web-api/src/business/useCases/trialSessions/setNoticesForCalendaredTrialSessionInteractor.locking.test.ts index 3b084603677..4bf4cf779bd 100644 --- a/web-api/src/business/useCases/trialSessions/setNoticesForCalendaredTrialSessionInteractor.locking.test.ts +++ b/web-api/src/business/useCases/trialSessions/setNoticesForCalendaredTrialSessionInteractor.locking.test.ts @@ -9,7 +9,7 @@ import { handleLockError, setNoticesForCalendaredTrialSessionInteractor, } from './setNoticesForCalendaredTrialSessionInteractor'; -import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; +import { mockTrialClerkUser } from '@shared/test/mockAuthUsers'; describe('determineEntitiesToLock', () => { const trialSessionId = '6805d1ab-18d0-43ec-bafb-654e83405416'; @@ -53,20 +53,17 @@ describe('determineEntitiesToLock', () => { }); describe('handleLockError', () => { - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - }); - - it('should determine who the user is based on applicationContext', async () => { - await handleLockError(applicationContext, { foo: 'bar' }); - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); - }); - it('should send a notification to the user with "retry_async_request" and the originalRequest', async () => { const mockOriginalRequest = { foo: 'bar', }; - await handleLockError(applicationContext, mockOriginalRequest); + + await handleLockError( + applicationContext, + mockOriginalRequest, + mockTrialClerkUser, + ); + expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock .calls[0][0].message, @@ -85,7 +82,10 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { { ...MOCK_CASE, docketNumber: '100-23' }, { ...MOCK_CASE, docketNumber: '101-23' }, ]; - let mockRequest = { trialSessionId }; + let mockRequest = { + clientConnectionId: '8916f743-a22d-4946-ab06-57ddcf386912', + trialSessionId, + }; let mockLock; beforeEach(() => { @@ -97,7 +97,6 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { applicationContext .getPersistenceGateway() .getLock.mockImplementation(() => mockLock); - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); applicationContext .getPersistenceGateway() @@ -127,6 +126,7 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { setNoticesForCalendaredTrialSessionInteractor( applicationContext, mockRequest, + mockTrialClerkUser, ), ).rejects.toThrow(ServiceUnavailableError); @@ -140,6 +140,7 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { setNoticesForCalendaredTrialSessionInteractor( applicationContext, mockRequest, + mockTrialClerkUser, ), ).rejects.toThrow(ServiceUnavailableError); @@ -147,12 +148,13 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { applicationContext.getNotificationGateway().sendNotificationToUser, ).toHaveBeenCalledWith({ applicationContext, + clientConnectionId: mockRequest.clientConnectionId, message: { action: 'retry_async_request', originalRequest: mockRequest, requestToRetry: 'set_notices_for_calendared_trial_session', }, - userId: docketClerkUser.userId, + userId: mockTrialClerkUser.userId, }); expect( @@ -170,6 +172,7 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { await setNoticesForCalendaredTrialSessionInteractor( applicationContext, mockRequest, + mockTrialClerkUser, ); expect( @@ -185,6 +188,7 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { await setNoticesForCalendaredTrialSessionInteractor( applicationContext, mockRequest, + mockTrialClerkUser, ); const expectedIdentifiers = mockCases.map( diff --git a/web-api/src/business/useCases/trialSessions/setNoticesForCalendaredTrialSessionInteractor.test.ts b/web-api/src/business/useCases/trialSessions/setNoticesForCalendaredTrialSessionInteractor.test.ts index 99c13024e19..cca1883314b 100644 --- a/web-api/src/business/useCases/trialSessions/setNoticesForCalendaredTrialSessionInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/setNoticesForCalendaredTrialSessionInteractor.test.ts @@ -1,27 +1,15 @@ import { MOCK_TRIAL_REGULAR } from '../../../../../shared/src/test/mockTrial'; -import { - PARTY_TYPES, - ROLES, - TRIAL_SESSION_PROCEEDING_TYPES, -} from '../../../../../shared/src/business/entities/EntityConstants'; -import { User } from '../../../../../shared/src/business/entities/User'; +import { TRIAL_SESSION_PROCEEDING_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { setNoticesForCalendaredTrialSessionInteractor } from './setNoticesForCalendaredTrialSessionInteractor'; describe('setNoticesForCalendaredTrialSessionInteractor', () => { - const unAuthorizedUser = new User({ - name: PARTY_TYPES.petitioner, - role: ROLES.petitioner, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - - const user = new User({ - name: PARTY_TYPES.petitioner, - role: ROLES.petitionsClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - const trialSessionId = '6805d1ab-18d0-43ec-bafb-654e83405416'; + const clientConnectionId = '334304ba-79e6-4a1d-bd36-1e61f657a7ff'; beforeEach(() => { applicationContext @@ -37,7 +25,6 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { docketNumber: '103-20', }, ]); - applicationContext.getCurrentUser.mockReturnValue(user); applicationContext .getPersistenceGateway() .getTrialSessionById.mockResolvedValue({ @@ -68,18 +55,22 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { .mockImplementation((cb): ReturnType => { // eslint-disable-next-line promise/no-callback-in-promise (cb() as any).then(cb); - return undefined; + return undefined as any; }); }); it('should return an unauthorized error if the user does not have the TRIAL_SESSIONS permission', async () => { - applicationContext.getCurrentUser.mockReturnValue(unAuthorizedUser); let error; try { - await setNoticesForCalendaredTrialSessionInteractor(applicationContext, { - trialSessionId, - }); + await setNoticesForCalendaredTrialSessionInteractor( + applicationContext, + { + clientConnectionId, + trialSessionId, + }, + mockPetitionerUser, + ); } catch (e) { error = e; } @@ -92,9 +83,14 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { .getPersistenceGateway() .isFileExists.mockResolvedValue(false); - await setNoticesForCalendaredTrialSessionInteractor(applicationContext, { - trialSessionId, - }); + await setNoticesForCalendaredTrialSessionInteractor( + applicationContext, + { + clientConnectionId, + trialSessionId, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getDocument, @@ -109,9 +105,14 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { .getPersistenceGateway() .getTrialSessionProcessingStatus.mockResolvedValueOnce('processing'); - await setNoticesForCalendaredTrialSessionInteractor(applicationContext, { - trialSessionId, - }); + await setNoticesForCalendaredTrialSessionInteractor( + applicationContext, + { + clientConnectionId, + trialSessionId, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getMessageGateway().sendSetTrialSessionCalendarEvent, ).not.toHaveBeenCalled(); @@ -123,9 +124,14 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { .getPersistenceGateway() .getTrialSessionProcessingStatus.mockResolvedValueOnce('complete'); - await setNoticesForCalendaredTrialSessionInteractor(applicationContext, { - trialSessionId, - }); + await setNoticesForCalendaredTrialSessionInteractor( + applicationContext, + { + clientConnectionId, + trialSessionId, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getMessageGateway().sendSetTrialSessionCalendarEvent, ).not.toHaveBeenCalled(); @@ -135,9 +141,14 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { }); it('should set trialSessionStatus to processing if this is the first trial session calendering event', async () => { - await setNoticesForCalendaredTrialSessionInteractor(applicationContext, { - trialSessionId, - }); + await setNoticesForCalendaredTrialSessionInteractor( + applicationContext, + { + clientConnectionId, + trialSessionId, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -156,9 +167,14 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { unfinishedCases: 0, }); - await setNoticesForCalendaredTrialSessionInteractor(applicationContext, { - trialSessionId, - }); + await setNoticesForCalendaredTrialSessionInteractor( + applicationContext, + { + clientConnectionId, + trialSessionId, + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway() @@ -175,9 +191,14 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { .getPersistenceGateway() .getCalendaredCasesForTrialSession.mockResolvedValue([]); - await setNoticesForCalendaredTrialSessionInteractor(applicationContext, { - trialSessionId, - }); + await setNoticesForCalendaredTrialSessionInteractor( + applicationContext, + { + clientConnectionId, + trialSessionId, + }, + mockPetitionsClerkUser, + ); const result = applicationContext.getNotificationGateway().sendNotificationToUser.mock @@ -189,7 +210,7 @@ describe('setNoticesForCalendaredTrialSessionInteractor', () => { hasPaper: false, trialNoticePdfsKeys: [], }, - userId: user.userId, + userId: mockPetitionsClerkUser.userId, }); }); }); diff --git a/web-api/src/business/useCases/trialSessions/setNoticesForCalendaredTrialSessionInteractor.ts b/web-api/src/business/useCases/trialSessions/setNoticesForCalendaredTrialSessionInteractor.ts index 968ed295ac6..6e93674eba8 100644 --- a/web-api/src/business/useCases/trialSessions/setNoticesForCalendaredTrialSessionInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/setNoticesForCalendaredTrialSessionInteractor.ts @@ -6,18 +6,18 @@ import { import { ServerApplicationContext } from '@web-api/applicationContext'; import { TrialSession } from '../../../../../shared/src/business/entities/trialSessions/TrialSession'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; -export const setNoticesForCalendaredTrialSession = async ( +const setNoticesForCalendaredTrialSession = async ( applicationContext: ServerApplicationContext, { clientConnectionId, trialSessionId, }: { trialSessionId: string; clientConnectionId: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } @@ -40,7 +40,7 @@ export const setNoticesForCalendaredTrialSession = async ( trialNoticePdfsKeys, trialSessionId, }, - userId: user.userId, + userId: authorizedUser.userId, }); return; @@ -53,7 +53,7 @@ export const setNoticesForCalendaredTrialSession = async ( action: 'notice_generation_start', totalCases: calendaredCases.length, }, - userId: user.userId, + userId: authorizedUser.userId, }); const trialSession = await applicationContext @@ -67,9 +67,7 @@ export const setNoticesForCalendaredTrialSession = async ( throw new NotFoundError(`Trial session ${trialSessionId} was not found.`); } - const trialSessionEntity = new TrialSession(trialSession, { - applicationContext, - }); + const trialSessionEntity = new TrialSession(trialSession); const trialSessionProcessingStatus = await applicationContext .getPersistenceGateway() @@ -116,7 +114,7 @@ export const setNoticesForCalendaredTrialSession = async ( docketNumber: calendaredCase.docketNumber, jobId, trialSession, - userId: user.userId, + userId: authorizedUser.userId, }, }); } @@ -162,17 +160,21 @@ export const setNoticesForCalendaredTrialSession = async ( trialNoticePdfsKeys, trialSessionId: trialSessionEntity.trialSessionId, }, - userId: user.userId, + userId: authorizedUser.userId, }); if (trialNoticePdfsKeys.length) { await applicationContext .getUseCases() - .generateTrialSessionPaperServicePdfInteractor(applicationContext, { - clientConnectionId, - trialNoticePdfsKeys, - trialSessionId, - }); + .generateTrialSessionPaperServicePdfInteractor( + applicationContext, + { + clientConnectionId, + trialNoticePdfsKeys, + trialSessionId, + }, + authorizedUser, + ); } }; @@ -216,19 +218,20 @@ export const determineEntitiesToLock = async ( export const handleLockError = async ( applicationContext: ServerApplicationContext, originalRequest: any, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - await applicationContext.getNotificationGateway().sendNotificationToUser({ - applicationContext, - clientConnectionId: originalRequest.clientConnectionId, - message: { - action: 'retry_async_request', - originalRequest, - requestToRetry: 'set_notices_for_calendared_trial_session', - }, - userId: user.userId, - }); + if (authorizedUser?.userId) { + await applicationContext.getNotificationGateway().sendNotificationToUser({ + applicationContext, + clientConnectionId: originalRequest.clientConnectionId, + message: { + action: 'retry_async_request', + originalRequest, + requestToRetry: 'set_notices_for_calendared_trial_session', + }, + userId: authorizedUser.userId, + }); + } }; export const setNoticesForCalendaredTrialSessionInteractor = withLocking( diff --git a/web-api/src/business/useCases/trialSessions/setTrialSessionCalendarInteractor.test.ts b/web-api/src/business/useCases/trialSessions/setTrialSessionCalendarInteractor.test.ts index 4d730b80729..49fb0b05a43 100644 --- a/web-api/src/business/useCases/trialSessions/setTrialSessionCalendarInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/setTrialSessionCalendarInteractor.test.ts @@ -1,17 +1,15 @@ import '@web-api/persistence/postgres/messages/mocks.jest'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; -import { - PARTY_TYPES, - ROLES, - TRIAL_SESSION_PROCEEDING_TYPES, -} from '../../../../../shared/src/business/entities/EntityConstants'; -import { User } from '../../../../../shared/src/business/entities/User'; +import { TRIAL_SESSION_PROCEEDING_TYPES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; import { setTrialSessionCalendarInteractor } from './setTrialSessionCalendarInteractor'; describe('setTrialSessionCalendarInteractor', () => { - let user; const MOCK_TRIAL = { chambersPhoneNumber: '1111111', joinPhoneNumber: '0987654321', @@ -38,16 +36,11 @@ describe('setTrialSessionCalendarInteractor', () => { applicationContext .getPersistenceGateway() .getLock.mockImplementation(() => mockLock); - applicationContext.getCurrentUser.mockImplementation(() => user); }); beforeEach(() => { mockLock = undefined; - user = new User({ - name: 'petitionsClerk', - role: ROLES.petitionsClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); + applicationContext .getPersistenceGateway() .getTrialSessionById.mockReturnValue(MOCK_TRIAL); @@ -58,19 +51,18 @@ describe('setTrialSessionCalendarInteractor', () => { }); it('throws an exception when there is a permissions issue', async () => { - user = new User({ - name: PARTY_TYPES.petitioner, - role: ROLES.petitioner, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); applicationContext .getPersistenceGateway() .getEligibleCasesForTrialSession.mockReturnValue([MOCK_CASE]); - await setTrialSessionCalendarInteractor(applicationContext, { - clientConnectionId: 'hellomom', - trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); + await setTrialSessionCalendarInteractor( + applicationContext, + { + clientConnectionId: 'hellomom', + trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', + }, + mockPetitionerUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock @@ -105,10 +97,14 @@ describe('setTrialSessionCalendarInteractor', () => { .getPersistenceGateway() .setPriorityOnAllWorkItems.mockReturnValue({}); - await setTrialSessionCalendarInteractor(applicationContext, { - clientConnectionId: 'hellomom', - trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); + await setTrialSessionCalendarInteractor( + applicationContext, + { + clientConnectionId: 'hellomom', + trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock @@ -146,10 +142,14 @@ describe('setTrialSessionCalendarInteractor', () => { }, ]); - await setTrialSessionCalendarInteractor(applicationContext, { - clientConnectionId: 'hi', - trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); + await setTrialSessionCalendarInteractor( + applicationContext, + { + clientConnectionId: 'hi', + trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -185,10 +185,14 @@ describe('setTrialSessionCalendarInteractor', () => { }, ]); - await setTrialSessionCalendarInteractor(applicationContext, { - clientConnectionId: 'hi', - trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); + await setTrialSessionCalendarInteractor( + applicationContext, + { + clientConnectionId: 'hi', + trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().setPriorityOnAllWorkItems, @@ -218,10 +222,14 @@ describe('setTrialSessionCalendarInteractor', () => { .getPersistenceGateway() .getCalendaredCasesForTrialSession.mockReturnValue([]); - await setTrialSessionCalendarInteractor(applicationContext, { - clientConnectionId: 'hi', - trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); + await setTrialSessionCalendarInteractor( + applicationContext, + { + clientConnectionId: 'hi', + trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getEligibleCasesForTrialSession @@ -244,10 +252,14 @@ describe('setTrialSessionCalendarInteractor', () => { }, ]); - await setTrialSessionCalendarInteractor(applicationContext, { - clientConnectionId: 'hi', - trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); + await setTrialSessionCalendarInteractor( + applicationContext, + { + clientConnectionId: 'hi', + trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().getEligibleCasesForTrialSession @@ -260,10 +272,14 @@ describe('setTrialSessionCalendarInteractor', () => { it('should throw a ServiceUnavailableError if the Case is currently locked', async () => { mockLock = MOCK_LOCK; - await setTrialSessionCalendarInteractor(applicationContext, { - clientConnectionId: 'hi', - trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); + await setTrialSessionCalendarInteractor( + applicationContext, + { + clientConnectionId: 'hi', + trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock @@ -275,10 +291,14 @@ describe('setTrialSessionCalendarInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await setTrialSessionCalendarInteractor(applicationContext, { - clientConnectionId: 'hi', - trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); + await setTrialSessionCalendarInteractor( + applicationContext, + { + clientConnectionId: 'hi', + trialSessionId: '6805d1ab-18d0-43ec-bafb-654e83405416', + }, + mockPetitionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/trialSessions/setTrialSessionCalendarInteractor.ts b/web-api/src/business/useCases/trialSessions/setTrialSessionCalendarInteractor.ts index 8d6282d256a..e2338d0a7d2 100644 --- a/web-api/src/business/useCases/trialSessions/setTrialSessionCalendarInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/setTrialSessionCalendarInteractor.ts @@ -1,3 +1,7 @@ +import { + AuthUser, + UnknownAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; import { Case } from '../../../../../shared/src/business/entities/cases/Case'; import { NotFoundError, UnauthorizedError } from '../../../errors/errors'; import { @@ -18,11 +22,12 @@ export const setTrialSessionCalendarInteractor = async ( clientConnectionId, trialSessionId, }: { trialSessionId: string; clientConnectionId: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - try { - if (!isAuthorized(user, ROLE_PERMISSIONS.SET_TRIAL_SESSION_CALENDAR)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.SET_TRIAL_SESSION_CALENDAR) + ) { throw new UnauthorizedError('Unauthorized'); } @@ -37,9 +42,7 @@ export const setTrialSessionCalendarInteractor = async ( throw new NotFoundError(`Trial session ${trialSessionId} was not found.`); } - const trialSessionEntity = new TrialSession(trialSession, { - applicationContext, - }); + const trialSessionEntity = new TrialSession(trialSession); trialSessionEntity.validate(); @@ -97,6 +100,7 @@ export const setTrialSessionCalendarInteractor = async ( await acquireLock({ applicationContext, + authorizedUser, identifiers: allDocketNumbers.map(item => `case|${item}`), ttl: 900, }); @@ -104,27 +108,36 @@ export const setTrialSessionCalendarInteractor = async ( const funcs = [ ...manuallyAddedQcIncompleteCases.map( caseRecord => () => - removeManuallyAddedCaseFromTrialSession({ - applicationContext, - caseRecord, - trialSessionEntity, - }), + removeManuallyAddedCaseFromTrialSession( + { + applicationContext, + caseRecord, + trialSessionEntity, + }, + authorizedUser, + ), ), ...manuallyAddedQcCompleteCases.map( aCase => () => - setManuallyAddedCaseAsCalendared({ - applicationContext, - caseRecord: aCase, - trialSessionEntity, - }), + setManuallyAddedCaseAsCalendared( + { + applicationContext, + caseRecord: aCase, + trialSessionEntity, + }, + authorizedUser, + ), ), ...eligibleCases.map( aCase => () => - setTrialSessionCalendarForEligibleCase({ - applicationContext, - caseRecord: aCase, - trialSessionEntity, - }), + setTrialSessionCalendarForEligibleCase( + { + applicationContext, + caseRecord: aCase, + trialSessionEntity, + }, + authorizedUser, + ), ), ]; @@ -157,13 +170,14 @@ export const setTrialSessionCalendarInteractor = async ( action: 'set_trial_session_calendar_complete', trialSessionId, }, - userId: user.userId, + userId: authorizedUser.userId, }); } catch (error: any) { applicationContext.logger.error( `Error setting trial session calendar for trialSessionId: ${trialSessionId}`, ); applicationContext.logger.error(error); + console.log(error); await applicationContext.getNotificationGateway().sendNotificationToUser({ applicationContext, clientConnectionId, @@ -171,44 +185,53 @@ export const setTrialSessionCalendarInteractor = async ( action: 'set_trial_session_calendar_error', message: `Error setting trial session calendar: ${error?.message}`, }, - userId: user.userId, + userId: authorizedUser?.userId || '', }); } }; -const removeManuallyAddedCaseFromTrialSession = ({ - applicationContext, - caseRecord, - trialSessionEntity, -}: { - applicationContext: ServerApplicationContext; - caseRecord: RawCase; - trialSessionEntity: TrialSession; -}): Promise => { +const removeManuallyAddedCaseFromTrialSession = ( + { + applicationContext, + caseRecord, + trialSessionEntity, + }: { + applicationContext: ServerApplicationContext; + caseRecord: RawCase; + trialSessionEntity: TrialSession; + }, + authorizedUser: AuthUser, +): Promise => { trialSessionEntity.deleteCaseFromCalendar({ docketNumber: caseRecord.docketNumber, }); - const caseEntity = new Case(caseRecord, { applicationContext }); + const caseEntity = new Case(caseRecord, { + authorizedUser, + }); caseEntity.removeFromTrialWithAssociatedJudge(); return applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); }; -const setManuallyAddedCaseAsCalendared = async ({ - applicationContext, - caseRecord, - trialSessionEntity, -}: { - applicationContext: ServerApplicationContext; - caseRecord: RawCase; - trialSessionEntity: TrialSession; -}): Promise => { - const caseEntity = new Case(caseRecord, { applicationContext }); +const setManuallyAddedCaseAsCalendared = async ( + { + applicationContext, + caseRecord, + trialSessionEntity, + }: { + applicationContext: ServerApplicationContext; + caseRecord: RawCase; + trialSessionEntity: TrialSession; + }, + authorizedUser: AuthUser, +): Promise => { + const caseEntity = new Case(caseRecord, { authorizedUser }); caseEntity.setAsCalendared(trialSessionEntity); @@ -221,21 +244,25 @@ const setManuallyAddedCaseAsCalendared = async ({ }), applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }), ]); }; -const setTrialSessionCalendarForEligibleCase = async ({ - applicationContext, - caseRecord, - trialSessionEntity, -}: { - applicationContext: ServerApplicationContext; - caseRecord: RawCase; - trialSessionEntity: TrialSession; -}): Promise => { - const caseEntity = new Case(caseRecord, { applicationContext }); +const setTrialSessionCalendarForEligibleCase = async ( + { + applicationContext, + caseRecord, + trialSessionEntity, + }: { + applicationContext: ServerApplicationContext; + caseRecord: RawCase; + trialSessionEntity: TrialSession; + }, + authorizedUser: AuthUser, +): Promise => { + const caseEntity = new Case(caseRecord, { authorizedUser }); caseEntity.setAsCalendared(trialSessionEntity); trialSessionEntity.addCaseToCalendar(caseEntity); @@ -249,6 +276,7 @@ const setTrialSessionCalendarForEligibleCase = async ({ }), applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }), applicationContext diff --git a/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.locking.test.ts b/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.locking.test.ts index 78cd8933255..59adf10045d 100644 --- a/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.locking.test.ts +++ b/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.locking.test.ts @@ -8,7 +8,7 @@ import { handleLockError, updateTrialSessionInteractor, } from './updateTrialSessionInteractor'; -import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('determineEntitiesToLock', () => { const trialSessionId = '6805d1ab-18d0-43ec-bafb-654e83405416'; @@ -61,20 +61,15 @@ describe('determineEntitiesToLock', () => { }); describe('handleLockError', () => { - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - }); - - it('should determine who the user is based on applicationContext', async () => { - await handleLockError(applicationContext, { foo: 'bar' }); - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); - }); - it('should send a notification to the user with "retry_async_request" and the originalRequest', async () => { const mockOriginalRequest = { foo: 'bar', }; - await handleLockError(applicationContext, mockOriginalRequest); + await handleLockError( + applicationContext, + mockOriginalRequest, + mockDocketClerkUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock .calls[0][0].message, @@ -101,8 +96,6 @@ describe('updateTrialSessionInteractor', () => { applicationContext .getPersistenceGateway() .getLock.mockImplementation(() => mockLock); - - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); }); describe('is locked', () => { @@ -112,7 +105,11 @@ describe('updateTrialSessionInteractor', () => { it('should throw a ServiceUnavailableError if a Case is currently locked', async () => { await expect( - updateTrialSessionInteractor(applicationContext, mockRequest), + updateTrialSessionInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -122,7 +119,11 @@ describe('updateTrialSessionInteractor', () => { it('should return a "retry_async_request" notification with the original request', async () => { await expect( - updateTrialSessionInteractor(applicationContext, mockRequest), + updateTrialSessionInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -134,7 +135,7 @@ describe('updateTrialSessionInteractor', () => { originalRequest: mockRequest, requestToRetry: 'update_trial_session', }, - userId: docketClerkUser.userId, + userId: mockDocketClerkUser.userId, }); expect( @@ -149,7 +150,11 @@ describe('updateTrialSessionInteractor', () => { }); it('should acquire a lock that lasts for 15 minutes', async () => { - await updateTrialSessionInteractor(applicationContext, mockRequest); + await updateTrialSessionInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ); MOCK_TRIAL_INPERSON.caseOrder!.forEach(({ docketNumber }) => { expect( @@ -163,7 +168,11 @@ describe('updateTrialSessionInteractor', () => { }); it('should remove the lock', async () => { - await updateTrialSessionInteractor(applicationContext, mockRequest); + await updateTrialSessionInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ); let expectedIdentifiers = MOCK_TRIAL_INPERSON.caseOrder!.map( ({ docketNumber }) => `case|${docketNumber}`, diff --git a/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.noticeGeneration.test.ts b/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.noticeGeneration.test.ts index 7ba90636006..1c172f17a27 100644 --- a/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.noticeGeneration.test.ts +++ b/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.noticeGeneration.test.ts @@ -1,6 +1,5 @@ import { CASE_STATUS_TYPES, - ROLES, TRIAL_SESSION_PROCEEDING_TYPES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; @@ -8,20 +7,12 @@ import { MOCK_TRIAL_INPERSON, MOCK_TRIAL_REMOTE, } from '../../../../../shared/src/test/mockTrial'; -import { User } from '../../../../../shared/src/business/entities/User'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { updateTrialSessionInteractor } from './updateTrialSessionInteractor'; describe('updateTrialSessionInteractor should Generate Notices of', () => { - const mockUser = new User({ - name: 'Docket Clerk', - role: ROLES.docketClerk, - userId: '6805d1ab-18d0-43ec-bafb-654e83405416', - }); - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(mockUser); - applicationContext .getUseCaseHelpers() .saveFileAndGenerateUrl.mockReturnValue({ @@ -57,10 +48,14 @@ describe('updateTrialSessionInteractor should Generate Notices of', () => { trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: inPersonNonCalendaredTrialSession, - }); + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: inPersonNonCalendaredTrialSession, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers() @@ -96,10 +91,14 @@ describe('updateTrialSessionInteractor should Generate Notices of', () => { trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: inPersonCalendaredTrialSession, - }); + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: inPersonCalendaredTrialSession, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers() @@ -132,10 +131,14 @@ describe('updateTrialSessionInteractor should Generate Notices of', () => { trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: inPersonCalendaredTrialSession, - }); + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: inPersonCalendaredTrialSession, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers() @@ -169,10 +172,14 @@ describe('updateTrialSessionInteractor should Generate Notices of', () => { trialSessionId: MOCK_TRIAL_INPERSON.trialSessionId, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: inPersonCalendaredTrialSession, - }); + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: inPersonCalendaredTrialSession, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers() @@ -207,10 +214,14 @@ describe('updateTrialSessionInteractor should Generate Notices of', () => { trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: remoteCalendaredTrialSession, - }); + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: remoteCalendaredTrialSession, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers() @@ -246,10 +257,14 @@ describe('updateTrialSessionInteractor should Generate Notices of', () => { trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: remoteCalendaredTrialSession, - }); + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: remoteCalendaredTrialSession, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers() @@ -283,10 +298,14 @@ describe('updateTrialSessionInteractor should Generate Notices of', () => { trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: remoteTrialSession, - }); + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: remoteTrialSession, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers() @@ -333,13 +352,17 @@ describe('Change of Trial Judge', () => { trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...remoteCalendaredTrialSession, - judge: mockJudgeOne, + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...remoteCalendaredTrialSession, + judge: mockJudgeOne, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().setNoticeOfChangeOfTrialJudge, @@ -374,13 +397,17 @@ describe('Change of Trial Judge', () => { trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...remoteCalendaredTrialSession, - judge: mockJudgeTwo, + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...remoteCalendaredTrialSession, + judge: mockJudgeTwo, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().setNoticeOfChangeOfTrialJudge, @@ -413,13 +440,17 @@ describe('Change of Trial Judge', () => { trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...remoteCalendaredTrialSession, - judge: mockJudgeTwo, + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...remoteCalendaredTrialSession, + judge: mockJudgeTwo, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().setNoticeOfChangeOfTrialJudge, @@ -453,13 +484,17 @@ describe('Change of Trial Judge', () => { trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...remoteCalendaredTrialSession, - judge: mockJudgeOne, + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...remoteCalendaredTrialSession, + judge: mockJudgeOne, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().setNoticeOfChangeOfTrialJudge, @@ -492,13 +527,17 @@ describe('Change of Trial Judge', () => { trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...remoteCalendaredTrialSession, - judge: undefined, + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...remoteCalendaredTrialSession, + judge: undefined, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().setNoticeOfChangeOfTrialJudge, @@ -532,13 +571,17 @@ describe('Change of Trial Judge', () => { trialSessionId: MOCK_TRIAL_REMOTE.trialSessionId, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...remoteCalendaredTrialSession, - judge: mockJudgeTwo, + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...remoteCalendaredTrialSession, + judge: mockJudgeTwo, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().setNoticeOfChangeOfTrialJudge, diff --git a/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.test.ts b/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.test.ts index 2a29d0f181e..47461af33ad 100644 --- a/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.test.ts @@ -10,18 +10,15 @@ import { } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { cloneDeep } from 'lodash'; +import { judgeUser, trialClerkUser } from '@shared/test/mockUsers'; import { - docketClerkUser, - judgeUser, - petitionerUser, - trialClerkUser, -} from '@shared/test/mockUsers'; + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { updateTrialSessionInteractor } from './updateTrialSessionInteractor'; describe('updateTrialSessionInteractor', () => { beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getUseCaseHelpers() .saveFileAndGenerateUrl.mockReturnValue({ @@ -35,13 +32,15 @@ describe('updateTrialSessionInteractor', () => { }); it('should throw an error when the user is not unauthorized to update a trial session', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - await expect( - updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: MOCK_TRIAL_REMOTE, - }), + updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: MOCK_TRIAL_REMOTE, + }, + mockPetitionerUser, + ), ).rejects.toThrow(); }); @@ -54,10 +53,14 @@ describe('updateTrialSessionInteractor', () => { }); await expect( - updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { ...MOCK_TRIAL_REMOTE, startDate: '1776-12-01' }, - }), + updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { ...MOCK_TRIAL_REMOTE, startDate: '1776-12-01' }, + }, + mockDocketClerkUser, + ), ).rejects.toThrow('Trial session cannot be updated after its start date'); }); @@ -69,10 +72,14 @@ describe('updateTrialSessionInteractor', () => { }); await expect( - updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: MOCK_TRIAL_REMOTE, - }), + updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: MOCK_TRIAL_REMOTE, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(); }); @@ -81,10 +88,14 @@ describe('updateTrialSessionInteractor', () => { .getPersistenceGateway() .getTrialSessionById.mockResolvedValue(MOCK_TRIAL_INPERSON); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: MOCK_TRIAL_INPERSON, - }); + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: MOCK_TRIAL_INPERSON, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateTrialSession, @@ -99,13 +110,17 @@ describe('updateTrialSessionInteractor', () => { judge: undefined, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...MOCK_TRIAL_INPERSON, - judge: undefined, + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...MOCK_TRIAL_INPERSON, + judge: undefined, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createTrialSessionWorkingCopy, @@ -121,13 +136,17 @@ describe('updateTrialSessionInteractor', () => { .getPersistenceGateway() .getTrialSessionById.mockResolvedValue(mockTrialSessionWithJudge); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...MOCK_TRIAL_INPERSON, - judge: judgeUser, + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...MOCK_TRIAL_INPERSON, + judge: judgeUser, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createTrialSessionWorkingCopy @@ -149,16 +168,20 @@ describe('updateTrialSessionInteractor', () => { }, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...MOCK_TRIAL_INPERSON, - judge: { - name: 'Judge North', - userId: 'c7d90c05-f6cd-442c-a168-202db587f16f', // different judge id + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...MOCK_TRIAL_INPERSON, + judge: { + name: 'Judge North', + userId: 'c7d90c05-f6cd-442c-a168-202db587f16f', // different judge id + }, }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createTrialSessionWorkingCopy @@ -177,13 +200,17 @@ describe('updateTrialSessionInteractor', () => { trialClerk: undefined, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...MOCK_TRIAL_INPERSON, - trialClerk: trialClerkUser, + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...MOCK_TRIAL_INPERSON, + trialClerk: trialClerkUser, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createTrialSessionWorkingCopy @@ -205,16 +232,20 @@ describe('updateTrialSessionInteractor', () => { }, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...MOCK_TRIAL_INPERSON, - trialClerk: { - name: 'Clerk Magni', - userId: 'c7d90c05-f6cd-442c-a168-202db587f16f', // different trial clerk id + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...MOCK_TRIAL_INPERSON, + trialClerk: { + name: 'Clerk Magni', + userId: 'c7d90c05-f6cd-442c-a168-202db587f16f', // different trial clerk id + }, }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createTrialSessionWorkingCopy @@ -237,10 +268,14 @@ describe('updateTrialSessionInteractor', () => { .getPersistenceGateway() .getTrialSessionById.mockReturnValue(MOCK_TRIAL_INPERSON); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: MOCK_TRIAL_INPERSON, - }); + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: MOCK_TRIAL_INPERSON, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCaseHearing.mock @@ -265,10 +300,14 @@ describe('updateTrialSessionInteractor', () => { .getPersistenceGateway() .getTrialSessionById.mockReturnValue(MOCK_TRIAL_INPERSON); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: MOCK_TRIAL_INPERSON, - }); + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: MOCK_TRIAL_INPERSON, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -318,13 +357,17 @@ describe('updateTrialSessionInteractor', () => { .getPersistenceGateway() .getTrialSessionById.mockReturnValue(MOCK_TRIAL_INPERSON); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...MOCK_TRIAL_INPERSON, - ...updatedFields, + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...MOCK_TRIAL_INPERSON, + ...updatedFields, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateTrialSession.mock @@ -344,13 +387,17 @@ describe('updateTrialSessionInteractor', () => { .getPersistenceGateway() .getTrialSessionById.mockReturnValue(MOCK_TRIAL_INPERSON); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...MOCK_TRIAL_INPERSON, - ...updatedFields, + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...MOCK_TRIAL_INPERSON, + ...updatedFields, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateTrialSession.mock @@ -369,13 +416,17 @@ describe('updateTrialSessionInteractor', () => { isCalendared: false, }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...MOCK_TRIAL_INPERSON, - isCalendared: true, + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...MOCK_TRIAL_INPERSON, + isCalendared: true, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateTrialSession.mock @@ -395,10 +446,14 @@ describe('updateTrialSessionInteractor', () => { .getPersistenceGateway() .getTrialSessionById.mockReturnValue(MOCK_TRIAL_INPERSON); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: MOCK_TRIAL_INPERSON, - }); + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: MOCK_TRIAL_INPERSON, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase, @@ -413,10 +468,14 @@ describe('updateTrialSessionInteractor', () => { caseOrder: [], }); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: MOCK_TRIAL_INPERSON, - }); + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: MOCK_TRIAL_INPERSON, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -430,18 +489,22 @@ describe('updateTrialSessionInteractor', () => { .getPersistenceGateway() .getTrialSessionById.mockReturnValue(MOCK_TRIAL_INPERSON); - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...MOCK_TRIAL_INPERSON, - caseOrder: [ - { - docketNumber: mockCaseRemovedFromTrialDocketNumber, - removedFromTrial: true, - }, - ], + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...MOCK_TRIAL_INPERSON, + caseOrder: [ + { + docketNumber: mockCaseRemovedFromTrialDocketNumber, + removedFromTrial: true, + }, + ], + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getCaseByDocketNumber, @@ -454,14 +517,18 @@ describe('updateTrialSessionInteractor', () => { it('should associate swing trial sessions when the current trial session has a swing session', async () => { const mockSwingSessionId = '06419775-e726-4c3b-a7e0-193d379fa39d'; - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: { - ...MOCK_TRIAL_INPERSON, - swingSession: true, - swingSessionId: mockSwingSessionId, + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: { + ...MOCK_TRIAL_INPERSON, + swingSession: true, + swingSessionId: mockSwingSessionId, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().associateSwingTrialSessions, @@ -515,10 +582,14 @@ describe('updateTrialSessionInteractor', () => { desiredTrialSession.judge!.userId = '07a2a119-c142-4811-87e0-7d6bc2d06a1b'; - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: desiredTrialSession, - }); + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: desiredTrialSession, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().setNoticeOfChangeOfTrialJudge, @@ -535,10 +606,14 @@ describe('updateTrialSessionInteractor', () => { originalTrialSession.proceedingType = TRIAL_SESSION_PROCEEDING_TYPES.remote; - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: desiredTrialSession, - }); + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: desiredTrialSession, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers() @@ -559,10 +634,14 @@ describe('updateTrialSessionInteractor', () => { originalTrialSession.proceedingType = TRIAL_SESSION_PROCEEDING_TYPES.inPerson; - await updateTrialSessionInteractor(applicationContext, { - clientConnectionId: '123', - trialSession: desiredTrialSession, - }); + await updateTrialSessionInteractor( + applicationContext, + { + clientConnectionId: '123', + trialSession: desiredTrialSession, + }, + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers() diff --git a/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.ts b/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.ts index 0e2e0d722b1..9baadc4e9fd 100644 --- a/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/updateTrialSessionInteractor.ts @@ -1,4 +1,8 @@ /* eslint-disable complexity */ +import { + AuthUser, + UnknownAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; import { Case } from '../../../../../shared/src/business/entities/cases/Case'; import { NotFoundError } from '../../../errors/errors'; import { @@ -22,10 +26,9 @@ export const updateTrialSession = async ( clientConnectionId, trialSession, }: { trialSession: RawTrialSession; clientConnectionId: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSIONS)) { throw new UnauthorizedError('Unauthorized'); } @@ -81,12 +84,10 @@ export const updateTrialSession = async ( trialLocation: trialSession.trialLocation, }; - const updatedTrialSessionEntity = new TrialSession( - { ...currentTrialSession, ...editableFields }, - { - applicationContext, - }, - ); + const updatedTrialSessionEntity = new TrialSession({ + ...currentTrialSession, + ...editableFields, + }); const shouldCreateWorkingCopyForNewJudge = (!get(currentTrialSession, 'judge.userId') && @@ -150,13 +151,13 @@ export const updateTrialSession = async ( await updateCasesAndSetNoticeOfChange({ applicationContext, + authorizedUser, currentTrialSession, paperServicePdfsCombined, shouldIssueNoticeOfChangeOfTrialJudge, shouldSetNoticeOfChangeToInPersonProceeding, shouldSetNoticeOfChangeToRemoteProceeding, updatedTrialSessionEntity, - user, }); hasPaper = !!paperServicePdfsCombined.getPageCount(); @@ -181,12 +182,14 @@ export const updateTrialSession = async ( } if (trialSession.swingSession && trialSession.swingSessionId) { - await applicationContext - .getUseCaseHelpers() - .associateSwingTrialSessions(applicationContext, { + await applicationContext.getUseCaseHelpers().associateSwingTrialSessions( + applicationContext, + { swingSessionId: trialSession.swingSessionId, trialSessionEntity: updatedTrialSessionEntity, - }); + }, + authorizedUser, + ); } await applicationContext.getPersistenceGateway().updateTrialSession({ @@ -204,25 +207,25 @@ export const updateTrialSession = async ( pdfUrl, trialSessionId: trialSession.trialSessionId, }, - userId: user.userId, + userId: authorizedUser.userId, }); }; const updateCasesAndSetNoticeOfChange = async ({ applicationContext, + authorizedUser, currentTrialSession, paperServicePdfsCombined, shouldIssueNoticeOfChangeOfTrialJudge, shouldSetNoticeOfChangeToInPersonProceeding, shouldSetNoticeOfChangeToRemoteProceeding, updatedTrialSessionEntity, - user, }: { applicationContext: ServerApplicationContext; currentTrialSession: RawTrialSession; paperServicePdfsCombined: any; updatedTrialSessionEntity: TrialSession; - user: any; + authorizedUser: AuthUser; shouldSetNoticeOfChangeToRemoteProceeding: boolean; shouldSetNoticeOfChangeToInPersonProceeding: boolean; shouldIssueNoticeOfChangeOfTrialJudge: boolean; @@ -237,7 +240,7 @@ const updateCasesAndSetNoticeOfChange = async ({ applicationContext, docketNumber: c.docketNumber, }); - return new Case(aCase, { applicationContext }); + return new Case(aCase, { authorizedUser }); }), ); const casesThatShouldReceiveNotices = calendaredCaseEntities @@ -250,41 +253,51 @@ const updateCasesAndSetNoticeOfChange = async ({ if (shouldSetNoticeOfChangeToRemoteProceeding) { await applicationContext .getUseCaseHelpers() - .setNoticeOfChangeToRemoteProceeding(applicationContext, { - caseEntity, - newPdfDoc: paperServicePdfsCombined, - newTrialSessionEntity: updatedTrialSessionEntity, - user: applicationContext.getCurrentUser(), - }); + .setNoticeOfChangeToRemoteProceeding( + applicationContext, + { + caseEntity, + newPdfDoc: paperServicePdfsCombined, + newTrialSessionEntity: updatedTrialSessionEntity, + }, + authorizedUser, + ); } if (shouldSetNoticeOfChangeToInPersonProceeding) { await applicationContext .getUseCaseHelpers() - .setNoticeOfChangeToInPersonProceeding(applicationContext, { - caseEntity, - newPdfDoc: paperServicePdfsCombined, - newTrialSessionEntity: updatedTrialSessionEntity, - user: applicationContext.getCurrentUser(), - }); + .setNoticeOfChangeToInPersonProceeding( + applicationContext, + { + caseEntity, + newPdfDoc: paperServicePdfsCombined, + newTrialSessionEntity: updatedTrialSessionEntity, + }, + authorizedUser, + ); } if (shouldIssueNoticeOfChangeOfTrialJudge) { await applicationContext .getUseCaseHelpers() - .setNoticeOfChangeOfTrialJudge(applicationContext, { - caseEntity, - currentTrialSession, - newPdfDoc: paperServicePdfsCombined, - newTrialSessionEntity: updatedTrialSessionEntity, - user, - }); + .setNoticeOfChangeOfTrialJudge( + applicationContext, + { + caseEntity, + currentTrialSession, + newPdfDoc: paperServicePdfsCombined, + newTrialSessionEntity: updatedTrialSessionEntity, + }, + authorizedUser, + ); } caseEntity.updateTrialSessionInformation(updatedTrialSessionEntity); await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); } @@ -371,18 +384,19 @@ export const determineEntitiesToLock = async ( export const handleLockError = async ( applicationContext: ServerApplicationContext, originalRequest: any, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - await applicationContext.getNotificationGateway().sendNotificationToUser({ - applicationContext, - message: { - action: 'retry_async_request', - originalRequest, - requestToRetry: 'update_trial_session', - }, - userId: user.userId, - }); + if (authorizedUser?.userId) { + await applicationContext.getNotificationGateway().sendNotificationToUser({ + applicationContext, + message: { + action: 'retry_async_request', + originalRequest, + requestToRetry: 'update_trial_session', + }, + userId: authorizedUser.userId, + }); + } }; export const updateTrialSessionInteractor = withLocking( diff --git a/web-api/src/business/useCases/trialSessions/updateTrialSessionWorkingCopyInteractor.test.ts b/web-api/src/business/useCases/trialSessions/updateTrialSessionWorkingCopyInteractor.test.ts index c6ab86808e4..02b114e12ca 100644 --- a/web-api/src/business/useCases/trialSessions/updateTrialSessionWorkingCopyInteractor.test.ts +++ b/web-api/src/business/useCases/trialSessions/updateTrialSessionWorkingCopyInteractor.test.ts @@ -1,7 +1,7 @@ -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { RawTrialSessionWorkingCopy } from '@shared/business/entities/trialSessions/TrialSessionWorkingCopy'; import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { mockJudgeUser } from '@shared/test/mockAuthUsers'; import { omit } from 'lodash'; import { updateTrialSessionWorkingCopyInteractor } from './updateTrialSessionWorkingCopyInteractor'; @@ -20,7 +20,6 @@ const MOCK_WORKING_COPY = { describe('Update trial session working copy', () => { beforeEach(() => { applicationContext.environment.stage = 'local'; - applicationContext.getCurrentUser.mockImplementation(() => user); applicationContext .getPersistenceGateway() .getTrialSessionWorkingCopy.mockReturnValue(MOCK_WORKING_COPY); @@ -37,19 +36,18 @@ describe('Update trial session working copy', () => { .updateTrialSessionWorkingCopy.mockReturnValue({}); await expect( - updateTrialSessionWorkingCopyInteractor(applicationContext, { - trialSessionWorkingCopyToUpdate: - MOCK_WORKING_COPY as unknown as RawTrialSessionWorkingCopy, - }), + updateTrialSessionWorkingCopyInteractor( + applicationContext, + { + trialSessionWorkingCopyToUpdate: + MOCK_WORKING_COPY as unknown as RawTrialSessionWorkingCopy, + }, + user, + ), ).rejects.toThrow(UnauthorizedError); }); it('throws an error if the entity returned from persistence is invalid', async () => { - user = { - role: ROLES.judge, - userId: 'd7d90c05-f6cd-442c-a168-202db587f16f', - }; - applicationContext .getPersistenceGateway() .getTrialSessionWorkingCopy.mockResolvedValue( @@ -57,19 +55,18 @@ describe('Update trial session working copy', () => { ); await expect( - updateTrialSessionWorkingCopyInteractor(applicationContext, { - trialSessionWorkingCopyToUpdate: - MOCK_WORKING_COPY as unknown as RawTrialSessionWorkingCopy, - }), + updateTrialSessionWorkingCopyInteractor( + applicationContext, + { + trialSessionWorkingCopyToUpdate: + MOCK_WORKING_COPY as unknown as RawTrialSessionWorkingCopy, + }, + mockJudgeUser, + ), ).rejects.toThrow('The TrialSessionWorkingCopy entity was invalid'); }); it('correctly returns data from persistence', async () => { - user = { - role: ROLES.judge, - userId: 'd7d90c05-f6cd-442c-a168-202db587f16f', - }; - applicationContext .getPersistenceGateway() .updateTrialSessionWorkingCopy.mockResolvedValue(MOCK_WORKING_COPY); @@ -80,6 +77,7 @@ describe('Update trial session working copy', () => { trialSessionWorkingCopyToUpdate: MOCK_WORKING_COPY as unknown as RawTrialSessionWorkingCopy, }, + mockJudgeUser, ); expect(result).toMatchObject(MOCK_WORKING_COPY); }); diff --git a/web-api/src/business/useCases/trialSessions/updateTrialSessionWorkingCopyInteractor.ts b/web-api/src/business/useCases/trialSessions/updateTrialSessionWorkingCopyInteractor.ts index 5770ed9081f..48baa0b4d07 100644 --- a/web-api/src/business/useCases/trialSessions/updateTrialSessionWorkingCopyInteractor.ts +++ b/web-api/src/business/useCases/trialSessions/updateTrialSessionWorkingCopyInteractor.ts @@ -8,6 +8,7 @@ import { } from '../../../../../shared/src/business/entities/trialSessions/TrialSessionWorkingCopy'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * updateTrialSessionWorkingCopyInteractor @@ -22,9 +23,11 @@ export const updateTrialSessionWorkingCopyInteractor = async ( { trialSessionWorkingCopyToUpdate, }: { trialSessionWorkingCopyToUpdate: RawTrialSessionWorkingCopy }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - if (!isAuthorized(user, ROLE_PERMISSIONS.TRIAL_SESSION_WORKING_COPY)) { + if ( + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.TRIAL_SESSION_WORKING_COPY) + ) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/user/checkEmailAvailabilityInteractor.test.ts b/web-api/src/business/useCases/user/checkEmailAvailabilityInteractor.test.ts index 8a29d1b09ec..1195b0738cf 100644 --- a/web-api/src/business/useCases/user/checkEmailAvailabilityInteractor.test.ts +++ b/web-api/src/business/useCases/user/checkEmailAvailabilityInteractor.test.ts @@ -3,31 +3,33 @@ import { UserStatusType } from '@aws-sdk/client-cognito-identity-provider'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { checkEmailAvailabilityInteractor } from './checkEmailAvailabilityInteractor'; import { - petitionsClerkUser, - privatePractitionerUser, -} from '@shared/test/mockUsers'; + mockPetitionsClerkUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; describe('checkEmailAvailabilityInteractor', () => { const mockEmail = 'test@example.com'; - beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(privatePractitionerUser); - }); - it('should throw an error when the logged in user is unauthorized to check email availability', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - await expect( - checkEmailAvailabilityInteractor(applicationContext, { - email: mockEmail, - }), + checkEmailAvailabilityInteractor( + applicationContext, + { + email: mockEmail, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('Unauthorized to manage emails.'); }); it('should attempt to retrieve the user by email', async () => { - await checkEmailAvailabilityInteractor(applicationContext, { - email: mockEmail, - }); + await checkEmailAvailabilityInteractor( + applicationContext, + { + email: mockEmail, + }, + mockPrivatePractitionerUser, + ); expect( applicationContext.getUserGateway().getUserByEmail.mock.calls[0][1], @@ -39,9 +41,13 @@ describe('checkEmailAvailabilityInteractor', () => { it('should return true when the specified email is not already in use', async () => { applicationContext.getUserGateway().getUserByEmail.mockReturnValue(); - const result = await checkEmailAvailabilityInteractor(applicationContext, { - email: mockEmail, - }); + const result = await checkEmailAvailabilityInteractor( + applicationContext, + { + email: mockEmail, + }, + mockPrivatePractitionerUser, + ); expect(result.isEmailAvailable).toEqual(true); }); @@ -55,9 +61,13 @@ describe('checkEmailAvailabilityInteractor', () => { userId: '85e2ca3e-6521-4b10-8edb-91c934c78c43', }); - const result = await checkEmailAvailabilityInteractor(applicationContext, { - email: mockEmail, - }); + const result = await checkEmailAvailabilityInteractor( + applicationContext, + { + email: mockEmail, + }, + mockPrivatePractitionerUser, + ); expect(result.isEmailAvailable).toEqual(false); }); diff --git a/web-api/src/business/useCases/user/checkEmailAvailabilityInteractor.ts b/web-api/src/business/useCases/user/checkEmailAvailabilityInteractor.ts index 8729a648732..36436c846df 100644 --- a/web-api/src/business/useCases/user/checkEmailAvailabilityInteractor.ts +++ b/web-api/src/business/useCases/user/checkEmailAvailabilityInteractor.ts @@ -4,14 +4,14 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { UserStatusType } from '@aws-sdk/client-cognito-identity-provider'; export const checkEmailAvailabilityInteractor = async ( applicationContext: ServerApplicationContext, { email }: { email: string }, + authorizedUser: UnknownAuthUser, ): Promise<{ isAccountUnverified: boolean; isEmailAvailable: boolean }> => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.EMAIL_MANAGEMENT)) { throw new UnauthorizedError('Unauthorized to manage emails.'); } diff --git a/web-api/src/business/useCases/user/createUserInteractor.spec.ts b/web-api/src/business/useCases/user/createUserInteractor.spec.ts index bcc9ded623f..29aac574cab 100644 --- a/web-api/src/business/useCases/user/createUserInteractor.spec.ts +++ b/web-api/src/business/useCases/user/createUserInteractor.spec.ts @@ -1,8 +1,8 @@ -import { ROLES } from '@shared/business/entities/EntityConstants'; import { applicationContext } from '@shared/business/test/createTestApplicationContext'; import { createOrUpdateUser } from '../../../../../shared/admin-tools/user/admin'; import { createUserInteractor } from '@web-api/business/useCases/user/createUserInteractor'; import { docketClerk1User } from '@shared/test/mockUsers'; +import { mockAdminUser, mockPetitionerUser } from '@shared/test/mockAuthUsers'; jest.mock('../../../../../shared/admin-tools/user/admin', () => ({ createOrUpdateUser: jest.fn(), @@ -10,27 +10,26 @@ jest.mock('../../../../../shared/admin-tools/user/admin', () => ({ describe('createUserInteractor', () => { it('should throw an error if a user with create permissions tries to create a user', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.legacyJudge, - userId: '47cc9719-a392-4cb0-b744-ffb243eff3a3', - }); await expect( - createUserInteractor(applicationContext, { - user: { ...docketClerk1User, password: 'junkPass' }, - }), + createUserInteractor( + applicationContext, + { + user: { ...docketClerk1User, password: 'junkPass' }, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); expect(createOrUpdateUser).not.toHaveBeenCalled(); }); it('should create a new user when an admin tries to create a user', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.admin, - userId: '3aa4b9c3-a66a-486a-bd01-fb370f52f45a', - }); - - await createUserInteractor(applicationContext, { - user: { ...docketClerk1User, password: 'junkPass' }, - }); + await createUserInteractor( + applicationContext, + { + user: { ...docketClerk1User, password: 'junkPass' }, + }, + mockAdminUser, + ); expect(createOrUpdateUser).toHaveBeenCalledWith(expect.anything(), { password: 'junkPass', diff --git a/web-api/src/business/useCases/user/createUserInteractor.ts b/web-api/src/business/useCases/user/createUserInteractor.ts index c4222533e59..27e2c45351b 100644 --- a/web-api/src/business/useCases/user/createUserInteractor.ts +++ b/web-api/src/business/useCases/user/createUserInteractor.ts @@ -6,6 +6,7 @@ import { RawPractitioner } from '../../../../../shared/src/business/entities/Pra import { RawUser } from '../../../../../shared/src/business/entities/User'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '../../../errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { createOrUpdateUser } from '../../../../../shared/admin-tools/user/admin'; export const createUserInteractor = async ( @@ -17,10 +18,9 @@ export const createUserInteractor = async ( password: string; }; }, + authorizedUser: UnknownAuthUser, ): Promise => { - const requestUser = applicationContext.getCurrentUser(); - - if (!isAuthorized(requestUser, ROLE_PERMISSIONS.CREATE_USER)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.CREATE_USER)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/user/generateChangeOfAddress.ts b/web-api/src/business/useCases/user/generateChangeOfAddress.ts index 3c87a59a2d3..695132da6c9 100644 --- a/web-api/src/business/useCases/user/generateChangeOfAddress.ts +++ b/web-api/src/business/useCases/user/generateChangeOfAddress.ts @@ -1,4 +1,5 @@ import { ALLOWLIST_FEATURE_FLAGS } from '@shared/business/entities/EntityConstants'; +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs'; import { ServerApplicationContext } from '@web-api/applicationContext'; @@ -31,6 +32,7 @@ export type TUserContact = { */ const generateChangeOfAddressForPractitioner = async ({ applicationContext, + authorizedUser, bypassDocketEntry = false, contactInfo, firmName, @@ -49,6 +51,7 @@ const generateChangeOfAddressForPractitioner = async ({ updatedName?: string; user: any; websocketMessagePrefix?: string; + authorizedUser: AuthUser; }): Promise => { const associatedUserCases = await applicationContext .getPersistenceGateway() @@ -100,7 +103,7 @@ const generateChangeOfAddressForPractitioner = async ({ firmName, jobId, requestUser: { - ...applicationContext.getCurrentUser(), + ...authorizedUser, token: undefined, }, requestUserId, @@ -120,6 +123,7 @@ const generateChangeOfAddressForPractitioner = async ({ .getUseCaseHelpers() .generateChangeOfAddressHelper({ applicationContext, + authorizedUser, bypassDocketEntry, contactInfo, docketNumber: caseInfo.docketNumber, diff --git a/web-api/src/business/useCases/user/generateChangeOfAddressForPractitioner.irsPractitioners.test.ts b/web-api/src/business/useCases/user/generateChangeOfAddressForPractitioner.irsPractitioners.test.ts index 8dbf66d62ee..567e3a2522e 100644 --- a/web-api/src/business/useCases/user/generateChangeOfAddressForPractitioner.irsPractitioners.test.ts +++ b/web-api/src/business/useCases/user/generateChangeOfAddressForPractitioner.irsPractitioners.test.ts @@ -6,8 +6,8 @@ import { } from '../../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; -import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; import { generateChangeOfAddress } from './generateChangeOfAddress'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; jest.mock('../addCoversheetInteractor', () => ({ addCoverToPdf: jest.fn().mockReturnValue({ @@ -56,8 +56,6 @@ describe('generateChangeOfAddress', () => { }; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getUseCaseHelpers() .updateCaseAndAssociations.mockImplementation( @@ -87,6 +85,7 @@ describe('generateChangeOfAddress', () => { it('should run a change of address when address1 changes for an irs practitioner', async () => { await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, bypassDocketEntry: false, contactInfo: { ...mockIrsPractitioner.contact, @@ -117,6 +116,7 @@ describe('generateChangeOfAddress', () => { it('should not set partyIrsPractitioner if role is not irsPractitioner', async () => { await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, bypassDocketEntry: false, contactInfo: { ...mockIrsPractitioner.contact, @@ -141,6 +141,7 @@ describe('generateChangeOfAddress', () => { it('should send a notification to the user initially and after each case is updated', async () => { await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, bypassDocketEntry: false, contactInfo: { ...mockIrsPractitioner.contact, @@ -180,6 +181,7 @@ describe('generateChangeOfAddress', () => { await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, bypassDocketEntry: false, contactInfo: { ...mockIrsPractitioner.contact, @@ -206,6 +208,7 @@ describe('generateChangeOfAddress', () => { await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, bypassDocketEntry: false, contactInfo: { ...mockIrsPractitioner.contact, @@ -236,6 +239,7 @@ describe('generateChangeOfAddress', () => { it('should set isAutoGenerated to true on the generated "Notice of Change of Address" document', async () => { await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, bypassDocketEntry: false, contactInfo: { ...mockIrsPractitioner.contact, diff --git a/web-api/src/business/useCases/user/generateChangeOfAddressForPractitioner.privatePractitioners.test.ts b/web-api/src/business/useCases/user/generateChangeOfAddressForPractitioner.privatePractitioners.test.ts index e7258c8ae59..f591aeb8036 100644 --- a/web-api/src/business/useCases/user/generateChangeOfAddressForPractitioner.privatePractitioners.test.ts +++ b/web-api/src/business/useCases/user/generateChangeOfAddressForPractitioner.privatePractitioners.test.ts @@ -7,8 +7,8 @@ import { import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { calculateISODate } from '../../../../../shared/src/business/utilities/DateHandler'; -import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; import { generateChangeOfAddress } from './generateChangeOfAddress'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; jest.mock('../addCoversheetInteractor', () => ({ addCoverToPdf: jest.fn().mockReturnValue({ @@ -66,8 +66,6 @@ describe('generateChangeOfAddress', () => { ); }); beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - applicationContext .getPersistenceGateway() .getCasesForUser.mockReturnValue([{ docketNumber }]); @@ -123,6 +121,7 @@ describe('generateChangeOfAddress', () => { }); await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, contactInfo: { ...mockPrivatePractitioner.contact, address1: '234 Main St', @@ -152,6 +151,7 @@ describe('generateChangeOfAddress', () => { await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, contactInfo: { ...mockPrivatePractitioner.contact, address1: '234 Main St', @@ -180,6 +180,7 @@ describe('generateChangeOfAddress', () => { await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, contactInfo: { ...mockPrivatePractitioner.contact, address1: '234 Main St', @@ -201,6 +202,7 @@ describe('generateChangeOfAddress', () => { it("should NOT create a work item for an associated practitioner's notice of change of address when there is no paper service for the case", async () => { await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, contactInfo: { ...mockPrivatePractitioner.contact, address1: '234 Main St', @@ -222,6 +224,7 @@ describe('generateChangeOfAddress', () => { it('should not create a docket entry, work item, or serve anything if the bypassDocketEntry flag is true', async () => { await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, bypassDocketEntry: true, contactInfo: { ...mockPrivatePractitioner.contact, @@ -255,6 +258,7 @@ describe('generateChangeOfAddress', () => { await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, contactInfo: { ...mockPrivatePractitioner.contact, address1: '234 Main St', @@ -287,6 +291,7 @@ describe('generateChangeOfAddress', () => { await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, contactInfo: { ...mockPrivatePractitioner.contact, address1: '234 Main St', @@ -321,6 +326,7 @@ describe('generateChangeOfAddress', () => { await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, contactInfo: { ...mockPrivatePractitioner.contact, address1: '234 Main St', @@ -364,6 +370,7 @@ describe('generateChangeOfAddress', () => { await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, contactInfo: { ...mockPrivatePractitioner.contact, }, @@ -389,6 +396,7 @@ describe('generateChangeOfAddress', () => { it('should use original case caption to create case title when creating work item', async () => { await generateChangeOfAddress({ applicationContext, + authorizedUser: mockDocketClerkUser, contactInfo: { ...mockPrivatePractitioner.contact, address1: '234 Main St', diff --git a/web-api/src/business/useCases/user/getInternalUsersInteractor.test.ts b/web-api/src/business/useCases/user/getInternalUsersInteractor.test.ts index eef79c8a343..82225464cf7 100644 --- a/web-api/src/business/useCases/user/getInternalUsersInteractor.test.ts +++ b/web-api/src/business/useCases/user/getInternalUsersInteractor.test.ts @@ -1,13 +1,12 @@ -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getInternalUsersInteractor } from './getInternalUsersInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('Get internal users', () => { beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketclerk', - }); applicationContext .getPersistenceGateway() .getInternalUsers.mockReturnValue([ @@ -27,7 +26,10 @@ describe('Get internal users', () => { }); it('returns the same users that were returned from mocked persistence', async () => { - const users = await getInternalUsersInteractor(applicationContext); + const users = await getInternalUsersInteractor( + applicationContext, + mockDocketClerkUser, + ); expect(users).toMatchObject([ { name: 'Saul Goodman', @@ -45,14 +47,9 @@ describe('Get internal users', () => { }); it('throws unauthorized error for unauthorized users', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Saul Goodman', - role: ROLES.petitioner, - userId: 'petitioner', - }); let error; try { - await getInternalUsersInteractor(applicationContext); + await getInternalUsersInteractor(applicationContext, mockPetitionerUser); } catch (err) { error = err; } diff --git a/web-api/src/business/useCases/user/getInternalUsersInteractor.ts b/web-api/src/business/useCases/user/getInternalUsersInteractor.ts index d6dcabc19e2..719d9e24f34 100644 --- a/web-api/src/business/useCases/user/getInternalUsersInteractor.ts +++ b/web-api/src/business/useCases/user/getInternalUsersInteractor.ts @@ -4,6 +4,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { User } from '../../../../../shared/src/business/entities/User'; /** @@ -14,13 +15,9 @@ import { User } from '../../../../../shared/src/business/entities/User'; */ export const getInternalUsersInteractor = async ( applicationContext: ServerApplicationContext, + authorizedUser: UnknownAuthUser, ) => { - if ( - !isAuthorized( - applicationContext.getCurrentUser(), - ROLE_PERMISSIONS.WORKITEM, - ) - ) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.WORKITEM)) { throw new UnauthorizedError('Unauthorized'); } @@ -30,5 +27,5 @@ export const getInternalUsersInteractor = async ( applicationContext, }); - return User.validateRawCollection(rawUsers, { applicationContext }); + return User.validateRawCollection(rawUsers); }; diff --git a/web-api/src/business/useCases/user/getIrsPractitionersBySearchKeyInteractor.test.ts b/web-api/src/business/useCases/user/getIrsPractitionersBySearchKeyInteractor.test.ts index 4639eb73a55..45112573c76 100644 --- a/web-api/src/business/useCases/user/getIrsPractitionersBySearchKeyInteractor.test.ts +++ b/web-api/src/business/useCases/user/getIrsPractitionersBySearchKeyInteractor.test.ts @@ -1,32 +1,30 @@ import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getIrsPractitionersBySearchKeyInteractor } from './getIrsPractitionersBySearchKeyInteractor'; - -let user; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('getIrsPractitionersBySearchKeyInteractor', () => { beforeEach(() => { applicationContext.environment.stage = 'local'; - applicationContext.getCurrentUser.mockImplementation(() => user); }); it('should throw an error when not authorized', async () => { - user = { - barNumber: 'PT1234', - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.petitioner, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; - applicationContext .getPersistenceGateway() .getUsersBySearchKey.mockResolvedValue([]); let error; try { - await getIrsPractitionersBySearchKeyInteractor(applicationContext, { - searchKey: 'something', - }); + await getIrsPractitionersBySearchKeyInteractor( + applicationContext, + { + searchKey: 'something', + }, + mockPetitionerUser, + ); } catch (err) { error = err; } @@ -34,12 +32,6 @@ describe('getIrsPractitionersBySearchKeyInteractor', () => { }); it('should return users from persistence', async () => { - user = { - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.petitionsClerk, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; - applicationContext .getPersistenceGateway() .getUsersBySearchKey.mockResolvedValue([ @@ -56,6 +48,7 @@ describe('getIrsPractitionersBySearchKeyInteractor', () => { { searchKey: 'Test Practitioner', }, + mockPetitionsClerkUser, ); expect(result).toMatchObject([{ name: 'Test Practitioner' }]); diff --git a/web-api/src/business/useCases/user/getIrsPractitionersBySearchKeyInteractor.ts b/web-api/src/business/useCases/user/getIrsPractitionersBySearchKeyInteractor.ts index 93419f16f65..5ffe49c631e 100644 --- a/web-api/src/business/useCases/user/getIrsPractitionersBySearchKeyInteractor.ts +++ b/web-api/src/business/useCases/user/getIrsPractitionersBySearchKeyInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * getIrsPractitionersBySearchKeyInteractor @@ -17,11 +18,10 @@ import { UnauthorizedError } from '@web-api/errors/errors'; export const getIrsPractitionersBySearchKeyInteractor = async ( applicationContext: ServerApplicationContext, { searchKey }: { searchKey: string }, + authorizedUser: UnknownAuthUser, ) => { - const authenticatedUser = applicationContext.getCurrentUser(); - if ( - !isAuthorized(authenticatedUser, ROLE_PERMISSIONS.ASSOCIATE_USER_WITH_CASE) + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.ASSOCIATE_USER_WITH_CASE) ) { throw new UnauthorizedError('Unauthorized'); } @@ -34,7 +34,5 @@ export const getIrsPractitionersBySearchKeyInteractor = async ( type: 'irsPractitioner', }); - return IrsPractitioner.validateRawCollection(users, { - applicationContext, - }); + return IrsPractitioner.validateRawCollection(users); }; diff --git a/web-api/src/business/useCases/user/getJudgeInSectionInteractor.test.ts b/web-api/src/business/useCases/user/getJudgeInSectionInteractor.test.ts index 9b342dd76d3..0f929d1dad4 100644 --- a/web-api/src/business/useCases/user/getJudgeInSectionInteractor.test.ts +++ b/web-api/src/business/useCases/user/getJudgeInSectionInteractor.test.ts @@ -1,6 +1,6 @@ -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; -import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { applicationContext } from '@shared/business/test/createTestApplicationContext'; import { getJudgeInSectionInteractor } from './getJudgeInSectionInteractor'; +import { mockJudgeUser, mockPetitionerUser } from '@shared/test/mockAuthUsers'; describe('getJudgeInSectionInteractor', () => { beforeEach(() => { @@ -12,26 +12,26 @@ describe('getJudgeInSectionInteractor', () => { }); it('throws an exception if a petitioner tries to get the judge of a section', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - }); - await expect(() => - getJudgeInSectionInteractor(applicationContext, { - section: 'buchsChambers', - }), + getJudgeInSectionInteractor( + applicationContext, + { + section: 'buchsChambers', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('returns the correct judge returned from the helper', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.judge, - }); - expect( - await getJudgeInSectionInteractor(applicationContext, { - section: 'buchsChambers', - }), + await getJudgeInSectionInteractor( + applicationContext, + { + section: 'buchsChambers', + }, + mockJudgeUser, + ), ).toEqual({ judgeName: 'buch', }); diff --git a/web-api/src/business/useCases/user/getJudgeInSectionInteractor.ts b/web-api/src/business/useCases/user/getJudgeInSectionInteractor.ts index e5d070bbbbf..f933bd16ec8 100644 --- a/web-api/src/business/useCases/user/getJudgeInSectionInteractor.ts +++ b/web-api/src/business/useCases/user/getJudgeInSectionInteractor.ts @@ -1,27 +1,18 @@ import { ROLE_PERMISSIONS, isAuthorized, -} from '../../../../../shared/src/authorization/authorizationClientService'; +} from '@shared/authorization/authorizationClientService'; import { RawUser } from '@shared/business/entities/User'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; - -/** - * getJudgeInSectionInteractor - returns the judge user for a given section - * - * @param {object} applicationContext the application context - * @param {object} obj the options object - * @param {string} obj.section the section to fetch the judge from - * @returns {User} the judge user in this section provided - */ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const getJudgeInSectionInteractor = async ( applicationContext: ServerApplicationContext, { section }: { section: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.GET_USERS_IN_SECTION)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.GET_USERS_IN_SECTION)) { throw new UnauthorizedError('Unauthorized'); } diff --git a/web-api/src/business/useCases/user/getPrivatePractitionersBySearchKeyInteractor.test.ts b/web-api/src/business/useCases/user/getPrivatePractitionersBySearchKeyInteractor.test.ts index ca365e10d7b..d098456ebc7 100644 --- a/web-api/src/business/useCases/user/getPrivatePractitionersBySearchKeyInteractor.test.ts +++ b/web-api/src/business/useCases/user/getPrivatePractitionersBySearchKeyInteractor.test.ts @@ -1,29 +1,32 @@ import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getPrivatePractitionersBySearchKeyInteractor } from './getPrivatePractitionersBySearchKeyInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; let user; describe('getPrivatePractitionersBySearchKeyInteractor', () => { beforeEach(() => { applicationContext.environment.stage = 'local'; - applicationContext.getCurrentUser.mockImplementation(() => user); }); it('should throw an error when not authorized', async () => { let error; - user = { - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.petitioner, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; + user = mockPetitionerUser; applicationContext .getPersistenceGateway() .getUsersBySearchKey.mockResolvedValue([]); try { - await getPrivatePractitionersBySearchKeyInteractor(applicationContext, { - searchKey: 'something', - }); + await getPrivatePractitionersBySearchKeyInteractor( + applicationContext, + { + searchKey: 'something', + }, + user, + ); } catch (err) { error = err; } @@ -31,11 +34,7 @@ describe('getPrivatePractitionersBySearchKeyInteractor', () => { }); it('should return users from persistence', async () => { - user = { - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.petitionsClerk, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; + user = mockPetitionsClerkUser; applicationContext .getPersistenceGateway() .getUsersBySearchKey.mockResolvedValue([ @@ -52,6 +51,7 @@ describe('getPrivatePractitionersBySearchKeyInteractor', () => { { searchKey: 'Test Practitioner', }, + user, ); expect(result).toMatchObject([{ name: 'Test Practitioner' }]); diff --git a/web-api/src/business/useCases/user/getPrivatePractitionersBySearchKeyInteractor.ts b/web-api/src/business/useCases/user/getPrivatePractitionersBySearchKeyInteractor.ts index 47a6e9e0f06..dd43d1f086c 100644 --- a/web-api/src/business/useCases/user/getPrivatePractitionersBySearchKeyInteractor.ts +++ b/web-api/src/business/useCases/user/getPrivatePractitionersBySearchKeyInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * getPrivatePractitionersBySearchKeyInteractor @@ -17,11 +18,10 @@ import { UnauthorizedError } from '@web-api/errors/errors'; export const getPrivatePractitionersBySearchKeyInteractor = async ( applicationContext: ServerApplicationContext, { searchKey }: { searchKey: string }, + authorizedUser: UnknownAuthUser, ) => { - const authenticatedUser = applicationContext.getCurrentUser(); - if ( - !isAuthorized(authenticatedUser, ROLE_PERMISSIONS.ASSOCIATE_USER_WITH_CASE) + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.ASSOCIATE_USER_WITH_CASE) ) { throw new UnauthorizedError('Unauthorized'); } @@ -34,7 +34,5 @@ export const getPrivatePractitionersBySearchKeyInteractor = async ( type: 'privatePractitioner', }); - return PrivatePractitioner.validateRawCollection(users, { - applicationContext, - }); + return PrivatePractitioner.validateRawCollection(users); }; diff --git a/web-api/src/business/useCases/user/getUserPendingEmailInteractor.test.ts b/web-api/src/business/useCases/user/getUserPendingEmailInteractor.test.ts index 8457e580bed..12ec03fb95f 100644 --- a/web-api/src/business/useCases/user/getUserPendingEmailInteractor.test.ts +++ b/web-api/src/business/useCases/user/getUserPendingEmailInteractor.test.ts @@ -1,35 +1,24 @@ import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getUserPendingEmailInteractor } from './getUserPendingEmailInteractor'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('getUserPendingEmailInteractor', () => { - let currentLoggedInUser; const PENDING_EMAIL = 'pending@example.com'; const USER_ID = 'a8024d79-1cd0-4864-bdd9-60325bd6d6b9'; - beforeEach(() => { - currentLoggedInUser = { - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.petitionsClerk, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; - - applicationContext.getCurrentUser.mockImplementation( - () => currentLoggedInUser, - ); - }); - it('should throw an error when not authorized', async () => { - currentLoggedInUser = { - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.petitioner, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; - await expect( - getUserPendingEmailInteractor(applicationContext, { - userId: USER_ID, - }), + getUserPendingEmailInteractor( + applicationContext, + { + userId: USER_ID, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -41,9 +30,13 @@ describe('getUserPendingEmailInteractor', () => { userId: USER_ID, }); - const result = await getUserPendingEmailInteractor(applicationContext, { - userId: USER_ID, - }); + const result = await getUserPendingEmailInteractor( + applicationContext, + { + userId: USER_ID, + }, + mockPetitionsClerkUser, + ); expect(result).toEqual(PENDING_EMAIL); }); @@ -55,9 +48,13 @@ describe('getUserPendingEmailInteractor', () => { userId: USER_ID, }); - const result = await getUserPendingEmailInteractor(applicationContext, { - userId: USER_ID, - }); + const result = await getUserPendingEmailInteractor( + applicationContext, + { + userId: USER_ID, + }, + mockPetitionsClerkUser, + ); expect(result).toBeUndefined(); }); @@ -67,9 +64,13 @@ describe('getUserPendingEmailInteractor', () => { .getPersistenceGateway() .getUserById.mockResolvedValue(undefined); - const result = await getUserPendingEmailInteractor(applicationContext, { - userId: USER_ID, - }); + const result = await getUserPendingEmailInteractor( + applicationContext, + { + userId: USER_ID, + }, + mockPetitionsClerkUser, + ); expect(result).toBeUndefined(); }); diff --git a/web-api/src/business/useCases/user/getUserPendingEmailInteractor.ts b/web-api/src/business/useCases/user/getUserPendingEmailInteractor.ts index 3944fe1d467..0e1d5cbbf5f 100644 --- a/web-api/src/business/useCases/user/getUserPendingEmailInteractor.ts +++ b/web-api/src/business/useCases/user/getUserPendingEmailInteractor.ts @@ -4,6 +4,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { User } from '../../../../../shared/src/business/entities/User'; /** @@ -17,9 +18,8 @@ import { User } from '../../../../../shared/src/business/entities/User'; export const getUserPendingEmailInteractor = async ( applicationContext: ServerApplicationContext, { userId }: { userId: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.GET_USER_PENDING_EMAIL)) { throw new UnauthorizedError('Unauthorized to get user pending email'); } diff --git a/web-api/src/business/useCases/user/getUserPendingEmailStatusInteractor.test.ts b/web-api/src/business/useCases/user/getUserPendingEmailStatusInteractor.test.ts index 30a408172fa..8ad0e2eb369 100644 --- a/web-api/src/business/useCases/user/getUserPendingEmailStatusInteractor.test.ts +++ b/web-api/src/business/useCases/user/getUserPendingEmailStatusInteractor.test.ts @@ -1,35 +1,27 @@ import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getUserPendingEmailStatusInteractor } from './getUserPendingEmailStatusInteractor'; +import { + mockPetitionerUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getUserPendingEmailStatusInteractor', () => { - let currentLoggedInUser; const PENDING_EMAIL = 'pending@example.com'; const USER_ID = 'a8024d79-1cd0-4864-bdd9-60325bd6d6b9'; - beforeEach(() => { - currentLoggedInUser = { - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.privatePractitioner, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; - - applicationContext.getCurrentUser.mockImplementation( - () => currentLoggedInUser, - ); - }); - it('should throw an error when not authorized', async () => { - currentLoggedInUser = { - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.inactivePractitioner, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; - await expect( - getUserPendingEmailStatusInteractor(applicationContext, { - userId: USER_ID, - }), + getUserPendingEmailStatusInteractor( + applicationContext, + { + userId: USER_ID, + }, + { + ...mockPrivatePractitionerUser, + role: ROLES.inactivePractitioner, + }, + ), ).rejects.toThrow('Unauthorized'); }); @@ -46,6 +38,7 @@ describe('getUserPendingEmailStatusInteractor', () => { { userId: USER_ID, }, + mockPetitionerUser, ); expect(result).toEqual(true); @@ -63,6 +56,7 @@ describe('getUserPendingEmailStatusInteractor', () => { { userId: USER_ID, }, + mockPetitionerUser, ); expect(result).toEqual(false); @@ -78,6 +72,7 @@ describe('getUserPendingEmailStatusInteractor', () => { { userId: USER_ID, }, + mockPetitionerUser, ); expect(result).toBeUndefined(); diff --git a/web-api/src/business/useCases/user/getUserPendingEmailStatusInteractor.ts b/web-api/src/business/useCases/user/getUserPendingEmailStatusInteractor.ts index f4713f3cdf2..4cbde5e1901 100644 --- a/web-api/src/business/useCases/user/getUserPendingEmailStatusInteractor.ts +++ b/web-api/src/business/useCases/user/getUserPendingEmailStatusInteractor.ts @@ -4,6 +4,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { User } from '../../../../../shared/src/business/entities/User'; /** @@ -17,9 +18,8 @@ import { User } from '../../../../../shared/src/business/entities/User'; export const getUserPendingEmailStatusInteractor = async ( applicationContext: ServerApplicationContext, { userId }: { userId: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if ( !isAuthorized( authorizedUser, diff --git a/web-api/src/business/useCases/user/getUsersInSectionInteractor.test.ts b/web-api/src/business/useCases/user/getUsersInSectionInteractor.test.ts index 21008ee4495..0639d2f815b 100644 --- a/web-api/src/business/useCases/user/getUsersInSectionInteractor.test.ts +++ b/web-api/src/business/useCases/user/getUsersInSectionInteractor.test.ts @@ -1,49 +1,43 @@ import { NotFoundError, UnauthorizedError } from '@web-api/errors/errors'; -import { - PETITIONS_SECTION, - ROLES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { PETITIONS_SECTION } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getUsersInSectionInteractor } from './getUsersInSectionInteractor'; +import { + mockDocketClerkUser, + mockJudgeUser, + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('Get users in section', () => { const MOCK_SECTION = [ + mockPetitionerUser, { - name: 'Test Petitioner 1', - role: ROLES.petitioner, - userId: '304a756b-ce23-438a-a9bb-3732c6a439b7', - }, - { - name: 'Test Petitioner 2', - role: ROLES.petitioner, + ...mockPetitionerUser, + name: 'Tax Payer 2', userId: 'a79d2fac-aa2c-4183-9877-01ab1cdff127', }, ]; const MOCK_JUDGE_SECTION = [ { + ...mockJudgeUser, isSeniorJudge: false, judgeFullName: 'Test Judge 1', judgeTitle: 'Judge', name: 'Test Judge 1', - role: ROLES.judge, - userId: 'ce5add74-1559-448d-a67d-c887c8351b2e', }, { + ...mockJudgeUser, isSeniorJudge: false, judgeFullName: 'Test Judge 1', judgeTitle: 'Judge', name: 'Test Judge 2', - role: ROLES.judge, userId: 'ea83cea2-5ce9-451d-b3d6-1e7c0e51d311', }, ]; it('retrieves the users in the petitions section', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: '5a797be2-a4b7-469f-9cfb-32b7f169d489', - }); applicationContext .getPersistenceGateway() .getUsersInSection.mockReturnValue(MOCK_SECTION); @@ -52,24 +46,25 @@ describe('Get users in section', () => { const section = await getUsersInSectionInteractor( applicationContext, sectionToGet, + mockPetitionsClerkUser, ); expect(section.length).toEqual(2); - expect(section[0].name).toEqual('Test Petitioner 1'); + expect(section[0].name).toEqual('Tax Payer'); }); it('returns notfounderror when section not found', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: '5a797be2-a4b7-469f-9cfb-32b7f169d489', - }); applicationContext .getPersistenceGateway() .getUsersInSection.mockReturnValue(MOCK_SECTION); let result = 'error'; try { const sectionToGet = { section: 'unknown' }; - await getUsersInSectionInteractor(applicationContext, sectionToGet); + await getUsersInSectionInteractor( + applicationContext, + sectionToGet, + mockPetitionsClerkUser, + ); } catch (e) { if (e instanceof NotFoundError) { result = 'error'; @@ -79,10 +74,6 @@ describe('Get users in section', () => { }); it('returns unauthorizederror when user not authorized', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '5a797be2-a4b7-469f-9cfb-32b7f169d489', - }); applicationContext .getPersistenceGateway() .getUsersInSection.mockReturnValue(MOCK_SECTION); @@ -90,7 +81,11 @@ describe('Get users in section', () => { let result = 'error'; try { const sectionToGet = { section: 'unknown' }; - await getUsersInSectionInteractor(applicationContext, sectionToGet); + await getUsersInSectionInteractor( + applicationContext, + sectionToGet, + mockPetitionerUser, + ); } catch (e) { if (e instanceof UnauthorizedError) { result = 'error'; @@ -100,10 +95,6 @@ describe('Get users in section', () => { }); it('retrieves the users in the judge section when the current user has the appropriate permissions', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: '5a797be2-a4b7-469f-9cfb-32b7f169d489', - }); applicationContext .getPersistenceGateway() .getUsersInSection.mockReturnValue(MOCK_JUDGE_SECTION); @@ -111,22 +102,23 @@ describe('Get users in section', () => { const section = await getUsersInSectionInteractor( applicationContext, sectionToGet, + mockDocketClerkUser, ); expect(section.length).toEqual(2); expect(section[0].name).toEqual('Test Judge 1'); }); - it('returns unauthorizederror when the desired section is judge and current user does not have appropriate permissions', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '5a797be2-a4b7-469f-9cfb-32b7f169d489', - }); + it('returns unauthorizedError when the desired section is judge and current user does not have appropriate permissions', async () => { applicationContext .getPersistenceGateway() .getUsersInSection.mockReturnValue(MOCK_JUDGE_SECTION); const sectionToGet = { section: 'judge' }; await expect( - getUsersInSectionInteractor(applicationContext, sectionToGet), + getUsersInSectionInteractor( + applicationContext, + sectionToGet, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); }); diff --git a/web-api/src/business/useCases/user/getUsersInSectionInteractor.ts b/web-api/src/business/useCases/user/getUsersInSectionInteractor.ts index 4a02f757704..bc3092a70f3 100644 --- a/web-api/src/business/useCases/user/getUsersInSectionInteractor.ts +++ b/web-api/src/business/useCases/user/getUsersInSectionInteractor.ts @@ -8,12 +8,13 @@ import { } from '../../../../../shared/src/business/entities/User'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '../../../errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; export const getUsersInSectionInteractor = async ( applicationContext: ServerApplicationContext, { section }: { section: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const user = applicationContext.getCurrentUser(); let rolePermission; if (section === 'judge') { @@ -22,7 +23,7 @@ export const getUsersInSectionInteractor = async ( rolePermission = ROLE_PERMISSIONS.GET_USERS_IN_SECTION; } - if (!isAuthorized(user, rolePermission)) { + if (!isAuthorized(authorizedUser, rolePermission)) { throw new UnauthorizedError('Unauthorized'); } @@ -33,5 +34,5 @@ export const getUsersInSectionInteractor = async ( section, }); - return User.validateRawCollection(rawUsers, { applicationContext }); + return User.validateRawCollection(rawUsers); }; diff --git a/web-api/src/business/useCases/user/getUsersPendingEmailInteractor.test.ts b/web-api/src/business/useCases/user/getUsersPendingEmailInteractor.test.ts index 1c1c6c1c8fb..521f1e3e04c 100644 --- a/web-api/src/business/useCases/user/getUsersPendingEmailInteractor.test.ts +++ b/web-api/src/business/useCases/user/getUsersPendingEmailInteractor.test.ts @@ -1,38 +1,27 @@ import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getUsersPendingEmailInteractor } from './getUsersPendingEmailInteractor'; +import { + mockAdminUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('getUsersPendingEmailInteractor', () => { - let currentLoggedInUser; const PENDING_EMAIL = 'pending@example.com'; const USER_IDS = [ 'a8024d79-1cd0-4864-bdd9-60325bd6d6b9', 'f8024d79-1cd0-4864-bdd9-60325bd6d6b1', ]; - beforeEach(() => { - currentLoggedInUser = { - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.petitionsClerk, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; - - applicationContext.getCurrentUser.mockImplementation( - () => currentLoggedInUser, - ); - }); - it('should throw an error when not authorized', async () => { - currentLoggedInUser = { - name: 'Emmett Lathrop "Doc" Brown, Ph.D.', - role: ROLES.admin, - userId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }; - await expect( - getUsersPendingEmailInteractor(applicationContext, { - userIds: USER_IDS, - }), + getUsersPendingEmailInteractor( + applicationContext, + { + userIds: USER_IDS, + }, + mockAdminUser, + ), ).rejects.toThrow('Unauthorized'); }); @@ -52,9 +41,13 @@ describe('getUsersPendingEmailInteractor', () => { }, ]); - const result = await getUsersPendingEmailInteractor(applicationContext, { - userIds: USER_IDS, - }); + const result = await getUsersPendingEmailInteractor( + applicationContext, + { + userIds: USER_IDS, + }, + mockPetitionsClerkUser, + ); expect(result).toEqual({ [USER_IDS[0]]: PENDING_EMAIL, @@ -76,9 +69,13 @@ describe('getUsersPendingEmailInteractor', () => { }, ]); - const result = await getUsersPendingEmailInteractor(applicationContext, { - userIds: USER_IDS, - }); + const result = await getUsersPendingEmailInteractor( + applicationContext, + { + userIds: USER_IDS, + }, + mockPetitionsClerkUser, + ); expect(result).toEqual({ [USER_IDS[0]]: undefined, @@ -91,9 +88,13 @@ describe('getUsersPendingEmailInteractor', () => { .getPersistenceGateway() .getUsersById.mockResolvedValue([]); - const result = await getUsersPendingEmailInteractor(applicationContext, { - userIds: USER_IDS, - }); + const result = await getUsersPendingEmailInteractor( + applicationContext, + { + userIds: USER_IDS, + }, + mockPetitionsClerkUser, + ); expect(result).toBeUndefined(); }); diff --git a/web-api/src/business/useCases/user/getUsersPendingEmailInteractor.ts b/web-api/src/business/useCases/user/getUsersPendingEmailInteractor.ts index e9a3d8dee72..09893414ddb 100644 --- a/web-api/src/business/useCases/user/getUsersPendingEmailInteractor.ts +++ b/web-api/src/business/useCases/user/getUsersPendingEmailInteractor.ts @@ -4,6 +4,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { User } from '../../../../../shared/src/business/entities/User'; /** @@ -17,9 +18,8 @@ import { User } from '../../../../../shared/src/business/entities/User'; export const getUsersPendingEmailInteractor = async ( applicationContext: ServerApplicationContext, { userIds }: { userIds: string[] }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if ( !isAuthorized( authorizedUser, diff --git a/web-api/src/business/useCases/user/queueUpdateAssociatedCasesWorker.test.ts b/web-api/src/business/useCases/user/queueUpdateAssociatedCasesWorker.test.ts index 8aa1b0cfbdb..f75182142a8 100644 --- a/web-api/src/business/useCases/user/queueUpdateAssociatedCasesWorker.test.ts +++ b/web-api/src/business/useCases/user/queueUpdateAssociatedCasesWorker.test.ts @@ -11,11 +11,19 @@ describe('queueUpdateAssociatedCasesWorker', () => { applicationContext .getPersistenceGateway() .getDocketNumbersByUser.mockReturnValue(['111-20', '222-20', '333-20']); - applicationContext.getCurrentUser.mockReturnValue(MOCK_PRACTITIONER); - await queueUpdateAssociatedCasesWorker(applicationContext, { - user: MOCK_PRACTITIONER, - }); + await queueUpdateAssociatedCasesWorker( + applicationContext, + { + user: MOCK_PRACTITIONER, + }, + { + email: MOCK_PRACTITIONER.email!, + name: MOCK_PRACTITIONER.name, + role: MOCK_PRACTITIONER.role, + userId: MOCK_PRACTITIONER.userId, + }, + ); expect( await applicationContext.getPersistenceGateway().getDocketNumbersByUser, @@ -29,38 +37,47 @@ describe('queueUpdateAssociatedCasesWorker', () => { applicationContext .getPersistenceGateway() .getDocketNumbersByUser.mockReturnValue(['111-20', '222-20', '333-20']); - applicationContext.getCurrentUser.mockReturnValue(MOCK_PRACTITIONER); applicationContext.getWorkerGateway().queueWork.mockReturnValue({}); + const authorizedUser = { + email: MOCK_PRACTITIONER.email!, + name: MOCK_PRACTITIONER.name, + role: MOCK_PRACTITIONER.role, + userId: MOCK_PRACTITIONER.userId, + }; - await queueUpdateAssociatedCasesWorker(applicationContext, { - user: MOCK_PRACTITIONER, - }); + await queueUpdateAssociatedCasesWorker( + applicationContext, + { + user: MOCK_PRACTITIONER, + }, + authorizedUser, + ); expect( applicationContext.getWorkerGateway().queueWork, ).toHaveBeenCalledWith(applicationContext, { message: { + authorizedUser, payload: { docketNumber: '111-20', user: MOCK_PRACTITIONER }, type: MESSAGE_TYPES.UPDATE_ASSOCIATED_CASE, - user: MOCK_PRACTITIONER, }, }); expect( applicationContext.getWorkerGateway().queueWork, ).toHaveBeenCalledWith(applicationContext, { message: { + authorizedUser, payload: { docketNumber: '222-20', user: MOCK_PRACTITIONER }, type: MESSAGE_TYPES.UPDATE_ASSOCIATED_CASE, - user: MOCK_PRACTITIONER, }, }); expect( applicationContext.getWorkerGateway().queueWork, ).toHaveBeenCalledWith(applicationContext, { message: { + authorizedUser, payload: { docketNumber: '333-20', user: MOCK_PRACTITIONER }, type: MESSAGE_TYPES.UPDATE_ASSOCIATED_CASE, - user: MOCK_PRACTITIONER, }, }); }); @@ -69,38 +86,47 @@ describe('queueUpdateAssociatedCasesWorker', () => { applicationContext .getPersistenceGateway() .getDocketNumbersByUser.mockReturnValue(['111-20', '222-20', '333-20']); - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); applicationContext.getWorkerGateway().queueWork.mockReturnValue({}); + const authorizedUser = { + email: petitionerUser.email, + name: petitionerUser.name, + role: petitionerUser.role, + userId: petitionerUser.userId, + }; - await queueUpdateAssociatedCasesWorker(applicationContext, { - user: petitionerUser, - }); + await queueUpdateAssociatedCasesWorker( + applicationContext, + { + user: petitionerUser, + }, + authorizedUser, + ); expect( applicationContext.getWorkerGateway().queueWork, ).toHaveBeenCalledWith(applicationContext, { message: { + authorizedUser, payload: { docketNumber: '111-20', user: petitionerUser }, type: MESSAGE_TYPES.UPDATE_ASSOCIATED_CASE, - user: petitionerUser, }, }); expect( applicationContext.getWorkerGateway().queueWork, ).toHaveBeenCalledWith(applicationContext, { message: { + authorizedUser, payload: { docketNumber: '222-20', user: petitionerUser }, type: MESSAGE_TYPES.UPDATE_ASSOCIATED_CASE, - user: petitionerUser, }, }); expect( applicationContext.getWorkerGateway().queueWork, ).toHaveBeenCalledWith(applicationContext, { message: { + authorizedUser, payload: { docketNumber: '333-20', user: petitionerUser }, type: MESSAGE_TYPES.UPDATE_ASSOCIATED_CASE, - user: petitionerUser, }, }); }); diff --git a/web-api/src/business/useCases/user/queueUpdateAssociatedCasesWorker.ts b/web-api/src/business/useCases/user/queueUpdateAssociatedCasesWorker.ts index ad71f821e1d..99031861223 100644 --- a/web-api/src/business/useCases/user/queueUpdateAssociatedCasesWorker.ts +++ b/web-api/src/business/useCases/user/queueUpdateAssociatedCasesWorker.ts @@ -1,3 +1,4 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { MESSAGE_TYPES } from '@web-api/gateways/worker/workerRouter'; import { RawPractitioner } from '../../../../../shared/src/business/entities/Practitioner'; import { RawUser } from '../../../../../shared/src/business/entities/User'; @@ -6,6 +7,7 @@ import { ServerApplicationContext } from '@web-api/applicationContext'; export const queueUpdateAssociatedCasesWorker = async ( applicationContext: ServerApplicationContext, { user }: { user: RawUser | RawPractitioner }, + authorizedUser: AuthUser, ): Promise => { const docketNumbersAssociatedWithUser = await applicationContext .getPersistenceGateway() @@ -18,9 +20,9 @@ export const queueUpdateAssociatedCasesWorker = async ( docketNumbersAssociatedWithUser.map(docketNumber => applicationContext.getWorkerGateway().queueWork(applicationContext, { message: { + authorizedUser, payload: { docketNumber, user }, type: MESSAGE_TYPES.UPDATE_ASSOCIATED_CASE, - user: applicationContext.getCurrentUser(), }, }), ), diff --git a/web-api/src/business/useCases/user/updateAssociatedCaseWorker.test.ts b/web-api/src/business/useCases/user/updateAssociatedCaseWorker.test.ts index 0f52899f612..3e3c34a441a 100644 --- a/web-api/src/business/useCases/user/updateAssociatedCaseWorker.test.ts +++ b/web-api/src/business/useCases/user/updateAssociatedCaseWorker.test.ts @@ -17,6 +17,10 @@ import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '@shared/business/test/createTestApplicationContext'; import { calculateISODate } from '@shared/business/utilities/DateHandler'; import { getContactPrimary } from '@shared/business/entities/cases/Case'; +import { + mockPetitionerUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; import { updateAssociatedCaseWorker, updatePetitionerCase, @@ -72,10 +76,14 @@ describe('updateAssociatedCaseWorker', () => { privatePractitioners: [], }); - await updateAssociatedCaseWorker(applicationContext, { - docketNumber: '101-18', - user: mockPractitioner, - }); + await updateAssociatedCaseWorker( + applicationContext, + { + docketNumber: '101-18', + user: mockPractitioner, + }, + mockPrivatePractitionerUser, + ); expect(applicationContext.logger.error.mock.calls[0][0]).toEqual( 'Could not find user|3ab77c88-1dd0-4adb-a03c-c466ad72d417 barNumber: RA3333 on 101-18', @@ -91,13 +99,17 @@ describe('updateAssociatedCaseWorker', () => { userId: 'cde00f40-56e8-46c2-94c3-b1155b89a203', }); - await updateAssociatedCaseWorker(applicationContext, { - docketNumber: '101-18', - user: { - ...mockPetitioner, - userId: 'cde00f40-56e8-46c2-94c3-b1155b89a203', + await updateAssociatedCaseWorker( + applicationContext, + { + docketNumber: '101-18', + user: { + ...mockPetitioner, + userId: 'cde00f40-56e8-46c2-94c3-b1155b89a203', + }, }, - }); + mockPetitionerUser, + ); expect(applicationContext.logger.error.mock.calls[0][0]).toEqual( 'Could not find user|cde00f40-56e8-46c2-94c3-b1155b89a203 on 101-18', @@ -113,10 +125,14 @@ describe('updateAssociatedCaseWorker', () => { .getPersistenceGateway() .getLock.mockImplementation(() => MOCK_LOCK); await expect( - updateAssociatedCaseWorker(applicationContext, { - docketNumber: '123-45', - user: MOCK_PRACTITIONER, - }), + updateAssociatedCaseWorker( + applicationContext, + { + docketNumber: '123-45', + user: MOCK_PRACTITIONER, + }, + mockPrivatePractitionerUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -128,10 +144,14 @@ describe('updateAssociatedCaseWorker', () => { applicationContext .getPersistenceGateway() .getLock.mockImplementation(() => undefined); - await updateAssociatedCaseWorker(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - user: MOCK_PRACTITIONER, - }); + await updateAssociatedCaseWorker( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + user: MOCK_PRACTITIONER, + }, + mockPrivatePractitionerUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -143,10 +163,14 @@ describe('updateAssociatedCaseWorker', () => { }); it('should remove the lock', async () => { - await updateAssociatedCaseWorker(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - user: MOCK_PRACTITIONER, - }); + await updateAssociatedCaseWorker( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + user: MOCK_PRACTITIONER, + }, + mockPrivatePractitionerUser, + ); expect( applicationContext.getPersistenceGateway().removeLock, @@ -185,10 +209,14 @@ describe('updateAssociatedCaseWorker', () => { ...mockCase, privatePractitioners: [], }); - await updateAssociatedCaseWorker(applicationContext, { - docketNumber: mockCase.docketNumber, - user: mockPetitioner, - }); + await updateAssociatedCaseWorker( + applicationContext, + { + docketNumber: mockCase.docketNumber, + user: mockPetitioner, + }, + mockPetitionerUser, + ); const { servedParties } = applicationContext.getUseCaseHelpers().generateAndServeDocketEntry.mock .calls[0][0]; @@ -198,10 +226,14 @@ describe('updateAssociatedCaseWorker', () => { }); it("should update the user's case with the new email", async () => { - await updateAssociatedCaseWorker(applicationContext, { - docketNumber: mockCase.docketNumber, - user: mockPractitioner, - }); + await updateAssociatedCaseWorker( + applicationContext, + { + docketNumber: mockCase.docketNumber, + user: mockPractitioner, + }, + mockPrivatePractitionerUser, + ); expect( applicationContext.getUseCaseHelpers().updateCaseAndAssociations, @@ -223,10 +255,14 @@ describe('updateAssociatedCaseWorker', () => { ); await expect( - updateAssociatedCaseWorker(applicationContext, { - docketNumber: mockCase.docketNumber, - user: mockPractitioner, - }), + updateAssociatedCaseWorker( + applicationContext, + { + docketNumber: mockCase.docketNumber, + user: mockPractitioner, + }, + mockPrivatePractitionerUser, + ), ).rejects.toThrow('updateCaseAndAssociations failure'); expect( @@ -257,10 +293,14 @@ describe('updateAssociatedCaseWorker', () => { .getCaseByDocketNumber.mockReturnValue(mockCase); await expect( - updateAssociatedCaseWorker(applicationContext, { - docketNumber: mockCase.docketNumber, - user: mockPetitioner, - }), + updateAssociatedCaseWorker( + applicationContext, + { + docketNumber: mockCase.docketNumber, + user: mockPetitioner, + }, + mockPetitionerUser, + ), ).resolves.toBeUndefined(); // has no return value expect( @@ -282,10 +322,14 @@ describe('updateAssociatedCaseWorker', () => { }); await expect( - updateAssociatedCaseWorker(applicationContext, { - docketNumber: mockCase.docketNumber, - user: mockPetitioner, - }), + updateAssociatedCaseWorker( + applicationContext, + { + docketNumber: mockCase.docketNumber, + user: mockPetitioner, + }, + mockPetitionerUser, + ), ).resolves.toBeUndefined(); // has no return value expect( @@ -308,10 +352,14 @@ describe('updateAssociatedCaseWorker', () => { }); await expect( - updateAssociatedCaseWorker(applicationContext, { - docketNumber: mockCase.docketNumber, - user: mockPetitioner, - }), + updateAssociatedCaseWorker( + applicationContext, + { + docketNumber: mockCase.docketNumber, + user: mockPetitioner, + }, + mockPetitionerUser, + ), ).resolves.toBeUndefined(); // has no return value expect( @@ -322,7 +370,7 @@ describe('updateAssociatedCaseWorker', () => { }); describe('updatePetitionerCases', () => { const UPDATED_EMAIL = 'hello@example.com'; - const mockPetitionerUser = { + const mockPetitionerUser2 = { ...validUser, email: UPDATED_EMAIL, role: ROLES.petitioner, @@ -342,8 +390,9 @@ describe('updatePetitionerCases', () => { await updatePetitionerCase({ applicationContext, + authorizedUser: mockPetitionerUser2, docketNumber: MOCK_CASE.docketNumber, - user: mockPetitionerUser, + user: mockPetitionerUser2, }); expect( @@ -376,14 +425,15 @@ describe('updatePetitionerCases', () => { await expect( updatePetitionerCase({ applicationContext, + authorizedUser: mockPetitionerUser2, docketNumber: '101-21', - user: mockPetitionerUser, + user: mockPetitionerUser2, }), ).resolves.not.toThrow(); expect(applicationContext.logger.error).toHaveBeenCalledTimes(1); expect(applicationContext.logger.error).toHaveBeenCalledWith( - `Could not find user|${mockPetitionerUser.userId} on ${caseMock.docketNumber}`, + `Could not find user|${mockPetitionerUser2.userId} on ${caseMock.docketNumber}`, ); expect( applicationContext.getUseCaseHelpers().updateCaseAndAssociations, @@ -402,8 +452,9 @@ describe('updatePetitionerCases', () => { await expect( updatePetitionerCase({ applicationContext, + authorizedUser: mockPetitionerUser2, docketNumber: MOCK_CASE.docketNumber, - user: mockPetitionerUser, + user: mockPetitionerUser2, }), ).rejects.toThrow('entity was invalid'); @@ -425,7 +476,7 @@ describe('updatePetitionerCases', () => { }, { ...MOCK_CASE.petitioners[0], - contactId: mockPetitionerUser.userId, + contactId: mockPetitionerUser2.userId, contactType: CONTACT_TYPES.secondary, inCareOf: 'Barney', }, @@ -434,8 +485,9 @@ describe('updatePetitionerCases', () => { await updatePetitionerCase({ applicationContext, + authorizedUser: mockPetitionerUser2, docketNumber: MOCK_CASE.docketNumber, - user: mockPetitionerUser, + user: mockPetitionerUser2, }); const { caseToUpdate } = @@ -458,7 +510,7 @@ describe('updatePetitionerCases', () => { }, { ...MOCK_CASE.petitioners[0], - contactId: mockPetitionerUser.userId, + contactId: mockPetitionerUser2.userId, contactType: CONTACT_TYPES.secondary, inCareOf: 'Barney', serviceIndicator: SERVICE_INDICATOR_TYPES.SI_NONE, @@ -474,8 +526,9 @@ describe('updatePetitionerCases', () => { await updatePetitionerCase({ applicationContext, + authorizedUser: mockPetitionerUser2, docketNumber: MOCK_CASE.docketNumber, - user: mockPetitionerUser, + user: mockPetitionerUser2, }); const { caseToUpdate } = @@ -498,7 +551,7 @@ describe('updatePetitionerCases', () => { ...MOCK_CASE.petitioners, { ...MOCK_CASE.petitioners[0], - contactId: mockPetitionerUser.userId, + contactId: mockPetitionerUser2.userId, contactType: CONTACT_TYPES.secondary, inCareOf: 'Barney', serviceIndicator: SERVICE_INDICATOR_TYPES.SI_NONE, @@ -507,15 +560,16 @@ describe('updatePetitionerCases', () => { privatePractitioners: [ { ...MOCK_ELIGIBLE_CASE_WITH_PRACTITIONERS.privatePractitioners[0], - representing: [mockPetitionerUser.userId], + representing: [mockPetitionerUser2.userId], }, ], }); await updatePetitionerCase({ applicationContext, + authorizedUser: mockPetitionerUser2, docketNumber: MOCK_CASE.docketNumber, - user: mockPetitionerUser, + user: mockPetitionerUser2, }); const { caseToUpdate } = @@ -553,6 +607,7 @@ describe('updatePractitionerCases', () => { it('should set the service serviceIndicator to ELECTRONIC when confirming the email', async () => { await updatePractitionerCase({ applicationContext, + authorizedUser: mockPractitionerUser, docketNumber: MOCK_CASE.docketNumber, user: mockPractitionerUser, }); diff --git a/web-api/src/business/useCases/user/updateAssociatedCaseWorker.ts b/web-api/src/business/useCases/user/updateAssociatedCaseWorker.ts index f0c9f378041..461b0ea7941 100644 --- a/web-api/src/business/useCases/user/updateAssociatedCaseWorker.ts +++ b/web-api/src/business/useCases/user/updateAssociatedCaseWorker.ts @@ -1,3 +1,4 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { Case } from '@shared/business/entities/cases/Case'; import { ROLES, @@ -10,9 +11,11 @@ import { aggregatePartiesForService } from '@shared/business/utilities/aggregate export const updateAssociatedCaseWorker = async ( applicationContext: ServerApplicationContext, { docketNumber, user }: { docketNumber: string; user: RawUser }, + authorizedUser: AuthUser, ): Promise => { await applicationContext.getUseCaseHelpers().acquireLock({ applicationContext, + authorizedUser, identifiers: [`case|${docketNumber}`], retries: 10, ttl: 900, @@ -22,6 +25,7 @@ export const updateAssociatedCaseWorker = async ( if (user.role === ROLES.petitioner) { await updatePetitionerCase({ applicationContext, + authorizedUser, docketNumber, user, }); @@ -33,6 +37,7 @@ export const updateAssociatedCaseWorker = async ( ) { await updatePractitionerCase({ applicationContext, + authorizedUser, docketNumber, user, }); @@ -46,12 +51,14 @@ export const updateAssociatedCaseWorker = async ( export const updatePetitionerCase = async ({ applicationContext, + authorizedUser, docketNumber, user, }: { applicationContext: ServerApplicationContext; docketNumber: string; user: RawUser; + authorizedUser: AuthUser; }): Promise => { const rawCaseToUpdate = await applicationContext .getPersistenceGateway() @@ -62,6 +69,7 @@ export const updatePetitionerCase = async ({ const caseToUpdate = await updateCaseEntityAndGenerateChange({ applicationContext, + authorizedUser, rawCaseData: rawCaseToUpdate, user, }); @@ -70,18 +78,21 @@ export const updatePetitionerCase = async ({ await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate, }); }; export const updatePractitionerCase = async ({ applicationContext, + authorizedUser, docketNumber, user, }: { applicationContext: ServerApplicationContext; docketNumber: string; user: any; + authorizedUser: AuthUser; }): Promise => { const caseToUpdate = await applicationContext .getPersistenceGateway() @@ -90,7 +101,9 @@ export const updatePractitionerCase = async ({ docketNumber, }); - const caseEntity = new Case(caseToUpdate, { applicationContext }); + const caseEntity = new Case(caseToUpdate, { + authorizedUser, + }); const practitionerObject = [ ...caseEntity.privatePractitioners, ...caseEntity.irsPractitioners, @@ -109,26 +122,29 @@ export const updatePractitionerCase = async ({ // we do this again so that it will convert '' to null const validatedCaseToUpdate = new Case(caseEntity, { - applicationContext, + authorizedUser, }).validate(); await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: validatedCaseToUpdate, }); }; const updateCaseEntityAndGenerateChange = async ({ applicationContext, + authorizedUser, rawCaseData, user, }: { applicationContext: ServerApplicationContext; rawCaseData: RawCase; user: RawUser; + authorizedUser: AuthUser; }): Promise => { const caseEntity = new Case(rawCaseData, { - applicationContext, + authorizedUser, }); const petitionerObject = caseEntity.getPetitionerById(user.userId); @@ -173,6 +189,7 @@ const updateCaseEntityAndGenerateChange = async ({ .getUseCaseHelpers() .generateAndServeDocketEntry({ applicationContext, + authorizedUser, caseEntity, documentType, newData, diff --git a/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.createWorkItemForChange.test.ts b/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.createWorkItemForChange.test.ts index 0c1ebb4727e..1e8c9eecde9 100644 --- a/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.createWorkItemForChange.test.ts +++ b/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.createWorkItemForChange.test.ts @@ -5,19 +5,15 @@ import { SERVICE_INDICATOR_TYPES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; -import { - MOCK_PRACTITIONER, - docketClerkUser, -} from '../../../../../shared/src/test/mockUsers'; -import { User } from '../../../../../shared/src/business/entities/User'; +import { MOCK_PRACTITIONER } from '../../../../../shared/src/test/mockUsers'; import { UserCase } from '../../../../../shared/src/business/entities/UserCase'; import { addCoverToPdf } from '@web-api/business/useCases/addCoverToPdf'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { updatePetitionerInformationInteractor } from './updatePetitionerInformationInteractor'; jest.mock('@web-api/business/useCases/addCoverToPdf'); describe('updatePetitionerInformationInteractor createWorkItemForChange', () => { - let mockUser; let mockCase; const PRIMARY_CONTACT_ID = MOCK_CASE.petitioners[0].contactId; @@ -43,10 +39,6 @@ describe('updatePetitionerInformationInteractor createWorkItemForChange', () => beforeAll(() => { (addCoverToPdf as jest.Mock).mockResolvedValue({}); - applicationContext.getCurrentUser.mockImplementation( - () => new User(mockUser), - ); - applicationContext .getUseCaseHelpers() .addExistingUserToCase.mockImplementation(({ caseEntity }) => caseEntity); @@ -57,8 +49,6 @@ describe('updatePetitionerInformationInteractor createWorkItemForChange', () => }); beforeEach(() => { - mockUser = docketClerkUser; - mockCase = { ...MOCK_CASE, petitioners: mockPetitioners, @@ -93,6 +83,7 @@ describe('updatePetitionerInformationInteractor createWorkItemForChange', () => address1: 'A Changed Street', }, }, + mockDocketClerkUser, ); const noticeOfChangeDocketEntryWithWorkItem = @@ -126,6 +117,7 @@ describe('updatePetitionerInformationInteractor createWorkItemForChange', () => address1: 'A Changed Street', }, }, + mockDocketClerkUser, ); const noticeOfChangeDocketEntryWithWorkItem = @@ -159,6 +151,7 @@ describe('updatePetitionerInformationInteractor createWorkItemForChange', () => serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }, }, + mockDocketClerkUser, ); const noticeOfChangeDocketEntryWithWorkItem = @@ -194,6 +187,7 @@ describe('updatePetitionerInformationInteractor createWorkItemForChange', () => address1: 'A Changed Street', }, }, + mockDocketClerkUser, ); const noticeOfChangeDocketEntryWithWorkItem = diff --git a/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.getIsUserAuthorized.test.ts b/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.getIsUserAuthorized.test.ts index ef1c140baee..8969692afe4 100644 --- a/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.getIsUserAuthorized.test.ts +++ b/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.getIsUserAuthorized.test.ts @@ -1,17 +1,16 @@ import { CASE_STATUS_TYPES, CONTACT_TYPES, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; -import { - MOCK_PRACTITIONER, - docketClerkUser, -} from '../../../../../shared/src/test/mockUsers'; +import { MOCK_PRACTITIONER } from '../../../../../shared/src/test/mockUsers'; import { getIsUserAuthorized } from './updatePetitionerInformationInteractor'; +import { + mockPetitionerUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; describe('updatePetitionerInformationInteractor getIsUserAuthorized', () => { - let mockUser; let mockCase; const SECONDARY_CONTACT_ID = '56387318-0092-49a3-8cc1-921b0432bd16'; @@ -35,8 +34,6 @@ describe('updatePetitionerInformationInteractor getIsUserAuthorized', () => { }; beforeEach(() => { - mockUser = docketClerkUser; - mockCase = { ...MOCK_CASE, petitioners: mockPetitioners, @@ -51,8 +48,7 @@ describe('updatePetitionerInformationInteractor getIsUserAuthorized', () => { oldCase: mockCase, updatedPetitionerData: {}, user: { - ...mockUser, - role: ROLES.privatePractitioner, + ...mockPrivatePractitionerUser, userId: 'a003e912-7b2f-4d2f-bf00-b99ec0d29de1', }, }); @@ -65,8 +61,7 @@ describe('updatePetitionerInformationInteractor getIsUserAuthorized', () => { oldCase: mockCase, updatedPetitionerData: {}, user: { - ...mockUser, - role: ROLES.petitioner, + ...mockPetitionerUser, userId: 'a003e912-7b2f-4d2f-bf00-b99ec0d29de1', }, }); @@ -79,8 +74,7 @@ describe('updatePetitionerInformationInteractor getIsUserAuthorized', () => { oldCase: mockCase, updatedPetitionerData: { contactId: SECONDARY_CONTACT_ID }, user: { - ...mockUser, - role: ROLES.petitioner, + ...mockPetitionerUser, userId: SECONDARY_CONTACT_ID, }, }); @@ -103,8 +97,7 @@ describe('updatePetitionerInformationInteractor getIsUserAuthorized', () => { }, updatedPetitionerData: { contactId: SECONDARY_CONTACT_ID }, user: { - ...mockUser, - role: ROLES.privatePractitioner, + ...mockPrivatePractitionerUser, userId: SECONDARY_CONTACT_ID, }, }); diff --git a/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.test.ts b/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.test.ts index 76416e9a857..e49be24a635 100644 --- a/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.test.ts +++ b/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.test.ts @@ -20,18 +20,21 @@ import { } from '../../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; import { ServiceUnavailableError } from '@web-api/errors/errors'; -import { User } from '../../../../../shared/src/business/entities/User'; import { UserCase } from '../../../../../shared/src/business/entities/UserCase'; import { addCoverToPdf } from '@web-api/business/useCases/addCoverToPdf'; import { addExistingUserToCase } from '../../useCaseHelper/caseAssociation/addExistingUserToCase'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { calculateISODate } from '../../../../../shared/src/business/utilities/DateHandler'; -import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; +import { + mockAdmissionsClerkUser, + mockDocketClerkUser, + mockPetitionerUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; import { updatePetitionerInformationInteractor } from './updatePetitionerInformationInteractor'; jest.mock('@web-api/business/useCases/addCoverToPdf'); describe('updatePetitionerInformationInteractor', () => { - let mockUser; let mockCase; const PRIMARY_CONTACT_ID = MOCK_CASE.petitioners[0].contactId; @@ -53,10 +56,6 @@ describe('updatePetitionerInformationInteractor', () => { beforeAll(() => { (addCoverToPdf as jest.Mock).mockResolvedValue({}); - applicationContext.getCurrentUser.mockImplementation( - () => new User(mockUser), - ); - applicationContext .getUseCaseHelpers() .addExistingUserToCase.mockReturnValue(PRIMARY_CONTACT_ID); @@ -71,7 +70,6 @@ describe('updatePetitionerInformationInteractor', () => { beforeEach(() => { mockLock = undefined; - mockUser = docketClerkUser; mockCase = { ...MOCK_CASE, @@ -85,20 +83,35 @@ describe('updatePetitionerInformationInteractor', () => { .getCaseByDocketNumber.mockImplementation(() => mockCase); }); - it('should throw an error when the user making the request does not have permission to edit petition details', async () => { - mockUser = { ...mockUser, role: ROLES.petitioner }; + it('should throw an error when an undefined user attempts to update petitioner information', async () => { + await expect( + updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: {}, + }, + undefined, + ), + ).rejects.toThrow( + 'User attempting to update petitioner information is not an auth user', + ); + }); + it('should throw an error when the user making the request does not have permission to edit petition details', async () => { await expect( - updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: {}, - }), + updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: {}, + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized for editing petition details'); }); it('should throw an error when the user making the request is a private practitioner not associated with the case', async () => { - mockUser = { ...mockUser, role: ROLES.privatePractitioner }; - applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValueOnce({ @@ -107,24 +120,18 @@ describe('updatePetitionerInformationInteractor', () => { }); await expect( - updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: {}, - }), + updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: {}, + }, + mockPrivatePractitionerUser, + ), ).rejects.toThrow('Unauthorized for editing petition details'); }); it('should not throw an error when the user making the request is a private practitioner who is associated with the case', async () => { - const mockRepresentingId = '1a061240-1320-47c5-9f54-0ff975045d84'; - applicationContext.getCurrentUser.mockImplementationOnce( - () => - new User({ - ...mockUser, - role: ROLES.privatePractitioner, - userId: mockRepresentingId, - }), - ); - applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValueOnce({ @@ -135,19 +142,23 @@ describe('updatePetitionerInformationInteractor', () => { name: 'Example Practitioner', representing: [PRIMARY_CONTACT_ID], role: ROLES.privatePractitioner, - userId: mockRepresentingId, + userId: mockPrivatePractitionerUser.userId, }, ], }); await expect( - updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], - countryType: COUNTRY_TYPES.DOMESTIC, + updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + countryType: COUNTRY_TYPES.DOMESTIC, + }, }, - }), + mockPrivatePractitionerUser, + ), ).resolves.toBeDefined(); }); @@ -155,13 +166,17 @@ describe('updatePetitionerInformationInteractor', () => { const mockNotFoundContactId = 'cd37d820-cbde-4591-8b5a-dc74da12f2a2'; // this contactId is not on the case await expect( - updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - contactId: mockNotFoundContactId, - countryType: COUNTRY_TYPES.DOMESTIC, + updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + contactId: mockNotFoundContactId, + countryType: COUNTRY_TYPES.DOMESTIC, + }, }, - }), + mockDocketClerkUser, + ), ).rejects.toThrow( `Case contact with id ${mockNotFoundContactId} was not found on the case`, ); @@ -174,13 +189,17 @@ describe('updatePetitionerInformationInteractor', () => { }; await expect( - updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - contactId: PRIMARY_CONTACT_ID, - countryType: COUNTRY_TYPES.DOMESTIC, + updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + contactId: PRIMARY_CONTACT_ID, + countryType: COUNTRY_TYPES.DOMESTIC, + }, }, - }), + mockDocketClerkUser, + ), ).rejects.toThrow( `Case with docketNumber ${mockCase.docketNumber} has not been served`, ); @@ -188,13 +207,17 @@ describe('updatePetitionerInformationInteractor', () => { it('should throw an error when the contact to update is not valid', async () => { await expect( - updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - contactId: PRIMARY_CONTACT_ID, - countryType: COUNTRY_TYPES.DOMESTIC, + updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + contactId: PRIMARY_CONTACT_ID, + countryType: COUNTRY_TYPES.DOMESTIC, + }, }, - }), + mockDocketClerkUser, + ), ).rejects.toThrow('Case entity was invalid'); expect( @@ -211,14 +234,18 @@ describe('updatePetitionerInformationInteractor', () => { .getUseCaseHelpers() .countPagesInDocument.mockReturnValue(mockNumberOfPages); - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], - address1: 'changed address', - contactId: mockPetitioners[0].contactId, + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + address1: 'changed address', + contactId: mockPetitioners[0].contactId, + }, }, - }); + mockDocketClerkUser, + ); const autoGeneratedDocument = applicationContext .getPersistenceGateway() @@ -245,21 +272,25 @@ describe('updatePetitionerInformationInteractor', () => { }); it('should update contact information even when the update is changing a value to null', async () => { - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - address1: '989 Division St', - city: 'Somewhere', - contactId: mockPetitioners[0].contactId, - countryType: COUNTRY_TYPES.DOMESTIC, - name: 'Test Primary Petitioner', - phone: '1234568', - postalCode: '12345', - serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, - state: 'TN', - title: 'Executor', + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + address1: '989 Division St', + city: 'Somewhere', + contactId: mockPetitioners[0].contactId, + countryType: COUNTRY_TYPES.DOMESTIC, + name: 'Test Primary Petitioner', + phone: '1234568', + postalCode: '12345', + serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, + state: 'TN', + title: 'Executor', + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -277,6 +308,7 @@ describe('updatePetitionerInformationInteractor', () => { address1: 'A Changed Street', }, }, + mockDocketClerkUser, ); const noticeOfChangeDocketEntryWithWorkItem = @@ -296,6 +328,7 @@ describe('updatePetitionerInformationInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }, }, + mockDocketClerkUser, ); expect( @@ -320,6 +353,7 @@ describe('updatePetitionerInformationInteractor', () => { serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, }, }, + mockDocketClerkUser, ); expect( @@ -335,13 +369,17 @@ describe('updatePetitionerInformationInteractor', () => { }); it('should not update petitioner email even when it is provided', async () => { - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], - email: 'test2@example.com', + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + email: 'test2@example.com', + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -353,12 +391,16 @@ describe('updatePetitionerInformationInteractor', () => { mockPetitioners[0].paperPetitionEmail = 'paperPetitionEmail@example.com'; mockPetitioners[0].hasConsentedToEService = true; - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -372,13 +414,17 @@ describe('updatePetitionerInformationInteractor', () => { it('should update petitioner additionalName when it is passed in', async () => { const mockAdditionalName = 'Tina Belcher'; - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], - additionalName: mockAdditionalName, + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + additionalName: mockAdditionalName, + }, }, - }); + mockDocketClerkUser, + ); const updatedPetitioners = applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -394,13 +440,17 @@ describe('updatePetitionerInformationInteractor', () => { }; const otherFilerToUpdate = getOtherFilers(mockCase)[0]; - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE_WITH_SECONDARY_OTHERS.docketNumber, - updatedPetitionerData: { - ...otherFilerToUpdate, - contactType: CONTACT_TYPES.otherPetitioner, + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE_WITH_SECONDARY_OTHERS.docketNumber, + updatedPetitionerData: { + ...otherFilerToUpdate, + contactType: CONTACT_TYPES.otherPetitioner, + }, }, - }); + mockDocketClerkUser, + ); const updatedPetitioners = applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] @@ -414,14 +464,18 @@ describe('updatePetitionerInformationInteractor', () => { it('should throw an error when attempting to update countryType to an invalid value', async () => { await expect( - updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], - countryType: 'alien', - serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, + updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + countryType: 'alien', + serviceIndicator: SERVICE_INDICATOR_TYPES.SI_PAPER, + }, }, - }), + mockDocketClerkUser, + ), ).rejects.toThrow('The Case entity was invalid'); expect( @@ -441,14 +495,18 @@ describe('updatePetitionerInformationInteractor', () => { ], }; - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockCase.petitioners[0], - address1: '456 Center St TEST', - isAddressSealed: true, + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockCase.petitioners[0], + address1: '456 Center St TEST', + isAddressSealed: true, + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveDocumentFromLambda, @@ -456,15 +514,19 @@ describe('updatePetitionerInformationInteractor', () => { }); it('should use original case caption to create case title when creating work item', async () => { - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], - address1: 'changed address', - contactId: mockPetitioners[0].contactId, - name: 'Test Person22222', + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + address1: 'changed address', + contactId: mockPetitioners[0].contactId, + name: 'Test Person22222', + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveWorkItem.mock.calls[0][0] @@ -482,13 +544,17 @@ describe('updatePetitionerInformationInteractor', () => { closedDate: '2018-01-01T05:00:00.000Z', status: 'Closed', })); - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], - address1: 'changed address', + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + address1: 'changed address', + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().generateAndServeDocketEntry, @@ -515,15 +581,19 @@ describe('updatePetitionerInformationInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockImplementation(() => mockCase); - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], - address1: 'changed address', - contactId: mockPetitioners[0].contactId, - name: 'Test Person22222', + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + address1: 'changed address', + contactId: mockPetitioners[0].contactId, + name: 'Test Person22222', + }, }, - }); + mockDocketClerkUser, + ); expect(updatePetitionerSpy).toHaveBeenCalled(); expect( @@ -541,14 +611,18 @@ describe('updatePetitionerInformationInteractor', () => { .getPersistenceGateway() .getUserById.mockReturnValue(unverifiedNewPetitioner); - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], - email: undefined, - updatedEmail: 'testing@example.com', + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + email: undefined, + updatedEmail: 'testing@example.com', + }, }, - }); + mockDocketClerkUser, + ); expect( applicationContext.getUseCaseHelpers().generateAndServeDocketEntry, @@ -575,15 +649,19 @@ describe('updatePetitionerInformationInteractor', () => { .getPersistenceGateway() .getCaseByDocketNumber.mockImplementation(() => mockCase); - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], - address1: 'changed address', - contactId: mockPetitioners[0].contactId, - name: 'Test Person22222', + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + address1: 'changed address', + contactId: mockPetitioners[0].contactId, + name: 'Test Person22222', + }, }, - }); + mockDocketClerkUser, + ); expect(updatePetitionerSpy).toHaveBeenCalled(); expect( @@ -599,19 +677,6 @@ describe('updatePetitionerInformationInteractor', () => { userId: applicationContext.getUniqueId(), }; beforeAll(() => { - const admissionsClerkUser = { - email: 'admissionsclerk@example.com', - entityName: 'User', - name: 'Test Admissions Clerk', - role: 'admissionsclerk', - section: 'admissions', - userId: '9d7d63b7-d7a5-4905-ba89-ef71bf30057f', - }; - - applicationContext.getCurrentUser.mockImplementation( - () => new User(admissionsClerkUser), - ); - applicationContext .getUserGateway() .getUserByEmail.mockReturnValue('someMockId'); @@ -647,17 +712,21 @@ describe('updatePetitionerInformationInteractor', () => { receivedAt: '2018-03-01T05:00:00.000Z', userId: '7805d1ab-18d0-43ec-bafb-654e83405416', }, - { applicationContext }, + { authorizedUser: undefined }, ), }); - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], - updatedEmail: mockUpdatedEmail, + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + updatedEmail: mockUpdatedEmail, + }, }, - }); + mockAdmissionsClerkUser, + ); expect( applicationContext.getUseCaseHelpers().addExistingUserToCase, @@ -672,10 +741,14 @@ describe('updatePetitionerInformationInteractor', () => { }); it('should not call the update addExistingUserToCase use case helper when the petitioner is unchanged', async () => { - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: mockPetitioners[0], - }); + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: mockPetitioners[0], + }, + mockAdmissionsClerkUser, + ); expect( applicationContext.getUseCaseHelpers().addExistingUserToCase, @@ -687,13 +760,17 @@ describe('updatePetitionerInformationInteractor', () => { .getPersistenceGateway() .isEmailAvailable.mockImplementation(() => false); - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], - updatedEmail: 'changed-email@example.com', + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + updatedEmail: 'changed-email@example.com', + }, }, - }); + mockAdmissionsClerkUser, + ); expect( applicationContext.getUseCaseHelpers().createUserForContact, @@ -709,13 +786,17 @@ describe('updatePetitionerInformationInteractor', () => { .getPersistenceGateway() .isEmailAvailable.mockImplementation(() => true); - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], - updatedEmail: 'changed-email@example.com', + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + updatedEmail: 'changed-email@example.com', + }, }, - }); + mockAdmissionsClerkUser, + ); expect( applicationContext.getUseCaseHelpers().createUserForContact, @@ -731,13 +812,17 @@ describe('updatePetitionerInformationInteractor', () => { mockLock = MOCK_LOCK; await expect( - updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], - updatedEmail: 'changed-email@example.com', + updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + updatedEmail: 'changed-email@example.com', + }, }, - }), + mockAdmissionsClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -746,13 +831,17 @@ describe('updatePetitionerInformationInteractor', () => { }); it('should acquire and remove the lock on the case', async () => { - await updatePetitionerInformationInteractor(applicationContext, { - docketNumber: MOCK_CASE.docketNumber, - updatedPetitionerData: { - ...mockPetitioners[0], - updatedEmail: 'changed-email@example.com', + await updatePetitionerInformationInteractor( + applicationContext, + { + docketNumber: MOCK_CASE.docketNumber, + updatedPetitionerData: { + ...mockPetitioners[0], + updatedEmail: 'changed-email@example.com', + }, }, - }); + mockAdmissionsClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, diff --git a/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.ts b/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.ts index 6c5d8c91685..9a5c10463cf 100644 --- a/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.ts +++ b/web-api/src/business/useCases/user/updatePetitionerInformationInteractor.ts @@ -1,3 +1,8 @@ +import { + AuthUser, + UnknownAuthUser, + isAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; import { CASE_STATUS_TYPES, ROLES, @@ -13,6 +18,7 @@ import { ROLE_PERMISSIONS, isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { aggregatePartiesForService } from '../../../../../shared/src/business/utilities/aggregatePartiesForService'; import { defaults, pick } from 'lodash'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; @@ -48,10 +54,18 @@ export const getIsUserAuthorized = ({ const updateCaseEntityAndGenerateChange = async ({ applicationContext, + authorizedUser, caseEntity, petitionerOnCase, user, userHasAnEmail, +}: { + applicationContext: ServerApplicationContext; + caseEntity: any; + petitionerOnCase: any; + user: any; + userHasAnEmail: any; + authorizedUser: AuthUser; }) => { const newData = { email: petitionerOnCase.newEmail, @@ -79,6 +93,7 @@ const updateCaseEntityAndGenerateChange = async ({ .getUseCaseHelpers() .generateAndServeDocketEntry({ applicationContext, + authorizedUser, caseEntity, documentType, newData, @@ -105,10 +120,15 @@ const updateCaseEntityAndGenerateChange = async ({ * @returns {object} the updated case data */ export const updatePetitionerInformation = async ( - applicationContext, + applicationContext: ServerApplicationContext, { docketNumber, updatedPetitionerData }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); + if (!isAuthUser(authorizedUser)) { + throw new Error( + 'User attempting to update petitioner information is not an auth user', + ); + } const oldCase = await applicationContext .getPersistenceGateway() @@ -117,7 +137,7 @@ export const updatePetitionerInformation = async ( const hasAuthorization = getIsUserAuthorized({ oldCase, updatedPetitionerData, - user, + user: authorizedUser, }); if (!hasAuthorization) { @@ -175,7 +195,7 @@ export const updatePetitionerInformation = async ( { ...oldCase, }, - { applicationContext }, + { authorizedUser }, ); caseToUpdateContacts.updatePetitioner({ @@ -196,7 +216,7 @@ export const updatePetitionerInformation = async ( { ...caseToUpdateContacts.toRawObject(), }, - { applicationContext }, + { authorizedUser }, ).validate(); const servedParties = aggregatePartiesForService(caseEntity); @@ -225,13 +245,14 @@ export const updatePetitionerInformation = async ( .getUseCaseHelpers() .generateAndServeDocketEntry({ applicationContext, + authorizedUser, caseEntity, documentType: documentTypeToGenerate, newData, oldData, privatePractitionersRepresentingContact, servedParties, - user, + user: authorizedUser, }); serviceUrl = url; } @@ -252,6 +273,7 @@ export const updatePetitionerInformation = async ( .getUseCaseHelpers() .createUserForContact({ applicationContext, + authorizedUser, caseEntity, contactId: updatedPetitionerData.contactId, email: updatedPetitionerData.updatedEmail, @@ -262,6 +284,7 @@ export const updatePetitionerInformation = async ( .getUseCaseHelpers() .addExistingUserToCase({ applicationContext, + authorizedUser, caseEntity, contactId: updatedPetitionerData.contactId, email: updatedPetitionerData.updatedEmail, @@ -281,9 +304,10 @@ export const updatePetitionerInformation = async ( await updateCaseEntityAndGenerateChange({ applicationContext, + authorizedUser, caseEntity, petitionerOnCase: oldCaseContact, - user, + user: authorizedUser, userHasAnEmail: userToUpdate.email, }); } @@ -293,6 +317,7 @@ export const updatePetitionerInformation = async ( .getUseCaseHelpers() .updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate: caseEntity, }); diff --git a/web-api/src/business/useCases/user/updateUserContactInformationInteractor.locking.test.ts b/web-api/src/business/useCases/user/updateUserContactInformationInteractor.locking.test.ts index f674d3fdacb..337e76034d4 100644 --- a/web-api/src/business/useCases/user/updateUserContactInformationInteractor.locking.test.ts +++ b/web-api/src/business/useCases/user/updateUserContactInformationInteractor.locking.test.ts @@ -3,6 +3,7 @@ import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; import { MOCK_PRACTITIONER } from '../../../../../shared/src/test/mockUsers'; import { ServiceUnavailableError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { determineEntitiesToLock, @@ -60,16 +61,15 @@ describe('determineEntitiesToLock', () => { }); describe('handleLockError', () => { - it('should determine who the user is based on applicationContext', async () => { - await handleLockError(applicationContext, { foo: 'bar' }); - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); - }); - it('should send a notification to the user with "retry_async_request" and the originalRequest', async () => { const mockOriginalRequest = { foo: 'bar', }; - await handleLockError(applicationContext, mockOriginalRequest); + await handleLockError( + applicationContext, + mockOriginalRequest, + MOCK_PRACTITIONER as UnknownAuthUser, + ); expect( applicationContext.getNotificationGateway().sendNotificationToUser.mock .calls[0][0].message, @@ -102,8 +102,6 @@ describe('updateUserContactInformationInteractor', () => { beforeEach(() => { mockLock = undefined; // unlocked - applicationContext.getCurrentUser.mockReturnValue(MOCK_PRACTITIONER); - applicationContext.getPersistenceGateway().getUserById.mockReturnValue({ ...MOCK_PRACTITIONER, entityName: 'Practitioner', @@ -129,7 +127,11 @@ describe('updateUserContactInformationInteractor', () => { it('should throw a ServiceUnavailableError if a Case is currently locked', async () => { await expect( - updateUserContactInformationInteractor(applicationContext, mockRequest), + updateUserContactInformationInteractor( + applicationContext, + mockRequest, + MOCK_PRACTITIONER as UnknownAuthUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -139,7 +141,11 @@ describe('updateUserContactInformationInteractor', () => { it('should return a "retry_async_request" notification with the original request', async () => { await expect( - updateUserContactInformationInteractor(applicationContext, mockRequest), + updateUserContactInformationInteractor( + applicationContext, + mockRequest, + MOCK_PRACTITIONER as UnknownAuthUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -169,6 +175,7 @@ describe('updateUserContactInformationInteractor', () => { await updateUserContactInformationInteractor( applicationContext, mockRequest, + MOCK_PRACTITIONER as UnknownAuthUser, ); expect( @@ -184,6 +191,7 @@ describe('updateUserContactInformationInteractor', () => { await updateUserContactInformationInteractor( applicationContext, mockRequest, + MOCK_PRACTITIONER as UnknownAuthUser, ); expect( diff --git a/web-api/src/business/useCases/user/updateUserContactInformationInteractor.test.ts b/web-api/src/business/useCases/user/updateUserContactInformationInteractor.test.ts index e1db0a7dcf8..109a3bb415d 100644 --- a/web-api/src/business/useCases/user/updateUserContactInformationInteractor.test.ts +++ b/web-api/src/business/useCases/user/updateUserContactInformationInteractor.test.ts @@ -14,6 +14,7 @@ jest.mock('./generateChangeOfAddress'); import { IrsPractitioner } from '@shared/business/entities/IrsPractitioner'; import { Practitioner } from '@shared/business/entities/Practitioner'; import { generateChangeOfAddress } from './generateChangeOfAddress'; +import { mockPetitionsClerkUser } from '@shared/test/mockAuthUsers'; describe('updateUserContactInformationInteractor', () => { let mockUser; @@ -30,10 +31,6 @@ describe('updateUserContactInformationInteractor', () => { state: 'IL', }; - beforeAll(() => { - applicationContext.getCurrentUser.mockImplementation(() => mockUser); - }); - beforeEach(() => { mockUser = { ...irsPractitionerUser, @@ -62,34 +59,43 @@ describe('updateUserContactInformationInteractor', () => { }); it('should throw unauthorized error when user does not have permission to update contact information', async () => { - mockUser = { - role: ROLES.petitionsClerk, - userId: 'asdf1234-f6cd-442c-a168-202db587f16f', - }; + mockUser = mockPetitionsClerkUser; await expect( - updateUserContactInformationInteractor(applicationContext, { - contactInfo, - userId: mockUser.userId, - } as any), + updateUserContactInformationInteractor( + applicationContext, + { + contactInfo, + userId: mockUser.userId, + } as any, + mockUser, + ), ).rejects.toThrow(UnauthorizedError); }); it('should throw unauthorized error when the user attempts to modify contact information for a different user', async () => { await expect( - updateUserContactInformationInteractor(applicationContext, { - contactInfo, - userId: 'asdf1234-f6cd-442c-a168-202db587f16f', - } as any), + updateUserContactInformationInteractor( + applicationContext, + { + contactInfo, + userId: 'asdf1234-f6cd-442c-a168-202db587f16f', + } as any, + mockUser, + ), ).rejects.toThrow(UnauthorizedError); }); it('should return without updating user or cases when the contact information has not changed', async () => { - await updateUserContactInformationInteractor(applicationContext, { - contactInfo: mockUser.contact, - firmName: 'broken', - userId: mockUser.userId, - }); + await updateUserContactInformationInteractor( + applicationContext, + { + contactInfo: mockUser.contact, + firmName: 'broken', + userId: mockUser.userId, + }, + mockUser, + ); expect(applicationContext.getUseCases().updateUser).not.toHaveBeenCalled(); expect(generateChangeOfAddress).not.toHaveBeenCalled(); @@ -119,10 +125,14 @@ describe('updateUserContactInformationInteractor', () => { }); await expect( - updateUserContactInformationInteractor(applicationContext, { - contactInfo, - userId: mockUser.userId, - } as any), + updateUserContactInformationInteractor( + applicationContext, + { + contactInfo, + userId: mockUser.userId, + } as any, + mockUser, + ), ).rejects.toThrow('something wicked'); expect( @@ -148,10 +158,14 @@ describe('updateUserContactInformationInteractor', () => { practitionerType: PRACTITIONER_TYPE_OPTIONS[0], role: ROLES.irsPractitioner, }; - await updateUserContactInformationInteractor(applicationContext, { - contactInfo, - userId: mockUser.userId, - } as any); + await updateUserContactInformationInteractor( + applicationContext, + { + contactInfo, + userId: mockUser.userId, + } as any, + mockUser, + ); expect( applicationContext.getPersistenceGateway().updateUser.mock.calls[0][0] @@ -182,10 +196,14 @@ describe('updateUserContactInformationInteractor', () => { role: ROLES.irsPractitioner, }; - await updateUserContactInformationInteractor(applicationContext, { - contactInfo, - userId: mockUser.userId, - } as any); + await updateUserContactInformationInteractor( + applicationContext, + { + contactInfo, + userId: mockUser.userId, + } as any, + mockUser, + ); expect( applicationContext.getPersistenceGateway().updateUser.mock.calls[0][0] @@ -202,10 +220,14 @@ describe('updateUserContactInformationInteractor', () => { }); await expect( - updateUserContactInformationInteractor(applicationContext, { - contactInfo, - userId: mockUser.userId, - } as any), + updateUserContactInformationInteractor( + applicationContext, + { + contactInfo, + userId: mockUser.userId, + } as any, + mockUser, + ), ).rejects.toThrow(); expect( @@ -224,10 +246,14 @@ describe('updateUserContactInformationInteractor', () => { }); it('should generate a change of address document', async () => { - await updateUserContactInformationInteractor(applicationContext, { - contactInfo, - userId: mockUser.userId, - } as any); + await updateUserContactInformationInteractor( + applicationContext, + { + contactInfo, + userId: mockUser.userId, + } as any, + mockUser, + ); expect(generateChangeOfAddress).toHaveBeenCalled(); }); @@ -235,26 +261,30 @@ describe('updateUserContactInformationInteractor', () => { it('should clean up DB and send websocket message if "generateChangeOfAddress" returns empty array', async () => { (generateChangeOfAddress as jest.Mock).mockReturnValue([]); - await updateUserContactInformationInteractor(applicationContext, { - contactInfo, - userId: mockUser.userId, - } as any); + await updateUserContactInformationInteractor( + applicationContext, + { + contactInfo, + userId: mockUser.userId, + } as any, + mockUser, + ); expect( applicationContext.getPersistenceGateway().updateUser.mock.calls[1][0] .isUpdatingInformation, ).not.toBeDefined(); - const notificatsionCalls = + const notificationCalls = applicationContext.getNotificationGateway().sendNotificationToUser.mock .calls; expect( - notificatsionCalls[notificatsionCalls.length - 1][0].message.action, + notificationCalls[notificationCalls.length - 1][0].message.action, ).toEqual('user_contact_full_update_complete'); expect( - notificatsionCalls[notificatsionCalls.length - 1][0].message.user, + notificationCalls[notificationCalls.length - 1][0].message.user, ).toMatchObject({ contact: contactInfo, }); @@ -263,10 +293,14 @@ describe('updateUserContactInformationInteractor', () => { it('should not clean up DB and send websocket message if "generateChangeOfAddress" returns undefined', async () => { (generateChangeOfAddress as jest.Mock).mockReturnValue(undefined); - await updateUserContactInformationInteractor(applicationContext, { - contactInfo, - userId: mockUser.userId, - } as any); + await updateUserContactInformationInteractor( + applicationContext, + { + contactInfo, + userId: mockUser.userId, + } as any, + mockUser, + ); expect( applicationContext.getPersistenceGateway().updateUser.mock.calls.length, @@ -282,11 +316,15 @@ describe('updateUserContactInformationInteractor', () => { }); it('should update the firmName if user is a practitioner and firmName is passed in', async () => { - await updateUserContactInformationInteractor(applicationContext, { - contactInfo, - firmName: 'testing', - userId: mockUser.userId, - }); + await updateUserContactInformationInteractor( + applicationContext, + { + contactInfo, + firmName: 'testing', + userId: mockUser.userId, + }, + mockUser, + ); expect( applicationContext.getPersistenceGateway().updateUser.mock.calls[0][0] .user, @@ -303,11 +341,15 @@ describe('updateUserContactInformationInteractor', () => { contact: contactInfo, })); - await updateUserContactInformationInteractor(applicationContext, { - contactInfo, - firmName: mockUser.firmName, - userId: mockUser.userId, - }); + await updateUserContactInformationInteractor( + applicationContext, + { + contactInfo, + firmName: mockUser.firmName, + userId: mockUser.userId, + }, + mockUser, + ); expect( applicationContext.getPersistenceGateway().updateUser, diff --git a/web-api/src/business/useCases/user/updateUserContactInformationInteractor.ts b/web-api/src/business/useCases/user/updateUserContactInformationInteractor.ts index 2c63e7b69bb..0994799fb13 100644 --- a/web-api/src/business/useCases/user/updateUserContactInformationInteractor.ts +++ b/web-api/src/business/useCases/user/updateUserContactInformationInteractor.ts @@ -1,3 +1,7 @@ +import { + AuthUser, + UnknownAuthUser, +} from '@shared/business/entities/authUser/AuthUser'; import { IrsPractitioner } from '@shared/business/entities/IrsPractitioner'; import { Practitioner } from '../../../../../shared/src/business/entities/Practitioner'; import { PrivatePractitioner } from '../../../../../shared/src/business/entities/PrivatePractitioner'; @@ -27,6 +31,7 @@ const updateUserContactInformationHelper = async ( firmName, userId, }: { contactInfo: any; firmName: string; userId: string }, + authorizedUser: AuthUser, ) => { const user = await applicationContext .getPersistenceGateway() @@ -99,6 +104,7 @@ const updateUserContactInformationHelper = async ( const results = await generateChangeOfAddress({ applicationContext, + authorizedUser, contactInfo, firmName, user: userEntity.validate().toRawObject(), @@ -137,22 +143,25 @@ export const updateUserContactInformation = async ( firmName, userId, }: { contactInfo: any; firmName: string; userId: string }, + authorizedUser: UnknownAuthUser, ) => { - const authenticatedUser = applicationContext.getCurrentUser(); - if ( - !isAuthorized(authenticatedUser, ROLE_PERMISSIONS.UPDATE_CONTACT_INFO) || - authenticatedUser.userId !== userId + !isAuthorized(authorizedUser, ROLE_PERMISSIONS.UPDATE_CONTACT_INFO) || + authorizedUser?.userId !== userId ) { throw new UnauthorizedError('Unauthorized'); } try { - await updateUserContactInformationHelper(applicationContext, { - contactInfo, - firmName, - userId, - }); + await updateUserContactInformationHelper( + applicationContext, + { + contactInfo, + firmName, + userId, + }, + authorizedUser, + ); } catch (error) { applicationContext.logger.error(error); await applicationContext.getNotificationGateway().sendNotificationToUser({ @@ -161,7 +170,7 @@ export const updateUserContactInformation = async ( action: 'user_contact_update_error', error: (error as Error).toString(), }, - userId: authenticatedUser.userId, + userId: authorizedUser.userId, }); throw error; } @@ -170,18 +179,19 @@ export const updateUserContactInformation = async ( export const handleLockError = async ( applicationContext: ServerApplicationContext, originalRequest: any, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - await applicationContext.getNotificationGateway().sendNotificationToUser({ - applicationContext, - message: { - action: 'retry_async_request', - originalRequest, - requestToRetry: 'update_user_contact_information', - }, - userId: user.userId, - }); + if (authorizedUser?.userId) { + await applicationContext.getNotificationGateway().sendNotificationToUser({ + applicationContext, + message: { + action: 'retry_async_request', + originalRequest, + requestToRetry: 'update_user_contact_information', + }, + userId: authorizedUser.userId, + }); + } }; export const determineEntitiesToLock = async ( diff --git a/web-api/src/business/useCases/user/updateUserPendingEmailInteractor.test.ts b/web-api/src/business/useCases/user/updateUserPendingEmailInteractor.test.ts index 9b3a884d591..9d14b127d1a 100644 --- a/web-api/src/business/useCases/user/updateUserPendingEmailInteractor.test.ts +++ b/web-api/src/business/useCases/user/updateUserPendingEmailInteractor.test.ts @@ -1,6 +1,10 @@ -import { ROLES } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; import { updateUserPendingEmailInteractor } from './updateUserPendingEmailInteractor'; import { validUser } from '../../../../../shared/src/test/mockUsers'; @@ -11,6 +15,7 @@ describe('updateUserPendingEmailInteractor', () => { beforeEach(() => { mockUser = { ...validUser, + ...mockPrivatePractitionerUser, admissionsDate: '2019-03-01', admissionsStatus: 'Active', barNumber: 'RA3333', @@ -22,10 +27,8 @@ describe('updateUserPendingEmailInteractor', () => { originalBarState: 'FL', practiceType: 'Private', practitionerType: 'Attorney', - role: ROLES.privatePractitioner, }; - applicationContext.getCurrentUser.mockImplementation(() => mockUser); applicationContext .getPersistenceGateway() .getUserById.mockImplementation(() => mockUser); @@ -38,15 +41,14 @@ describe('updateUserPendingEmailInteractor', () => { }); it('should throw unauthorized error when user does not have permission to manage emails', async () => { - mockUser = { - role: ROLES.petitionsClerk, - userId: 'f7d90c05-f6cd-442c-a168-202db587f16f', - }; - await expect( - updateUserPendingEmailInteractor(applicationContext, { - pendingEmail, - }), + updateUserPendingEmailInteractor( + applicationContext, + { + pendingEmail, + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -56,24 +58,24 @@ describe('updateUserPendingEmailInteractor', () => { .isEmailAvailable.mockReturnValue(false); await expect( - updateUserPendingEmailInteractor(applicationContext, { - pendingEmail, - }), + updateUserPendingEmailInteractor( + applicationContext, + { + pendingEmail, + }, + mockPrivatePractitionerUser, + ), ).rejects.toThrow('Email is not available'); }); - it('should make a call to get the current user', async () => { - await updateUserPendingEmailInteractor(applicationContext, { - pendingEmail, - }); - - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); - }); - it('should make a call to getUserById with the logged in user.userId', async () => { - await updateUserPendingEmailInteractor(applicationContext, { - pendingEmail, - }); + await updateUserPendingEmailInteractor( + applicationContext, + { + pendingEmail, + }, + mockPrivatePractitionerUser, + ); expect( applicationContext.getPersistenceGateway().getUserById.mock.calls[0][0], @@ -81,9 +83,13 @@ describe('updateUserPendingEmailInteractor', () => { }); it('should update the user record in persistence with the pendingEmail value', async () => { - await updateUserPendingEmailInteractor(applicationContext, { - pendingEmail, - }); + await updateUserPendingEmailInteractor( + applicationContext, + { + pendingEmail, + }, + mockPrivatePractitionerUser, + ); expect( applicationContext.getPersistenceGateway().updateUser.mock.calls[0][0] @@ -92,24 +98,38 @@ describe('updateUserPendingEmailInteractor', () => { }); it('should return the updated User entity when currentUser.role is petitioner', async () => { - mockUser = validUser; + const mockUserPetitioner = { ...validUser, ...mockPetitionerUser }; + applicationContext + .getPersistenceGateway() + .getUserById.mockReturnValueOnce(mockUserPetitioner); + applicationContext + .getPersistenceGateway() + .updateUser.mockReturnValueOnce(mockUserPetitioner); - const results = await updateUserPendingEmailInteractor(applicationContext, { - pendingEmail, - }); + const results = await updateUserPendingEmailInteractor( + applicationContext, + { + pendingEmail, + }, + mockPetitionerUser, + ); expect(results.entityName).toBe('User'); expect(results).toMatchObject({ - ...mockUser, + ...mockUserPetitioner, pendingEmail, pendingEmailVerificationToken: expect.anything(), }); }); it('should return the updated Practitioner entity when currentUser.role is NOT petitioner', async () => { - const results = await updateUserPendingEmailInteractor(applicationContext, { - pendingEmail, - }); + const results = await updateUserPendingEmailInteractor( + applicationContext, + { + pendingEmail, + }, + mockPrivatePractitionerUser, + ); expect(results.entityName).toBe('Practitioner'); expect(results).toMatchObject({ @@ -120,9 +140,13 @@ describe('updateUserPendingEmailInteractor', () => { }); it('should call applicationContext.getUseCaseHelpers().sendEmailVerificationLink to send the verification link to the user', async () => { - await updateUserPendingEmailInteractor(applicationContext, { - pendingEmail, - }); + await updateUserPendingEmailInteractor( + applicationContext, + { + pendingEmail, + }, + mockPrivatePractitionerUser, + ); expect( applicationContext.getUseCaseHelpers().sendEmailVerificationLink.mock diff --git a/web-api/src/business/useCases/user/updateUserPendingEmailInteractor.ts b/web-api/src/business/useCases/user/updateUserPendingEmailInteractor.ts index aa245f72cfc..0f124682fd2 100644 --- a/web-api/src/business/useCases/user/updateUserPendingEmailInteractor.ts +++ b/web-api/src/business/useCases/user/updateUserPendingEmailInteractor.ts @@ -6,6 +6,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { User } from '../../../../../shared/src/business/entities/User'; /** @@ -20,9 +21,8 @@ import { User } from '../../../../../shared/src/business/entities/User'; export const updateUserPendingEmailInteractor = async ( applicationContext: ServerApplicationContext, { pendingEmail }: { pendingEmail: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.EMAIL_MANAGEMENT)) { throw new UnauthorizedError('Unauthorized to manage emails.'); } diff --git a/web-api/src/business/useCases/user/verifyUserPendingEmailInteractor.test.ts b/web-api/src/business/useCases/user/verifyUserPendingEmailInteractor.test.ts index 55c1baa4ef2..42b8ce21bfb 100644 --- a/web-api/src/business/useCases/user/verifyUserPendingEmailInteractor.test.ts +++ b/web-api/src/business/useCases/user/verifyUserPendingEmailInteractor.test.ts @@ -6,6 +6,11 @@ import { import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getContactPrimary } from '../../../../../shared/src/business/entities/cases/Case'; +import { + mockPetitionerUser, + mockPetitionsClerkUser, + mockPrivatePractitionerUser, +} from '@shared/test/mockAuthUsers'; import { validUser } from '../../../../../shared/src/test/mockUsers'; import { verifyUserPendingEmailInteractor } from './verifyUserPendingEmailInteractor'; @@ -13,6 +18,7 @@ describe('verifyUserPendingEmailInteractor', () => { const TOKEN = '41189629-abe1-46d7-b7a4-9d3834f919cb'; const mockPractitioner = { ...validUser, + ...mockPrivatePractitionerUser, admissionsDate: '2019-03-01', admissionsStatus: 'Active', barNumber: 'RA3333', @@ -32,6 +38,7 @@ describe('verifyUserPendingEmailInteractor', () => { const mockPetitioner = { ...validUser, + ...mockPetitionerUser, firstName: 'Olden', lastName: 'Vivas', pendingEmail: 'other@example.com', @@ -53,7 +60,6 @@ describe('verifyUserPendingEmailInteractor', () => { }; beforeEach(() => { - applicationContext.getCurrentUser.mockReturnValue(mockPractitioner); applicationContext .getPersistenceGateway() .getUserById.mockReturnValue(mockPractitioner); @@ -72,23 +78,26 @@ describe('verifyUserPendingEmailInteractor', () => { }); it('should throw unauthorized error when user does not have permission to verify emails', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - userId: 'f7d90c05-f6cd-442c-a168-202db587f16f', - }); - await expect( - verifyUserPendingEmailInteractor(applicationContext, { - token: 'abc', - }), + verifyUserPendingEmailInteractor( + applicationContext, + { + token: 'abc', + }, + mockPetitionsClerkUser, + ), ).rejects.toThrow('Unauthorized to manage emails'); }); it('should throw an unauthorized error when the token passed as an argument does not match stored token on user', async () => { await expect( - verifyUserPendingEmailInteractor(applicationContext, { - token: 'abc', - }), + verifyUserPendingEmailInteractor( + applicationContext, + { + token: 'abc', + }, + mockPrivatePractitionerUser, + ), ).rejects.toThrow('Tokens do not match'); }); @@ -99,9 +108,13 @@ describe('verifyUserPendingEmailInteractor', () => { }); await expect( - verifyUserPendingEmailInteractor(applicationContext, { - token: undefined as any, - }), + verifyUserPendingEmailInteractor( + applicationContext, + { + token: undefined as any, + }, + mockPrivatePractitionerUser, + ), ).rejects.toThrow('Tokens do not match'); }); @@ -111,16 +124,24 @@ describe('verifyUserPendingEmailInteractor', () => { .isEmailAvailable.mockReturnValue(false); await expect( - verifyUserPendingEmailInteractor(applicationContext, { - token: TOKEN, - }), + verifyUserPendingEmailInteractor( + applicationContext, + { + token: TOKEN, + }, + mockPrivatePractitionerUser, + ), ).rejects.toThrow('Email is not available'); }); it('should update the cognito email when tokens match', async () => { - await verifyUserPendingEmailInteractor(applicationContext, { - token: TOKEN, - }); + await verifyUserPendingEmailInteractor( + applicationContext, + { + token: TOKEN, + }, + mockPrivatePractitionerUser, + ); expect(applicationContext.getUserGateway().updateUser).toHaveBeenCalledWith( applicationContext, @@ -134,9 +155,13 @@ describe('verifyUserPendingEmailInteractor', () => { }); it('should update the dynamo record with the new info', async () => { - await verifyUserPendingEmailInteractor(applicationContext, { - token: TOKEN, - }); + await verifyUserPendingEmailInteractor( + applicationContext, + { + token: TOKEN, + }, + mockPrivatePractitionerUser, + ); expect( applicationContext.getPersistenceGateway().updateUser.mock.calls[0][0] @@ -149,9 +174,13 @@ describe('verifyUserPendingEmailInteractor', () => { }); it('should call updateUser with email set to pendingEmail and pendingEmail set to undefined, and service indicator set to electronic with a practitioner user', async () => { - await verifyUserPendingEmailInteractor(applicationContext, { - token: TOKEN, - }); + await verifyUserPendingEmailInteractor( + applicationContext, + { + token: TOKEN, + }, + mockPrivatePractitionerUser, + ); expect( applicationContext.getPersistenceGateway().updateUser.mock.calls[0][0] @@ -169,9 +198,13 @@ describe('verifyUserPendingEmailInteractor', () => { .getPersistenceGateway() .getUserById.mockReturnValue(mockPetitioner); - await verifyUserPendingEmailInteractor(applicationContext, { - token: mockPetitioner.pendingEmailVerificationToken, - }); + await verifyUserPendingEmailInteractor( + applicationContext, + { + token: mockPetitioner.pendingEmailVerificationToken, + }, + mockPetitionerUser, + ); expect( applicationContext.getPersistenceGateway().updateUser.mock.calls[0][0] diff --git a/web-api/src/business/useCases/user/verifyUserPendingEmailInteractor.ts b/web-api/src/business/useCases/user/verifyUserPendingEmailInteractor.ts index b22c6b41dd5..c7af447e398 100644 --- a/web-api/src/business/useCases/user/verifyUserPendingEmailInteractor.ts +++ b/web-api/src/business/useCases/user/verifyUserPendingEmailInteractor.ts @@ -5,14 +5,14 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '../../../errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { updateUserPendingEmailRecord } from '@web-api/business/useCases/auth/changePasswordInteractor'; export const verifyUserPendingEmailInteractor = async ( applicationContext: ServerApplicationContext, { token }: { token: string }, + authorizedUser: UnknownAuthUser, ): Promise => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.EMAIL_MANAGEMENT)) { throw new UnauthorizedError('Unauthorized to manage emails.'); } @@ -59,9 +59,9 @@ export const verifyUserPendingEmailInteractor = async ( await applicationContext.getWorkerGateway().queueWork(applicationContext, { message: { + authorizedUser, payload: { user: updatedUser }, type: MESSAGE_TYPES.QUEUE_UPDATE_ASSOCIATED_CASES, - user: applicationContext.getCurrentUser(), }, }); }; diff --git a/web-api/src/business/useCases/workItems/assignWorkItemsInteractor.test.ts b/web-api/src/business/useCases/workItems/assignWorkItemsInteractor.test.ts index dbb6f26afed..cd4fbfbf1db 100644 --- a/web-api/src/business/useCases/workItems/assignWorkItemsInteractor.test.ts +++ b/web-api/src/business/useCases/workItems/assignWorkItemsInteractor.test.ts @@ -2,24 +2,16 @@ import { CASE_STATUS_TYPES, DOCKET_NUMBER_SUFFIXES, DOCKET_SECTION, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { assignWorkItemsInteractor } from './assignWorkItemsInteractor'; import { caseServicesSupervisorUser } from '../../../../../shared/src/test/mockUsers'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('assignWorkItemsInteractor', () => { const options = { assigneeId: 'ss', assigneeName: 'ss', workItemId: '' }; - const mockUserId = 'ebb34e3f-8ac1-4ac2-bc22-265b80a2acb2'; let mockWorkItem; - const mockDocketClerkUser = { - name: 'Alex Docketclerk', - role: ROLES.docketClerk, - section: 'docket', - userId: mockUserId, - }; - beforeEach(() => { mockWorkItem = { assigneeId: '03b74100-10ac-45f1-865d-b063978cac9c', @@ -50,11 +42,11 @@ describe('assignWorkItemsInteractor', () => { updatedAt: '2018-12-27T18:06:02.968Z', workItemId: '78de1ba3-add3-4329-8372-ce37bda6bc93', }; - applicationContext.getCurrentUser.mockReturnValue(mockDocketClerkUser); - applicationContext - .getPersistenceGateway() - .getUserById.mockReturnValue(mockDocketClerkUser); + applicationContext.getPersistenceGateway().getUserById.mockReturnValue({ + ...mockDocketClerkUser, + section: DOCKET_SECTION, + }); applicationContext .getPersistenceGateway() @@ -62,12 +54,12 @@ describe('assignWorkItemsInteractor', () => { }); it('should throw an unauthorized error when the user does not have permission to assign work items', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - userId: 'baduser', - }); - await expect( - assignWorkItemsInteractor(applicationContext, options), + assignWorkItemsInteractor( + applicationContext, + options, + mockDocketClerkUser, + ), ).rejects.toThrow(); }); @@ -78,24 +70,32 @@ describe('assignWorkItemsInteractor', () => { }); await expect( - assignWorkItemsInteractor(applicationContext, options), + assignWorkItemsInteractor( + applicationContext, + options, + mockDocketClerkUser, + ), ).rejects.toThrow(); }); it('assigns a work item to the current user', async () => { - await assignWorkItemsInteractor(applicationContext, { - assigneeId: mockUserId, - assigneeName: 'Ted Docket', - workItemId: mockWorkItem.workItemId, - }); + await assignWorkItemsInteractor( + applicationContext, + { + assigneeId: mockDocketClerkUser.userId, + assigneeName: 'Ted Docket', + workItemId: mockWorkItem.workItemId, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveWorkItem.mock.calls[0][0] .workItem, ).toMatchObject({ - section: mockDocketClerkUser.section, + section: DOCKET_SECTION, sentBy: mockDocketClerkUser.name, - sentBySection: mockDocketClerkUser.section, + sentBySection: DOCKET_SECTION, sentByUserId: mockDocketClerkUser.userId, }); }); @@ -104,19 +104,26 @@ describe('assignWorkItemsInteractor', () => { applicationContext .getPersistenceGateway() .getUserById.mockReturnValueOnce(caseServicesSupervisorUser) - .mockReturnValueOnce(mockDocketClerkUser); + .mockReturnValueOnce({ + ...mockDocketClerkUser, + section: DOCKET_SECTION, + }); - await assignWorkItemsInteractor(applicationContext, { - assigneeId: mockUserId, - assigneeName: 'Ted Docket', - workItemId: mockWorkItem.workItemId, - }); + await assignWorkItemsInteractor( + applicationContext, + { + assigneeId: mockDocketClerkUser.userId, + assigneeName: 'Ted Docket', + workItemId: mockWorkItem.workItemId, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveWorkItem.mock.calls[0][0] .workItem, ).toMatchObject({ - section: mockDocketClerkUser.section, + section: DOCKET_SECTION, sentBy: caseServicesSupervisorUser.name, sentBySection: caseServicesSupervisorUser.section, sentByUserId: caseServicesSupervisorUser.userId, diff --git a/web-api/src/business/useCases/workItems/assignWorkItemsInteractor.ts b/web-api/src/business/useCases/workItems/assignWorkItemsInteractor.ts index 8117d5d89e0..b7c83df048c 100644 --- a/web-api/src/business/useCases/workItems/assignWorkItemsInteractor.ts +++ b/web-api/src/business/useCases/workItems/assignWorkItemsInteractor.ts @@ -4,6 +4,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { User } from '../../../../../shared/src/business/entities/User'; import { WorkItem } from '../../../../../shared/src/business/entities/WorkItem'; @@ -27,8 +28,8 @@ export const assignWorkItemsInteractor = async ( assigneeName: string; workItemId: string; }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.ASSIGN_WORK_ITEM)) { throw new UnauthorizedError('Unauthorized to assign work item'); } @@ -52,9 +53,7 @@ export const assignWorkItemsInteractor = async ( workItemId, }); - const workItemEntity = new WorkItem(workItemRecord, { - applicationContext, - }); + const workItemEntity = new WorkItem(workItemRecord); const userIsCaseServices = User.isCaseServicesUser({ section: user.section }); const userBeingAssignedIsCaseServices = User.isCaseServicesUser({ section: userBeingAssigned.section, diff --git a/web-api/src/business/useCases/workItems/completeWorkItemInteractor.locking.test.ts b/web-api/src/business/useCases/workItems/completeWorkItemInteractor.locking.test.ts index b914ad01f88..61853ab4c6d 100644 --- a/web-api/src/business/useCases/workItems/completeWorkItemInteractor.locking.test.ts +++ b/web-api/src/business/useCases/workItems/completeWorkItemInteractor.locking.test.ts @@ -7,7 +7,7 @@ import { MOCK_LOCK } from '../../../../../shared/src/test/mockLock'; import { ServiceUnavailableError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { completeWorkItemInteractor } from './completeWorkItemInteractor'; -import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('completeWorkItemInteractor', () => { let mockLock; @@ -50,7 +50,6 @@ describe('completeWorkItemInteractor', () => { beforeEach(() => { mockLock = undefined; - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); applicationContext .getPersistenceGateway() .getCaseByDocketNumber.mockReturnValue(MOCK_CASE); @@ -62,7 +61,11 @@ describe('completeWorkItemInteractor', () => { it('throws a ServiceUnavailableError if a Case is currently locked', async () => { mockLock = MOCK_LOCK; await expect( - completeWorkItemInteractor(applicationContext, mockRequest), + completeWorkItemInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ), ).rejects.toThrow(ServiceUnavailableError); expect( @@ -71,7 +74,11 @@ describe('completeWorkItemInteractor', () => { }); it('acquires a lock that lasts for 30 seconds on the case', async () => { - await completeWorkItemInteractor(applicationContext, mockRequest); + await completeWorkItemInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().createLock, @@ -84,7 +91,11 @@ describe('completeWorkItemInteractor', () => { it('resolves and calls updateCaseAndAssociations', async () => { await expect( - completeWorkItemInteractor(applicationContext, mockRequest), + completeWorkItemInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ), ).resolves.not.toThrow(); expect( applicationContext.getUseCaseHelpers().updateCaseAndAssociations, @@ -92,7 +103,11 @@ describe('completeWorkItemInteractor', () => { }); it('removes the lock when it is finished', async () => { - await completeWorkItemInteractor(applicationContext, mockRequest); + await completeWorkItemInteractor( + applicationContext, + mockRequest, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().removeLock, diff --git a/web-api/src/business/useCases/workItems/completeWorkItemInteractor.test.ts b/web-api/src/business/useCases/workItems/completeWorkItemInteractor.test.ts index f9a7e14fbf2..edbc4ac0de7 100644 --- a/web-api/src/business/useCases/workItems/completeWorkItemInteractor.test.ts +++ b/web-api/src/business/useCases/workItems/completeWorkItemInteractor.test.ts @@ -1,16 +1,16 @@ import { DOCKET_NUMBER_SUFFIXES, DOCKET_SECTION, - PARTY_TYPES, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { completeWorkItemInteractor } from './completeWorkItemInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('completeWorkItemInteractor', () => { - let mockUser; - const mockWorkItem = { assigneeId: applicationContext.getUniqueId(), createdAt: '2019-03-11T21:56:01.625Z', @@ -36,14 +36,6 @@ describe('completeWorkItemInteractor', () => { }; beforeEach(() => { - mockUser = { - name: 'docket clerk', - role: ROLES.docketClerk, - userId: applicationContext.getUniqueId(), - }; - - applicationContext.getCurrentUser.mockImplementation(() => mockUser); - applicationContext .getPersistenceGateway() .getWorkItemById.mockResolvedValue(mockWorkItem); @@ -58,27 +50,29 @@ describe('completeWorkItemInteractor', () => { }); it('should throw an error when the user does not have permission to complete the work item', async () => { - mockUser = { - name: PARTY_TYPES.petitioner, - role: ROLES.petitioner, - userId: 'petitioner', - }; - await expect( - completeWorkItemInteractor(applicationContext, { - completedMessage: 'Completed', - workItemId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }), + completeWorkItemInteractor( + applicationContext, + { + completedMessage: 'Completed', + workItemId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized for complete workItem'); }); it('should retrieve the original work item from persistence', async () => { const mockWorkItemId = 'c54ba5a9-b37b-479d-9201-067ec6e335bb'; - await completeWorkItemInteractor(applicationContext, { - completedMessage: 'Completed', - workItemId: mockWorkItemId, - }); + await completeWorkItemInteractor( + applicationContext, + { + completedMessage: 'Completed', + workItemId: mockWorkItemId, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getWorkItemById.mock @@ -117,10 +111,14 @@ describe('completeWorkItemInteractor', () => { ], }); - await completeWorkItemInteractor(applicationContext, { - completedMessage: 'Completed', - workItemId: mockWorkItem.workItemId, - }); + await completeWorkItemInteractor( + applicationContext, + { + completedMessage: 'Completed', + workItemId: mockWorkItem.workItemId, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateCase.mock.calls[0][0] diff --git a/web-api/src/business/useCases/workItems/completeWorkItemInteractor.ts b/web-api/src/business/useCases/workItems/completeWorkItemInteractor.ts index 76952b14810..6d69f5d2fdd 100644 --- a/web-api/src/business/useCases/workItems/completeWorkItemInteractor.ts +++ b/web-api/src/business/useCases/workItems/completeWorkItemInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { WorkItem } from '../../../../../shared/src/business/entities/WorkItem'; import { createISODateString } from '../../../../../shared/src/business/utilities/DateHandler'; import { withLocking } from '@web-api/business/useCaseHelper/acquireLock'; @@ -27,10 +28,9 @@ export const completeWorkItem = async ( completedMessage: string; workItemId: string; }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.WORKITEM)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.WORKITEM)) { throw new UnauthorizedError('Unauthorized for complete workItem'); } @@ -40,20 +40,19 @@ export const completeWorkItem = async ( applicationContext, workItemId, }); - const originalWorkItemEntity = new WorkItem(originalWorkItem, { - applicationContext, - }); + const originalWorkItemEntity = new WorkItem(originalWorkItem); const completedWorkItem = originalWorkItemEntity .setAsCompleted({ message: completedMessage, - user, + user: authorizedUser, }) .validate() .toRawObject(); await applicationContext.getPersistenceGateway().putWorkItemInOutbox({ applicationContext, + authorizedUser, workItem: { ...completedWorkItem, createdAt: createISODateString(), @@ -72,11 +71,9 @@ export const completeWorkItem = async ( docketNumber: completedWorkItem.docketNumber, }); - const caseToUpdate = new Case(caseObject, { applicationContext }); + const caseToUpdate = new Case(caseObject, { authorizedUser }); - const workItemEntity = new WorkItem(completedWorkItem, { - applicationContext, - }); + const workItemEntity = new WorkItem(completedWorkItem); caseToUpdate.docketEntries.forEach(doc => { if (doc.workItem && doc.workItem.workItemId === workItemEntity.workItemId) { @@ -86,6 +83,7 @@ export const completeWorkItem = async ( await applicationContext.getUseCaseHelpers().updateCaseAndAssociations({ applicationContext, + authorizedUser, caseToUpdate, }); diff --git a/web-api/src/business/useCases/workItems/getDocumentQCInboxForSectionInteractor.test.ts b/web-api/src/business/useCases/workItems/getDocumentQCInboxForSectionInteractor.test.ts index f1251b32ac9..da9f5cad66c 100644 --- a/web-api/src/business/useCases/workItems/getDocumentQCInboxForSectionInteractor.test.ts +++ b/web-api/src/business/useCases/workItems/getDocumentQCInboxForSectionInteractor.test.ts @@ -1,33 +1,33 @@ -import { - DOCKET_SECTION, - ROLES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { DOCKET_SECTION } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getDocumentQCInboxForSectionInteractor } from './getDocumentQCInboxForSectionInteractor'; +import { + mockDocketClerkUser, + mockJudgeUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getDocumentQCInboxForSectionInteractor', () => { it('should throw an error when the user does not have permission to retrieve work items', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: 'petitioner', - }); - await expect( - getDocumentQCInboxForSectionInteractor(applicationContext, { - section: DOCKET_SECTION, - }), + getDocumentQCInboxForSectionInteractor( + applicationContext, + { + section: DOCKET_SECTION, + }, + mockPetitionerUser, + ), ).rejects.toThrow(); }); it('should query workItems for the provided section', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketclerk', - }); - - await getDocumentQCInboxForSectionInteractor(applicationContext, { - section: DOCKET_SECTION, - }); + await getDocumentQCInboxForSectionInteractor( + applicationContext, + { + section: DOCKET_SECTION, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getDocumentQCInboxForSection @@ -36,14 +36,13 @@ describe('getDocumentQCInboxForSectionInteractor', () => { }); it('should default to query workItems for the DOCKET_SECTION when a section is provided that is NOT PETITIONS_SECTION', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: 'docketclerk', - }); - - await getDocumentQCInboxForSectionInteractor(applicationContext, { - section: 'ANY_OTHER_SECTION', - }); + await getDocumentQCInboxForSectionInteractor( + applicationContext, + { + section: 'ANY_OTHER_SECTION', + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getDocumentQCInboxForSection @@ -52,16 +51,15 @@ describe('getDocumentQCInboxForSectionInteractor', () => { }); it('should query workItems using a judge name when one is provided', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.judge, - userId: 'judge', - }); - - await getDocumentQCInboxForSectionInteractor(applicationContext, { - judgeUserName: 'Ashford', - section: applicationContext.getPersistenceGateway().getJudgesChambers() - .ASHFORDS_CHAMBERS_SECTION.section, - }); + await getDocumentQCInboxForSectionInteractor( + applicationContext, + { + judgeUserName: 'Ashford', + section: applicationContext.getPersistenceGateway().getJudgesChambers() + .ASHFORDS_CHAMBERS_SECTION.section, + }, + mockJudgeUser, + ); expect( applicationContext.getPersistenceGateway().getDocumentQCInboxForSection diff --git a/web-api/src/business/useCases/workItems/getDocumentQCInboxForSectionInteractor.ts b/web-api/src/business/useCases/workItems/getDocumentQCInboxForSectionInteractor.ts index 78ea9e28ca3..2d001b54ea5 100644 --- a/web-api/src/business/useCases/workItems/getDocumentQCInboxForSectionInteractor.ts +++ b/web-api/src/business/useCases/workItems/getDocumentQCInboxForSectionInteractor.ts @@ -8,6 +8,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { WorkItem } from '../../../../../shared/src/business/entities/WorkItem'; /** @@ -26,9 +27,8 @@ export const getDocumentQCInboxForSectionInteractor = async ( judgeUserName?: string; section: string; }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.WORKITEM)) { throw new UnauthorizedError( 'Unauthorized for getting completed work items', @@ -48,7 +48,5 @@ export const getDocumentQCInboxForSectionInteractor = async ( section: sectionToShow, }); - return WorkItem.validateRawCollection(workItems, { - applicationContext, - }); + return WorkItem.validateRawCollection(workItems); }; diff --git a/web-api/src/business/useCases/workItems/getDocumentQCInboxForUserInteractor.test.ts b/web-api/src/business/useCases/workItems/getDocumentQCInboxForUserInteractor.test.ts index b7d100d0794..e8355b39523 100644 --- a/web-api/src/business/useCases/workItems/getDocumentQCInboxForUserInteractor.test.ts +++ b/web-api/src/business/useCases/workItems/getDocumentQCInboxForUserInteractor.test.ts @@ -1,11 +1,14 @@ import { DOCKET_NUMBER_SUFFIXES, DOCKET_SECTION, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { docketClerkUser } from '../../../../../shared/src/test/mockUsers'; import { getDocumentQCInboxForUserInteractor } from './getDocumentQCInboxForUserInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getDocumentQCInboxForUserInteractor', () => { beforeEach(() => { @@ -31,37 +34,40 @@ describe('getDocumentQCInboxForUserInteractor', () => { }); it('should throw an error when the user does not have access retrieve work items', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: 'petitioner', - }); - await expect( - getDocumentQCInboxForUserInteractor(applicationContext, { - userId: null, - }), + getDocumentQCInboxForUserInteractor( + applicationContext, + { + userId: '', + }, + mockPetitionerUser, + ), ).rejects.toThrow('Unauthorized'); }); it('should fetch the user from persistence', async () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - - await getDocumentQCInboxForUserInteractor(applicationContext, { - userId: docketClerkUser.userId, - }); + await getDocumentQCInboxForUserInteractor( + applicationContext, + { + userId: docketClerkUser.userId, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getUserById.mock.calls[0][0] .userId, - ).toEqual(docketClerkUser.userId); + ).toEqual(mockDocketClerkUser.userId); }); it('should query workItems that are associated with the provided userId', async () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - - await getDocumentQCInboxForUserInteractor(applicationContext, { - userId: docketClerkUser.userId, - }); + await getDocumentQCInboxForUserInteractor( + applicationContext, + { + userId: docketClerkUser.userId, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().getDocumentQCInboxForUser.mock @@ -70,10 +76,12 @@ describe('getDocumentQCInboxForUserInteractor', () => { }); it('should filter the workItems for the provided user', async () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - - await getDocumentQCInboxForUserInteractor(applicationContext, { - userId: docketClerkUser.userId, - }); + await getDocumentQCInboxForUserInteractor( + applicationContext, + { + userId: docketClerkUser.userId, + }, + mockDocketClerkUser, + ); }); }); diff --git a/web-api/src/business/useCases/workItems/getDocumentQCInboxForUserInteractor.ts b/web-api/src/business/useCases/workItems/getDocumentQCInboxForUserInteractor.ts index 80ffe09513c..0e80335f04b 100644 --- a/web-api/src/business/useCases/workItems/getDocumentQCInboxForUserInteractor.ts +++ b/web-api/src/business/useCases/workItems/getDocumentQCInboxForUserInteractor.ts @@ -4,6 +4,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { WorkItem } from '../../../../../shared/src/business/entities/WorkItem'; /** @@ -17,9 +18,8 @@ import { WorkItem } from '../../../../../shared/src/business/entities/WorkItem'; export const getDocumentQCInboxForUserInteractor = async ( applicationContext: ServerApplicationContext, { userId }: { userId: string }, + authorizedUser: UnknownAuthUser, ) => { - const authorizedUser = applicationContext.getCurrentUser(); - if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.WORKITEM)) { throw new UnauthorizedError('Unauthorized'); } @@ -40,7 +40,5 @@ export const getDocumentQCInboxForUserInteractor = async ( workItem.assigneeId === user.userId && workItem.section === user.section, ); - return WorkItem.validateRawCollection(filteredWorkItems, { - applicationContext, - }); + return WorkItem.validateRawCollection(filteredWorkItems); }; diff --git a/web-api/src/business/useCases/workItems/getDocumentQCServedForSectionInteractor.test.ts b/web-api/src/business/useCases/workItems/getDocumentQCServedForSectionInteractor.test.ts index b4dd6cb4280..adf08f26d47 100644 --- a/web-api/src/business/useCases/workItems/getDocumentQCServedForSectionInteractor.test.ts +++ b/web-api/src/business/useCases/workItems/getDocumentQCServedForSectionInteractor.test.ts @@ -1,7 +1,6 @@ import { DOCKET_SECTION, PETITIONS_SECTION, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { MOCK_USERS } from '../../../../../shared/src/test/mockUsers'; import { UnauthorizedError } from '@web-api/errors/errors'; @@ -14,18 +13,15 @@ import { calculateISODate, createISODateAtStartOfDayEST, } from '../../../../../shared/src/business/utilities/DateHandler'; +import { + mockDocketClerkUser, + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('getDocumentQCServedForSectionInteractor', () => { describe('interactor', () => { - let user; - beforeEach(() => { - user = { - role: ROLES.docketClerk, - userId: 'a7d90c05-f6cd-442c-a168-202db587f16f', - }; - applicationContext.getCurrentUser.mockReturnValue(user); - applicationContext.getPersistenceGateway().getDocumentQCServedForSection = () => [ { @@ -79,16 +75,14 @@ describe('getDocumentQCServedForSectionInteractor', () => { }); it('throws an error if the user does not have access to the work item', async () => { - user = { - role: ROLES.petitioner, - userId: 'd7d90c05-f6cd-442c-a168-202db587f16f', - }; - applicationContext.getCurrentUser.mockReturnValue(user); - await expect( - getDocumentQCServedForSectionInteractor(applicationContext, { - section: DOCKET_SECTION, - }), + getDocumentQCServedForSectionInteractor( + applicationContext, + { + section: DOCKET_SECTION, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -98,6 +92,7 @@ describe('getDocumentQCServedForSectionInteractor', () => { { section: DOCKET_SECTION, }, + mockDocketClerkUser, ); expect(result).toMatchObject([ @@ -128,17 +123,12 @@ describe('getDocumentQCServedForSectionInteractor', () => { }); it('successfully returns the work item for a petitionsclerk', async () => { - user = { - role: ROLES.petitionsClerk, - userId: '4b423e1f-4eb2-4011-a845-873b82bee0a8', - }; - applicationContext.getCurrentUser.mockReturnValue(user); - const result = await getDocumentQCServedForSectionInteractor( applicationContext, { section: PETITIONS_SECTION, }, + mockPetitionsClerkUser, ); expect(result).toMatchObject([ diff --git a/web-api/src/business/useCases/workItems/getDocumentQCServedForSectionInteractor.ts b/web-api/src/business/useCases/workItems/getDocumentQCServedForSectionInteractor.ts index 52f09053fe7..3e9785f7c95 100644 --- a/web-api/src/business/useCases/workItems/getDocumentQCServedForSectionInteractor.ts +++ b/web-api/src/business/useCases/workItems/getDocumentQCServedForSectionInteractor.ts @@ -6,6 +6,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { calculateISODate, createISODateAtStartOfDayEST, @@ -21,10 +22,9 @@ import { export const getDocumentQCServedForSectionInteractor = async ( applicationContext: ServerApplicationContext, { section }: { section: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.WORKITEM)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.WORKITEM)) { throw new UnauthorizedError( 'Unauthorized for getting completed work items', ); @@ -41,7 +41,7 @@ export const getDocumentQCServedForSectionInteractor = async ( const filteredWorkItems = workItems .filter(workItem => - user.role === ROLES.petitionsClerk ? !!workItem.section : true, + authorizedUser.role === ROLES.petitionsClerk ? !!workItem.section : true, ) .map(workItem => new OutboxItem(workItem, { applicationContext })); diff --git a/web-api/src/business/useCases/workItems/getDocumentQCServedForUserInteractor.test.ts b/web-api/src/business/useCases/workItems/getDocumentQCServedForUserInteractor.test.ts index 785e072fc8a..d7bf63cd9e4 100644 --- a/web-api/src/business/useCases/workItems/getDocumentQCServedForUserInteractor.test.ts +++ b/web-api/src/business/useCases/workItems/getDocumentQCServedForUserInteractor.test.ts @@ -1,21 +1,15 @@ -import { - DOCKET_SECTION, - ROLES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { DOCKET_SECTION } from '../../../../../shared/src/business/entities/EntityConstants'; import { UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getDocumentQCServedForUserInteractor } from './getDocumentQCServedForUserInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, + mockPetitionsClerkUser, +} from '@shared/test/mockAuthUsers'; describe('getDocumentQCServedForUserInteractor', () => { - let user; - beforeEach(() => { - user = { - role: ROLES.petitionsClerk, - userId: 'petitionsclerk', - }; - applicationContext.getCurrentUser.mockReturnValue(user); - applicationContext.getPersistenceGateway().getDocumentQCServedForUser = () => [ { @@ -64,17 +58,14 @@ describe('getDocumentQCServedForUserInteractor', () => { }); it('throws an error if the user does not have access to the work item', async () => { - user = { - role: ROLES.petitioner, - userId: 'petitioner', - }; - - applicationContext.getCurrentUser.mockReturnValue(user); - await expect( - getDocumentQCServedForUserInteractor(applicationContext, { - userId: '123', - }), + getDocumentQCServedForUserInteractor( + applicationContext, + { + userId: '123', + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -84,7 +75,9 @@ describe('getDocumentQCServedForUserInteractor', () => { { userId: '123', }, + mockPetitionsClerkUser, ); + expect(result).toMatchObject([ { docketEntry: { sentBy: 'petitioner' }, @@ -104,18 +97,12 @@ describe('getDocumentQCServedForUserInteractor', () => { }); it('successfully returns the work items for a docket clerk', async () => { - user = { - role: ROLES.docketClerk, - userId: 'docketclerk', - }; - - applicationContext.getCurrentUser.mockReturnValue(user); - const result = await getDocumentQCServedForUserInteractor( applicationContext, { userId: 'abc', }, + mockDocketClerkUser, ); expect(result).toMatchObject([ { diff --git a/web-api/src/business/useCases/workItems/getDocumentQCServedForUserInteractor.ts b/web-api/src/business/useCases/workItems/getDocumentQCServedForUserInteractor.ts index f3f7c51db52..9730f4dfc78 100644 --- a/web-api/src/business/useCases/workItems/getDocumentQCServedForUserInteractor.ts +++ b/web-api/src/business/useCases/workItems/getDocumentQCServedForUserInteractor.ts @@ -5,6 +5,7 @@ import { } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnauthorizedError } from '@web-api/errors/errors'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { WorkItem } from '../../../../../shared/src/business/entities/WorkItem'; /** @@ -17,10 +18,9 @@ import { WorkItem } from '../../../../../shared/src/business/entities/WorkItem'; export const getDocumentQCServedForUserInteractor = async ( applicationContext: ServerApplicationContext, { userId }: { userId: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.WORKITEM)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.WORKITEM)) { throw new UnauthorizedError('Unauthorized'); } @@ -32,10 +32,8 @@ export const getDocumentQCServedForUserInteractor = async ( }); const filteredWorkItems = workItems.filter(workItem => - user.role === ROLES.petitionsClerk ? !!workItem.section : true, + authorizedUser.role === ROLES.petitionsClerk ? !!workItem.section : true, ); - return WorkItem.validateRawCollection(filteredWorkItems, { - applicationContext, - }); + return WorkItem.validateRawCollection(filteredWorkItems); }; diff --git a/web-api/src/business/useCases/workItems/getWorkItemInteractor.test.ts b/web-api/src/business/useCases/workItems/getWorkItemInteractor.test.ts index 53b805d7b35..ed1010f4439 100644 --- a/web-api/src/business/useCases/workItems/getWorkItemInteractor.test.ts +++ b/web-api/src/business/useCases/workItems/getWorkItemInteractor.test.ts @@ -1,9 +1,10 @@ -import { - DOCKET_SECTION, - ROLES, -} from '../../../../../shared/src/business/entities/EntityConstants'; +import { DOCKET_SECTION } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { getWorkItemInteractor } from './getWorkItemInteractor'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; describe('getWorkItemInteractor', () => { let mockWorkItem = { @@ -28,26 +29,19 @@ describe('getWorkItemInteractor', () => { workItemId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', }; - const mockPetitionerUser = { - role: ROLES.petitioner, - userId: 'petitioner', - }; - - const mockDocketClerkUser = { - role: ROLES.docketClerk, - userId: 'docketclerk', - }; - it('throws an error if the work item was not found', async () => { - applicationContext.getCurrentUser.mockReturnValue(mockPetitionerUser); applicationContext .getPersistenceGateway() .getWorkItemById.mockResolvedValue(null); let error; try { - await getWorkItemInteractor(applicationContext, { - workItemId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + await getWorkItemInteractor( + applicationContext, + { + workItemId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockPetitionerUser, + ); } catch (e) { error = e; } @@ -55,16 +49,19 @@ describe('getWorkItemInteractor', () => { }); it('throws an error if the user does not have access to the work item', async () => { - applicationContext.getCurrentUser.mockReturnValue(mockPetitionerUser); applicationContext .getPersistenceGateway() .getWorkItemById.mockResolvedValue(mockWorkItem); let error; try { - await getWorkItemInteractor(applicationContext, { - workItemId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + await getWorkItemInteractor( + applicationContext, + { + workItemId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockPetitionerUser, + ); } catch (e) { error = e; } @@ -72,14 +69,17 @@ describe('getWorkItemInteractor', () => { }); it('successfully returns the work item for a docketclerk', async () => { - applicationContext.getCurrentUser.mockReturnValue(mockDocketClerkUser); applicationContext .getPersistenceGateway() .getWorkItemById.mockResolvedValue(mockWorkItem); - const result = await getWorkItemInteractor(applicationContext, { - workItemId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', - }); + const result = await getWorkItemInteractor( + applicationContext, + { + workItemId: 'c54ba5a9-b37b-479d-9201-067ec6e335bb', + }, + mockDocketClerkUser, + ); expect(result).toMatchObject({ docketEntry: { sentBy: 'petitioner' }, docketNumber: '101-18', diff --git a/web-api/src/business/useCases/workItems/getWorkItemInteractor.ts b/web-api/src/business/useCases/workItems/getWorkItemInteractor.ts index b524124150e..ded74818da2 100644 --- a/web-api/src/business/useCases/workItems/getWorkItemInteractor.ts +++ b/web-api/src/business/useCases/workItems/getWorkItemInteractor.ts @@ -4,6 +4,7 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { WorkItem } from '../../../../../shared/src/business/entities/WorkItem'; /** @@ -17,6 +18,7 @@ import { WorkItem } from '../../../../../shared/src/business/entities/WorkItem'; export const getWorkItemInteractor = async ( applicationContext: ServerApplicationContext, { workItemId }: { workItemId: string }, + authorizedUser: UnknownAuthUser, ) => { const workItem = await applicationContext .getPersistenceGateway() @@ -29,13 +31,15 @@ export const getWorkItemInteractor = async ( throw new NotFoundError(`WorkItem ${workItemId} was not found.`); } - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.WORKITEM, workItem.assigneeId)) { + if ( + !isAuthorized( + authorizedUser, + ROLE_PERMISSIONS.WORKITEM, + workItem.assigneeId, + ) + ) { throw new UnauthorizedError('Unauthorized'); } - return new WorkItem(workItem, { applicationContext }) - .validate() - .toRawObject(); + return new WorkItem(workItem).validate().toRawObject(); }; diff --git a/web-api/src/business/useCases/workItems/setWorkItemAsReadInteractor.test.ts b/web-api/src/business/useCases/workItems/setWorkItemAsReadInteractor.test.ts index b20c5552ced..2819573f75c 100644 --- a/web-api/src/business/useCases/workItems/setWorkItemAsReadInteractor.test.ts +++ b/web-api/src/business/useCases/workItems/setWorkItemAsReadInteractor.test.ts @@ -2,16 +2,17 @@ import { CASE_STATUS_TYPES, DOCKET_NUMBER_SUFFIXES, DOCKET_SECTION, - ROLES, } from '../../../../../shared/src/business/entities/EntityConstants'; import { MOCK_CASE } from '../../../../../shared/src/test/mockCase'; import { NotFoundError, UnauthorizedError } from '@web-api/errors/errors'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { setWorkItemAsReadInteractor } from './setWorkItemAsReadInteractor'; describe('setWorkItemAsReadInteractor', () => { - let user; - const mockWorkItem = { assigneeId: '8b4cd447-6278-461b-b62b-d9e357eea62c', assigneeName: 'bob', @@ -26,13 +27,6 @@ describe('setWorkItemAsReadInteractor', () => { }; beforeEach(() => { - user = { - role: ROLES.docketClerk, - userId: 'docketclerk', - }; - - applicationContext.getCurrentUser.mockImplementation(() => user); - applicationContext .getPersistenceGateway() .getWorkItemById.mockResolvedValue(mockWorkItem); @@ -48,14 +42,14 @@ describe('setWorkItemAsReadInteractor', () => { }); it('should throw an error when an unauthorized user tries to invoke this interactor', async () => { - user = { - userId: 'baduser', - }; - await expect( - setWorkItemAsReadInteractor(applicationContext, { - workItemId: mockWorkItem.workItemId, - }), + setWorkItemAsReadInteractor( + applicationContext, + { + workItemId: mockWorkItem.workItemId, + }, + mockPetitionerUser, + ), ).rejects.toThrow(UnauthorizedError); }); @@ -68,16 +62,24 @@ describe('setWorkItemAsReadInteractor', () => { }); await expect( - setWorkItemAsReadInteractor(applicationContext, { - workItemId: mockWorkItem.workItemId, - }), + setWorkItemAsReadInteractor( + applicationContext, + { + workItemId: mockWorkItem.workItemId, + }, + mockDocketClerkUser, + ), ).rejects.toThrow(NotFoundError); }); it('should call updateDocketEntry with the docket entry work item marked as read', async () => { - await setWorkItemAsReadInteractor(applicationContext, { - workItemId: mockWorkItem.workItemId, - }); + await setWorkItemAsReadInteractor( + applicationContext, + { + workItemId: mockWorkItem.workItemId, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().updateDocketEntry.mock @@ -88,9 +90,13 @@ describe('setWorkItemAsReadInteractor', () => { }); it('should call saveWorkItem with the work item marked as read', async () => { - await setWorkItemAsReadInteractor(applicationContext, { - workItemId: mockWorkItem.workItemId, - }); + await setWorkItemAsReadInteractor( + applicationContext, + { + workItemId: mockWorkItem.workItemId, + }, + mockDocketClerkUser, + ); expect( applicationContext.getPersistenceGateway().saveWorkItem.mock.calls[0][0], diff --git a/web-api/src/business/useCases/workItems/setWorkItemAsReadInteractor.ts b/web-api/src/business/useCases/workItems/setWorkItemAsReadInteractor.ts index 19ded896870..50bbe94c7e1 100644 --- a/web-api/src/business/useCases/workItems/setWorkItemAsReadInteractor.ts +++ b/web-api/src/business/useCases/workItems/setWorkItemAsReadInteractor.ts @@ -5,6 +5,7 @@ import { isAuthorized, } from '../../../../../shared/src/authorization/authorizationClientService'; import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; /** * setWorkItemAsReadInteractor @@ -17,10 +18,9 @@ import { ServerApplicationContext } from '@web-api/applicationContext'; export const setWorkItemAsReadInteractor = async ( applicationContext: ServerApplicationContext, { workItemId }: { workItemId: string }, + authorizedUser: UnknownAuthUser, ) => { - const user = applicationContext.getCurrentUser(); - - if (!isAuthorized(user, ROLE_PERMISSIONS.GET_READ_MESSAGES)) { + if (!isAuthorized(authorizedUser, ROLE_PERMISSIONS.GET_READ_MESSAGES)) { throw new UnauthorizedError('Unauthorized'); } @@ -38,7 +38,7 @@ export const setWorkItemAsReadInteractor = async ( docketNumber, }); - const caseEntity = new Case(caseRecord, { applicationContext }); + const caseEntity = new Case(caseRecord, { authorizedUser }); const docketEntryEntity = caseEntity.getDocketEntryById({ docketEntryId, diff --git a/web-api/src/dispatchers/ses/sendBulkTemplatedEmail.test.ts b/web-api/src/dispatchers/ses/sendBulkTemplatedEmail.test.ts index 7ccf4b12151..03ff8ca5995 100644 --- a/web-api/src/dispatchers/ses/sendBulkTemplatedEmail.test.ts +++ b/web-api/src/dispatchers/ses/sendBulkTemplatedEmail.test.ts @@ -130,6 +130,7 @@ describe('sendBulkTemplatedEmail', () => { await sendWithRetry({ applicationContext, params: { + DefaultTemplateData: undefined, Destinations: [ { Destination: { @@ -200,6 +201,7 @@ describe('sendBulkTemplatedEmail', () => { sendWithRetry({ applicationContext, params: { + DefaultTemplateData: undefined, Destinations: [ { Destination: { diff --git a/web-api/src/dispatchers/sns/sendNotificationOfSealing.ts b/web-api/src/dispatchers/sns/sendNotificationOfSealing.ts index d5589bef36b..5329a0fda24 100644 --- a/web-api/src/dispatchers/sns/sendNotificationOfSealing.ts +++ b/web-api/src/dispatchers/sns/sendNotificationOfSealing.ts @@ -3,13 +3,10 @@ import { ServerApplicationContext } from '@web-api/applicationContext'; export const sendNotificationOfSealing = async ( applicationContext: ServerApplicationContext, - { - docketEntryId, - docketNumber, - }: { docketEntryId: string; docketNumber: string }, + { docketNumber }: { docketNumber: string }, ): Promise => { const params = { - Message: JSON.stringify({ docketEntryId, docketNumber }), + Message: JSON.stringify({ docketNumber }), TopicArn: `arn:aws:sns:us-east-1:${process.env.AWS_ACCOUNT_ID}:seal_notifier`, }; @@ -22,7 +19,6 @@ export const sendNotificationOfSealing = async ( .getNotificationService() .send(publishCommand); applicationContext.logger.info('sent notification of sealing', { - docketEntryId, docketNumber, response, }); diff --git a/web-api/src/gateways/user/createUserLocal.ts b/web-api/src/gateways/user/createUserLocal.ts new file mode 100644 index 00000000000..9e91213a78e --- /dev/null +++ b/web-api/src/gateways/user/createUserLocal.ts @@ -0,0 +1,41 @@ +import { Role } from '@shared/business/entities/EntityConstants'; +import { ServerApplicationContext } from '@web-api/applicationContext'; +import { createUser } from '@web-api/gateways/user/createUser'; + +export async function createUserLocal( + applicationContext: ServerApplicationContext, + { + email, + name, + poolId, + role, + sendWelcomeEmail, + temporaryPassword, + userId, + }: { + email: string; + role: Role; + name: string; + userId: string; + poolId?: string; + temporaryPassword?: string; + sendWelcomeEmail: boolean; + }, +): Promise { + await createUser(applicationContext, { + email, + name, + poolId, + role, + sendWelcomeEmail, + temporaryPassword, + userId, + }); + + // Locally we need to store the user name in custom:name because of cognito-local + await applicationContext.getCognito().adminUpdateUserAttributes({ + UserAttributes: [{ Name: 'custom:name', Value: name }], + UserPoolId: poolId ?? applicationContext.environment.userPoolId, + Username: email.toLowerCase(), + }); +} diff --git a/web-api/src/gateways/user/signUpLocal.ts b/web-api/src/gateways/user/signUpLocal.ts new file mode 100644 index 00000000000..41944c8e608 --- /dev/null +++ b/web-api/src/gateways/user/signUpLocal.ts @@ -0,0 +1,39 @@ +import { Role } from '@shared/business/entities/EntityConstants'; +import { ServerApplicationContext } from '@web-api/applicationContext'; +import { signUp } from '@web-api/gateways/user/signUp'; + +export async function signUpLocal( + applicationContext: ServerApplicationContext, + { + email, + name, + password, + role, + }: { + password: string; + email: string; + name: string; + role: Role; + }, +): Promise<{ userId: string }> { + const userId = await signUp(applicationContext, { + email, + name, + password, + role, + }); + + // Locally we must set the custom:name attribute for cognito-local + await applicationContext.getCognito().adminUpdateUserAttributes({ + UserAttributes: [ + { + Name: 'custom:name', + Value: name, + }, + ], + UserPoolId: applicationContext.environment.userPoolId, + Username: email.toLowerCase(), + }); + + return userId; +} diff --git a/web-api/src/gateways/user/updateUser.test.ts b/web-api/src/gateways/user/updateUser.test.ts index fa9d82e02e0..76c7a076c40 100644 --- a/web-api/src/gateways/user/updateUser.test.ts +++ b/web-api/src/gateways/user/updateUser.test.ts @@ -60,6 +60,31 @@ describe('updateUser', () => { }); }); + it('should update the user`s name in persistence when it is provided as an attribute to update', async () => { + const mockUserPoolId = 'test'; + applicationContext.environment.UserPoolId = mockUserPoolId; + + await updateUser(applicationContext, { + attributesToUpdate: { + name: 'Tattersail', + }, + email: mockEmail, + }); + + expect( + applicationContext.getCognito().adminUpdateUserAttributes, + ).toHaveBeenCalledWith({ + UserAttributes: [ + { + Name: 'name', + Value: 'Tattersail', + }, + ], + UserPoolId: applicationContext.environment.userPoolId, + Username: mockLowerCasedEmail, + }); + }); + it('should update the user`s role and email in persistence when they are both provided as attributes to update', async () => { const mockUserPoolId = 'test'; applicationContext.environment.userPoolId = mockUserPoolId; diff --git a/web-api/src/gateways/user/updateUser.ts b/web-api/src/gateways/user/updateUser.ts index 210f52e4c18..443a4901cf4 100644 --- a/web-api/src/gateways/user/updateUser.ts +++ b/web-api/src/gateways/user/updateUser.ts @@ -5,6 +5,7 @@ import { ServerApplicationContext } from '@web-api/applicationContext'; interface UserAttributes { role?: Role; email?: string; + name?: string; } export async function updateUser( @@ -35,6 +36,13 @@ export async function updateUser( }); } + if (attributesToUpdate.name) { + formattedAttributesToUpdate.push({ + Name: 'name', + Value: attributesToUpdate.name, + }); + } + await applicationContext.getCognito().adminUpdateUserAttributes({ UserAttributes: formattedAttributesToUpdate, UserPoolId: poolId ?? applicationContext.environment.userPoolId, diff --git a/web-api/src/gateways/worker/worker.test.ts b/web-api/src/gateways/worker/worker.test.ts index bd541216976..474e1bb9c54 100644 --- a/web-api/src/gateways/worker/worker.test.ts +++ b/web-api/src/gateways/worker/worker.test.ts @@ -8,15 +8,16 @@ import { worker } from '@web-api/gateways/worker/worker'; describe('worker', () => { it('should use the messaging service to send the provided message to the environment`s message queue', async () => { const mockMessage: WorkerMessage = { + authorizedUser: { + email: 'person@hello.com', + name: 'ignored', + role: 'adc', + userId: 'ignored', + }, payload: { abc: 'def', }, type: MESSAGE_TYPES.QUEUE_UPDATE_ASSOCIATED_CASES, - user: { - name: 'ignored', - role: 'ignored', - userId: 'ignored', - }, }; const mockQueueUrl = 'www.send_a_message.com'; applicationContext.environment.workerQueueUrl = mockQueueUrl; diff --git a/web-api/src/gateways/worker/workerLocal.ts b/web-api/src/gateways/worker/workerLocal.ts index e9a18f162f5..458e8116ca2 100644 --- a/web-api/src/gateways/worker/workerLocal.ts +++ b/web-api/src/gateways/worker/workerLocal.ts @@ -13,7 +13,7 @@ export const workerLocal: WorkerHandler = async ( { message }: { message: WorkerMessage }, ): Promise => { // Simulate what happens on a deployed environment when a message is sent to SQS. - const appContext = createApplicationContext(message.user); + const appContext = createApplicationContext(message.authorizedUser); setTimeout( async () => { try { diff --git a/web-api/src/gateways/worker/workerRouter.test.ts b/web-api/src/gateways/worker/workerRouter.test.ts index 3d743173b02..29f5b13727a 100644 --- a/web-api/src/gateways/worker/workerRouter.test.ts +++ b/web-api/src/gateways/worker/workerRouter.test.ts @@ -4,10 +4,12 @@ import { workerRouter, } from '@web-api/gateways/worker/workerRouter'; import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; describe('workerRouter', () => { it('should make a call to update a user`s associated case when the message type is UPDATE_ASSOCIATED_CASE', async () => { const mockMessage: WorkerMessage = { + authorizedUser: mockDocketClerkUser, payload: { abc: '123', }, @@ -20,11 +22,16 @@ describe('workerRouter', () => { expect( applicationContext.getUseCases().updateAssociatedCaseWorker, - ).toHaveBeenCalledWith(applicationContext, mockMessage.payload); + ).toHaveBeenCalledWith( + applicationContext, + mockMessage.payload, + mockMessage.authorizedUser, + ); }); it('should make a call to queue a user`s associated cases for update when the message type is QUEUE_UPDATE_ASSOCIATED_CASES', async () => { const mockMessage: WorkerMessage = { + authorizedUser: mockDocketClerkUser, payload: { abc: '123', }, @@ -37,14 +44,20 @@ describe('workerRouter', () => { expect( applicationContext.getUseCases().queueUpdateAssociatedCasesWorker, - ).toHaveBeenCalledWith(applicationContext, mockMessage.payload); + ).toHaveBeenCalledWith( + applicationContext, + mockMessage.payload, + mockMessage.authorizedUser, + ); }); it('should throw an error when the message type provided was not recognized by the router', async () => { const mockMessage: WorkerMessage = { + authorizedUser: mockDocketClerkUser, payload: { abc: '123', }, + type: 'DOES_NOT_EXIST' as any, }; diff --git a/web-api/src/gateways/worker/workerRouter.ts b/web-api/src/gateways/worker/workerRouter.ts index bbf329ca265..c61b7316710 100644 --- a/web-api/src/gateways/worker/workerRouter.ts +++ b/web-api/src/gateways/worker/workerRouter.ts @@ -1,13 +1,10 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { ServerApplicationContext } from '@web-api/applicationContext'; export type WorkerMessage = { payload: any; type: WorkerMessageType; - user: { - role: string; - userId: string; - name: string; - }; + authorizedUser: AuthUser; }; export const MESSAGE_TYPES = { @@ -30,12 +27,20 @@ export const workerRouter = async ( case MESSAGE_TYPES.UPDATE_ASSOCIATED_CASE: await applicationContext .getUseCases() - .updateAssociatedCaseWorker(applicationContext, message.payload); + .updateAssociatedCaseWorker( + applicationContext, + message.payload, + message.authorizedUser, + ); break; case MESSAGE_TYPES.QUEUE_UPDATE_ASSOCIATED_CASES: await applicationContext .getUseCases() - .queueUpdateAssociatedCasesWorker(applicationContext, message.payload); + .queueUpdateAssociatedCasesWorker( + applicationContext, + message.payload, + message.authorizedUser, + ); break; default: throw new Error( diff --git a/web-api/src/genericHandler.test.ts b/web-api/src/genericHandler.test.ts index 420b66e5e2a..1d363f9aea3 100644 --- a/web-api/src/genericHandler.test.ts +++ b/web-api/src/genericHandler.test.ts @@ -28,6 +28,12 @@ jest.mock('./applicationContext', () => ({ }, })); +jest.mock('./applicationContext', () => ({ + createApplicationContext: () => { + return mockApplicationContext; + }, +})); + // Suppress console output in test runner (RAE SAID THIS WOULD BE COOL) console.error = () => null; console.info = () => null; diff --git a/web-api/src/getUserGateway.ts b/web-api/src/getUserGateway.ts index be10e62d245..0f4e50f9433 100644 --- a/web-api/src/getUserGateway.ts +++ b/web-api/src/getUserGateway.ts @@ -1,13 +1,16 @@ import { changePassword } from '@web-api/gateways/user/changePassword'; import { confirmSignUp } from '@web-api/gateways/user/confirmSignUp'; import { createUser } from '@web-api/gateways/user/createUser'; +import { createUserLocal } from '@web-api/gateways/user/createUserLocal'; import { disableUser } from '@web-api/gateways/user/disableUser'; +import { environment } from '@web-api/environment'; import { forgotPassword } from '@web-api/gateways/user/forgotPassword'; import { getUserByEmail } from '@web-api/gateways/user/getUserByEmail'; import { initiateAuth } from '@web-api/gateways/user/initiateAuth'; import { renewIdToken } from '@web-api/gateways/user/renewIdToken'; import { resendTemporaryPassword } from '@web-api/business/useCaseHelper/auth/resendTemporaryPassword'; import { signUp } from '@web-api/gateways/user/signUp'; +import { signUpLocal } from '@web-api/gateways/user/signUpLocal'; import { updateUser } from '@web-api/gateways/user/updateUser'; /* @@ -18,13 +21,13 @@ We need to lowercase the email address as we currently have a case SENSITIVE Use export const getUserGateway = () => ({ changePassword, confirmSignUp, - createUser, + createUser: environment.stage === 'local' ? createUserLocal : createUser, disableUser, forgotPassword, getUserByEmail, initiateAuth, renewIdToken, resendTemporaryPassword, - signUp, + signUp: environment.stage === 'local' ? signUpLocal : signUp, updateUser, }); diff --git a/web-api/src/lambdaWrapper.ts b/web-api/src/lambdaWrapper.ts index 03b943af5e2..6d9bc78bec8 100644 --- a/web-api/src/lambdaWrapper.ts +++ b/web-api/src/lambdaWrapper.ts @@ -1,3 +1,4 @@ +import { ServerApplicationContext } from '@web-api/applicationContext'; import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { get } from 'lodash'; import { getCurrentInvoke } from '@vendia/serverless-express'; @@ -22,7 +23,7 @@ const defaultOptions: { export const lambdaWrapper = ( lambda: (awsEvent: any, user?: UnknownAuthUser) => any, options = defaultOptions, - applicationContext?: IApplicationContext, + applicationContext?: ServerApplicationContext, ) => { return async (req, res) => { // 'shouldMimicApiGatewayAsyncEndpoint' flag is set to mimic how API gateway async endpoints work locally. @@ -65,7 +66,7 @@ export const lambdaWrapper = ( const { asyncsyncid } = req.headers; - if (options.isAsyncSync && asyncsyncid && applicationContext) { + if (options.isAsyncSync && asyncsyncid && applicationContext && user) { try { const fullResponse = { ...response, diff --git a/web-api/src/lambdas/auth/forgotPasswordLambda.ts b/web-api/src/lambdas/auth/forgotPasswordLambda.ts index 8607772557f..a72595b61f9 100644 --- a/web-api/src/lambdas/auth/forgotPasswordLambda.ts +++ b/web-api/src/lambdas/auth/forgotPasswordLambda.ts @@ -1,11 +1,10 @@ import { APIGatewayProxyEvent } from 'aws-lambda'; +import { forgotPasswordInteractor } from '@web-api/business/useCases/auth/forgotPasswordInteractor'; import { genericHandler } from '../../genericHandler'; export const forgotPasswordLambda = (event: APIGatewayProxyEvent) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .forgotPasswordInteractor(applicationContext, { - ...JSON.parse(event.body!), - }); + return await forgotPasswordInteractor(applicationContext, { + ...JSON.parse(event.body!), + }); }); diff --git a/web-api/src/lambdas/caseAssociations/generateEntryOfAppearancePdfLambda.ts b/web-api/src/lambdas/caseAssociations/generateEntryOfAppearancePdfLambda.ts index cbf926e3c02..c739dfc893d 100644 --- a/web-api/src/lambdas/caseAssociations/generateEntryOfAppearancePdfLambda.ts +++ b/web-api/src/lambdas/caseAssociations/generateEntryOfAppearancePdfLambda.ts @@ -1,11 +1,18 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { generateEntryOfAppearancePdfInteractor } from '@web-api/business/useCases/caseAssociationRequest/generateEntryOfAppearancePdfInteractor'; import { genericHandler } from '../../genericHandler'; -export const generateEntryOfAppearancePdfLambda = event => +export const generateEntryOfAppearancePdfLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .generateEntryOfAppearancePdfInteractor(applicationContext, { + return await generateEntryOfAppearancePdfInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/caseDeadline/createCaseDeadlineLambda.ts b/web-api/src/lambdas/caseDeadline/createCaseDeadlineLambda.ts index 0598fb633ea..df7d5bcf26b 100644 --- a/web-api/src/lambdas/caseDeadline/createCaseDeadlineLambda.ts +++ b/web-api/src/lambdas/caseDeadline/createCaseDeadlineLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { createCaseDeadlineInteractor } from '@web-api/business/useCases/caseDeadline/createCaseDeadlineInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const createCaseDeadlineLambda = event => +export const createCaseDeadlineLambda = ( + event, + authorizedUser: UnknownAuthUser, +): Promise => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .createCaseDeadlineInteractor(applicationContext, { + return await createCaseDeadlineInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/caseDeadline/deleteCaseDeadlineLambda.ts b/web-api/src/lambdas/caseDeadline/deleteCaseDeadlineLambda.ts index ae0556e68b9..3ea5d69a110 100644 --- a/web-api/src/lambdas/caseDeadline/deleteCaseDeadlineLambda.ts +++ b/web-api/src/lambdas/caseDeadline/deleteCaseDeadlineLambda.ts @@ -1,3 +1,4 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +7,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const deleteCaseDeadlineLambda = event => +export const deleteCaseDeadlineLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .deleteCaseDeadlineInteractor(applicationContext, { + return await applicationContext.getUseCases().deleteCaseDeadlineInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/caseDeadline/getCaseDeadlinesForCaseLambda.ts b/web-api/src/lambdas/caseDeadline/getCaseDeadlinesForCaseLambda.ts index 8105dac5a3a..0ae0f2d30bd 100644 --- a/web-api/src/lambdas/caseDeadline/getCaseDeadlinesForCaseLambda.ts +++ b/web-api/src/lambdas/caseDeadline/getCaseDeadlinesForCaseLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { getCaseDeadlinesForCaseInteractor } from '@web-api/business/useCases/caseDeadline/getCaseDeadlinesForCaseInteractor'; /** * get case deadlines for case @@ -8,9 +9,7 @@ import { genericHandler } from '../../genericHandler'; */ export const getCaseDeadlinesForCaseLambda = event => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getCaseDeadlinesForCaseInteractor(applicationContext, { - docketNumber: event.pathParameters.docketNumber, - }); + return await getCaseDeadlinesForCaseInteractor(applicationContext, { + docketNumber: event.pathParameters.docketNumber, + }); }); diff --git a/web-api/src/lambdas/caseDeadline/getCaseDeadlinesLambda.ts b/web-api/src/lambdas/caseDeadline/getCaseDeadlinesLambda.ts index 351b6022878..6a740de6e92 100644 --- a/web-api/src/lambdas/caseDeadline/getCaseDeadlinesLambda.ts +++ b/web-api/src/lambdas/caseDeadline/getCaseDeadlinesLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getCaseDeadlinesInteractor } from '@shared/business/useCases/getCaseDeadlinesInteractor'; /** * get case deadlines between start and end date @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getCaseDeadlinesLambda = event => +export const getCaseDeadlinesLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getCaseDeadlinesInteractor(applicationContext, { + return await getCaseDeadlinesInteractor( + applicationContext, + { ...event.queryStringParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/caseDeadline/updateCaseDeadlineLambda.ts b/web-api/src/lambdas/caseDeadline/updateCaseDeadlineLambda.ts index 0704e546cc1..531ad482094 100644 --- a/web-api/src/lambdas/caseDeadline/updateCaseDeadlineLambda.ts +++ b/web-api/src/lambdas/caseDeadline/updateCaseDeadlineLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateCaseDeadlineInteractor } from '@web-api/business/useCases/caseDeadline/updateCaseDeadlineInteractor'; /** * update case deadline @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateCaseDeadlineLambda = event => +export const updateCaseDeadlineLambda = ( + event, + authorizedUser: UnknownAuthUser, +): Promise => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateCaseDeadlineInteractor(applicationContext, { + return await updateCaseDeadlineInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/caseNote/deleteCaseNoteLambda.ts b/web-api/src/lambdas/caseNote/deleteCaseNoteLambda.ts index 62554b4264d..80c446126a6 100644 --- a/web-api/src/lambdas/caseNote/deleteCaseNoteLambda.ts +++ b/web-api/src/lambdas/caseNote/deleteCaseNoteLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { deleteCaseNoteInteractor } from '@web-api/business/useCases/caseNote/deleteCaseNoteInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,13 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const deleteCaseNoteLambda = event => +export const deleteCaseNoteLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .deleteCaseNoteInteractor(applicationContext, { + return await deleteCaseNoteInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/caseNote/deleteUserCaseNoteLambda.ts b/web-api/src/lambdas/caseNote/deleteUserCaseNoteLambda.ts index eaa8d5efdf6..da88c4e550e 100644 --- a/web-api/src/lambdas/caseNote/deleteUserCaseNoteLambda.ts +++ b/web-api/src/lambdas/caseNote/deleteUserCaseNoteLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { deleteUserCaseNoteInteractor } from '@web-api/business/useCases/caseNote/deleteUserCaseNoteInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const deleteUserCaseNoteLambda = event => +export const deleteUserCaseNoteLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .deleteUserCaseNoteInteractor(applicationContext, { + return await deleteUserCaseNoteInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/caseNote/getUserCaseNoteForCasesLambda.ts b/web-api/src/lambdas/caseNote/getUserCaseNoteForCasesLambda.ts index ba2ffd2dc07..3d535fc9cf0 100644 --- a/web-api/src/lambdas/caseNote/getUserCaseNoteForCasesLambda.ts +++ b/web-api/src/lambdas/caseNote/getUserCaseNoteForCasesLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getUserCaseNoteForCasesInteractor } from '@web-api/business/useCases/caseNote/getUserCaseNoteForCasesInteractor'; /** * used for fetching a judge's case note @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getUserCaseNoteForCasesLambda = event => +export const getUserCaseNoteForCasesLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getUserCaseNoteForCasesInteractor(applicationContext, { + return await getUserCaseNoteForCasesInteractor( + applicationContext, + { docketNumbers: JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/caseNote/getUserCaseNoteLambda.ts b/web-api/src/lambdas/caseNote/getUserCaseNoteLambda.ts index c5b62cff9ac..2372fddb30d 100644 --- a/web-api/src/lambdas/caseNote/getUserCaseNoteLambda.ts +++ b/web-api/src/lambdas/caseNote/getUserCaseNoteLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getUserCaseNoteInteractor } from '@web-api/business/useCases/caseNote/getUserCaseNoteInteractor'; /** * used for fetching a judge's case note @@ -6,11 +8,13 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getUserCaseNoteLambda = event => +export const getUserCaseNoteLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getUserCaseNoteInteractor(applicationContext, { + return await getUserCaseNoteInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/caseNote/saveCaseNoteLambda.ts b/web-api/src/lambdas/caseNote/saveCaseNoteLambda.ts index 9362e4dba10..dfb5034b4e0 100644 --- a/web-api/src/lambdas/caseNote/saveCaseNoteLambda.ts +++ b/web-api/src/lambdas/caseNote/saveCaseNoteLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { saveCaseNoteInteractor } from '@web-api/business/useCases/caseNote/saveCaseNoteInteractor'; /** * used for saving a case note @@ -6,16 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const saveCaseNoteLambda = event => +export const saveCaseNoteLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { const lambdaArguments = { ...event.pathParameters, ...JSON.parse(event.body), }; - return await applicationContext - .getUseCases() - .saveCaseNoteInteractor(applicationContext, { + return await saveCaseNoteInteractor( + applicationContext, + { ...lambdaArguments, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/caseNote/updateUserCaseNoteLambda.ts b/web-api/src/lambdas/caseNote/updateUserCaseNoteLambda.ts index 68bdad9a9ad..6d53bfaffc0 100644 --- a/web-api/src/lambdas/caseNote/updateUserCaseNoteLambda.ts +++ b/web-api/src/lambdas/caseNote/updateUserCaseNoteLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateUserCaseNoteInteractor } from '@web-api/business/useCases/caseNote/updateUserCaseNoteInteractor'; /** * used for updating a judge's case note @@ -6,16 +8,21 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateUserCaseNoteLambda = event => +export const updateUserCaseNoteLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const lambdaArguments = { ...event.pathParameters, ...JSON.parse(event.body), }; - return await applicationContext - .getUseCases() - .updateUserCaseNoteInteractor(applicationContext, { + return await updateUserCaseNoteInteractor( + applicationContext, + { ...lambdaArguments, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/caseWorksheet/updateCaseWorksheetLambda.ts b/web-api/src/lambdas/caseWorksheet/updateCaseWorksheetLambda.ts index eef00889cb0..6eac6e3aa84 100644 --- a/web-api/src/lambdas/caseWorksheet/updateCaseWorksheetLambda.ts +++ b/web-api/src/lambdas/caseWorksheet/updateCaseWorksheetLambda.ts @@ -1,11 +1,15 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateCaseWorksheetInteractor } from '@web-api/business/useCases/caseWorksheet/updateCaseWorksheetInteractor'; -export const updateCaseWorksheetLambda = event => +export const updateCaseWorksheetLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateCaseWorksheetInteractor( - applicationContext, - JSON.parse(event.body), - ); + return await updateCaseWorksheetInteractor( + applicationContext, + JSON.parse(event.body), + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/addConsolidatedCaseLambda.ts b/web-api/src/lambdas/cases/addConsolidatedCaseLambda.ts index a6ff64e6dcf..e7083a4c647 100644 --- a/web-api/src/lambdas/cases/addConsolidatedCaseLambda.ts +++ b/web-api/src/lambdas/cases/addConsolidatedCaseLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { addConsolidatedCaseInteractor } from '@web-api/business/useCases/caseConsolidation/addConsolidatedCaseInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const addConsolidatedCaseLambda = event => +export const addConsolidatedCaseLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - await applicationContext - .getUseCases() - .addConsolidatedCaseInteractor(applicationContext, { + await addConsolidatedCaseInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/addDeficiencyStatisticLambda.ts b/web-api/src/lambdas/cases/addDeficiencyStatisticLambda.ts index a0dba962efd..b28c16596d8 100644 --- a/web-api/src/lambdas/cases/addDeficiencyStatisticLambda.ts +++ b/web-api/src/lambdas/cases/addDeficiencyStatisticLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { addDeficiencyStatisticInteractor } from '@web-api/business/useCases/caseStatistics/addDeficiencyStatisticInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const addDeficiencyStatisticLambda = event => +export const addDeficiencyStatisticLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .addDeficiencyStatisticInteractor(applicationContext, { + return await addDeficiencyStatisticInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/addPetitionerToCaseLambda.ts b/web-api/src/lambdas/cases/addPetitionerToCaseLambda.ts index 8145f878bec..b0dd30aee8d 100644 --- a/web-api/src/lambdas/cases/addPetitionerToCaseLambda.ts +++ b/web-api/src/lambdas/cases/addPetitionerToCaseLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { addPetitionerToCaseInteractor } from '@web-api/business/useCases/addPetitionerToCaseInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const addPetitionerToCaseLambda = event => +export const addPetitionerToCaseLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .addPetitionerToCaseInteractor(applicationContext, { + return await addPetitionerToCaseInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/blockCaseFromTrialLambda.ts b/web-api/src/lambdas/cases/blockCaseFromTrialLambda.ts index 5c0ba669591..eeef043aa19 100644 --- a/web-api/src/lambdas/cases/blockCaseFromTrialLambda.ts +++ b/web-api/src/lambdas/cases/blockCaseFromTrialLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { blockCaseFromTrialInteractor } from '@web-api/business/useCases/blockCaseFromTrialInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,16 +8,21 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const blockCaseFromTrialLambda = event => +export const blockCaseFromTrialLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const lambdaArguments = { ...event.pathParameters, ...JSON.parse(event.body), }; - return await applicationContext - .getUseCases() - .blockCaseFromTrialInteractor(applicationContext, { + return await blockCaseFromTrialInteractor( + applicationContext, + { ...lambdaArguments, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/caseAdvancedSearchLambda.ts b/web-api/src/lambdas/cases/caseAdvancedSearchLambda.ts index 99af569db6e..d355ba43abf 100644 --- a/web-api/src/lambdas/cases/caseAdvancedSearchLambda.ts +++ b/web-api/src/lambdas/cases/caseAdvancedSearchLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { caseAdvancedSearchInteractor } from '@web-api/business/useCases/caseAdvancedSearchInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const caseAdvancedSearchLambda = event => +export const caseAdvancedSearchLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .caseAdvancedSearchInteractor(applicationContext, { + return await caseAdvancedSearchInteractor( + applicationContext, + { ...event.queryStringParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/checkForReadyForTrialCasesLambda.ts b/web-api/src/lambdas/cases/checkForReadyForTrialCasesLambda.ts index 4f2d5831d4c..f7756019f19 100644 --- a/web-api/src/lambdas/cases/checkForReadyForTrialCasesLambda.ts +++ b/web-api/src/lambdas/cases/checkForReadyForTrialCasesLambda.ts @@ -1,3 +1,4 @@ +import { checkForReadyForTrialCasesInteractor } from '@web-api/business/useCases/checkForReadyForTrialCasesInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -8,7 +9,5 @@ import { genericHandler } from '../../genericHandler'; */ export const checkForReadyForTrialCasesLambda = event => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .checkForReadyForTrialCasesInteractor(applicationContext); + return await checkForReadyForTrialCasesInteractor(applicationContext); }); diff --git a/web-api/src/lambdas/cases/createCaseFromPaperLambda.ts b/web-api/src/lambdas/cases/createCaseFromPaperLambda.ts index 17409c6c41b..40aefdc7ef6 100644 --- a/web-api/src/lambdas/cases/createCaseFromPaperLambda.ts +++ b/web-api/src/lambdas/cases/createCaseFromPaperLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { createCaseFromPaperInteractor } from '@web-api/business/useCases/createCaseFromPaperInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const createCaseFromPaperLambda = event => +export const createCaseFromPaperLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .createCaseFromPaperInteractor(applicationContext, { + return await createCaseFromPaperInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/createCaseLambda.ts b/web-api/src/lambdas/cases/createCaseLambda.ts index 715b791be7e..d3665029342 100644 --- a/web-api/src/lambdas/cases/createCaseLambda.ts +++ b/web-api/src/lambdas/cases/createCaseLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { createCaseInteractor } from '@web-api/business/useCases/createCaseInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,13 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const createCaseLambda = event => +export const createCaseLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .createCaseInteractor(applicationContext, { + return await createCaseInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/deleteCounselFromCaseLambda.ts b/web-api/src/lambdas/cases/deleteCounselFromCaseLambda.ts index 29afcb34f19..ca48af23c67 100644 --- a/web-api/src/lambdas/cases/deleteCounselFromCaseLambda.ts +++ b/web-api/src/lambdas/cases/deleteCounselFromCaseLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { deleteCounselFromCaseInteractor } from '@web-api/business/useCases/caseAssociation/deleteCounselFromCaseInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const deleteCounselFromCaseLambda = event => +export const deleteCounselFromCaseLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .deleteCounselFromCaseInteractor(applicationContext, { + return await deleteCounselFromCaseInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/deleteDeficiencyStatisticLambda.ts b/web-api/src/lambdas/cases/deleteDeficiencyStatisticLambda.ts index dc4e82af4fb..cf61d46309d 100644 --- a/web-api/src/lambdas/cases/deleteDeficiencyStatisticLambda.ts +++ b/web-api/src/lambdas/cases/deleteDeficiencyStatisticLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { deleteDeficiencyStatisticInteractor } from '@web-api/business/useCases/caseStatistics/deleteDeficiencyStatisticInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const deleteDeficiencyStatisticLambda = event => +export const deleteDeficiencyStatisticLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .deleteDeficiencyStatisticInteractor(applicationContext, { + return await deleteDeficiencyStatisticInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/fileAndServeCourtIssuedDocumentLambda.ts b/web-api/src/lambdas/cases/fileAndServeCourtIssuedDocumentLambda.ts index 3f6f492340f..8c23940583b 100644 --- a/web-api/src/lambdas/cases/fileAndServeCourtIssuedDocumentLambda.ts +++ b/web-api/src/lambdas/cases/fileAndServeCourtIssuedDocumentLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { fileAndServeCourtIssuedDocumentInteractor } from '@web-api/business/useCases/courtIssuedDocument/fileAndServeCourtIssuedDocumentInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const fileAndServeCourtIssuedDocumentLambda = event => +export const fileAndServeCourtIssuedDocumentLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .fileAndServeCourtIssuedDocumentInteractor(applicationContext, { + return await fileAndServeCourtIssuedDocumentInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/generateDocketRecordPdfLambda.ts b/web-api/src/lambdas/cases/generateDocketRecordPdfLambda.ts index 194ce469a38..4f30cca0592 100644 --- a/web-api/src/lambdas/cases/generateDocketRecordPdfLambda.ts +++ b/web-api/src/lambdas/cases/generateDocketRecordPdfLambda.ts @@ -1,19 +1,21 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { generateDocketRecordPdfInteractor } from '@web-api/business/useCases/generateDocketRecordPdfInteractor'; import { genericHandler } from '../../genericHandler'; -/** - * used for generating a printable PDF of a docket record - * @param {object} event the AWS event object - * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers - */ -export const generateDocketRecordPdfLambda = event => +export const generateDocketRecordPdfLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .generateDocketRecordPdfInteractor(applicationContext, { + return await generateDocketRecordPdfInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/cases/generatePetitionPdfLambda.ts b/web-api/src/lambdas/cases/generatePetitionPdfLambda.ts index 1302df816d2..3a57d36cfcb 100644 --- a/web-api/src/lambdas/cases/generatePetitionPdfLambda.ts +++ b/web-api/src/lambdas/cases/generatePetitionPdfLambda.ts @@ -1,11 +1,18 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { generatePetitionPdfInteractor } from '@shared/business/useCases/generatePetitionPdfInteractor'; import { genericHandler } from '../../genericHandler'; -export const generatePetitionPdfLambda = event => +export const generatePetitionPdfLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .generatePetitionPdfInteractor(applicationContext, { + return await generatePetitionPdfInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/generatePractitionerCaseListPdfLambda.ts b/web-api/src/lambdas/cases/generatePractitionerCaseListPdfLambda.ts index be3443f33d4..06444e2daab 100644 --- a/web-api/src/lambdas/cases/generatePractitionerCaseListPdfLambda.ts +++ b/web-api/src/lambdas/cases/generatePractitionerCaseListPdfLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { generatePractitionerCaseListPdfInteractor } from '@shared/business/useCases/generatePractitionerCaseListPdfInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,17 +8,22 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const generatePractitionerCaseListPdfLambda = event => +export const generatePractitionerCaseListPdfLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler( event, async ({ applicationContext }) => { const { userId } = event.pathParameters; - return await applicationContext - .getUseCases() - .generatePractitionerCaseListPdfInteractor(applicationContext, { + return await generatePractitionerCaseListPdfInteractor( + applicationContext, + { userId, - }); + }, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/cases/getCaseExistsLambda.ts b/web-api/src/lambdas/cases/getCaseExistsLambda.ts index 276c7b1ebeb..649587c0a4b 100644 --- a/web-api/src/lambdas/cases/getCaseExistsLambda.ts +++ b/web-api/src/lambdas/cases/getCaseExistsLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { getCaseExistsInteractor } from '@shared/business/useCases/getCaseExistsInteractor'; /** * used for fetching existence of a single case @@ -8,9 +9,7 @@ import { genericHandler } from '../../genericHandler'; */ export const getCaseExistsLambda = event => genericHandler(event, ({ applicationContext }) => - applicationContext - .getUseCases() - .getCaseExistsInteractor(applicationContext, { - docketNumber: event.pathParameters.docketNumber, - }), + getCaseExistsInteractor(applicationContext, { + docketNumber: event.pathParameters.docketNumber, + }), ); diff --git a/web-api/src/lambdas/cases/getCaseLambda.ts b/web-api/src/lambdas/cases/getCaseLambda.ts index b62f7cb3847..5875e40cf0e 100644 --- a/web-api/src/lambdas/cases/getCaseLambda.ts +++ b/web-api/src/lambdas/cases/getCaseLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getCaseInteractor } from '@shared/business/useCases/getCaseInteractor'; /** * used for fetching a single case @@ -6,9 +8,13 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getCaseLambda = event => +export const getCaseLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, ({ applicationContext }) => - applicationContext.getUseCases().getCaseInteractor(applicationContext, { - docketNumber: event.pathParameters.docketNumber, - }), + getCaseInteractor( + applicationContext, + { + docketNumber: event.pathParameters.docketNumber, + }, + authorizedUser, + ), ); diff --git a/web-api/src/lambdas/cases/getCasesForUserLambda.ts b/web-api/src/lambdas/cases/getCasesForUserLambda.ts index d6c5f2583f4..c9ceaedcec3 100644 --- a/web-api/src/lambdas/cases/getCasesForUserLambda.ts +++ b/web-api/src/lambdas/cases/getCasesForUserLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getCasesForUserInteractor } from '@shared/business/useCases/getCasesForUserInteractor'; /** * used for fetching all open and closed cases for a particular user @@ -6,9 +8,7 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getCasesForUserLambda = event => +export const getCasesForUserLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getCasesForUserInteractor(applicationContext); + return await getCasesForUserInteractor(applicationContext, authorizedUser); }); diff --git a/web-api/src/lambdas/cases/prioritizeCaseLambda.ts b/web-api/src/lambdas/cases/prioritizeCaseLambda.ts index f46596591e6..67bc946aa71 100644 --- a/web-api/src/lambdas/cases/prioritizeCaseLambda.ts +++ b/web-api/src/lambdas/cases/prioritizeCaseLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { prioritizeCaseInteractor } from '@shared/business/useCases/prioritizeCaseInteractor'; /** * used for prioritizing a case @@ -6,12 +8,14 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const prioritizeCaseLambda = event => +export const prioritizeCaseLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .prioritizeCaseInteractor(applicationContext, { + return await prioritizeCaseInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/privatePractitionerCaseAssociationLambda.ts b/web-api/src/lambdas/cases/privatePractitionerCaseAssociationLambda.ts index ec4be8fdf4f..7f5a71f8d91 100644 --- a/web-api/src/lambdas/cases/privatePractitionerCaseAssociationLambda.ts +++ b/web-api/src/lambdas/cases/privatePractitionerCaseAssociationLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { submitCaseAssociationRequestInteractor } from '@web-api/business/useCases/caseAssociationRequest/submitCaseAssociationRequestInteractor'; /** * lambda which is used for associating a user to a case @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const privatePractitionerCaseAssociationLambda = event => +export const privatePractitionerCaseAssociationLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .submitCaseAssociationRequestInteractor(applicationContext, { + return await submitCaseAssociationRequestInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/privatePractitionerPendingCaseAssociationLambda.ts b/web-api/src/lambdas/cases/privatePractitionerPendingCaseAssociationLambda.ts index 3405d9f8d53..1fe188df87f 100644 --- a/web-api/src/lambdas/cases/privatePractitionerPendingCaseAssociationLambda.ts +++ b/web-api/src/lambdas/cases/privatePractitionerPendingCaseAssociationLambda.ts @@ -1,3 +1,4 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +7,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const privatePractitionerPendingCaseAssociationLambda = event => +export const privatePractitionerPendingCaseAssociationLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { return await applicationContext .getUseCases() - .submitPendingCaseAssociationRequestInteractor(applicationContext, { - ...event.pathParameters, - }); + .submitPendingCaseAssociationRequestInteractor( + applicationContext, + { + ...event.pathParameters, + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/removeCasePendingItemLambda.ts b/web-api/src/lambdas/cases/removeCasePendingItemLambda.ts index 38e232438af..b0372be16a2 100644 --- a/web-api/src/lambdas/cases/removeCasePendingItemLambda.ts +++ b/web-api/src/lambdas/cases/removeCasePendingItemLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { removeCasePendingItemInteractor } from '@shared/business/useCases/removeCasePendingItemInteractor'; /** * used for removing pending items from a case @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const removeCasePendingItemLambda = event => +export const removeCasePendingItemLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .removeCasePendingItemInteractor(applicationContext, { + return await removeCasePendingItemInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/removeConsolidatedCasesLambda.ts b/web-api/src/lambdas/cases/removeConsolidatedCasesLambda.ts index 119ddf18757..88583893f18 100644 --- a/web-api/src/lambdas/cases/removeConsolidatedCasesLambda.ts +++ b/web-api/src/lambdas/cases/removeConsolidatedCasesLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { removeConsolidatedCasesInteractor } from '@web-api/business/useCases/caseConsolidation/removeConsolidatedCasesInteractor'; /** * used for removing cases from consolidation @@ -6,16 +8,21 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const removeConsolidatedCasesLambda = event => +export const removeConsolidatedCasesLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const docketNumbersToRemove = ( event.queryStringParameters.docketNumbersToRemove || '' ).split(','); - return await applicationContext - .getUseCases() - .removeConsolidatedCasesInteractor(applicationContext, { + return await removeConsolidatedCasesInteractor( + applicationContext, + { ...event.pathParameters, docketNumbersToRemove, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/removePetitionerAndUpdateCaptionLambda.ts b/web-api/src/lambdas/cases/removePetitionerAndUpdateCaptionLambda.ts index 5e9d729661a..15ed5034326 100644 --- a/web-api/src/lambdas/cases/removePetitionerAndUpdateCaptionLambda.ts +++ b/web-api/src/lambdas/cases/removePetitionerAndUpdateCaptionLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { removePetitionerAndUpdateCaptionInteractor } from '@shared/business/useCases/removePetitionerAndUpdateCaptionInteractor'; /** * lambda which is used for removing a petitioner from a case @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const removePetitionerAndUpdateCaptionLambda = event => +export const removePetitionerAndUpdateCaptionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .removePetitionerAndUpdateCaptionInteractor(applicationContext, { + return await removePetitionerAndUpdateCaptionInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/saveCaseDetailInternalEditLambda.ts b/web-api/src/lambdas/cases/saveCaseDetailInternalEditLambda.ts index bfb72dacb00..e0741e6bd3d 100644 --- a/web-api/src/lambdas/cases/saveCaseDetailInternalEditLambda.ts +++ b/web-api/src/lambdas/cases/saveCaseDetailInternalEditLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { saveCaseDetailInternalEditInteractor } from '@shared/business/useCases/saveCaseDetailInternalEditInteractor'; /** * used for updating a case @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const saveCaseDetailInternalEditLambda = event => +export const saveCaseDetailInternalEditLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .saveCaseDetailInternalEditInteractor(applicationContext, { + return await saveCaseDetailInternalEditInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), caseToUpdate: JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/sealCaseContactAddressLambda.ts b/web-api/src/lambdas/cases/sealCaseContactAddressLambda.ts index 3144fcdb0a4..4d4ecd199ed 100644 --- a/web-api/src/lambdas/cases/sealCaseContactAddressLambda.ts +++ b/web-api/src/lambdas/cases/sealCaseContactAddressLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { sealCaseContactAddressInteractor } from '@shared/business/useCases/sealCaseContactAddressInteractor'; /** * used for sealing an address on a case @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const sealCaseContactAddressLambda = event => +export const sealCaseContactAddressLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .sealCaseContactAddressInteractor(applicationContext, { + return await sealCaseContactAddressInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/sealCaseLambda.ts b/web-api/src/lambdas/cases/sealCaseLambda.ts index 87ad9d7b757..58531d3f3be 100644 --- a/web-api/src/lambdas/cases/sealCaseLambda.ts +++ b/web-api/src/lambdas/cases/sealCaseLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { sealCaseInteractor } from '@shared/business/useCases/sealCaseInteractor'; /** * used for marking a case as sealed @@ -6,11 +8,13 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const sealCaseLambda = event => +export const sealCaseLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .sealCaseInteractor(applicationContext, { + return await sealCaseInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/sealInLowerEnvironmentLambda.ts b/web-api/src/lambdas/cases/sealInLowerEnvironmentLambda.ts index 7cadad35c4f..694b9a4fb56 100644 --- a/web-api/src/lambdas/cases/sealInLowerEnvironmentLambda.ts +++ b/web-api/src/lambdas/cases/sealInLowerEnvironmentLambda.ts @@ -1,4 +1,6 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { createApplicationContext } from '../../applicationContext'; +import { sealInLowerEnvironment } from '@web-api/business/useCaseHelper/sealInLowerEnvironment'; /** * used for retroactively sealing a case in a lower environment after it is sealed in the Production environment @@ -7,7 +9,12 @@ import { createApplicationContext } from '../../applicationContext'; * @returns {Promise<*>|undefined} the response to the topic */ export const sealInLowerEnvironmentLambda = async event => { - const user = { role: 'docketclerk' }; + const user: AuthUser = { + email: 'system@ustc.gov', + name: 'ustc automated system', + role: 'docketclerk', + userId: 'N/A', + }; const applicationContext = createApplicationContext(user); @@ -15,7 +22,5 @@ export const sealInLowerEnvironmentLambda = async event => { ...JSON.parse(record.Sns.Message), })); - return await applicationContext - .getUseCaseHelpers() - .sealInLowerEnvironment(applicationContext, records); + return await sealInLowerEnvironment(applicationContext, records, user); }; diff --git a/web-api/src/lambdas/cases/sendMaintenanceNotificationsLambda.ts b/web-api/src/lambdas/cases/sendMaintenanceNotificationsLambda.ts index d35088e6cc0..13d59401ad4 100644 --- a/web-api/src/lambdas/cases/sendMaintenanceNotificationsLambda.ts +++ b/web-api/src/lambdas/cases/sendMaintenanceNotificationsLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { sendMaintenanceNotificationsInteractor } from '@web-api/business/useCases/maintenance/sendMaintenanceNotificationsInteractor'; /** * lambda which is used to send notifications to all users when maintenance mode is toggled @@ -10,11 +11,9 @@ export const sendMaintenanceNotificationsLambda = event => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .sendMaintenanceNotificationsInteractor(applicationContext, { - maintenanceMode: event.maintenanceMode, - }); + return await sendMaintenanceNotificationsInteractor(applicationContext, { + maintenanceMode: event.maintenanceMode, + }); }, { bypassMaintenanceCheck: true, diff --git a/web-api/src/lambdas/cases/serveCaseToIrsLambda.ts b/web-api/src/lambdas/cases/serveCaseToIrsLambda.ts index 9370931c50c..2eed0082d2c 100644 --- a/web-api/src/lambdas/cases/serveCaseToIrsLambda.ts +++ b/web-api/src/lambdas/cases/serveCaseToIrsLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { serveCaseToIrsInteractor } from '@web-api/business/useCases/serveCaseToIrs/serveCaseToIrsInteractor'; /** * serve case to irs @@ -6,16 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const serveCaseToIrsLambda = event => +export const serveCaseToIrsLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .serveCaseToIrsInteractor(applicationContext, { + return await serveCaseToIrsInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/cases/serveCourtIssuedDocumentLambda.ts b/web-api/src/lambdas/cases/serveCourtIssuedDocumentLambda.ts index 7805c0d8c3e..532d0c88054 100644 --- a/web-api/src/lambdas/cases/serveCourtIssuedDocumentLambda.ts +++ b/web-api/src/lambdas/cases/serveCourtIssuedDocumentLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { serveCourtIssuedDocumentInteractor } from '@web-api/business/useCases/courtIssuedDocument/serveCourtIssuedDocumentInteractor'; /** * used for serving a court-issued document on all parties and closing the case for some document types @@ -6,15 +8,20 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const serveCourtIssuedDocumentLambda = event => +export const serveCourtIssuedDocumentLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .serveCourtIssuedDocumentInteractor(applicationContext, { + return await serveCourtIssuedDocumentInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/cases/unblockCaseFromTrialLambda.ts b/web-api/src/lambdas/cases/unblockCaseFromTrialLambda.ts index 953d03b8133..29280fb965c 100644 --- a/web-api/src/lambdas/cases/unblockCaseFromTrialLambda.ts +++ b/web-api/src/lambdas/cases/unblockCaseFromTrialLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { unblockCaseFromTrialInteractor } from '@shared/business/useCases/unblockCaseFromTrialInteractor'; /** * used for unblocking a case @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const unblockCaseFromTrialLambda = event => +export const unblockCaseFromTrialLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .unblockCaseFromTrialInteractor(applicationContext, { + return await unblockCaseFromTrialInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/unprioritizeCaseLambda.ts b/web-api/src/lambdas/cases/unprioritizeCaseLambda.ts index 5b8a27ee965..756b2e424bd 100644 --- a/web-api/src/lambdas/cases/unprioritizeCaseLambda.ts +++ b/web-api/src/lambdas/cases/unprioritizeCaseLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { unprioritizeCaseInteractor } from '@shared/business/useCases/unprioritizeCaseInteractor'; /** * used for removing the high priority from a case @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const unprioritizeCaseLambda = event => +export const unprioritizeCaseLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .unprioritizeCaseInteractor(applicationContext, { + return await unprioritizeCaseInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/unsealCaseLambda.ts b/web-api/src/lambdas/cases/unsealCaseLambda.ts index b699e6a5b7d..6fe48de192b 100644 --- a/web-api/src/lambdas/cases/unsealCaseLambda.ts +++ b/web-api/src/lambdas/cases/unsealCaseLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { unsealCaseInteractor } from '@shared/business/useCases/unsealCaseInteractor'; /** * used for marking a case as unsealed @@ -6,11 +8,13 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const unsealCaseLambda = event => +export const unsealCaseLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .unsealCaseInteractor(applicationContext, { + return await unsealCaseInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/updateCaseContextLambda.ts b/web-api/src/lambdas/cases/updateCaseContextLambda.ts index e7cebae660e..e073f2fec1a 100644 --- a/web-api/src/lambdas/cases/updateCaseContextLambda.ts +++ b/web-api/src/lambdas/cases/updateCaseContextLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateCaseContextInteractor } from '@shared/business/useCases/updateCaseContextInteractor'; /** * used for updating a case status @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateCaseContextLambda = event => +export const updateCaseContextLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateCaseContextInteractor(applicationContext, { + return await updateCaseContextInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/updateCaseDetailsLambda.ts b/web-api/src/lambdas/cases/updateCaseDetailsLambda.ts index b77a5f111e6..ffc15ef3126 100644 --- a/web-api/src/lambdas/cases/updateCaseDetailsLambda.ts +++ b/web-api/src/lambdas/cases/updateCaseDetailsLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateCaseDetailsInteractor } from '@shared/business/useCases/updateCaseDetailsInteractor'; /** * used for updating a case's petition details information (IRS notice date, case type, case procedure, @@ -7,12 +9,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateCaseDetailsLambda = event => +export const updateCaseDetailsLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateCaseDetailsInteractor(applicationContext, { + return await updateCaseDetailsInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/updateCaseTrialSortTagsLambda.ts b/web-api/src/lambdas/cases/updateCaseTrialSortTagsLambda.ts index f885413f266..dabd851d701 100644 --- a/web-api/src/lambdas/cases/updateCaseTrialSortTagsLambda.ts +++ b/web-api/src/lambdas/cases/updateCaseTrialSortTagsLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateCaseTrialSortTagsInteractor } from '@shared/business/useCases/updateCaseTrialSortTagsInteractor'; /** * updates case trial sort tags @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateCaseTrialSortTagsLambda = event => +export const updateCaseTrialSortTagsLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateCaseTrialSortTagsInteractor(applicationContext, { + return await updateCaseTrialSortTagsInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/updateContactLambda.ts b/web-api/src/lambdas/cases/updateContactLambda.ts index a518f2d59c9..43a31f7a701 100644 --- a/web-api/src/lambdas/cases/updateContactLambda.ts +++ b/web-api/src/lambdas/cases/updateContactLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateContactInteractor } from '@shared/business/useCases/updateContactInteractor'; /** * used for updating a contact on a case @@ -6,11 +8,13 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateContactLambda = event => +export const updateContactLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateContactInteractor(applicationContext, { + return await updateContactInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/updateCounselOnCaseLambda.ts b/web-api/src/lambdas/cases/updateCounselOnCaseLambda.ts index 9fa05049ea0..aa92afd97fd 100644 --- a/web-api/src/lambdas/cases/updateCounselOnCaseLambda.ts +++ b/web-api/src/lambdas/cases/updateCounselOnCaseLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateCounselOnCaseInteractor } from '@web-api/business/useCases/caseAssociation/updateCounselOnCaseInteractor'; /** * used for updating a privatePractitioner or irsPractitioner on a case @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateCounselOnCaseLambda = event => +export const updateCounselOnCaseLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateCounselOnCaseInteractor(applicationContext, { + return await updateCounselOnCaseInteractor( + applicationContext, + { ...event.pathParameters, userData: JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/updateDeficiencyStatisticLambda.ts b/web-api/src/lambdas/cases/updateDeficiencyStatisticLambda.ts index b344d0505fa..27e8c846ccd 100644 --- a/web-api/src/lambdas/cases/updateDeficiencyStatisticLambda.ts +++ b/web-api/src/lambdas/cases/updateDeficiencyStatisticLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateDeficiencyStatisticInteractor } from '@web-api/business/useCases/caseStatistics/updateDeficiencyStatisticInteractor'; /** * updates a statistic on the case @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateDeficiencyStatisticLambda = event => +export const updateDeficiencyStatisticLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateDeficiencyStatisticInteractor(applicationContext, { + return await updateDeficiencyStatisticInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/updateOtherStatisticsLambda.ts b/web-api/src/lambdas/cases/updateOtherStatisticsLambda.ts index 2ddbea932c3..da463b927ec 100644 --- a/web-api/src/lambdas/cases/updateOtherStatisticsLambda.ts +++ b/web-api/src/lambdas/cases/updateOtherStatisticsLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateOtherStatisticsInteractor } from '@web-api/business/useCases/caseStatistics/updateOtherStatisticsInteractor'; /** * updates other statistics on the case (litigation costs and damages) @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateOtherStatisticsLambda = event => +export const updateOtherStatisticsLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateOtherStatisticsInteractor(applicationContext, { + return await updateOtherStatisticsInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/updatePetitionerInformationLambda.ts b/web-api/src/lambdas/cases/updatePetitionerInformationLambda.ts index 75723fa8283..ad296d8b3bb 100644 --- a/web-api/src/lambdas/cases/updatePetitionerInformationLambda.ts +++ b/web-api/src/lambdas/cases/updatePetitionerInformationLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updatePetitionerInformationInteractor } from '@web-api/business/useCases/user/updatePetitionerInformationInteractor'; /** * used for updating a case's petitioner information @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updatePetitionerInformationLambda = event => +export const updatePetitionerInformationLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updatePetitionerInformationInteractor(applicationContext, { + return await updatePetitionerInformationInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/updateQcCompleteForTrialLambda.ts b/web-api/src/lambdas/cases/updateQcCompleteForTrialLambda.ts index 508741fd07c..54bff5b485a 100644 --- a/web-api/src/lambdas/cases/updateQcCompleteForTrialLambda.ts +++ b/web-api/src/lambdas/cases/updateQcCompleteForTrialLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateQcCompleteForTrialInteractor } from '@shared/business/useCases/updateQcCompleteForTrialInteractor'; /** * used for updating whether a case is qc complete for trial @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateQcCompleteForTrialLambda = event => +export const updateQcCompleteForTrialLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }): Promise => { - return await applicationContext - .getUseCases() - .updateQcCompleteForTrialInteractor(applicationContext, { + return await updateQcCompleteForTrialInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/cases/verifyPendingCaseForUserLambda.ts b/web-api/src/lambdas/cases/verifyPendingCaseForUserLambda.ts index f5d5c346f22..01b5925a3b6 100644 --- a/web-api/src/lambdas/cases/verifyPendingCaseForUserLambda.ts +++ b/web-api/src/lambdas/cases/verifyPendingCaseForUserLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { verifyPendingCaseForUserInteractor } from '@web-api/business/useCases/caseAssociationRequest/verifyPendingCaseForUserInteractor'; /** * used for determining if a user has pending association with a case or not @@ -8,9 +9,7 @@ import { genericHandler } from '../../genericHandler'; */ export const verifyPendingCaseForUserLambda = event => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .verifyPendingCaseForUserInteractor(applicationContext, { - ...event.pathParameters, - }); + return await verifyPendingCaseForUserInteractor(applicationContext, { + ...event.pathParameters, + }); }); diff --git a/web-api/src/lambdas/cognitoAuthorizer/worker-handler.ts b/web-api/src/lambdas/cognitoAuthorizer/worker-handler.ts index 9191b1d4da9..f9deadf3861 100644 --- a/web-api/src/lambdas/cognitoAuthorizer/worker-handler.ts +++ b/web-api/src/lambdas/cognitoAuthorizer/worker-handler.ts @@ -9,6 +9,6 @@ export const workerHandler = async (event: SQSEvent): Promise => { const { Records } = event; const { body } = Records[0]; const message: WorkerMessage = JSON.parse(body); - const applicationContext = createApplicationContext(message.user); + const applicationContext = createApplicationContext(message.authorizedUser); await workerRouter(applicationContext, { message }); }; diff --git a/web-api/src/lambdas/correspondence/archiveCorrespondenceDocumentLambda.ts b/web-api/src/lambdas/correspondence/archiveCorrespondenceDocumentLambda.ts index c2ae1fc3387..589f21f4194 100644 --- a/web-api/src/lambdas/correspondence/archiveCorrespondenceDocumentLambda.ts +++ b/web-api/src/lambdas/correspondence/archiveCorrespondenceDocumentLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { archiveCorrespondenceDocumentInteractor } from '@web-api/business/useCases/correspondence/archiveCorrespondenceDocumentInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const archiveCorrespondenceDocumentLambda = event => +export const archiveCorrespondenceDocumentLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .archiveCorrespondenceDocumentInteractor(applicationContext, { + return await archiveCorrespondenceDocumentInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/correspondence/fileCorrespondenceDocumentLambda.ts b/web-api/src/lambdas/correspondence/fileCorrespondenceDocumentLambda.ts index 7dd9f597c5e..ec47a29cda1 100644 --- a/web-api/src/lambdas/correspondence/fileCorrespondenceDocumentLambda.ts +++ b/web-api/src/lambdas/correspondence/fileCorrespondenceDocumentLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { fileCorrespondenceDocumentInteractor } from '@web-api/business/useCases/correspondence/fileCorrespondenceDocumentInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const fileCorrespondenceDocumentLambda = event => +export const fileCorrespondenceDocumentLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .fileCorrespondenceDocumentInteractor(applicationContext, { + return await fileCorrespondenceDocumentInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/correspondence/updateCorrespondenceDocumentLambda.ts b/web-api/src/lambdas/correspondence/updateCorrespondenceDocumentLambda.ts index b4098c451aa..d17cc16a7bd 100644 --- a/web-api/src/lambdas/correspondence/updateCorrespondenceDocumentLambda.ts +++ b/web-api/src/lambdas/correspondence/updateCorrespondenceDocumentLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateCorrespondenceDocumentInteractor } from '@web-api/business/useCases/correspondence/updateCorrespondenceDocumentInteractor'; /** * upload a correspondence document @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateCorrespondenceDocumentLambda = event => +export const updateCorrespondenceDocumentLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateCorrespondenceDocumentInteractor(applicationContext, { + return await updateCorrespondenceDocumentInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/courtIssuedOrder/appendAmendedPetitionFormLambda.ts b/web-api/src/lambdas/courtIssuedOrder/appendAmendedPetitionFormLambda.ts index 236d2396485..cdedf391a87 100644 --- a/web-api/src/lambdas/courtIssuedOrder/appendAmendedPetitionFormLambda.ts +++ b/web-api/src/lambdas/courtIssuedOrder/appendAmendedPetitionFormLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { appendAmendedPetitionFormInteractor } from '@web-api/business/useCases/courtIssuedOrder/appendAmendedPetitionFormInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,16 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const appendAmendedPetitionFormLambda = event => +export const appendAmendedPetitionFormLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .appendAmendedPetitionFormInteractor( - applicationContext, - event.pathParameters, - ); + return await appendAmendedPetitionFormInteractor( + applicationContext, + event.pathParameters, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/courtIssuedOrder/createCourtIssuedOrderPdfFromHtmlLambda.ts b/web-api/src/lambdas/courtIssuedOrder/createCourtIssuedOrderPdfFromHtmlLambda.ts index b70ec8e00ce..7c772088b40 100644 --- a/web-api/src/lambdas/courtIssuedOrder/createCourtIssuedOrderPdfFromHtmlLambda.ts +++ b/web-api/src/lambdas/courtIssuedOrder/createCourtIssuedOrderPdfFromHtmlLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { createCourtIssuedOrderPdfFromHtmlInteractor } from '@web-api/business/useCases/courtIssuedOrder/createCourtIssuedOrderPdfFromHtmlInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,15 +8,20 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const createCourtIssuedOrderPdfFromHtmlLambda = event => +export const createCourtIssuedOrderPdfFromHtmlLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .createCourtIssuedOrderPdfFromHtmlInteractor(applicationContext, { + return await createCourtIssuedOrderPdfFromHtmlInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/documents/addCoversheetLambda.ts b/web-api/src/lambdas/documents/addCoversheetLambda.ts index 082a7ce9c0b..70390310d0c 100644 --- a/web-api/src/lambdas/documents/addCoversheetLambda.ts +++ b/web-api/src/lambdas/documents/addCoversheetLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { addCoversheetInteractor } from '@web-api/business/useCases/addCoversheetInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,13 +8,15 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const addCoversheetLambda = event => +export const addCoversheetLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler( event, async ({ applicationContext }) => { - await applicationContext - .getUseCases() - .addCoversheetInteractor(applicationContext, event.pathParameters); + await addCoversheetInteractor( + applicationContext, + event.pathParameters, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/documents/addPaperFilingLambda.ts b/web-api/src/lambdas/documents/addPaperFilingLambda.ts index 0baf72a6173..ec4d94fcfd0 100644 --- a/web-api/src/lambdas/documents/addPaperFilingLambda.ts +++ b/web-api/src/lambdas/documents/addPaperFilingLambda.ts @@ -1,16 +1,14 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { addPaperFilingInteractor } from '@web-api/business/useCases/docketEntry/addPaperFilingInteractor'; import { genericHandler } from '../../genericHandler'; -/** - * lambda used for adding a paper filing to a case - * - * @param {object} event the AWS event object - * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers - */ -export const addPaperFilingLambda = event => +export const addPaperFilingLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .addPaperFilingInteractor(applicationContext, { + return await addPaperFilingInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/archiveDraftDocumentLambda.ts b/web-api/src/lambdas/documents/archiveDraftDocumentLambda.ts index ae7246c4c8d..6a48f2592bc 100644 --- a/web-api/src/lambdas/documents/archiveDraftDocumentLambda.ts +++ b/web-api/src/lambdas/documents/archiveDraftDocumentLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { archiveDraftDocumentInteractor } from '@web-api/business/useCases/archiveDraftDocumentInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,9 +8,14 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const archiveDraftDocumentLambda = event => +export const archiveDraftDocumentLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .archiveDraftDocumentInteractor(applicationContext, event.pathParameters); + return await archiveDraftDocumentInteractor( + applicationContext, + event.pathParameters, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/batchDownloadDocketEntriesLambda.ts b/web-api/src/lambdas/documents/batchDownloadDocketEntriesLambda.ts index 7cfc3635940..5070a096e88 100644 --- a/web-api/src/lambdas/documents/batchDownloadDocketEntriesLambda.ts +++ b/web-api/src/lambdas/documents/batchDownloadDocketEntriesLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { batchDownloadDocketEntriesInteractor } from '@web-api/business/useCases/document/batchDownloadDocketEntriesInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,12 +8,14 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const batchDownloadDocketEntriesLambda = event => +export const batchDownloadDocketEntriesLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - await applicationContext - .getUseCases() - .batchDownloadDocketEntriesInteractor( - applicationContext, - JSON.parse(event.body), - ); + await batchDownloadDocketEntriesInteractor( + applicationContext, + JSON.parse(event.body), + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/completeDocketEntryQCLambda.ts b/web-api/src/lambdas/documents/completeDocketEntryQCLambda.ts index 04070f14fad..78d2e680b33 100644 --- a/web-api/src/lambdas/documents/completeDocketEntryQCLambda.ts +++ b/web-api/src/lambdas/documents/completeDocketEntryQCLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { completeDocketEntryQCInteractor } from '@web-api/business/useCases/docketEntry/completeDocketEntryQCInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,12 +8,14 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const completeDocketEntryQCLambda = event => +export const completeDocketEntryQCLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .completeDocketEntryQCInteractor( - applicationContext, - JSON.parse(event.body), - ); + return await completeDocketEntryQCInteractor( + applicationContext, + JSON.parse(event.body), + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/downloadPolicyUrlLambda.ts b/web-api/src/lambdas/documents/downloadPolicyUrlLambda.ts index 9079aed8a92..13c761ab63b 100644 --- a/web-api/src/lambdas/documents/downloadPolicyUrlLambda.ts +++ b/web-api/src/lambdas/documents/downloadPolicyUrlLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getDownloadPolicyUrlInteractor } from '@web-api/business/useCases/document/getDownloadPolicyUrlInteractor'; /** * used for getting the download policy which is needed for users to download files directly from S3 via the UI @@ -6,9 +8,14 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const downloadPolicyUrlLambda = event => +export const downloadPolicyUrlLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getDownloadPolicyUrlInteractor(applicationContext, event.pathParameters); + return await getDownloadPolicyUrlInteractor( + applicationContext, + event.pathParameters, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/editPaperFilingLambda.ts b/web-api/src/lambdas/documents/editPaperFilingLambda.ts index ebd94536771..32c15b488dc 100644 --- a/web-api/src/lambdas/documents/editPaperFilingLambda.ts +++ b/web-api/src/lambdas/documents/editPaperFilingLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { editPaperFilingInteractor } from '@web-api/business/useCases/docketEntry/editPaperFilingInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,9 +8,11 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const editPaperFilingLambda = event => +export const editPaperFilingLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .editPaperFilingInteractor(applicationContext, JSON.parse(event.body)); + return await editPaperFilingInteractor( + applicationContext, + JSON.parse(event.body), + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/fileCourtIssuedDocketEntryLambda.ts b/web-api/src/lambdas/documents/fileCourtIssuedDocketEntryLambda.ts index 40976b4a6a3..47e920967b2 100644 --- a/web-api/src/lambdas/documents/fileCourtIssuedDocketEntryLambda.ts +++ b/web-api/src/lambdas/documents/fileCourtIssuedDocketEntryLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { fileCourtIssuedDocketEntryInteractor } from '@web-api/business/useCases/docketEntry/fileCourtIssuedDocketEntryInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const fileCourtIssuedDocketEntryLambda = event => +export const fileCourtIssuedDocketEntryLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .fileCourtIssuedDocketEntryInteractor(applicationContext, { + return await fileCourtIssuedDocketEntryInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/fileCourtIssuedOrderToCaseLambda.ts b/web-api/src/lambdas/documents/fileCourtIssuedOrderToCaseLambda.ts index 1950cfd7f92..9a8c251c782 100644 --- a/web-api/src/lambdas/documents/fileCourtIssuedOrderToCaseLambda.ts +++ b/web-api/src/lambdas/documents/fileCourtIssuedOrderToCaseLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { fileCourtIssuedOrderInteractor } from '@web-api/business/useCases/courtIssuedOrder/fileCourtIssuedOrderInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,12 +8,14 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const fileCourtIssuedOrderToCaseLambda = event => +export const fileCourtIssuedOrderToCaseLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .fileCourtIssuedOrderInteractor( - applicationContext, - JSON.parse(event.body), - ); + return await fileCourtIssuedOrderInteractor( + applicationContext, + JSON.parse(event.body), + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/fileExternalDocumentToCaseLambda.ts b/web-api/src/lambdas/documents/fileExternalDocumentToCaseLambda.ts index c4e5a88efb9..64d87fe8a19 100644 --- a/web-api/src/lambdas/documents/fileExternalDocumentToCaseLambda.ts +++ b/web-api/src/lambdas/documents/fileExternalDocumentToCaseLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { fileExternalDocumentInteractor } from '@web-api/business/useCases/externalDocument/fileExternalDocumentInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,12 +8,14 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const fileExternalDocumentToCaseLambda = event => +export const fileExternalDocumentToCaseLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .fileExternalDocumentInteractor( - applicationContext, - JSON.parse(event.body), - ); + return await fileExternalDocumentInteractor( + applicationContext, + JSON.parse(event.body), + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/generateDraftStampOrderLambda.ts b/web-api/src/lambdas/documents/generateDraftStampOrderLambda.ts index fa88d4735ae..0cc6082e908 100644 --- a/web-api/src/lambdas/documents/generateDraftStampOrderLambda.ts +++ b/web-api/src/lambdas/documents/generateDraftStampOrderLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { generateDraftStampOrderInteractor } from '@shared/business/useCases/generateDraftStampOrderInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,16 +8,21 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const generateDraftStampOrderLambda = event => +export const generateDraftStampOrderLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler( event, async ({ applicationContext }) => { - await applicationContext - .getUseCases() - .generateDraftStampOrderInteractor(applicationContext, { + await generateDraftStampOrderInteractor( + applicationContext, + { ...event.pathParameters, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/documents/generatePrintableFilingReceiptLambda.ts b/web-api/src/lambdas/documents/generatePrintableFilingReceiptLambda.ts index 8f149c97947..e1dbb041529 100644 --- a/web-api/src/lambdas/documents/generatePrintableFilingReceiptLambda.ts +++ b/web-api/src/lambdas/documents/generatePrintableFilingReceiptLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { generatePrintableFilingReceiptInteractor } from '@web-api/business/useCases/docketEntry/generatePrintableFilingReceiptInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,12 +8,14 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const generatePrintableFilingReceiptLambda = event => +export const generatePrintableFilingReceiptLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .generatePrintableFilingReceiptInteractor( - applicationContext, - JSON.parse(event.body), - ); + return await generatePrintableFilingReceiptInteractor( + applicationContext, + JSON.parse(event.body), + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/getDocumentContentsForDocketEntryLambda.ts b/web-api/src/lambdas/documents/getDocumentContentsForDocketEntryLambda.ts index 9ca95bd9a58..fc24022f5bc 100644 --- a/web-api/src/lambdas/documents/getDocumentContentsForDocketEntryLambda.ts +++ b/web-api/src/lambdas/documents/getDocumentContentsForDocketEntryLambda.ts @@ -1,17 +1,15 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getDocumentContentsForDocketEntryInteractor } from '@web-api/business/useCases/document/getDocumentContentsForDocketEntryInteractor'; -/** - * used for getting the document contents for a docket entry - * - * @param {object} event the AWS event object - * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers - */ -export const getDocumentContentsForDocketEntryLambda = event => +export const getDocumentContentsForDocketEntryLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getDocumentContentsForDocketEntryInteractor( - applicationContext, - event.pathParameters, - ); + return await getDocumentContentsForDocketEntryInteractor( + applicationContext, + event.pathParameters, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/getDocumentDownloadUrlLambda.ts b/web-api/src/lambdas/documents/getDocumentDownloadUrlLambda.ts index ad025c40d18..6c9e74849d9 100644 --- a/web-api/src/lambdas/documents/getDocumentDownloadUrlLambda.ts +++ b/web-api/src/lambdas/documents/getDocumentDownloadUrlLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getDownloadPolicyUrlInteractor } from '@web-api/business/useCases/document/getDownloadPolicyUrlInteractor'; /** * TODO: clone of downloadPolicyUrlLambda? @@ -7,9 +9,14 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getDocumentDownloadUrlLambda = event => +export const getDocumentDownloadUrlLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getDownloadPolicyUrlInteractor(applicationContext, event.pathParameters); + return await getDownloadPolicyUrlInteractor( + applicationContext, + event.pathParameters, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/getUploadPolicyLambda.ts b/web-api/src/lambdas/documents/getUploadPolicyLambda.ts index b6610a30c62..5c6b32432d4 100644 --- a/web-api/src/lambdas/documents/getUploadPolicyLambda.ts +++ b/web-api/src/lambdas/documents/getUploadPolicyLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getUploadPolicyInteractor } from '@web-api/business/useCases/document/getUploadPolicyInteractor'; /** * used for getting the upload policy which is needed for users to upload directly to S3 via the UI @@ -6,11 +8,13 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getUploadPolicyLambda = event => +export const getUploadPolicyLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getUploadPolicyInteractor(applicationContext, { + return await getUploadPolicyInteractor( + applicationContext, + { key: event.pathParameters.key, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/opinionAdvancedSearchLambda.ts b/web-api/src/lambdas/documents/opinionAdvancedSearchLambda.ts index 85c92250957..9c0d1efdaa7 100644 --- a/web-api/src/lambdas/documents/opinionAdvancedSearchLambda.ts +++ b/web-api/src/lambdas/documents/opinionAdvancedSearchLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { opinionAdvancedSearchInteractor } from '@shared/business/useCases/opinionAdvancedSearchInteractor'; /** * used for fetching opinions matching the provided search string @@ -6,15 +8,20 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const opinionAdvancedSearchLambda = event => +export const opinionAdvancedSearchLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const opinionTypes = event.queryStringParameters.opinionTypes?.split(',') || []; - return await applicationContext - .getUseCases() - .opinionAdvancedSearchInteractor(applicationContext, { + return await opinionAdvancedSearchInteractor( + applicationContext, + { ...event.queryStringParameters, opinionTypes, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/orderAdvancedSearchLambda.ts b/web-api/src/lambdas/documents/orderAdvancedSearchLambda.ts index 912a91feee0..7be2bd4bd4a 100644 --- a/web-api/src/lambdas/documents/orderAdvancedSearchLambda.ts +++ b/web-api/src/lambdas/documents/orderAdvancedSearchLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { orderAdvancedSearchInteractor } from '@shared/business/useCases/orderAdvancedSearchInteractor'; /** * used for fetching orders matching the provided search string @@ -6,12 +8,14 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const orderAdvancedSearchLambda = event => +export const orderAdvancedSearchLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .orderAdvancedSearchInteractor( - applicationContext, - event.queryStringParameters, - ); + return await orderAdvancedSearchInteractor( + applicationContext, + event.queryStringParameters, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/removePdfFromDocketEntryLambda.ts b/web-api/src/lambdas/documents/removePdfFromDocketEntryLambda.ts index cb651bdc3c3..e851a4220e5 100644 --- a/web-api/src/lambdas/documents/removePdfFromDocketEntryLambda.ts +++ b/web-api/src/lambdas/documents/removePdfFromDocketEntryLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { removePdfFromDocketEntryInteractor } from '@shared/business/useCases/removePdfFromDocketEntryInteractor'; /** * used for removing a pdf from a docket entry @@ -6,12 +8,14 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const removePdfFromDocketEntryLambda = event => +export const removePdfFromDocketEntryLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .removePdfFromDocketEntryInteractor( - applicationContext, - event.pathParameters, - ); + return await removePdfFromDocketEntryInteractor( + applicationContext, + event.pathParameters, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/removeSignatureFromDocumentLambda.ts b/web-api/src/lambdas/documents/removeSignatureFromDocumentLambda.ts index e1f6dae628c..34d303e73e2 100644 --- a/web-api/src/lambdas/documents/removeSignatureFromDocumentLambda.ts +++ b/web-api/src/lambdas/documents/removeSignatureFromDocumentLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { removeSignatureFromDocumentInteractor } from '@shared/business/useCases/removeSignatureFromDocumentInteractor'; /** * used for removing signature from a signed document @@ -6,12 +8,14 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const removeSignatureFromDocumentLambda = event => +export const removeSignatureFromDocumentLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .removeSignatureFromDocumentInteractor( - applicationContext, - event.pathParameters, - ); + return await removeSignatureFromDocumentInteractor( + applicationContext, + event.pathParameters, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/saveSignedDocumentLambda.ts b/web-api/src/lambdas/documents/saveSignedDocumentLambda.ts index 98a52775619..94e275e2b50 100644 --- a/web-api/src/lambdas/documents/saveSignedDocumentLambda.ts +++ b/web-api/src/lambdas/documents/saveSignedDocumentLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { saveSignedDocumentInteractor } from '@shared/business/useCases/saveSignedDocumentInteractor'; /** * used for signing PDF documents @@ -6,18 +8,23 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const saveSignedDocumentLambda = event => +export const saveSignedDocumentLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { body, pathParameters: { docketEntryId: originalDocketEntryId, docketNumber }, } = event; - return await applicationContext - .getUseCases() - .saveSignedDocumentInteractor(applicationContext, { + return await saveSignedDocumentInteractor( + applicationContext, + { ...JSON.parse(body), docketNumber, originalDocketEntryId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/sealDocketEntryLambda.ts b/web-api/src/lambdas/documents/sealDocketEntryLambda.ts index 53c1329253c..f52abcde784 100644 --- a/web-api/src/lambdas/documents/sealDocketEntryLambda.ts +++ b/web-api/src/lambdas/documents/sealDocketEntryLambda.ts @@ -1,12 +1,15 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { sealDocketEntryInteractor } from '@web-api/business/useCases/docketEntry/sealDocketEntryInteractor'; /** * used for sealing docket entries * * @param {object} event the AWS event object + * @param {UnknownAuthUser} authorizedUser current user associated with the request * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const sealDocketEntryLambda = event => +export const sealDocketEntryLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { const { pathParameters: { docketEntryId, docketNumber }, @@ -14,11 +17,13 @@ export const sealDocketEntryLambda = event => const { docketEntrySealedTo } = JSON.parse(event.body); - return await applicationContext - .getUseCases() - .sealDocketEntryInteractor(applicationContext, { + return await sealDocketEntryInteractor( + applicationContext, + { docketEntryId, docketEntrySealedTo, docketNumber, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/serveExternallyFiledDocumentLambda.ts b/web-api/src/lambdas/documents/serveExternallyFiledDocumentLambda.ts index 8ebdd98273c..b414f42e46d 100644 --- a/web-api/src/lambdas/documents/serveExternallyFiledDocumentLambda.ts +++ b/web-api/src/lambdas/documents/serveExternallyFiledDocumentLambda.ts @@ -1,16 +1,17 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { serveExternallyFiledDocumentInteractor } from '@web-api/business/useCases/document/serveExternallyFiledDocumentInteractor'; -/** - * used for serving externally filed documents - * - * @param {object} event the AWS event object - * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers - */ -export const serveExternallyFiledDocumentLambda = event => +export const serveExternallyFiledDocumentLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .serveExternallyFiledDocumentInteractor(applicationContext, { + return await serveExternallyFiledDocumentInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/strikeDocketEntryLambda.ts b/web-api/src/lambdas/documents/strikeDocketEntryLambda.ts index eceaf1234f7..21afe92b647 100644 --- a/web-api/src/lambdas/documents/strikeDocketEntryLambda.ts +++ b/web-api/src/lambdas/documents/strikeDocketEntryLambda.ts @@ -1,21 +1,29 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { strikeDocketEntryInteractor } from '@web-api/business/useCases/docketEntry/strikeDocketEntryInteractor'; /** * used for striking docket records * * @param {object} event the AWS event object + * @param {UnknownAuthUser} authorizedUser current user associated with the request * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const strikeDocketEntryLambda = event => +export const strikeDocketEntryLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { pathParameters: { docketEntryId, docketNumber }, } = event; - return await applicationContext - .getUseCases() - .strikeDocketEntryInteractor(applicationContext, { + return await strikeDocketEntryInteractor( + applicationContext, + { docketEntryId, docketNumber, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/unsealDocketEntryLambda.ts b/web-api/src/lambdas/documents/unsealDocketEntryLambda.ts index 81113efa5a3..681b830f9a7 100644 --- a/web-api/src/lambdas/documents/unsealDocketEntryLambda.ts +++ b/web-api/src/lambdas/documents/unsealDocketEntryLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { unsealDocketEntryInteractor } from '@web-api/business/useCases/docketEntry/unsealDocketEntryInteractor'; /** * used for unsealing docket entries @@ -6,16 +8,21 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const unsealDocketEntryLambda = event => +export const unsealDocketEntryLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { pathParameters: { docketEntryId, docketNumber }, } = event; - return await applicationContext - .getUseCases() - .unsealDocketEntryInteractor(applicationContext, { + return await unsealDocketEntryInteractor( + applicationContext, + { docketEntryId, docketNumber, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/updateCourtIssuedDocketEntryLambda.ts b/web-api/src/lambdas/documents/updateCourtIssuedDocketEntryLambda.ts index 943565d44f2..f55515766b0 100644 --- a/web-api/src/lambdas/documents/updateCourtIssuedDocketEntryLambda.ts +++ b/web-api/src/lambdas/documents/updateCourtIssuedDocketEntryLambda.ts @@ -1,17 +1,22 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateCourtIssuedDocketEntryInteractor } from '@web-api/business/useCases/docketEntry/updateCourtIssuedDocketEntryInteractor'; /** * lambda which is used for updating a court issued docket entry * * @param {object} event the AWS event object + * @param {UnknownAuthUser} authorizedUser user associated with the current request * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateCourtIssuedDocketEntryLambda = event => +export const updateCourtIssuedDocketEntryLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateCourtIssuedDocketEntryInteractor( - applicationContext, - JSON.parse(event.body), - ); + return await updateCourtIssuedDocketEntryInteractor( + applicationContext, + JSON.parse(event.body), + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/updateCourtIssuedOrderToCaseLambda.ts b/web-api/src/lambdas/documents/updateCourtIssuedOrderToCaseLambda.ts index c2501692ff4..ae94379f12c 100644 --- a/web-api/src/lambdas/documents/updateCourtIssuedOrderToCaseLambda.ts +++ b/web-api/src/lambdas/documents/updateCourtIssuedOrderToCaseLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateCourtIssuedOrderInteractor } from '@web-api/business/useCases/courtIssuedOrder/updateCourtIssuedOrderInteractor'; /** * lambda which is used for updating a draft order @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateCourtIssuedOrderToCaseLambda = event => +export const updateCourtIssuedOrderToCaseLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateCourtIssuedOrderInteractor(applicationContext, { + return await updateCourtIssuedOrderInteractor( + applicationContext, + { ...JSON.parse(event.body), docketEntryIdToEdit: event.pathParameters.docketEntryId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/updateDocketEntryMetaLambda.ts b/web-api/src/lambdas/documents/updateDocketEntryMetaLambda.ts index 08b6fac5c34..e5cd4502557 100644 --- a/web-api/src/lambdas/documents/updateDocketEntryMetaLambda.ts +++ b/web-api/src/lambdas/documents/updateDocketEntryMetaLambda.ts @@ -1,17 +1,18 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateDocketEntryMetaInteractor } from '@web-api/business/useCases/docketEntry/updateDocketEntryMetaInteractor'; -/** - * lambda which is used for updating a docket entry's meta for a case - * - * @param {object} event the AWS event object - * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers - */ -export const updateDocketEntryMetaLambda = event => +export const updateDocketEntryMetaLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateDocketEntryMetaInteractor(applicationContext, { + return await updateDocketEntryMetaInteractor( + applicationContext, + { ...JSON.parse(event.body), ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/documents/validatePdfLambda.ts b/web-api/src/lambdas/documents/validatePdfLambda.ts index aec1cf2cdc4..c4f724ea2b5 100644 --- a/web-api/src/lambdas/documents/validatePdfLambda.ts +++ b/web-api/src/lambdas/documents/validatePdfLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { validatePdfInteractor } from '@web-api/business/useCases/pdf/validatePdfInteractor'; /** * used for validating PDF documents @@ -10,9 +11,7 @@ export const validatePdfLambda = event => genericHandler(event, async ({ applicationContext }) => { const { key } = event.pathParameters || {}; - return await applicationContext - .getUseCases() - .validatePdfInteractor(applicationContext, { - key, - }); + return await validatePdfInteractor(applicationContext, { + key, + }); }); diff --git a/web-api/src/lambdas/email/handleBounceNotificationsLambda.ts b/web-api/src/lambdas/email/handleBounceNotificationsLambda.ts index f1897b622da..05b1d7b2179 100644 --- a/web-api/src/lambdas/email/handleBounceNotificationsLambda.ts +++ b/web-api/src/lambdas/email/handleBounceNotificationsLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { handleBounceNotificationInteractor } from '@web-api/business/useCases/email/handleBounceNotificationInteractor'; /** * This lambda handles SNS notifications that occur whenever a service Email bounces. We @@ -17,9 +18,7 @@ export const handleBounceNotificationsLambda = event => return await Promise.all( records.map(record => - applicationContext - .getUseCases() - .handleBounceNotificationInteractor(applicationContext, record), + handleBounceNotificationInteractor(applicationContext, record), ), ); }, diff --git a/web-api/src/lambdas/featureFlag/getAllFeatureFlagsLambda.ts b/web-api/src/lambdas/featureFlag/getAllFeatureFlagsLambda.ts index 98d647e6bfc..e5c8cc4aba2 100644 --- a/web-api/src/lambdas/featureFlag/getAllFeatureFlagsLambda.ts +++ b/web-api/src/lambdas/featureFlag/getAllFeatureFlagsLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { getAllFeatureFlagsInteractor } from '@web-api/business/useCases/featureFlag/getAllFeatureFlagsInteractor'; /** * gets the value of the provided feature flag @@ -10,9 +11,7 @@ export const getAllFeatureFlagsLambda = event => genericHandler( event, ({ applicationContext }) => { - return applicationContext - .getUseCases() - .getAllFeatureFlagsInteractor(applicationContext); + return getAllFeatureFlagsInteractor(applicationContext); }, { bypassMaintenanceCheck: true }, ); diff --git a/web-api/src/lambdas/health/getCachedHealthCheckLambda.ts b/web-api/src/lambdas/health/getCachedHealthCheckLambda.ts index 8d555f403f1..e4626e9c968 100644 --- a/web-api/src/lambdas/health/getCachedHealthCheckLambda.ts +++ b/web-api/src/lambdas/health/getCachedHealthCheckLambda.ts @@ -1,8 +1,7 @@ import { genericHandler } from '@web-api/genericHandler'; +import { getCachedHealthCheckInteractor } from '@web-api/business/useCases/health/getCachedHealthCheckInteractor'; export const getCachedHealthCheckLambda = event => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getCachedHealthCheckInteractor(applicationContext); + return await getCachedHealthCheckInteractor(applicationContext); }); diff --git a/web-api/src/lambdas/health/getHealthCheckLambda.ts b/web-api/src/lambdas/health/getHealthCheckLambda.ts index c20590543e8..2a1ff70ac93 100644 --- a/web-api/src/lambdas/health/getHealthCheckLambda.ts +++ b/web-api/src/lambdas/health/getHealthCheckLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { getHealthCheckInteractor } from '@web-api/business/useCases/health/getHealthCheckInteractor'; /** * used for checking status of critical services @@ -8,7 +9,5 @@ import { genericHandler } from '../../genericHandler'; */ export const getHealthCheckLambda = event => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getHealthCheckInteractor(applicationContext); + return await getHealthCheckInteractor(applicationContext); }); diff --git a/web-api/src/lambdas/health/setHealthCheckCacheLambda.ts b/web-api/src/lambdas/health/setHealthCheckCacheLambda.ts index 034686c8bc1..7baa7a61d97 100644 --- a/web-api/src/lambdas/health/setHealthCheckCacheLambda.ts +++ b/web-api/src/lambdas/health/setHealthCheckCacheLambda.ts @@ -1,8 +1,7 @@ import { genericHandler } from '@web-api/genericHandler'; +import { setHealthCheckCacheInteractor } from '@web-api/business/useCases/health/setHealthCheckCacheInteractor'; export const setHealthCheckCacheLambda = event => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .setHealthCheckCacheInteractor(applicationContext); + return await setHealthCheckCacheInteractor(applicationContext); }); diff --git a/web-api/src/lambdas/maintenance/getMaintenanceModeLambda.ts b/web-api/src/lambdas/maintenance/getMaintenanceModeLambda.ts index e1ae7c6f7fa..0cd95dd773a 100644 --- a/web-api/src/lambdas/maintenance/getMaintenanceModeLambda.ts +++ b/web-api/src/lambdas/maintenance/getMaintenanceModeLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { getMaintenanceModeInteractor } from '@shared/business/useCases/getMaintenanceModeInteractor'; /** * used for fetching the value of maintenance mode @@ -10,9 +11,7 @@ export const getMaintenanceModeLambda = event => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getMaintenanceModeInteractor(applicationContext); + return await getMaintenanceModeInteractor(applicationContext); }, { bypassMaintenanceCheck: true }, ); diff --git a/web-api/src/lambdas/manualAssociation/associateIrsPractitionerWithCaseLambda.ts b/web-api/src/lambdas/manualAssociation/associateIrsPractitionerWithCaseLambda.ts index 8880fea03a1..395281c9b93 100644 --- a/web-api/src/lambdas/manualAssociation/associateIrsPractitionerWithCaseLambda.ts +++ b/web-api/src/lambdas/manualAssociation/associateIrsPractitionerWithCaseLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { associateIrsPractitionerWithCaseInteractor } from '@web-api/business/useCases/manualAssociation/associateIrsPractitionerWithCaseInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const associateIrsPractitionerWithCaseLambda = event => +export const associateIrsPractitionerWithCaseLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .associateIrsPractitionerWithCaseInteractor(applicationContext, { + return await associateIrsPractitionerWithCaseInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/manualAssociation/associatePrivatePractitionerWithCaseLambda.ts b/web-api/src/lambdas/manualAssociation/associatePrivatePractitionerWithCaseLambda.ts index 2fb4fdead18..aa7b04c6f36 100644 --- a/web-api/src/lambdas/manualAssociation/associatePrivatePractitionerWithCaseLambda.ts +++ b/web-api/src/lambdas/manualAssociation/associatePrivatePractitionerWithCaseLambda.ts @@ -1,16 +1,17 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { associatePrivatePractitionerWithCaseInteractor } from '@web-api/business/useCases/manualAssociation/associatePrivatePractitionerWithCaseInteractor'; import { genericHandler } from '../../genericHandler'; -/** - * associate practitioner with case - * - * @param {object} event the AWS event object - * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers - */ -export const associatePrivatePractitionerWithCaseLambda = event => +export const associatePrivatePractitionerWithCaseLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .associatePrivatePractitionerWithCaseInteractor(applicationContext, { + return await associatePrivatePractitionerWithCaseInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/messages/completeMessageLambda.ts b/web-api/src/lambdas/messages/completeMessageLambda.ts index f75653af303..51fdd6a40bf 100644 --- a/web-api/src/lambdas/messages/completeMessageLambda.ts +++ b/web-api/src/lambdas/messages/completeMessageLambda.ts @@ -1,4 +1,6 @@ import { ServerApplicationContext } from '@web-api/applicationContext'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { completeMessageInteractor } from '@web-api/business/useCases/messages/completeMessageInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -7,7 +9,7 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const completeMessageLambda = event => +export const completeMessageLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler( event, async ({ @@ -15,8 +17,10 @@ export const completeMessageLambda = event => }: { applicationContext: ServerApplicationContext; }) => { - return await applicationContext - .getUseCases() - .completeMessageInteractor(applicationContext, JSON.parse(event.body)); + return await completeMessageInteractor( + applicationContext, + JSON.parse(event.body), + authorizedUser, + ); }, ); diff --git a/web-api/src/lambdas/messages/createMessageLambda.ts b/web-api/src/lambdas/messages/createMessageLambda.ts index 1c6d0c9dc7e..4fc93bce9e5 100644 --- a/web-api/src/lambdas/messages/createMessageLambda.ts +++ b/web-api/src/lambdas/messages/createMessageLambda.ts @@ -1,16 +1,14 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { createMessageInteractor } from '@web-api/business/useCases/messages/createMessageInteractor'; import { genericHandler } from '../../genericHandler'; -/** - * lambda which is used for creating a new message - * - * @param {object} event the AWS event object - * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers - */ -export const createMessageLambda = event => +export const createMessageLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .createMessageInteractor(applicationContext, { + return await createMessageInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/messages/forwardMessageLambda.ts b/web-api/src/lambdas/messages/forwardMessageLambda.ts index 185dd22d2d9..973b3fe88ab 100644 --- a/web-api/src/lambdas/messages/forwardMessageLambda.ts +++ b/web-api/src/lambdas/messages/forwardMessageLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { forwardMessageInteractor } from '@web-api/business/useCases/messages/forwardMessageInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,12 +8,14 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const forwardMessageLambda = event => +export const forwardMessageLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .forwardMessageInteractor(applicationContext, { + return await forwardMessageInteractor( + applicationContext, + { parentMessageId: event.pathParameters.parentMessageId, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/messages/getCompletedMessagesForSectionLambda.ts b/web-api/src/lambdas/messages/getCompletedMessagesForSectionLambda.ts index 02440b0a6d4..4909a7ee9d8 100644 --- a/web-api/src/lambdas/messages/getCompletedMessagesForSectionLambda.ts +++ b/web-api/src/lambdas/messages/getCompletedMessagesForSectionLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getCompletedMessagesForSectionInteractor } from '@web-api/business/useCases/messages/getCompletedMessagesForSectionInteractor'; /** * gets the completed messages for the section @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getCompletedMessagesForSectionLambda = event => +export const getCompletedMessagesForSectionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getCompletedMessagesForSectionInteractor(applicationContext, { + return await getCompletedMessagesForSectionInteractor( + applicationContext, + { section: event.pathParameters.section, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/messages/getCompletedMessagesForUserLambda.ts b/web-api/src/lambdas/messages/getCompletedMessagesForUserLambda.ts index 4c36d8429eb..42ff75e10b0 100644 --- a/web-api/src/lambdas/messages/getCompletedMessagesForUserLambda.ts +++ b/web-api/src/lambdas/messages/getCompletedMessagesForUserLambda.ts @@ -1,16 +1,17 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getCompletedMessagesForUserInteractor } from '@web-api/business/useCases/messages/getCompletedMessagesForUserInteractor'; -/** - * gets the completed messages for the user - * - * @param {object} event the AWS event object - * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers - */ -export const getCompletedMessagesForUserLambda = event => +export const getCompletedMessagesForUserLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getCompletedMessagesForUserInteractor(applicationContext, { + return await getCompletedMessagesForUserInteractor( + applicationContext, + { userId: event.pathParameters.userId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/messages/getInboxMessagesForSectionLambda.ts b/web-api/src/lambdas/messages/getInboxMessagesForSectionLambda.ts index 5ca45c6321d..85743453539 100644 --- a/web-api/src/lambdas/messages/getInboxMessagesForSectionLambda.ts +++ b/web-api/src/lambdas/messages/getInboxMessagesForSectionLambda.ts @@ -1,16 +1,17 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getInboxMessagesForSectionInteractor } from '@web-api/business/useCases/messages/getInboxMessagesForSectionInteractor'; -/** - * gets the inbox messages for the section - * - * @param {object} event the AWS event object - * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers - */ -export const getInboxMessagesForSectionLambda = event => +export const getInboxMessagesForSectionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getInboxMessagesForSectionInteractor(applicationContext, { + return await getInboxMessagesForSectionInteractor( + applicationContext, + { section: event.pathParameters.section, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/messages/getInboxMessagesForUserLambda.ts b/web-api/src/lambdas/messages/getInboxMessagesForUserLambda.ts index 9e88019af7a..50e51b5eb25 100644 --- a/web-api/src/lambdas/messages/getInboxMessagesForUserLambda.ts +++ b/web-api/src/lambdas/messages/getInboxMessagesForUserLambda.ts @@ -1,16 +1,17 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getInboxMessagesForUserInteractor } from '@web-api/business/useCases/messages/getInboxMessagesForUserInteractor'; -/** - * gets the inbox messages for the user - * - * @param {object} event the AWS event object - * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers - */ -export const getInboxMessagesForUserLambda = event => +export const getInboxMessagesForUserLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getInboxMessagesForUserInteractor(applicationContext, { + return await getInboxMessagesForUserInteractor( + applicationContext, + { userId: event.pathParameters.userId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/messages/getMessageThreadLambda.ts b/web-api/src/lambdas/messages/getMessageThreadLambda.ts index 5720653f017..7faa339543a 100644 --- a/web-api/src/lambdas/messages/getMessageThreadLambda.ts +++ b/web-api/src/lambdas/messages/getMessageThreadLambda.ts @@ -1,16 +1,17 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getMessageThreadInteractor } from '@web-api/business/useCases/messages/getMessageThreadInteractor'; -/** - * lambda which is used for retrieving messages by the parent message id - * - * @param {object} event the AWS event object - * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers - */ -export const getMessageThreadLambda = event => +export const getMessageThreadLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getMessageThreadInteractor(applicationContext, { + return await getMessageThreadInteractor( + applicationContext, + { parentMessageId: event.pathParameters.parentMessageId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/messages/getMessagesForCaseLambda.ts b/web-api/src/lambdas/messages/getMessagesForCaseLambda.ts index ee14f7ae3d0..a351b1e9de3 100644 --- a/web-api/src/lambdas/messages/getMessagesForCaseLambda.ts +++ b/web-api/src/lambdas/messages/getMessagesForCaseLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getMessagesForCaseInteractor } from '@web-api/business/useCases/messages/getMessagesForCaseInteractor'; /** * lambda which is used for retrieving messages for a case @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getMessagesForCaseLambda = event => +export const getMessagesForCaseLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getMessagesForCaseInteractor(applicationContext, { + return await getMessagesForCaseInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/messages/getOutboxMessagesForSectionLambda.ts b/web-api/src/lambdas/messages/getOutboxMessagesForSectionLambda.ts index 30f3e8098f8..af88876c689 100644 --- a/web-api/src/lambdas/messages/getOutboxMessagesForSectionLambda.ts +++ b/web-api/src/lambdas/messages/getOutboxMessagesForSectionLambda.ts @@ -1,16 +1,17 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getOutboxMessagesForSectionInteractor } from '@web-api/business/useCases/messages/getOutboxMessagesForSectionInteractor'; -/** - * gets the outbox messages for the section - * - * @param {object} event the AWS event object - * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers - */ -export const getOutboxMessagesForSectionLambda = event => +export const getOutboxMessagesForSectionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getOutboxMessagesForSectionInteractor(applicationContext, { + return await getOutboxMessagesForSectionInteractor( + applicationContext, + { section: event.pathParameters.section, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/messages/getOutboxMessagesForUserLambda.ts b/web-api/src/lambdas/messages/getOutboxMessagesForUserLambda.ts index 953b4bde3cd..a094131d53d 100644 --- a/web-api/src/lambdas/messages/getOutboxMessagesForUserLambda.ts +++ b/web-api/src/lambdas/messages/getOutboxMessagesForUserLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getOutboxMessagesForUserInteractor } from '@web-api/business/useCases/messages/getOutboxMessagesForUserInteractor'; /** * gets the outbox messages for the user @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getOutboxMessagesForUserLambda = event => +export const getOutboxMessagesForUserLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getOutboxMessagesForUserInteractor(applicationContext, { + return await getOutboxMessagesForUserInteractor( + applicationContext, + { userId: event.pathParameters.userId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/messages/replyToMessageLambda.ts b/web-api/src/lambdas/messages/replyToMessageLambda.ts index 9f2233a785a..af4a591e6ec 100644 --- a/web-api/src/lambdas/messages/replyToMessageLambda.ts +++ b/web-api/src/lambdas/messages/replyToMessageLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { replyToMessageInteractor } from '@web-api/business/useCases/messages/replyToMessageInteractor'; /** * lambda which is used to reply to a message @@ -6,12 +8,14 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const replyToMessageLambda = event => +export const replyToMessageLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .replyToMessageInteractor(applicationContext, { + return await replyToMessageInteractor( + applicationContext, + { parentMessageId: event.pathParameters.parentMessageId, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/messages/setMessageAsReadLambda.ts b/web-api/src/lambdas/messages/setMessageAsReadLambda.ts index 652014e5c49..39efe824705 100644 --- a/web-api/src/lambdas/messages/setMessageAsReadLambda.ts +++ b/web-api/src/lambdas/messages/setMessageAsReadLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { setMessageAsReadInteractor } from '@web-api/business/useCases/messages/setMessageAsReadInteractor'; /** * sets the given message's read status @@ -6,14 +8,19 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const setMessageAsReadLambda = event => +export const setMessageAsReadLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { messageId } = event.pathParameters || {}; - return await applicationContext - .getUseCases() - .setMessageAsReadInteractor(applicationContext, { + return await setMessageAsReadInteractor( + applicationContext, + { messageId, ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/notifications/connectLambda.ts b/web-api/src/lambdas/notifications/connectLambda.ts index b6c4b0b3e9c..6288355a90a 100644 --- a/web-api/src/lambdas/notifications/connectLambda.ts +++ b/web-api/src/lambdas/notifications/connectLambda.ts @@ -1,4 +1,7 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getUserFromAuthHeader } from '@web-api/middleware/apiGatewayHelper'; +import { onConnectInteractor } from '@web-api/business/useCases/notifications/onConnectInteractor'; /** * save the information about a new websocket connection @@ -6,19 +9,22 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const connectLambda = event => - genericHandler( +export const connectLambda = event => { + const authorizedUser: UnknownAuthUser = getUserFromAuthHeader(event); + return genericHandler( event, async ({ applicationContext, clientConnectionId }) => { const endpoint = event.requestContext.domainName; - await applicationContext - .getUseCases() - .onConnectInteractor(applicationContext, { + await onConnectInteractor( + applicationContext, + { clientConnectionId, connectionId: event.requestContext.connectionId, endpoint, - }); + }, + authorizedUser, + ); applicationContext.logger.debug('Websocket connected', { requestId: { @@ -28,3 +34,4 @@ export const connectLambda = event => }, { bypassMaintenanceCheck: true }, ); +}; diff --git a/web-api/src/lambdas/notifications/disconnectLambda.ts b/web-api/src/lambdas/notifications/disconnectLambda.ts index f46a5ff8540..7e6f38a6209 100644 --- a/web-api/src/lambdas/notifications/disconnectLambda.ts +++ b/web-api/src/lambdas/notifications/disconnectLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { onDisconnectInteractor } from '@web-api/business/useCases/notifications/onDisconnectInteractor'; /** * remove the information about an existing websocket connection @@ -10,11 +11,9 @@ export const disconnectLambda = event => genericHandler( event, async ({ applicationContext }) => { - const results = await applicationContext - .getUseCases() - .onDisconnectInteractor(applicationContext, { - connectionId: event.requestContext.connectionId, - }); + const results = await onDisconnectInteractor(applicationContext, { + connectionId: event.requestContext.connectionId, + }); applicationContext.logger.debug('Websocket disconnected', { requestId: { diff --git a/web-api/src/lambdas/pdfGeneration/pdf-generation.ts b/web-api/src/lambdas/pdfGeneration/pdf-generation.ts index 49b5702d38d..2154661bf2e 100644 --- a/web-api/src/lambdas/pdfGeneration/pdf-generation.ts +++ b/web-api/src/lambdas/pdfGeneration/pdf-generation.ts @@ -36,6 +36,7 @@ export const changeOfAddressHandler = async event => { await applicationContext.getUseCaseHelpers().generateChangeOfAddressHelper({ applicationContext, + authorizedUser: eventBody.requestUser, bypassDocketEntry: eventBody.bypassDocketEntry, contactInfo: eventBody.contactInfo, docketNumber: eventBody.docketNumber, diff --git a/web-api/src/lambdas/pendingItems/exportPendingReportLambda.ts b/web-api/src/lambdas/pendingItems/exportPendingReportLambda.ts index 795ecf0788f..6cfdde8cad5 100644 --- a/web-api/src/lambdas/pendingItems/exportPendingReportLambda.ts +++ b/web-api/src/lambdas/pendingItems/exportPendingReportLambda.ts @@ -1,14 +1,21 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { exportPendingReportInteractor } from '@web-api/business/useCases/pendingItems/exportPendingReportInteractor'; import { genericHandler } from '../../genericHandler'; -export const exportPendingReportLambda = event => +export const exportPendingReportLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .exportPendingReportInteractor(applicationContext, { + return await exportPendingReportInteractor( + applicationContext, + { ...event.queryStringParameters, - }); + }, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/pendingItems/fetchPendingItemsLambda.ts b/web-api/src/lambdas/pendingItems/fetchPendingItemsLambda.ts index 9331136a61b..9d7c6d2e8f7 100644 --- a/web-api/src/lambdas/pendingItems/fetchPendingItemsLambda.ts +++ b/web-api/src/lambdas/pendingItems/fetchPendingItemsLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { fetchPendingItemsInteractor } from '@web-api/business/useCases/pendingItems/fetchPendingItemsInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const fetchPendingItemsLambda = event => +export const fetchPendingItemsLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .fetchPendingItemsInteractor(applicationContext, { + return await fetchPendingItemsInteractor( + applicationContext, + { ...event.queryStringParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/pendingItems/generatePrintablePendingReportLambda.ts b/web-api/src/lambdas/pendingItems/generatePrintablePendingReportLambda.ts index 9fb5d350ad7..2828b72a6df 100644 --- a/web-api/src/lambdas/pendingItems/generatePrintablePendingReportLambda.ts +++ b/web-api/src/lambdas/pendingItems/generatePrintablePendingReportLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { generatePrintablePendingReportInteractor } from '@web-api/business/useCases/pendingItems/generatePrintablePendingReportInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,15 +8,20 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const generatePrintablePendingReportLambda = event => +export const generatePrintablePendingReportLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .generatePrintablePendingReportInteractor(applicationContext, { + return await generatePrintablePendingReportInteractor( + applicationContext, + { ...event.queryStringParameters, - }); + }, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/pendingMotion/deleteDocketEntryWorksheetLambda.ts b/web-api/src/lambdas/pendingMotion/deleteDocketEntryWorksheetLambda.ts index 758a05bc8ef..7b8668d62cc 100644 --- a/web-api/src/lambdas/pendingMotion/deleteDocketEntryWorksheetLambda.ts +++ b/web-api/src/lambdas/pendingMotion/deleteDocketEntryWorksheetLambda.ts @@ -1,11 +1,15 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { deleteDocketEntryWorksheetInteractor } from '@web-api/business/useCases/pendingMotion/deleteDocketEntryWorksheetInteractor'; import { genericHandler } from '../../genericHandler'; -export const deleteDocketEntryWorksheetLambda = event => +export const deleteDocketEntryWorksheetLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, ({ applicationContext }) => { - return applicationContext - .getUseCases() - .deleteDocketEntryWorksheetInteractor( - applicationContext, - event.pathParameters.docketEntryId, - ); + return deleteDocketEntryWorksheetInteractor( + applicationContext, + event.pathParameters.docketEntryId, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/pendingMotion/getPendingMotionDocketEntriesForCurrentJudgeLambda.ts b/web-api/src/lambdas/pendingMotion/getPendingMotionDocketEntriesForCurrentJudgeLambda.ts index 02fb711ca0a..cac698f787d 100644 --- a/web-api/src/lambdas/pendingMotion/getPendingMotionDocketEntriesForCurrentJudgeLambda.ts +++ b/web-api/src/lambdas/pendingMotion/getPendingMotionDocketEntriesForCurrentJudgeLambda.ts @@ -1,11 +1,15 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getPendingMotionDocketEntriesForCurrentJudgeInteractor } from '@web-api/business/useCases/pendingMotion/getPendingMotionDocketEntriesForCurrentJudgeInteractor'; -export const getPendingMotionDocketEntriesForCurrentJudgeLambda = event => +export const getPendingMotionDocketEntriesForCurrentJudgeLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, ({ applicationContext }) => - applicationContext - .getUseCases() - .getPendingMotionDocketEntriesForCurrentJudgeInteractor( - applicationContext, - event.queryStringParameters, - ), + getPendingMotionDocketEntriesForCurrentJudgeInteractor( + applicationContext, + event.queryStringParameters, + authorizedUser, + ), ); diff --git a/web-api/src/lambdas/pendingMotion/updateDocketEntryWorksheetLambda.ts b/web-api/src/lambdas/pendingMotion/updateDocketEntryWorksheetLambda.ts index 31c37f28e6f..10a7a6d7239 100644 --- a/web-api/src/lambdas/pendingMotion/updateDocketEntryWorksheetLambda.ts +++ b/web-api/src/lambdas/pendingMotion/updateDocketEntryWorksheetLambda.ts @@ -1,11 +1,15 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateDocketEntryWorksheetInteractor } from '@web-api/business/useCases/pendingMotion/updateDocketEntryWorksheetInteractor'; -export const updateDocketEntryWorksheetLambda = event => +export const updateDocketEntryWorksheetLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateDocketEntryWorksheetInteractor( - applicationContext, - JSON.parse(event.body), - ); + return await updateDocketEntryWorksheetInteractor( + applicationContext, + JSON.parse(event.body), + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/polling/startPollingForResultsLambda.ts b/web-api/src/lambdas/polling/startPollingForResultsLambda.ts index d00f6f7b3cc..8466556e67c 100644 --- a/web-api/src/lambdas/polling/startPollingForResultsLambda.ts +++ b/web-api/src/lambdas/polling/startPollingForResultsLambda.ts @@ -1,10 +1,17 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { startPollingForResultsInteractor } from '@web-api/business/useCases/polling/startPollingForResultsInteractor'; -export const startPollingForResultsLambda = event => +export const startPollingForResultsLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .startPollingForResultsInteractor(applicationContext, { + return await startPollingForResultsInteractor( + applicationContext, + { ...event.pathParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/practitioners/createPractitionerDocumentLambda.ts b/web-api/src/lambdas/practitioners/createPractitionerDocumentLambda.ts index bef05cb41aa..7a9332e4f71 100644 --- a/web-api/src/lambdas/practitioners/createPractitionerDocumentLambda.ts +++ b/web-api/src/lambdas/practitioners/createPractitionerDocumentLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { createPractitionerDocumentInteractor } from '@web-api/business/useCases/practitioner/createPractitionerDocumentInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const createPractitionerDocumentLambda = event => +export const createPractitionerDocumentLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .createPractitionerDocumentInteractor(applicationContext, { + return await createPractitionerDocumentInteractor( + applicationContext, + { barNumber: event.pathParameters.barNumber, documentMetadata: JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/practitioners/createPractitionerUserLambda.ts b/web-api/src/lambdas/practitioners/createPractitionerUserLambda.ts index e73ed496894..3f76a324cfc 100644 --- a/web-api/src/lambdas/practitioners/createPractitionerUserLambda.ts +++ b/web-api/src/lambdas/practitioners/createPractitionerUserLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { createPractitionerUserInteractor } from '@web-api/business/useCases/practitioner/createPractitionerUserInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const createPractitionerUserLambda = event => +export const createPractitionerUserLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .createPractitionerUserInteractor(applicationContext, { + return await createPractitionerUserInteractor( + applicationContext, + { user: JSON.parse(event.body).user, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/practitioners/deletePractitionerDocumentLambda.ts b/web-api/src/lambdas/practitioners/deletePractitionerDocumentLambda.ts index afb3a0942c8..7097bee1d38 100644 --- a/web-api/src/lambdas/practitioners/deletePractitionerDocumentLambda.ts +++ b/web-api/src/lambdas/practitioners/deletePractitionerDocumentLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { deletePractitionerDocumentInteractor } from '@web-api/business/useCases/practitioner/deletePractitionerDocumentInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const deletePractitionerDocumentLambda = event => +export const deletePractitionerDocumentLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .deletePractitionerDocumentInteractor(applicationContext, { + return await deletePractitionerDocumentInteractor( + applicationContext, + { barNumber: event.pathParameters.barNumber, practitionerDocumentFileId: event.pathParameters.practitionerDocumentFileId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/practitioners/editPractitionerDocumentLambda.ts b/web-api/src/lambdas/practitioners/editPractitionerDocumentLambda.ts index 85018ccf9bc..28a1c0c23c0 100644 --- a/web-api/src/lambdas/practitioners/editPractitionerDocumentLambda.ts +++ b/web-api/src/lambdas/practitioners/editPractitionerDocumentLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { editPractitionerDocumentInteractor } from '@web-api/business/useCases/practitioner/editPractitionerDocumentInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const editPractitionerDocumentLambda = event => +export const editPractitionerDocumentLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .editPractitionerDocumentInteractor(applicationContext, { + return await editPractitionerDocumentInteractor( + applicationContext, + { barNumber: event.pathParameters.barNumber, documentMetadata: JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/practitioners/getPractitionerByBarNumberLambda.ts b/web-api/src/lambdas/practitioners/getPractitionerByBarNumberLambda.ts index a4c821d743d..44e5eed53f5 100644 --- a/web-api/src/lambdas/practitioners/getPractitionerByBarNumberLambda.ts +++ b/web-api/src/lambdas/practitioners/getPractitionerByBarNumberLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getPractitionerByBarNumberInteractor } from '@web-api/business/useCases/practitioner/getPractitionerByBarNumberInteractor'; /** * gets practitioner user by bar number @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getPractitionerByBarNumberLambda = event => +export const getPractitionerByBarNumberLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getPractitionerByBarNumberInteractor(applicationContext, { + return await getPractitionerByBarNumberInteractor( + applicationContext, + { barNumber: event.pathParameters.barNumber, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/practitioners/getPractitionerDocumentDownloadUrlLambda.ts b/web-api/src/lambdas/practitioners/getPractitionerDocumentDownloadUrlLambda.ts index dffd120dfc6..596eddec86f 100644 --- a/web-api/src/lambdas/practitioners/getPractitionerDocumentDownloadUrlLambda.ts +++ b/web-api/src/lambdas/practitioners/getPractitionerDocumentDownloadUrlLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getPractitionerDocumentDownloadUrlInteractor } from '@web-api/business/useCases/practitioner/getPractitionerDocumentDownloadUrlInteractor'; /** * Returns an upload url that allow the client to upload a practitioner document to an s3 bucket. @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getPractitionerDocumentDownloadUrlLambda = event => +export const getPractitionerDocumentDownloadUrlLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, ({ applicationContext }) => { - return applicationContext - .getUseCases() - .getPractitionerDocumentDownloadUrlInteractor(applicationContext, { + return getPractitionerDocumentDownloadUrlInteractor( + applicationContext, + { barNumber: event.pathParameters.barNumber, practitionerDocumentFileId: event.pathParameters.practitionerDocumentFileId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/practitioners/getPractitionerDocumentLambda.ts b/web-api/src/lambdas/practitioners/getPractitionerDocumentLambda.ts index 9d158b3bfa5..8c6f2c75256 100644 --- a/web-api/src/lambdas/practitioners/getPractitionerDocumentLambda.ts +++ b/web-api/src/lambdas/practitioners/getPractitionerDocumentLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getPractitionerDocumentInteractor } from '@web-api/business/useCases/practitioner/getPractitionerDocumentInteractor'; /** * Returns a practitioner document @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getPractitionerDocumentLambda = event => +export const getPractitionerDocumentLambda = ( + event, + authorizedUser: UnknownAuthUser, +): Promise => genericHandler(event, ({ applicationContext }) => { - return applicationContext - .getUseCases() - .getPractitionerDocumentInteractor(applicationContext, { + return getPractitionerDocumentInteractor( + applicationContext, + { barNumber: event.pathParameters.barNumber, practitionerDocumentFileId: event.pathParameters.practitionerDocumentFileId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/practitioners/getPractitionerDocumentsLambda.ts b/web-api/src/lambdas/practitioners/getPractitionerDocumentsLambda.ts index 4237b4c8d59..c2d9fc455d0 100644 --- a/web-api/src/lambdas/practitioners/getPractitionerDocumentsLambda.ts +++ b/web-api/src/lambdas/practitioners/getPractitionerDocumentsLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getPractitionerDocumentsInteractor } from '@web-api/business/useCases/practitioner/getPractitionerDocumentsInteractor'; /** * creates a practitioner document for a practitioner @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getPractitionerDocumentsLambda = event => +export const getPractitionerDocumentsLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getPractitionerDocumentsInteractor(applicationContext, { + return await getPractitionerDocumentsInteractor( + applicationContext, + { barNumber: event.pathParameters.barNumber, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/practitioners/getPractitionersByNameLambda.ts b/web-api/src/lambdas/practitioners/getPractitionersByNameLambda.ts index ed41b853ac9..d62e227d34d 100644 --- a/web-api/src/lambdas/practitioners/getPractitionersByNameLambda.ts +++ b/web-api/src/lambdas/practitioners/getPractitionersByNameLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getPractitionersByNameInteractor } from '@web-api/business/useCases/practitioner/getPractitionersByNameInteractor'; /** * gets practitioner users by a search string (name or bar number) @@ -6,14 +8,19 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getPractitionersByNameLambda = event => +export const getPractitionersByNameLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { name, searchAfter } = event.queryStringParameters; - return await applicationContext - .getUseCases() - .getPractitionersByNameInteractor(applicationContext, { + return await getPractitionersByNameInteractor( + applicationContext, + { name, searchAfter, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/practitioners/updatePractitionerUserLambda.ts b/web-api/src/lambdas/practitioners/updatePractitionerUserLambda.ts index 1b8baf5c5ea..9f5bbb91fb8 100644 --- a/web-api/src/lambdas/practitioners/updatePractitionerUserLambda.ts +++ b/web-api/src/lambdas/practitioners/updatePractitionerUserLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updatePractitionerUserInteractor } from '@web-api/business/useCases/practitioner/updatePractitionerUserInteractor'; /** * updates a privatePractitioner or irsPractitioner user @@ -6,15 +8,20 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updatePractitionerUserLambda = event => +export const updatePractitionerUserLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { bypassDocketEntry = false, user } = JSON.parse(event.body); - return await applicationContext - .getUseCases() - .updatePractitionerUserInteractor(applicationContext, { + return await updatePractitionerUserInteractor( + applicationContext, + { barNumber: event.pathParameters.barNumber, bypassDocketEntry: bypassDocketEntry || false, user, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/public-api/casePublicSearchLambda.ts b/web-api/src/lambdas/public-api/casePublicSearchLambda.ts index c95701d4f58..d8b54766004 100644 --- a/web-api/src/lambdas/public-api/casePublicSearchLambda.ts +++ b/web-api/src/lambdas/public-api/casePublicSearchLambda.ts @@ -1,3 +1,4 @@ +import { casePublicSearchInteractor } from '@web-api/business/useCases/public/casePublicSearchInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -8,9 +9,7 @@ import { genericHandler } from '../../genericHandler'; */ export const casePublicSearchLambda = event => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .casePublicSearchInteractor(applicationContext, { - ...event.queryStringParameters, - }); + return await casePublicSearchInteractor(applicationContext, { + ...event.queryStringParameters, + }); }); diff --git a/web-api/src/lambdas/public-api/generatePublicDocketRecordPdfLambda.ts b/web-api/src/lambdas/public-api/generatePublicDocketRecordPdfLambda.ts index 3a35d56f3af..cfa1db87358 100644 --- a/web-api/src/lambdas/public-api/generatePublicDocketRecordPdfLambda.ts +++ b/web-api/src/lambdas/public-api/generatePublicDocketRecordPdfLambda.ts @@ -1,3 +1,4 @@ +import { generateDocketRecordPdfInteractor } from '@web-api/business/useCases/generateDocketRecordPdfInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -10,12 +11,14 @@ export const generatePublicDocketRecordPdfLambda = event => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .generateDocketRecordPdfInteractor(applicationContext, { + return await generateDocketRecordPdfInteractor( + applicationContext, + { ...JSON.parse(event.body), includePartyDetail: false, - }); + }, + undefined, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/public-api/getCaseForPublicDocketSearchLambda.ts b/web-api/src/lambdas/public-api/getCaseForPublicDocketSearchLambda.ts index 9d2a6ac5782..d7ce5fada6f 100644 --- a/web-api/src/lambdas/public-api/getCaseForPublicDocketSearchLambda.ts +++ b/web-api/src/lambdas/public-api/getCaseForPublicDocketSearchLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { getCaseForPublicDocketSearchInteractor } from '@web-api/business/useCases/public/getCaseForPublicDocketSearchInteractor'; /** * used for fetching a single case @@ -8,9 +9,7 @@ import { genericHandler } from '../../genericHandler'; */ export const getCaseForPublicDocketSearchLambda = event => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getCaseForPublicDocketSearchInteractor(applicationContext, { - docketNumber: event.pathParameters.docketNumber, - }); + return await getCaseForPublicDocketSearchInteractor(applicationContext, { + docketNumber: event.pathParameters.docketNumber, + }); }); diff --git a/web-api/src/lambdas/public-api/getPublicCaseExistsLambda.ts b/web-api/src/lambdas/public-api/getPublicCaseExistsLambda.ts index d2d7fa432f3..e340176cde0 100644 --- a/web-api/src/lambdas/public-api/getPublicCaseExistsLambda.ts +++ b/web-api/src/lambdas/public-api/getPublicCaseExistsLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { getCaseExistsInteractor } from '@shared/business/useCases/getCaseExistsInteractor'; /** * used for fetching existence of a single case @@ -8,9 +9,7 @@ import { genericHandler } from '../../genericHandler'; */ export const getPublicCaseExistsLambda = event => genericHandler(event, ({ applicationContext }) => - applicationContext - .getUseCases() - .getCaseExistsInteractor(applicationContext, { - docketNumber: event.pathParameters.docketNumber, - }), + getCaseExistsInteractor(applicationContext, { + docketNumber: event.pathParameters.docketNumber, + }), ); diff --git a/web-api/src/lambdas/public-api/getPublicCaseLambda.ts b/web-api/src/lambdas/public-api/getPublicCaseLambda.ts index ff70c6981bd..8693a9d438d 100644 --- a/web-api/src/lambdas/public-api/getPublicCaseLambda.ts +++ b/web-api/src/lambdas/public-api/getPublicCaseLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { getPublicCaseInteractor } from '@web-api/business/useCases/public/getPublicCaseInteractor'; /** * used for fetching a single case @@ -8,9 +9,7 @@ import { genericHandler } from '../../genericHandler'; */ export const getPublicCaseLambda = event => genericHandler(event, ({ applicationContext }) => - applicationContext - .getUseCases() - .getPublicCaseInteractor(applicationContext, { - docketNumber: event.pathParameters.docketNumber, - }), + getPublicCaseInteractor(applicationContext, { + docketNumber: event.pathParameters.docketNumber, + }), ); diff --git a/web-api/src/lambdas/public-api/getPublicDocumentDownloadUrlLambda.ts b/web-api/src/lambdas/public-api/getPublicDocumentDownloadUrlLambda.ts index e3738e20a22..bf49c8efae3 100644 --- a/web-api/src/lambdas/public-api/getPublicDocumentDownloadUrlLambda.ts +++ b/web-api/src/lambdas/public-api/getPublicDocumentDownloadUrlLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getPublicDownloadPolicyUrlInteractor } from '@web-api/business/useCases/public/getPublicDownloadPolicyUrlInteractor'; /** * used for fetching a single case @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getPublicDocumentDownloadUrlLambda = event => +export const getPublicDocumentDownloadUrlLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getPublicDownloadPolicyUrlInteractor(applicationContext, { + return await getPublicDownloadPolicyUrlInteractor( + applicationContext, + { ...event.pathParameters, isTerminalUser: event.isTerminalUser, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/public-api/opinionPublicSearchLambda.ts b/web-api/src/lambdas/public-api/opinionPublicSearchLambda.ts index 043895b2a3c..574dac6e6d7 100644 --- a/web-api/src/lambdas/public-api/opinionPublicSearchLambda.ts +++ b/web-api/src/lambdas/public-api/opinionPublicSearchLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { opinionPublicSearchInteractor } from '@web-api/business/useCases/public/opinionPublicSearchInteractor'; /** * used for fetching opinions matching the given filters @@ -11,10 +12,8 @@ export const opinionPublicSearchLambda = event => const opinionTypes = event.queryStringParameters.opinionTypes?.split(',') || []; - return await applicationContext - .getUseCases() - .opinionPublicSearchInteractor(applicationContext, { - ...event.queryStringParameters, - opinionTypes, - }); + return await opinionPublicSearchInteractor(applicationContext, { + ...event.queryStringParameters, + opinionTypes, + }); }); diff --git a/web-api/src/lambdas/public-api/orderPublicSearchLambda.ts b/web-api/src/lambdas/public-api/orderPublicSearchLambda.ts index 32c5983e3a6..d25db34f167 100644 --- a/web-api/src/lambdas/public-api/orderPublicSearchLambda.ts +++ b/web-api/src/lambdas/public-api/orderPublicSearchLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { orderPublicSearchInteractor } from '@web-api/business/useCases/public/orderPublicSearchInteractor'; /** * used for fetching orders matching the given a keyword @@ -8,9 +9,7 @@ import { genericHandler } from '../../genericHandler'; */ export const orderPublicSearchLambda = event => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .orderPublicSearchInteractor(applicationContext, { - ...event.queryStringParameters, - }); + return await orderPublicSearchInteractor(applicationContext, { + ...event.queryStringParameters, + }); }); diff --git a/web-api/src/lambdas/public-api/todaysOpinionsLambda.ts b/web-api/src/lambdas/public-api/todaysOpinionsLambda.ts index 5b861f4b5d3..74c960f4c8d 100644 --- a/web-api/src/lambdas/public-api/todaysOpinionsLambda.ts +++ b/web-api/src/lambdas/public-api/todaysOpinionsLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { getTodaysOpinionsInteractor } from '@web-api/business/useCases/public/getTodaysOpinionsInteractor'; /** * used for fetching opinions created for the current date @@ -8,7 +9,5 @@ import { genericHandler } from '../../genericHandler'; */ export const todaysOpinionsLambda = event => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getTodaysOpinionsInteractor(applicationContext); + return await getTodaysOpinionsInteractor(applicationContext); }); diff --git a/web-api/src/lambdas/public-api/todaysOrdersLambda.ts b/web-api/src/lambdas/public-api/todaysOrdersLambda.ts index aeb093d36a0..8b36c922c6d 100644 --- a/web-api/src/lambdas/public-api/todaysOrdersLambda.ts +++ b/web-api/src/lambdas/public-api/todaysOrdersLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../../genericHandler'; +import { getTodaysOrdersInteractor } from '@web-api/business/useCases/public/getTodaysOrdersInteractor'; /** * used for fetching orders served on the current date @@ -8,7 +9,8 @@ import { genericHandler } from '../../genericHandler'; */ export const todaysOrdersLambda = event => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getTodaysOrdersInteractor(applicationContext, event.pathParameters); + return await getTodaysOrdersInteractor( + applicationContext, + event.pathParameters, + ); }); diff --git a/web-api/src/lambdas/reports/coldCaseReportLambda.ts b/web-api/src/lambdas/reports/coldCaseReportLambda.ts index 0b2484b70d1..d18a46bb017 100644 --- a/web-api/src/lambdas/reports/coldCaseReportLambda.ts +++ b/web-api/src/lambdas/reports/coldCaseReportLambda.ts @@ -1,8 +1,8 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { coldCaseReportInteractor } from '@web-api/business/useCases/reports/coldCaseReportInteractor'; import { genericHandler } from '../../genericHandler'; -export const coldCaseReportLambda = event => +export const coldCaseReportLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .coldCaseReportInteractor(applicationContext); + return await coldCaseReportInteractor(applicationContext, authorizedUser); }); diff --git a/web-api/src/lambdas/reports/createCsvCustomCaseReportFileLambda.ts b/web-api/src/lambdas/reports/createCsvCustomCaseReportFileLambda.ts index 85e38b90b1d..e9037608cb2 100644 --- a/web-api/src/lambdas/reports/createCsvCustomCaseReportFileLambda.ts +++ b/web-api/src/lambdas/reports/createCsvCustomCaseReportFileLambda.ts @@ -1,11 +1,15 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { createCsvCustomCaseReportFileInteractor } from '@web-api/business/useCases/customCaseReport/createCsvCustomCaseReportFileInteractor'; import { genericHandler } from '../../genericHandler'; -export const createCsvCustomCaseReportFileLambda = event => +export const createCsvCustomCaseReportFileLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .createCsvCustomCaseReportFileInteractor( - applicationContext, - JSON.parse(event.body), - ); + return await createCsvCustomCaseReportFileInteractor( + applicationContext, + JSON.parse(event.body), + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/reports/generatePrintableCaseInventoryReportLambda.ts b/web-api/src/lambdas/reports/generatePrintableCaseInventoryReportLambda.ts index 4e1aa51cb84..824847455b4 100644 --- a/web-api/src/lambdas/reports/generatePrintableCaseInventoryReportLambda.ts +++ b/web-api/src/lambdas/reports/generatePrintableCaseInventoryReportLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { generatePrintableCaseInventoryReportInteractor } from '@web-api/business/useCases/caseInventoryReport/generatePrintableCaseInventoryReportInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,15 +8,20 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const generatePrintableCaseInventoryReportLambda = event => +export const generatePrintableCaseInventoryReportLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .generatePrintableCaseInventoryReportInteractor(applicationContext, { + return await generatePrintableCaseInventoryReportInteractor( + applicationContext, + { ...event.queryStringParameters, - }); + }, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/reports/getBlockedCasesLambda.ts b/web-api/src/lambdas/reports/getBlockedCasesLambda.ts index e5333f6f4fb..fc20016f80b 100644 --- a/web-api/src/lambdas/reports/getBlockedCasesLambda.ts +++ b/web-api/src/lambdas/reports/getBlockedCasesLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getBlockedCasesInteractor } from '@shared/business/useCases/getBlockedCasesInteractor'; /** * used for getting all the blocked cases for a trial location @@ -6,11 +8,13 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getBlockedCasesLambda = event => +export const getBlockedCasesLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getBlockedCasesInteractor(applicationContext, { + return await getBlockedCasesInteractor( + applicationContext, + { trialLocation: event.pathParameters.trialLocation, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/reports/getCaseInventoryReportLambda.ts b/web-api/src/lambdas/reports/getCaseInventoryReportLambda.ts index 899dc41fdeb..456fea0d8b5 100644 --- a/web-api/src/lambdas/reports/getCaseInventoryReportLambda.ts +++ b/web-api/src/lambdas/reports/getCaseInventoryReportLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getCaseInventoryReportInteractor } from '@web-api/business/useCases/caseInventoryReport/getCaseInventoryReportInteractor'; /** * used for fetching the case inventory report data @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getCaseInventoryReportLambda = event => +export const getCaseInventoryReportLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getCaseInventoryReportInteractor(applicationContext, { + return await getCaseInventoryReportInteractor( + applicationContext, + { ...event.queryStringParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/reports/getCaseWorksheetsByJudgeLambda.ts b/web-api/src/lambdas/reports/getCaseWorksheetsByJudgeLambda.ts index 2a148721f3a..1d3b5c33043 100644 --- a/web-api/src/lambdas/reports/getCaseWorksheetsByJudgeLambda.ts +++ b/web-api/src/lambdas/reports/getCaseWorksheetsByJudgeLambda.ts @@ -1,16 +1,20 @@ -import { APIGatewayProxyEvent } from 'aws-lambda'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getCaseWorksheetsByJudgeInteractor } from '@web-api/business/useCases/judgeActivityReport/getCaseWorksheetsByJudgeInteractor'; -export const getCaseWorksheetsByJudgeLambda = (event: APIGatewayProxyEvent) => +export const getCaseWorksheetsByJudgeLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler( event, + async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getCaseWorksheetsByJudgeInteractor( - applicationContext, - event.queryStringParameters, - ); + return await getCaseWorksheetsByJudgeInteractor( + applicationContext, + event.queryStringParameters, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/reports/getCasesClosedByJudgeLambda.ts b/web-api/src/lambdas/reports/getCasesClosedByJudgeLambda.ts index 23b65351c7d..204daab14de 100644 --- a/web-api/src/lambdas/reports/getCasesClosedByJudgeLambda.ts +++ b/web-api/src/lambdas/reports/getCasesClosedByJudgeLambda.ts @@ -1,19 +1,21 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getCasesClosedByJudgeInteractor } from '@web-api/business/useCases/judgeActivityReport/getCasesClosedByJudgeInteractor'; -/** - * retrieves closed cases associated with the specified judge - * @param {object} event the AWS event object - * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers - */ -export const getCasesClosedByJudgeLambda = event => +export const getCasesClosedByJudgeLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getCasesClosedByJudgeInteractor(applicationContext, { + return await getCasesClosedByJudgeInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/reports/getCountOfCaseDocumentsFiledByJudgesLambda.ts b/web-api/src/lambdas/reports/getCountOfCaseDocumentsFiledByJudgesLambda.ts index dc7a12f2203..a466e05747c 100644 --- a/web-api/src/lambdas/reports/getCountOfCaseDocumentsFiledByJudgesLambda.ts +++ b/web-api/src/lambdas/reports/getCountOfCaseDocumentsFiledByJudgesLambda.ts @@ -1,19 +1,15 @@ -import { APIGatewayProxyEvent } from 'aws-lambda'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getCountOfCaseDocumentsFiledByJudgesInteractor } from '@web-api/business/useCases/judgeActivityReport/getCountOfCaseDocumentsFiledByJudgesInteractor'; -/** - * gets the count of cases documents filed by judge for their activity report - * @param {object} event the AWS event object - * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers - */ export const getCountOfCaseDocumentsFiledByJudgesLambda = ( - event: APIGatewayProxyEvent, + event, + authorizedUser: UnknownAuthUser, ) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getCountOfCaseDocumentsFiledByJudgesInteractor( - applicationContext, - event.queryStringParameters, - ); + return await getCountOfCaseDocumentsFiledByJudgesInteractor( + applicationContext, + event.queryStringParameters, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/reports/getTrialSessionsForJudgeActivityReportLambda.ts b/web-api/src/lambdas/reports/getTrialSessionsForJudgeActivityReportLambda.ts index 65deb2f8f28..d3b1491a5f0 100644 --- a/web-api/src/lambdas/reports/getTrialSessionsForJudgeActivityReportLambda.ts +++ b/web-api/src/lambdas/reports/getTrialSessionsForJudgeActivityReportLambda.ts @@ -1,14 +1,21 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getTrialSessionsForJudgeActivityReportInteractor } from '@web-api/business/useCases/judgeActivityReport/getTrialSessionsForJudgeActivityReportInteractor'; -export const getTrialSessionsForJudgeActivityReportLambda = event => +export const getTrialSessionsForJudgeActivityReportLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getTrialSessionsForJudgeActivityReportInteractor(applicationContext, { + return await getTrialSessionsForJudgeActivityReportInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/trialSessions/addCaseToTrialSessionLambda.ts b/web-api/src/lambdas/trialSessions/addCaseToTrialSessionLambda.ts index 7187d83c42f..a7a115a1f52 100644 --- a/web-api/src/lambdas/trialSessions/addCaseToTrialSessionLambda.ts +++ b/web-api/src/lambdas/trialSessions/addCaseToTrialSessionLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { addCaseToTrialSessionInteractor } from '@web-api/business/useCases/trialSessions/addCaseToTrialSessionInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,16 +8,21 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const addCaseToTrialSessionLambda = event => +export const addCaseToTrialSessionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { docketNumber, trialSessionId } = event.pathParameters || event.path; const { calendarNotes } = JSON.parse(event.body); - return await applicationContext - .getUseCases() - .addCaseToTrialSessionInteractor(applicationContext, { + return await addCaseToTrialSessionInteractor( + applicationContext, + { calendarNotes, docketNumber, trialSessionId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/batchDownloadTrialSessionLambda.ts b/web-api/src/lambdas/trialSessions/batchDownloadTrialSessionLambda.ts index 60f11d90b4b..cbdb7317a15 100644 --- a/web-api/src/lambdas/trialSessions/batchDownloadTrialSessionLambda.ts +++ b/web-api/src/lambdas/trialSessions/batchDownloadTrialSessionLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { batchDownloadTrialSessionInteractor } from '@web-api/business/useCases/trialSessions/batchDownloadTrialSessionInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const batchDownloadTrialSessionLambda = event => +export const batchDownloadTrialSessionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { trialSessionId } = event.pathParameters || event.path; - return await applicationContext - .getUseCases() - .batchDownloadTrialSessionInteractor(applicationContext, { + return await batchDownloadTrialSessionInteractor( + applicationContext, + { trialSessionId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/closeTrialSessionLambda.ts b/web-api/src/lambdas/trialSessions/closeTrialSessionLambda.ts index 3d8429854d5..51ba0394fd9 100644 --- a/web-api/src/lambdas/trialSessions/closeTrialSessionLambda.ts +++ b/web-api/src/lambdas/trialSessions/closeTrialSessionLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { closeTrialSessionInteractor } from '@web-api/business/useCases/trialSessions/closeTrialSessionInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const closeTrialSessionLambda = event => +export const closeTrialSessionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { trialSessionId } = event.pathParameters || {}; - return await applicationContext - .getUseCases() - .closeTrialSessionInteractor(applicationContext, { + return await closeTrialSessionInteractor( + applicationContext, + { trialSessionId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/createTrialSessionLambda.ts b/web-api/src/lambdas/trialSessions/createTrialSessionLambda.ts index c19b1b75307..ce141309ed0 100644 --- a/web-api/src/lambdas/trialSessions/createTrialSessionLambda.ts +++ b/web-api/src/lambdas/trialSessions/createTrialSessionLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { createTrialSessionInteractor } from '@web-api/business/useCases/trialSessions/createTrialSessionInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const createTrialSessionLambda = event => +export const createTrialSessionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .createTrialSessionInteractor(applicationContext, { + return await createTrialSessionInteractor( + applicationContext, + { trialSession: JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/deleteTrialSessionLambda.ts b/web-api/src/lambdas/trialSessions/deleteTrialSessionLambda.ts index c44b11ee602..02d1433f10c 100644 --- a/web-api/src/lambdas/trialSessions/deleteTrialSessionLambda.ts +++ b/web-api/src/lambdas/trialSessions/deleteTrialSessionLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { deleteTrialSessionInteractor } from '@web-api/business/useCases/trialSessions/deleteTrialSessionInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const deleteTrialSessionLambda = event => +export const deleteTrialSessionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { trialSessionId } = event.pathParameters || {}; - return await applicationContext - .getUseCases() - .deleteTrialSessionInteractor(applicationContext, { + return await deleteTrialSessionInteractor( + applicationContext, + { trialSessionId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/dismissNOTTReminderForTrialLambda.ts b/web-api/src/lambdas/trialSessions/dismissNOTTReminderForTrialLambda.ts index 78b5a516c83..71c30c1e93e 100644 --- a/web-api/src/lambdas/trialSessions/dismissNOTTReminderForTrialLambda.ts +++ b/web-api/src/lambdas/trialSessions/dismissNOTTReminderForTrialLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { dismissNOTTReminderForTrialInteractor } from '@web-api/business/useCases/trialSessions/dismissNOTTReminderForTrialInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -5,11 +7,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const dismissNOTTReminderForTrialLambda = event => +export const dismissNOTTReminderForTrialLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .dismissNOTTReminderForTrialInteractor(applicationContext, { + return await dismissNOTTReminderForTrialInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/generateTrialCalendarPdfLambda.ts b/web-api/src/lambdas/trialSessions/generateTrialCalendarPdfLambda.ts index 18366eb7cef..fa2cb16552f 100644 --- a/web-api/src/lambdas/trialSessions/generateTrialCalendarPdfLambda.ts +++ b/web-api/src/lambdas/trialSessions/generateTrialCalendarPdfLambda.ts @@ -1,3 +1,4 @@ +import { generateTrialCalendarPdfInteractor } from '@web-api/business/useCases/trialSessions/generateTrialCalendarPdfInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -12,11 +13,9 @@ export const generateTrialCalendarPdfLambda = event => async ({ applicationContext }) => { const { trialSessionId } = JSON.parse(event.body); - return await applicationContext - .getUseCases() - .generateTrialCalendarPdfInteractor(applicationContext, { - trialSessionId, - }); + return await generateTrialCalendarPdfInteractor(applicationContext, { + trialSessionId, + }); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/trialSessions/getCalendaredCasesForTrialSessionLambda.ts b/web-api/src/lambdas/trialSessions/getCalendaredCasesForTrialSessionLambda.ts index 851268ca194..db8286b9218 100644 --- a/web-api/src/lambdas/trialSessions/getCalendaredCasesForTrialSessionLambda.ts +++ b/web-api/src/lambdas/trialSessions/getCalendaredCasesForTrialSessionLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getCalendaredCasesForTrialSessionInteractor } from '@web-api/business/useCases/trialSessions/getCalendaredCasesForTrialSessionInteractor'; /** * get cases calendared on a trial session @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getCalendaredCasesForTrialSessionLambda = event => +export const getCalendaredCasesForTrialSessionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { trialSessionId } = event.pathParameters || {}; - return await applicationContext - .getUseCases() - .getCalendaredCasesForTrialSessionInteractor(applicationContext, { + return await getCalendaredCasesForTrialSessionInteractor( + applicationContext, + { trialSessionId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/getEligibleCasesForTrialSessionLambda.ts b/web-api/src/lambdas/trialSessions/getEligibleCasesForTrialSessionLambda.ts index 6b5696412b8..7730f9edb92 100644 --- a/web-api/src/lambdas/trialSessions/getEligibleCasesForTrialSessionLambda.ts +++ b/web-api/src/lambdas/trialSessions/getEligibleCasesForTrialSessionLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getEligibleCasesForTrialSessionInteractor } from '@web-api/business/useCases/trialSessions/getEligibleCasesForTrialSessionInteractor'; /** * get eligible cases for trial session @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getEligibleCasesForTrialSessionLambda = event => +export const getEligibleCasesForTrialSessionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { trialSessionId } = event.pathParameters || {}; - return await applicationContext - .getUseCases() - .getEligibleCasesForTrialSessionInteractor(applicationContext, { + return await getEligibleCasesForTrialSessionInteractor( + applicationContext, + { trialSessionId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/getGeneratePrintableTrialSessionCopyReportLambda.ts b/web-api/src/lambdas/trialSessions/getGeneratePrintableTrialSessionCopyReportLambda.ts index a22feeb91d2..51c07c05c16 100644 --- a/web-api/src/lambdas/trialSessions/getGeneratePrintableTrialSessionCopyReportLambda.ts +++ b/web-api/src/lambdas/trialSessions/getGeneratePrintableTrialSessionCopyReportLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { generatePrintableTrialSessionCopyReportInteractor } from '@web-api/business/useCases/trialSessions/generatePrintableTrialSessionCopyReportInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,12 +8,15 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getGeneratePrintableTrialSessionCopyReportLambda = event => +export const getGeneratePrintableTrialSessionCopyReportLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const body = JSON.parse(event.body); - return await applicationContext - .getUseCases() - .generatePrintableTrialSessionCopyReportInteractor(applicationContext, { + return await generatePrintableTrialSessionCopyReportInteractor( + applicationContext, + { filters: body.filters, formattedCases: body.formattedCases, formattedTrialSession: body.formattedTrialSession, @@ -19,5 +24,7 @@ export const getGeneratePrintableTrialSessionCopyReportLambda = event => showCaseNotes: body.showCaseNotes, sort: body.sort, userHeading: body.userHeading, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/getPaperServicePdfUrlLambda.ts b/web-api/src/lambdas/trialSessions/getPaperServicePdfUrlLambda.ts index 4edcb2131ff..b098ae1f646 100644 --- a/web-api/src/lambdas/trialSessions/getPaperServicePdfUrlLambda.ts +++ b/web-api/src/lambdas/trialSessions/getPaperServicePdfUrlLambda.ts @@ -1,16 +1,19 @@ -import { APIGatewayProxyEvent } from 'aws-lambda'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getPaperServicePdfUrlInteractor } from '@shared/business/useCases/getPaperServicePdfUrlInteractor'; -export const getPaperServicePdfUrlLambda = (event: APIGatewayProxyEvent) => +export const getPaperServicePdfUrlLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getPaperServicePdfUrlInteractor( - applicationContext, - event.pathParameters, - ); + return await getPaperServicePdfUrlInteractor( + applicationContext, + event.pathParameters, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/trialSessions/getTrialSessionDetailsLambda.ts b/web-api/src/lambdas/trialSessions/getTrialSessionDetailsLambda.ts index d57ee20f1c3..6b92235d009 100644 --- a/web-api/src/lambdas/trialSessions/getTrialSessionDetailsLambda.ts +++ b/web-api/src/lambdas/trialSessions/getTrialSessionDetailsLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getTrialSessionDetailsInteractor } from '@web-api/business/useCases/trialSessions/getTrialSessionDetailsInteractor'; /** * gets trial session details @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getTrialSessionDetailsLambda = event => +export const getTrialSessionDetailsLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { trialSessionId } = event.pathParameters || {}; - return await applicationContext - .getUseCases() - .getTrialSessionDetailsInteractor(applicationContext, { + return await getTrialSessionDetailsInteractor( + applicationContext, + { trialSessionId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/getTrialSessionWorkingCopyLambda.ts b/web-api/src/lambdas/trialSessions/getTrialSessionWorkingCopyLambda.ts index ff90a692db0..060abc2f821 100644 --- a/web-api/src/lambdas/trialSessions/getTrialSessionWorkingCopyLambda.ts +++ b/web-api/src/lambdas/trialSessions/getTrialSessionWorkingCopyLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getTrialSessionWorkingCopyInteractor } from '@web-api/business/useCases/trialSessions/getTrialSessionWorkingCopyInteractor'; /** * get a judge's working copy of a trial session @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getTrialSessionWorkingCopyLambda = event => +export const getTrialSessionWorkingCopyLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { trialSessionId } = event.pathParameters || {}; - return await applicationContext - .getUseCases() - .getTrialSessionWorkingCopyInteractor(applicationContext, { + return await getTrialSessionWorkingCopyInteractor( + applicationContext, + { trialSessionId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/getTrialSessionsForJudgeLambda.ts b/web-api/src/lambdas/trialSessions/getTrialSessionsForJudgeLambda.ts index ab395104279..c48051eea35 100644 --- a/web-api/src/lambdas/trialSessions/getTrialSessionsForJudgeLambda.ts +++ b/web-api/src/lambdas/trialSessions/getTrialSessionsForJudgeLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getTrialSessionsForJudgeInteractor } from '@web-api/business/useCases/trialSessions/getTrialSessionsForJudgeInteractor'; /** * gets all trial sessions for a judge @@ -6,12 +8,14 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getTrialSessionsForJudgeLambda = event => +export const getTrialSessionsForJudgeLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getTrialSessionsForJudgeInteractor( - applicationContext, - event.pathParameters.judgeId, - ); + return await getTrialSessionsForJudgeInteractor( + applicationContext, + event.pathParameters.judgeId, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/getTrialSessionsLambda.ts b/web-api/src/lambdas/trialSessions/getTrialSessionsLambda.ts index 395074488a6..c86f6e4e898 100644 --- a/web-api/src/lambdas/trialSessions/getTrialSessionsLambda.ts +++ b/web-api/src/lambdas/trialSessions/getTrialSessionsLambda.ts @@ -1,14 +1,18 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getTrialSessionsInteractor } from '@web-api/business/useCases/trialSessions/getTrialSessionsInteractor'; /** * gets all trial sessions * * @param {object} event the AWS event object + * @param {object} authorizedUser the user object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getTrialSessionsLambda = event => +export const getTrialSessionsLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getTrialSessionsInteractor(applicationContext); + return await getTrialSessionsInteractor(applicationContext, authorizedUser); }); diff --git a/web-api/src/lambdas/trialSessions/removeCaseFromTrialLambda.ts b/web-api/src/lambdas/trialSessions/removeCaseFromTrialLambda.ts index cc28b4c0eeb..07895a08989 100644 --- a/web-api/src/lambdas/trialSessions/removeCaseFromTrialLambda.ts +++ b/web-api/src/lambdas/trialSessions/removeCaseFromTrialLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { removeCaseFromTrialInteractor } from '@web-api/business/useCases/trialSessions/removeCaseFromTrialInteractor'; /** * used for setting a case on a trial session to removedFromTrial @@ -6,20 +8,25 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const removeCaseFromTrialLambda = event => +export const removeCaseFromTrialLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { docketNumber, trialSessionId } = event.pathParameters || event.path; const { associatedJudge, associatedJudgeId, caseStatus, disposition } = JSON.parse(event.body); - return await applicationContext - .getUseCases() - .removeCaseFromTrialInteractor(applicationContext, { + return await removeCaseFromTrialInteractor( + applicationContext, + { associatedJudge, associatedJudgeId, caseStatus, disposition, docketNumber, trialSessionId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/runTrialSessionPlanningReportLambda.ts b/web-api/src/lambdas/trialSessions/runTrialSessionPlanningReportLambda.ts index 06e67990d8d..df8a347d28e 100644 --- a/web-api/src/lambdas/trialSessions/runTrialSessionPlanningReportLambda.ts +++ b/web-api/src/lambdas/trialSessions/runTrialSessionPlanningReportLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { runTrialSessionPlanningReportInteractor } from '@web-api/business/useCases/trialSessions/runTrialSessionPlanningReportInteractor'; /** * run the trial session planning report @@ -6,15 +8,20 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const runTrialSessionPlanningReportLambda = event => +export const runTrialSessionPlanningReportLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .runTrialSessionPlanningReportInteractor(applicationContext, { + return await runTrialSessionPlanningReportInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }, { logResults: false }, ); diff --git a/web-api/src/lambdas/trialSessions/saveCalendarNoteLambda.ts b/web-api/src/lambdas/trialSessions/saveCalendarNoteLambda.ts index ac0d7f7d237..468914a60d3 100644 --- a/web-api/src/lambdas/trialSessions/saveCalendarNoteLambda.ts +++ b/web-api/src/lambdas/trialSessions/saveCalendarNoteLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { saveCalendarNoteInteractor } from '@web-api/business/useCases/trialSessions/saveCalendarNoteInteractor'; /** * used for saving a case's calendar note for a trial session @@ -6,16 +8,21 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const saveCalendarNoteLambda = event => +export const saveCalendarNoteLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const lambdaArguments = { ...event.pathParameters, ...JSON.parse(event.body), }; - return await applicationContext - .getUseCases() - .saveCalendarNoteInteractor(applicationContext, { + return await saveCalendarNoteInteractor( + applicationContext, + { ...lambdaArguments, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/serveThirtyDayNoticeLambda.ts b/web-api/src/lambdas/trialSessions/serveThirtyDayNoticeLambda.ts index edd41a12c17..68d6d304b4f 100644 --- a/web-api/src/lambdas/trialSessions/serveThirtyDayNoticeLambda.ts +++ b/web-api/src/lambdas/trialSessions/serveThirtyDayNoticeLambda.ts @@ -1,12 +1,19 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { serveThirtyDayNoticeInteractor } from '@web-api/business/useCases/trialSessions/serveThirtyDayNoticeInteractor'; -export const serveThirtyDayNoticeLambda = event => +export const serveThirtyDayNoticeLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { clientConnectionId, trialSessionId } = JSON.parse(event.body); - return await applicationContext - .getUseCases() - .serveThirtyDayNoticeInteractor(applicationContext, { + return await serveThirtyDayNoticeInteractor( + applicationContext, + { clientConnectionId, trialSessionId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/setForHearingLambda.ts b/web-api/src/lambdas/trialSessions/setForHearingLambda.ts index bd4a2d39e15..37d1fe7951c 100644 --- a/web-api/src/lambdas/trialSessions/setForHearingLambda.ts +++ b/web-api/src/lambdas/trialSessions/setForHearingLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { setForHearingInteractor } from '@web-api/business/useCases/trialSessions/setForHearingInteractor'; /** * creates a new trial session. @@ -6,17 +8,19 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const setForHearingLambda = event => +export const setForHearingLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { const { docketNumber, trialSessionId } = event.pathParameters || event.path || {}; const { calendarNotes } = JSON.parse(event.body); - return await applicationContext - .getUseCases() - .setForHearingInteractor(applicationContext, { + return await setForHearingInteractor( + applicationContext, + { calendarNotes, docketNumber, trialSessionId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/setNoticesForCalendaredTrialSessionLambda.ts b/web-api/src/lambdas/trialSessions/setNoticesForCalendaredTrialSessionLambda.ts index 5e6056cdfa4..147b209e131 100644 --- a/web-api/src/lambdas/trialSessions/setNoticesForCalendaredTrialSessionLambda.ts +++ b/web-api/src/lambdas/trialSessions/setNoticesForCalendaredTrialSessionLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { setNoticesForCalendaredTrialSessionInteractor } from '@web-api/business/useCases/trialSessions/setNoticesForCalendaredTrialSessionInteractor'; /** * used for generating / setting notices of trial on cases set for the given trial session @@ -6,14 +8,19 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const setNoticesForCalendaredTrialSessionLambda = event => +export const setNoticesForCalendaredTrialSessionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { trialSessionId } = event.pathParameters || event.path || {}; - return await applicationContext - .getUseCases() - .setNoticesForCalendaredTrialSessionInteractor(applicationContext, { + return await setNoticesForCalendaredTrialSessionInteractor( + applicationContext, + { ...JSON.parse(event.body), trialSessionId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/setTrialSessionCalendarLambda.ts b/web-api/src/lambdas/trialSessions/setTrialSessionCalendarLambda.ts index a7400a82044..e50743186e2 100644 --- a/web-api/src/lambdas/trialSessions/setTrialSessionCalendarLambda.ts +++ b/web-api/src/lambdas/trialSessions/setTrialSessionCalendarLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { setTrialSessionCalendarInteractor } from '@web-api/business/useCases/trialSessions/setTrialSessionCalendarInteractor'; /** * set trial session calendar @@ -6,14 +8,19 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const setTrialSessionCalendarLambda = event => +export const setTrialSessionCalendarLambda = ( + event, + authorizedUser: UnknownAuthUser, +): Promise => genericHandler(event, async ({ applicationContext }) => { const { trialSessionId } = event.pathParameters || {}; - return await applicationContext - .getUseCases() - .setTrialSessionCalendarInteractor(applicationContext, { + return await setTrialSessionCalendarInteractor( + applicationContext, + { ...JSON.parse(event.body), trialSessionId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/updateTrialSessionLambda.ts b/web-api/src/lambdas/trialSessions/updateTrialSessionLambda.ts index e358c470acb..f292cbadc9d 100644 --- a/web-api/src/lambdas/trialSessions/updateTrialSessionLambda.ts +++ b/web-api/src/lambdas/trialSessions/updateTrialSessionLambda.ts @@ -1,15 +1,22 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateTrialSessionInteractor } from '@web-api/business/useCases/trialSessions/updateTrialSessionInteractor'; /** * updates a trial session. * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateTrialSessionLambda = event => +export const updateTrialSessionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateTrialSessionInteractor(applicationContext, { + return await updateTrialSessionInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/trialSessions/updateTrialSessionWorkingCopyLambda.ts b/web-api/src/lambdas/trialSessions/updateTrialSessionWorkingCopyLambda.ts index bc6a7754e47..712c37f75b7 100644 --- a/web-api/src/lambdas/trialSessions/updateTrialSessionWorkingCopyLambda.ts +++ b/web-api/src/lambdas/trialSessions/updateTrialSessionWorkingCopyLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateTrialSessionWorkingCopyInteractor } from '@web-api/business/useCases/trialSessions/updateTrialSessionWorkingCopyInteractor'; /** * update a judge's working copy of a trial session @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateTrialSessionWorkingCopyLambda = event => +export const updateTrialSessionWorkingCopyLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateTrialSessionWorkingCopyInteractor(applicationContext, { + return await updateTrialSessionWorkingCopyInteractor( + applicationContext, + { trialSessionWorkingCopyToUpdate: JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/users/checkEmailAvailabilityLambda.ts b/web-api/src/lambdas/users/checkEmailAvailabilityLambda.ts index 7b57ff78064..a288a601b10 100644 --- a/web-api/src/lambdas/users/checkEmailAvailabilityLambda.ts +++ b/web-api/src/lambdas/users/checkEmailAvailabilityLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { checkEmailAvailabilityInteractor } from '@web-api/business/useCases/user/checkEmailAvailabilityInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const checkEmailAvailabilityLambda = event => +export const checkEmailAvailabilityLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { email } = event.queryStringParameters; - return await applicationContext - .getUseCases() - .checkEmailAvailabilityInteractor(applicationContext, { + return await checkEmailAvailabilityInteractor( + applicationContext, + { email, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/users/createUserLambda.ts b/web-api/src/lambdas/users/createUserLambda.ts index 131da54ebd6..617ae9d327e 100644 --- a/web-api/src/lambdas/users/createUserLambda.ts +++ b/web-api/src/lambdas/users/createUserLambda.ts @@ -1,10 +1,15 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { createUserInteractor } from '@web-api/business/useCases/user/createUserInteractor'; import { genericHandler } from '../../genericHandler'; // This is a special lambda that is only meant to be used by admins. -export const createUserLambda = event => +export const createUserLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await createUserInteractor(applicationContext, { - user: JSON.parse(event.body), - }); + return await createUserInteractor( + applicationContext, + { + user: JSON.parse(event.body), + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/users/getAllUsersByRoleLambda.ts b/web-api/src/lambdas/users/getAllUsersByRoleLambda.ts index 12e9b8abb7f..4bd8490891f 100644 --- a/web-api/src/lambdas/users/getAllUsersByRoleLambda.ts +++ b/web-api/src/lambdas/users/getAllUsersByRoleLambda.ts @@ -1,15 +1,19 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getAllUsersByRoleInteractor } from '@shared/business/useCases/getAllUsersByRoleInteractor'; -export const getAllUsersByRoleLambda = event => +export const getAllUsersByRoleLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getAllUsersByRoleInteractor( - applicationContext, - event.queryStringParameters, - ); + return await getAllUsersByRoleInteractor( + applicationContext, + event.queryStringParameters, + authorizedUser, + ); }, { bypassMaintenanceCheck: true, diff --git a/web-api/src/lambdas/users/getInternalUsersLambda.ts b/web-api/src/lambdas/users/getInternalUsersLambda.ts index 51956265395..28fe31ce72d 100644 --- a/web-api/src/lambdas/users/getInternalUsersLambda.ts +++ b/web-api/src/lambdas/users/getInternalUsersLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getInternalUsersInteractor } from '@web-api/business/useCases/user/getInternalUsersInteractor'; /** * creates a new document and attaches it to a case. It also creates a work item on the docket section. @@ -6,9 +8,10 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getInternalUsersLambda = event => +export const getInternalUsersLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getInternalUsersInteractor(applicationContext); + return await getInternalUsersInteractor(applicationContext, authorizedUser); }); diff --git a/web-api/src/lambdas/users/getIrsPractitionersBySearchKeyLambda.ts b/web-api/src/lambdas/users/getIrsPractitionersBySearchKeyLambda.ts index 3f56c5575be..59b7fdc5cc6 100644 --- a/web-api/src/lambdas/users/getIrsPractitionersBySearchKeyLambda.ts +++ b/web-api/src/lambdas/users/getIrsPractitionersBySearchKeyLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getIrsPractitionersBySearchKeyInteractor } from '@web-api/business/useCases/user/getIrsPractitionersBySearchKeyInteractor'; /** * gets irsPractitioner users by a search string (name or bar number) @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getIrsPractitionersBySearchKeyLambda = event => +export const getIrsPractitionersBySearchKeyLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { searchKey } = event.queryStringParameters; - return await applicationContext - .getUseCases() - .getIrsPractitionersBySearchKeyInteractor(applicationContext, { + return await getIrsPractitionersBySearchKeyInteractor( + applicationContext, + { searchKey, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/users/getJudgeInSectionLambda.ts b/web-api/src/lambdas/users/getJudgeInSectionLambda.ts index 8156c0360b9..cb5a6e5a7bd 100644 --- a/web-api/src/lambdas/users/getJudgeInSectionLambda.ts +++ b/web-api/src/lambdas/users/getJudgeInSectionLambda.ts @@ -1,16 +1,17 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getJudgeInSectionInteractor } from '@web-api/business/useCases/user/getJudgeInSectionInteractor'; -/** - * returns the judge associated with a chambers section - * - * @param {object} event the AWS event object - * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers - */ -export const getJudgeInSectionLambda = event => +export const getJudgeInSectionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getJudgeInSectionInteractor(applicationContext, { + return await getJudgeInSectionInteractor( + applicationContext, + { section: event.pathParameters.section, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/users/getNotificationsLambda.ts b/web-api/src/lambdas/users/getNotificationsLambda.ts index 8d696fabdf5..78e1d7b7f86 100644 --- a/web-api/src/lambdas/users/getNotificationsLambda.ts +++ b/web-api/src/lambdas/users/getNotificationsLambda.ts @@ -1,16 +1,23 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getNotificationsInteractor } from '@shared/business/useCases/getNotificationsInteractor'; /** - * creates a new document and attaches it to a case. It also creates a work item on the docket section. + * creates a new document and attaches it to a case. It also creates a work item on the docket section. * * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getNotificationsLambda = event => +export const getNotificationsLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getNotificationsInteractor(applicationContext, { + return await getNotificationsInteractor( + applicationContext, + { ...event.queryStringParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/users/getPrivatePractitionersBySearchKeyLambda.ts b/web-api/src/lambdas/users/getPrivatePractitionersBySearchKeyLambda.ts index c2d610e1360..325bace2ce7 100644 --- a/web-api/src/lambdas/users/getPrivatePractitionersBySearchKeyLambda.ts +++ b/web-api/src/lambdas/users/getPrivatePractitionersBySearchKeyLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getPrivatePractitionersBySearchKeyInteractor } from '@web-api/business/useCases/user/getPrivatePractitionersBySearchKeyInteractor'; /** * gets practitioner users by a search string (name or bar number) @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getPrivatePractitionersBySearchKeyLambda = event => +export const getPrivatePractitionersBySearchKeyLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { searchKey } = event.queryStringParameters; - return await applicationContext - .getUseCases() - .getPrivatePractitionersBySearchKeyInteractor(applicationContext, { + return await getPrivatePractitionersBySearchKeyInteractor( + applicationContext, + { searchKey, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/users/getUserLambda.ts b/web-api/src/lambdas/users/getUserLambda.ts index 212142d8d58..148f19ba020 100644 --- a/web-api/src/lambdas/users/getUserLambda.ts +++ b/web-api/src/lambdas/users/getUserLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getUserInteractor } from '@shared/business/useCases/getUserInteractor'; /** * used for fetching full user data @@ -6,13 +8,11 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getUserLambda = event => +export const getUserLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler( event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getUserInteractor(applicationContext); + return await getUserInteractor(applicationContext, authorizedUser); }, { bypassMaintenanceCheck: true, diff --git a/web-api/src/lambdas/users/getUserPendingEmailLambda.ts b/web-api/src/lambdas/users/getUserPendingEmailLambda.ts index 1b6c2de2d2f..24568e3741c 100644 --- a/web-api/src/lambdas/users/getUserPendingEmailLambda.ts +++ b/web-api/src/lambdas/users/getUserPendingEmailLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getUserPendingEmailInteractor } from '@web-api/business/useCases/user/getUserPendingEmailInteractor'; /** * gets the user pending email @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getUserPendingEmailLambda = event => +export const getUserPendingEmailLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getUserPendingEmailInteractor(applicationContext, { + return await getUserPendingEmailInteractor( + applicationContext, + { userId: event.pathParameters.userId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/users/getUserPendingEmailStatusLambda.ts b/web-api/src/lambdas/users/getUserPendingEmailStatusLambda.ts index d232a60955a..7276d89efa4 100644 --- a/web-api/src/lambdas/users/getUserPendingEmailStatusLambda.ts +++ b/web-api/src/lambdas/users/getUserPendingEmailStatusLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getUserPendingEmailStatusInteractor } from '@web-api/business/useCases/user/getUserPendingEmailStatusInteractor'; /** * gets the user pending email @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getUserPendingEmailStatusLambda = event => +export const getUserPendingEmailStatusLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getUserPendingEmailStatusInteractor(applicationContext, { + return await getUserPendingEmailStatusInteractor( + applicationContext, + { userId: event.pathParameters.userId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/users/getUsersInSectionLambda.ts b/web-api/src/lambdas/users/getUsersInSectionLambda.ts index 360c79c1095..eeab5421042 100644 --- a/web-api/src/lambdas/users/getUsersInSectionLambda.ts +++ b/web-api/src/lambdas/users/getUsersInSectionLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getUsersInSectionInteractor } from '@web-api/business/useCases/user/getUsersInSectionInteractor'; /** * creates a new document and attaches it to a case. It also creates a work item on the docket section. @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getUsersInSectionLambda = event => +export const getUsersInSectionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { section } = event.pathParameters || {}; - return await applicationContext - .getUseCases() - .getUsersInSectionInteractor(applicationContext, { + return await getUsersInSectionInteractor( + applicationContext, + { section, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/users/getUsersPendingEmailLambda.ts b/web-api/src/lambdas/users/getUsersPendingEmailLambda.ts index da1cd8d647f..24ed344ff22 100644 --- a/web-api/src/lambdas/users/getUsersPendingEmailLambda.ts +++ b/web-api/src/lambdas/users/getUsersPendingEmailLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getUsersPendingEmailInteractor } from '@web-api/business/useCases/user/getUsersPendingEmailInteractor'; /** * calls the interactor for obtaining a mapping of a given array of userIds and @@ -7,13 +9,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getUsersPendingEmailLambda = event => +export const getUsersPendingEmailLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const userIds = event.queryStringParameters.userIds?.split(',') || []; - return await applicationContext - .getUseCases() - .getUsersPendingEmailInteractor(applicationContext, { + return await getUsersPendingEmailInteractor( + applicationContext, + { userIds, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/users/updateUserContactInformationLambda.ts b/web-api/src/lambdas/users/updateUserContactInformationLambda.ts index 1e8df31f57b..30c9af574a6 100644 --- a/web-api/src/lambdas/users/updateUserContactInformationLambda.ts +++ b/web-api/src/lambdas/users/updateUserContactInformationLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateUserContactInformationInteractor } from '@web-api/business/useCases/user/updateUserContactInformationInteractor'; /** * updates the user contact info (used for a privatePractitioner or irsPractitioner) @@ -6,14 +8,19 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateUserContactInformationLambda = event => +export const updateUserContactInformationLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { contactInfo, firmName } = JSON.parse(event.body); - return await applicationContext - .getUseCases() - .updateUserContactInformationInteractor(applicationContext, { + return await updateUserContactInformationInteractor( + applicationContext, + { contactInfo, firmName, userId: (event.pathParameters || event.path).userId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/users/updateUserPendingEmailLambda.ts b/web-api/src/lambdas/users/updateUserPendingEmailLambda.ts index bf615dfb526..f3527edbee9 100644 --- a/web-api/src/lambdas/users/updateUserPendingEmailLambda.ts +++ b/web-api/src/lambdas/users/updateUserPendingEmailLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { updateUserPendingEmailInteractor } from '@web-api/business/useCases/user/updateUserPendingEmailInteractor'; /** * updates the user pending email @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const updateUserPendingEmailLambda = event => +export const updateUserPendingEmailLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .updateUserPendingEmailInteractor(applicationContext, { + return await updateUserPendingEmailInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/users/verifyUserPendingEmailLambda.ts b/web-api/src/lambdas/users/verifyUserPendingEmailLambda.ts index d34fc6f819c..9fd74ae8b9f 100644 --- a/web-api/src/lambdas/users/verifyUserPendingEmailLambda.ts +++ b/web-api/src/lambdas/users/verifyUserPendingEmailLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { verifyUserPendingEmailInteractor } from '@web-api/business/useCases/user/verifyUserPendingEmailInteractor'; /** * verifies the user pending email @@ -6,11 +8,16 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const verifyUserPendingEmailLambda = event => +export const verifyUserPendingEmailLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .verifyUserPendingEmailInteractor(applicationContext, { + return await verifyUserPendingEmailInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/v1/getCaseLambda.test.ts b/web-api/src/lambdas/v1/getCaseLambda.test.ts index d8e421b6a9f..68181663318 100644 --- a/web-api/src/lambdas/v1/getCaseLambda.test.ts +++ b/web-api/src/lambdas/v1/getCaseLambda.test.ts @@ -1,15 +1,16 @@ -import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { MOCK_CASE_WITH_TRIAL_SESSION } from '../../../../shared/src/test/mockCase'; -import { MOCK_USERS } from '../../../../shared/src/test/mockUsers'; -import { Role } from '@shared/business/entities/EntityConstants'; import { getCaseLambda } from './getCaseLambda'; import { createTestApplicationContext as mockCreateTestApplicationContext } from '@shared/business/test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { getCaseInteractor as mockGetCaseInteractor } from '@shared/business/useCases/getCaseInteractor'; jest.mock('@web-api/applicationContext', () => { return { - createApplicationContext: user => { - let appContext = mockCreateTestApplicationContext(user); + createApplicationContext: () => { + let appContext = mockCreateTestApplicationContext(); appContext.getUseCases().getAllFeatureFlagsInteractor = jest .fn() .mockResolvedValue(mockFeatureFlag); @@ -22,8 +23,6 @@ jest.mock('@web-api/applicationContext', () => { .fn() .mockImplementation(mockGetCaseInteractor); - appContext.getCurrentUser = jest.fn().mockReturnValue(mockUser); - if (mockShouldThrowError) { appContext.getDocumentClient = jest.fn().mockReturnValue({ query: jest.fn().mockRejectedValue(new Error('test error')), @@ -44,19 +43,15 @@ const mockDynamoCaseRecord = Object.assign({}, MOCK_CASE_WITH_TRIAL_SESSION, { let mockItems; let mockFeatureFlag; let mockShouldThrowError; -let mockUser; const setupMock = ({ featureFlag, items, shouldThrowError, - user, }: { items: (typeof mockDynamoCaseRecord)[]; featureFlag: boolean; shouldThrowError: boolean; - user: AuthUser; }) => { - mockUser = user; mockItems = items; mockShouldThrowError = shouldThrowError; mockFeatureFlag = featureFlag; @@ -103,7 +98,7 @@ describe('getCaseLambda (which fails if version increase is needed, DO NOT CHANG // disable logging by mimicking CI for this test beforeAll(() => { ({ CI } = process.env); - process.env.CI = true; + process.env.CI = 'true'; }); afterAll(() => (process.env.CI = CI)); @@ -115,15 +110,9 @@ describe('getCaseLambda (which fails if version increase is needed, DO NOT CHANG featureFlag: true, items: [], shouldThrowError: false, - user: { - email: '', - name: '', - role: 'roleWithNoPermissions' as Role, - userId: '', - }, }); - const response = await getCaseLambda(REQUEST_EVENT, {}); + const response = await getCaseLambda(REQUEST_EVENT, mockPetitionerUser); expect(response.statusCode).toBe(404); expect(response.headers['Content-Type']).toBe('application/json'); @@ -138,15 +127,9 @@ describe('getCaseLambda (which fails if version increase is needed, DO NOT CHANG featureFlag: true, items: [mockDynamoCaseRecord], shouldThrowError: false, - user: { - email: '', - name: '', - role: 'roleWithNoPermissions' as Role, - userId: '', - }, }); - const response = await getCaseLambda(REQUEST_EVENT, {}); + const response = await getCaseLambda(REQUEST_EVENT, mockPetitionerUser); expect(response.statusCode).toBe('200'); expect(response.headers['Content-Type']).toBe('application/json'); @@ -167,10 +150,9 @@ describe('getCaseLambda (which fails if version increase is needed, DO NOT CHANG featureFlag: true, items: [], shouldThrowError: false, - user: MOCK_USERS['b7d90c05-f6cd-442c-a168-202db587f16f'] as AuthUser, }); - const response = await getCaseLambda(REQUEST_EVENT, {}); + const response = await getCaseLambda(REQUEST_EVENT, mockDocketClerkUser); expect(response.statusCode).toBe(404); expect(response.headers['Content-Type']).toBe('application/json'); @@ -185,10 +167,9 @@ describe('getCaseLambda (which fails if version increase is needed, DO NOT CHANG featureFlag: true, items: [], shouldThrowError: true, - user: MOCK_USERS['b7d90c05-f6cd-442c-a168-202db587f16f'] as AuthUser, }); - const response = await getCaseLambda(REQUEST_EVENT, {}); + const response = await getCaseLambda(REQUEST_EVENT, mockDocketClerkUser); expect(response.statusCode).toBe(500); expect(response.headers['Content-Type']).toBe('application/json'); @@ -206,10 +187,9 @@ describe('getCaseLambda (which fails if version increase is needed, DO NOT CHANG featureFlag: isFeatureFlagOn, items: [mockDynamoCaseRecord], shouldThrowError: false, - user: MOCK_USERS['b7d90c05-f6cd-442c-a168-202db587f16f'] as AuthUser, }); - const response = await getCaseLambda(REQUEST_EVENT, {}); + const response = await getCaseLambda(REQUEST_EVENT, mockDocketClerkUser); expect(response.statusCode).toBe('200'); expect(response.headers['Content-Type']).toBe('application/json'); diff --git a/web-api/src/lambdas/v1/getCaseLambda.ts b/web-api/src/lambdas/v1/getCaseLambda.ts index 91b8c0ce6b6..40f23e03b6f 100644 --- a/web-api/src/lambdas/v1/getCaseLambda.ts +++ b/web-api/src/lambdas/v1/getCaseLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getCaseInteractor } from '@shared/business/useCases/getCaseInteractor'; import { marshallCase } from './marshallers/marshallCase'; import { v1ApiWrapper } from './v1ApiWrapper'; @@ -6,21 +8,19 @@ import { v1ApiWrapper } from './v1ApiWrapper'; * used for fetching a single case and returning it in v1 api format * * @param {object} event the AWS event object - * @param {object} options options to optionally pass to the genericHandler * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getCaseLambda = (event, options) => - genericHandler( - event, - ({ applicationContext }) => - v1ApiWrapper(async () => { - const caseObject = await applicationContext - .getUseCases() - .getCaseInteractor(applicationContext, { - docketNumber: event.pathParameters.docketNumber, - }); +export const getCaseLambda = (event, authorizedUser: UnknownAuthUser) => + genericHandler(event, ({ applicationContext }) => + v1ApiWrapper(async () => { + const caseObject = await getCaseInteractor( + applicationContext, + { + docketNumber: event.pathParameters.docketNumber, + }, + authorizedUser, + ); - return marshallCase(caseObject); - }), - options, + return marshallCase(caseObject); + }), ); diff --git a/web-api/src/lambdas/v1/getDocumentDownloadUrlLambda.test.ts b/web-api/src/lambdas/v1/getDocumentDownloadUrlLambda.test.ts index 4fcd20f6ae1..f2246fe2bd5 100644 --- a/web-api/src/lambdas/v1/getDocumentDownloadUrlLambda.test.ts +++ b/web-api/src/lambdas/v1/getDocumentDownloadUrlLambda.test.ts @@ -1,18 +1,17 @@ -import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; -import { - CASE_STATUS_TYPES, - Role, -} from '@shared/business/entities/EntityConstants'; +import { CASE_STATUS_TYPES } from '@shared/business/entities/EntityConstants'; import { MOCK_PETITION } from '@shared/test/mockDocketEntry'; -import { MOCK_USERS } from '../../../../shared/src/test/mockUsers'; import { getDocumentDownloadUrlLambda } from './getDocumentDownloadUrlLambda'; import { createTestApplicationContext as mockCreateTestApplicationContext } from '@shared/business/test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { getDownloadPolicyUrlInteractor as mockGetDownloadPolicyUrlInteractor } from '@web-api/business/useCases/document/getDownloadPolicyUrlInteractor'; jest.mock('@web-api/applicationContext', () => { return { - createApplicationContext: user => { - let appContext = mockCreateTestApplicationContext(user); + createApplicationContext: () => { + let appContext = mockCreateTestApplicationContext(); appContext.getUseCases().getAllFeatureFlagsInteractor = jest .fn() .mockResolvedValue(mockFeatureFlag); @@ -20,8 +19,6 @@ jest.mock('@web-api/applicationContext', () => { .fn() .mockImplementation(mockGetDownloadPolicyUrlInteractor); - appContext.getCurrentUser = jest.fn().mockReturnValue(mockUser); - appContext.getDocumentClient = jest.fn().mockReturnValue({ query: jest.fn().mockResolvedValue({ Items: mockItems, @@ -51,20 +48,16 @@ jest.mock('@web-api/applicationContext', () => { let mockFeatureFlag; let mockShouldThrowError; -let mockUser; let mockItems; const setupMock = ({ featureFlag, items, shouldThrowError, - user, }: { items: any[]; featureFlag: boolean; shouldThrowError: boolean; - user: AuthUser; }) => { - mockUser = user; mockShouldThrowError = shouldThrowError; mockFeatureFlag = featureFlag; mockItems = items; @@ -83,7 +76,7 @@ describe('getDocumentDownloadUrlLambda', () => { // disable logging by mimicking CI for this test beforeAll(() => { ({ CI } = process.env); - process.env.CI = true; + process.env.CI = 'true'; }); afterAll(() => (process.env.CI = CI)); @@ -95,15 +88,12 @@ describe('getDocumentDownloadUrlLambda', () => { featureFlag: true, items: [], shouldThrowError: false, - user: { - email: '', - name: '', - role: 'roleWithNoPermissions' as Role, - userId: '', - }, }); - const response = await getDocumentDownloadUrlLambda(REQUEST_EVENT, {}); + const response = await getDocumentDownloadUrlLambda( + REQUEST_EVENT, + undefined, + ); expect(response.statusCode).toBe(403); expect(response.headers['Content-Type']).toBe('application/json'); @@ -122,10 +112,12 @@ describe('getDocumentDownloadUrlLambda', () => { featureFlag: true, items: [], shouldThrowError: false, - user: MOCK_USERS['b7d90c05-f6cd-442c-a168-202db587f16f'] as AuthUser, }); - const response = await getDocumentDownloadUrlLambda(request, {}); + const response = await getDocumentDownloadUrlLambda( + request, + mockPetitionerUser, + ); expect(response.statusCode).toBe(404); expect(response.headers['Content-Type']).toBe('application/json'); @@ -162,10 +154,12 @@ describe('getDocumentDownloadUrlLambda', () => { }, ], shouldThrowError: false, - user: MOCK_USERS['2eee98ac-613f-46bc-afd5-2574d1b15664'] as AuthUser, }); - const response = await getDocumentDownloadUrlLambda(request, {}); + const response = await getDocumentDownloadUrlLambda( + request, + mockPetitionerUser, + ); expect(response.statusCode).toBe(404); expect(response.headers['Content-Type']).toBe('application/json'); @@ -187,10 +181,12 @@ describe('getDocumentDownloadUrlLambda', () => { featureFlag: true, items: [], shouldThrowError: true, - user: MOCK_USERS['b7d90c05-f6cd-442c-a168-202db587f16f'] as AuthUser, }); - const response = await getDocumentDownloadUrlLambda(request, {}); + const response = await getDocumentDownloadUrlLambda( + request, + mockDocketClerkUser, + ); expect(response.statusCode).toBe(500); expect(response.headers['Content-Type']).toBe('application/json'); @@ -228,10 +224,12 @@ describe('getDocumentDownloadUrlLambda', () => { }, ], shouldThrowError: false, - user: MOCK_USERS['b7d90c05-f6cd-442c-a168-202db587f16f'] as AuthUser, }); - const response = await getDocumentDownloadUrlLambda(request, {}); + const response = await getDocumentDownloadUrlLambda( + request, + mockDocketClerkUser, + ); expect(response.statusCode).toBe('200'); expect(response.headers['Content-Type']).toBe('application/json'); diff --git a/web-api/src/lambdas/v1/getDocumentDownloadUrlLambda.ts b/web-api/src/lambdas/v1/getDocumentDownloadUrlLambda.ts index 885029534f8..7599daf9e95 100644 --- a/web-api/src/lambdas/v1/getDocumentDownloadUrlLambda.ts +++ b/web-api/src/lambdas/v1/getDocumentDownloadUrlLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getDownloadPolicyUrlInteractor } from '@web-api/business/useCases/document/getDownloadPolicyUrlInteractor'; import { marshallDocumentDownloadUrl } from './marshallers/marshallDocumentDownloadUrl'; import { v1ApiWrapper } from './v1ApiWrapper'; @@ -6,22 +8,22 @@ import { v1ApiWrapper } from './v1ApiWrapper'; * used for getting the download policy which is needed for consumers to download files directly from S3 * * @param {object} event the AWS event object - * @param {object} options options to optionally pass to the genericHandler * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getDocumentDownloadUrlLambda = (event, options = {}) => - genericHandler( - event, - ({ applicationContext }) => { - return v1ApiWrapper(async () => { - const urlObject = await applicationContext - .getUseCases() - .getDownloadPolicyUrlInteractor(applicationContext, { - ...event.pathParameters, - }); +export const getDocumentDownloadUrlLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => + genericHandler(event, ({ applicationContext }) => { + return v1ApiWrapper(async () => { + const urlObject = await getDownloadPolicyUrlInteractor( + applicationContext, + { + ...event.pathParameters, + }, + authorizedUser, + ); - return marshallDocumentDownloadUrl(urlObject); - }); - }, - options, - ); + return marshallDocumentDownloadUrl(urlObject); + }); + }); diff --git a/web-api/src/lambdas/v2/getCaseLambda.test.ts b/web-api/src/lambdas/v2/getCaseLambda.test.ts index 554b8aa0326..42533a60855 100644 --- a/web-api/src/lambdas/v2/getCaseLambda.test.ts +++ b/web-api/src/lambdas/v2/getCaseLambda.test.ts @@ -1,19 +1,18 @@ -import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { MOCK_CASE_WITH_TRIAL_SESSION } from '../../../../shared/src/test/mockCase'; import { MOCK_COMPLEX_CASE } from '../../../../shared/src/test/mockComplexCase'; -import { - MOCK_PRACTITIONER, - MOCK_USERS, -} from '../../../../shared/src/test/mockUsers'; -import { Role } from '@shared/business/entities/EntityConstants'; +import { MOCK_PRACTITIONER } from '../../../../shared/src/test/mockUsers'; import { getCaseLambda } from './getCaseLambda'; import { createTestApplicationContext as mockCreateTestApplicationContext } from '@shared/business/test/createTestApplicationContext'; +import { + mockDocketClerkUser, + mockPetitionerUser, +} from '@shared/test/mockAuthUsers'; import { getCaseInteractor as mockGetCaseInteractor } from '@shared/business/useCases/getCaseInteractor'; jest.mock('@web-api/applicationContext', () => { return { - createApplicationContext: user => { - let appContext = mockCreateTestApplicationContext(user); + createApplicationContext: () => { + let appContext = mockCreateTestApplicationContext(); appContext.getUseCases().getAllFeatureFlagsInteractor = jest .fn() .mockResolvedValue(mockFeatureFlag); @@ -26,8 +25,6 @@ jest.mock('@web-api/applicationContext', () => { .fn() .mockImplementation(mockGetCaseInteractor); - appContext.getCurrentUser = jest.fn().mockReturnValue(mockUser); - if (mockShouldThrowError) { appContext.getDocumentClient = jest.fn().mockReturnValue({ query: jest.fn().mockRejectedValue(new Error('test error')), @@ -42,19 +39,15 @@ jest.mock('@web-api/applicationContext', () => { let mockItems; let mockFeatureFlag; let mockShouldThrowError; -let mockUser; const setupMock = ({ featureFlag, items, shouldThrowError, - user, }: { items: any[]; featureFlag: boolean; shouldThrowError: boolean; - user: AuthUser; }) => { - mockUser = user; mockItems = items; mockShouldThrowError = shouldThrowError; mockFeatureFlag = featureFlag; @@ -81,7 +74,7 @@ describe('getCaseLambda (which fails if version increase is needed, DO NOT CHANG // disable logging by mimicking CI for this test beforeAll(() => { ({ CI } = process.env); - process.env.CI = true; + process.env.CI = 'true'; }); afterAll(() => (process.env.CI = CI)); @@ -93,15 +86,9 @@ describe('getCaseLambda (which fails if version increase is needed, DO NOT CHANG featureFlag: true, items: [], shouldThrowError: false, - user: { - email: '', - name: '', - role: 'roleWithNoPermissions' as Role, - userId: '', - }, }); - const response = await getCaseLambda(REQUEST_EVENT, {}); + const response = await getCaseLambda(REQUEST_EVENT, mockPetitionerUser); expect(response.statusCode).toBe(404); expect(response.headers['Content-Type']).toBe('application/json'); @@ -116,15 +103,9 @@ describe('getCaseLambda (which fails if version increase is needed, DO NOT CHANG featureFlag: true, items: [mockDynamoCaseRecord], shouldThrowError: false, - user: { - email: '', - name: '', - role: 'roleWithNoPermissions' as Role, - userId: '', - }, }); - const response = await getCaseLambda(REQUEST_EVENT, {}); + const response = await getCaseLambda(REQUEST_EVENT, mockPetitionerUser); expect(response.statusCode).toBe('200'); expect(response.headers['Content-Type']).toBe('application/json'); @@ -145,10 +126,9 @@ describe('getCaseLambda (which fails if version increase is needed, DO NOT CHANG featureFlag: true, items: [], shouldThrowError: false, - user: MOCK_USERS['b7d90c05-f6cd-442c-a168-202db587f16f'] as AuthUser, }); - const response = await getCaseLambda(REQUEST_EVENT, {}); + const response = await getCaseLambda(REQUEST_EVENT, mockDocketClerkUser); expect(response.statusCode).toBe(404); expect(response.headers['Content-Type']).toBe('application/json'); @@ -163,10 +143,9 @@ describe('getCaseLambda (which fails if version increase is needed, DO NOT CHANG featureFlag: true, items: [], shouldThrowError: true, - user: MOCK_USERS['b7d90c05-f6cd-442c-a168-202db587f16f'] as AuthUser, }); - const response = await getCaseLambda(REQUEST_EVENT, {}); + const response = await getCaseLambda(REQUEST_EVENT, mockDocketClerkUser); expect(response.statusCode).toBe(500); expect(response.headers['Content-Type']).toBe('application/json'); @@ -208,10 +187,9 @@ describe('getCaseLambda (which fails if version increase is needed, DO NOT CHANG mockPrivatePractitionerRecord, ], shouldThrowError: false, - user: MOCK_USERS['b7d90c05-f6cd-442c-a168-202db587f16f'] as AuthUser, }); - const response = await getCaseLambda(REQUEST_EVENT, {}); + const response = await getCaseLambda(REQUEST_EVENT, mockDocketClerkUser); expect(response.statusCode).toBe('200'); expect(response.headers['Content-Type']).toBe('application/json'); diff --git a/web-api/src/lambdas/v2/getCaseLambda.ts b/web-api/src/lambdas/v2/getCaseLambda.ts index e205975b52e..8040bd54d28 100644 --- a/web-api/src/lambdas/v2/getCaseLambda.ts +++ b/web-api/src/lambdas/v2/getCaseLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getCaseInteractor } from '@shared/business/useCases/getCaseInteractor'; import { marshallCase } from './marshallers/marshallCase'; import { v2ApiWrapper } from './v2ApiWrapper'; @@ -6,21 +8,19 @@ import { v2ApiWrapper } from './v2ApiWrapper'; * used for fetching a single case and returning it in v1 api format * * @param {object} event the AWS event object - * @param {object} options options to optionally pass to the genericHandler * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getCaseLambda = (event, options) => - genericHandler( - event, - ({ applicationContext }) => - v2ApiWrapper(async () => { - const caseObject = await applicationContext - .getUseCases() - .getCaseInteractor(applicationContext, { - docketNumber: event.pathParameters.docketNumber, - }); +export const getCaseLambda = (event, authorizedUser: UnknownAuthUser) => + genericHandler(event, ({ applicationContext }) => + v2ApiWrapper(async () => { + const caseObject = await getCaseInteractor( + applicationContext, + { + docketNumber: event.pathParameters.docketNumber, + }, + authorizedUser, + ); - return marshallCase(caseObject); - }), - options, + return marshallCase(caseObject); + }), ); diff --git a/web-api/src/lambdas/v2/getDocumentDownloadUrlLambda.test.ts b/web-api/src/lambdas/v2/getDocumentDownloadUrlLambda.test.ts index d1363c4b194..ef2c2798f5f 100644 --- a/web-api/src/lambdas/v2/getDocumentDownloadUrlLambda.test.ts +++ b/web-api/src/lambdas/v2/getDocumentDownloadUrlLambda.test.ts @@ -1,18 +1,17 @@ -import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { CASE_STATUS_TYPES, Role, } from '@shared/business/entities/EntityConstants'; import { MOCK_PETITION } from '@shared/test/mockDocketEntry'; -import { MOCK_USERS } from '../../../../shared/src/test/mockUsers'; import { getDocumentDownloadUrlLambda } from './getDocumentDownloadUrlLambda'; import { createTestApplicationContext as mockCreateTestApplicationContext } from '@shared/business/test/createTestApplicationContext'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { getDownloadPolicyUrlInteractor as mockGetDownloadPolicyUrlInteractor } from '@web-api/business/useCases/document/getDownloadPolicyUrlInteractor'; jest.mock('@web-api/applicationContext', () => { return { - createApplicationContext: user => { - let appContext = mockCreateTestApplicationContext(user); + createApplicationContext: () => { + let appContext = mockCreateTestApplicationContext(); appContext.getUseCases().getAllFeatureFlagsInteractor = jest .fn() .mockResolvedValue(mockFeatureFlag); @@ -20,8 +19,6 @@ jest.mock('@web-api/applicationContext', () => { .fn() .mockImplementation(mockGetDownloadPolicyUrlInteractor); - appContext.getCurrentUser = jest.fn().mockReturnValue(mockUser); - appContext.getDocumentClient = jest.fn().mockReturnValue({ query: jest.fn().mockResolvedValue({ Items: mockItems, @@ -51,20 +48,16 @@ jest.mock('@web-api/applicationContext', () => { let mockFeatureFlag; let mockShouldThrowError; -let mockUser; let mockItems; const setupMock = ({ featureFlag, items, shouldThrowError, - user, }: { items: any[]; featureFlag: boolean; shouldThrowError: boolean; - user: AuthUser; }) => { - mockUser = user; mockShouldThrowError = shouldThrowError; mockFeatureFlag = featureFlag; mockItems = items; @@ -83,7 +76,7 @@ describe('getDocumentDownloadUrlLambda', () => { // disable logging by mimicking CI for this test beforeAll(() => { ({ CI } = process.env); - process.env.CI = true; + process.env.CI = 'true'; }); afterAll(() => (process.env.CI = CI)); @@ -95,15 +88,14 @@ describe('getDocumentDownloadUrlLambda', () => { featureFlag: true, items: [], shouldThrowError: false, - user: { - email: '', - name: '', - role: 'roleWithNoPermissions' as Role, - userId: '', - }, }); - const response = await getDocumentDownloadUrlLambda(REQUEST_EVENT, {}); + const response = await getDocumentDownloadUrlLambda(REQUEST_EVENT, { + email: 'test@e.mail', + name: '', + role: 'roleWithNoPermissions' as Role, + userId: '612e3eb3-332c-4f1f-aaff-44ac8eae9a5f', + }); expect(response.statusCode).toBe(403); expect(response.headers['Content-Type']).toBe('application/json'); @@ -122,10 +114,12 @@ describe('getDocumentDownloadUrlLambda', () => { featureFlag: true, items: [], shouldThrowError: false, - user: MOCK_USERS['b7d90c05-f6cd-442c-a168-202db587f16f'] as AuthUser, }); - const response = await getDocumentDownloadUrlLambda(request, {}); + const response = await getDocumentDownloadUrlLambda( + request, + mockDocketClerkUser, + ); expect(response.statusCode).toBe(404); expect(response.headers['Content-Type']).toBe('application/json'); @@ -162,10 +156,12 @@ describe('getDocumentDownloadUrlLambda', () => { }, ], shouldThrowError: false, - user: MOCK_USERS['2eee98ac-613f-46bc-afd5-2574d1b15664'] as AuthUser, }); - const response = await getDocumentDownloadUrlLambda(request, {}); + const response = await getDocumentDownloadUrlLambda( + request, + mockDocketClerkUser, + ); expect(response.statusCode).toBe(404); expect(response.headers['Content-Type']).toBe('application/json'); @@ -187,10 +183,12 @@ describe('getDocumentDownloadUrlLambda', () => { featureFlag: true, items: [], shouldThrowError: true, - user: MOCK_USERS['b7d90c05-f6cd-442c-a168-202db587f16f'] as AuthUser, }); - const response = await getDocumentDownloadUrlLambda(request, {}); + const response = await getDocumentDownloadUrlLambda( + request, + mockDocketClerkUser, + ); expect(response.statusCode).toBe(500); expect(response.headers['Content-Type']).toBe('application/json'); @@ -228,10 +226,12 @@ describe('getDocumentDownloadUrlLambda', () => { }, ], shouldThrowError: false, - user: MOCK_USERS['b7d90c05-f6cd-442c-a168-202db587f16f'] as AuthUser, }); - const response = await getDocumentDownloadUrlLambda(request, {}); + const response = await getDocumentDownloadUrlLambda( + request, + mockDocketClerkUser, + ); expect(response.statusCode).toBe('200'); expect(response.headers['Content-Type']).toBe('application/json'); diff --git a/web-api/src/lambdas/v2/getDocumentDownloadUrlLambda.ts b/web-api/src/lambdas/v2/getDocumentDownloadUrlLambda.ts index f619ed39601..687b2244a8d 100644 --- a/web-api/src/lambdas/v2/getDocumentDownloadUrlLambda.ts +++ b/web-api/src/lambdas/v2/getDocumentDownloadUrlLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getDownloadPolicyUrlInteractor } from '@web-api/business/useCases/document/getDownloadPolicyUrlInteractor'; import { marshallDocumentDownloadUrl } from './marshallers/marshallDocumentDownloadUrl'; import { v2ApiWrapper } from './v2ApiWrapper'; @@ -6,22 +8,22 @@ import { v2ApiWrapper } from './v2ApiWrapper'; * used for getting the download policy which is needed for consumers to download files directly from S3 * * @param {object} event the AWS event object - * @param {object} options options to optionally pass to the genericHandler * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getDocumentDownloadUrlLambda = (event, options = {}) => - genericHandler( - event, - ({ applicationContext }) => { - return v2ApiWrapper(async () => { - const urlObject = await applicationContext - .getUseCases() - .getDownloadPolicyUrlInteractor(applicationContext, { - ...event.pathParameters, - }); +export const getDocumentDownloadUrlLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => + genericHandler(event, ({ applicationContext }) => { + return v2ApiWrapper(async () => { + const urlObject = await getDownloadPolicyUrlInteractor( + applicationContext, + { + ...event.pathParameters, + }, + authorizedUser, + ); - return marshallDocumentDownloadUrl(urlObject); - }); - }, - options, - ); + return marshallDocumentDownloadUrl(urlObject); + }); + }); diff --git a/web-api/src/lambdas/v2/getReconciliationReportLambda.ts b/web-api/src/lambdas/v2/getReconciliationReportLambda.ts index 0af2640ea4b..4a48ec36a13 100644 --- a/web-api/src/lambdas/v2/getReconciliationReportLambda.ts +++ b/web-api/src/lambdas/v2/getReconciliationReportLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getReconciliationReportInteractor } from '@shared/business/useCases/getReconciliationReportInteractor'; import { v2ApiWrapper } from './v2ApiWrapper'; /** @@ -7,23 +9,23 @@ import { v2ApiWrapper } from './v2ApiWrapper'; * day (12:00am-11:59:59pm ET) * * @param {object} event the AWS event object - * @param {object} options options to optionally pass to the genericHandler * @returns {Promise<*|undefined>} the api gateway response object containing the reconciliation report */ -export const getReconciliationReportLambda = (event, options = {}) => - genericHandler( - event, - ({ applicationContext }) => { - return v2ApiWrapper(async () => { - const { end, start } = event.queryStringParameters; - //url will contain the reconciliation date in path parameters, and times in the query string - const parms = { ...event.pathParameters, end, start }; - const report = await applicationContext - .getUseCases() - .getReconciliationReportInteractor(applicationContext, parms); +export const getReconciliationReportLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => + genericHandler(event, ({ applicationContext }) => { + return v2ApiWrapper(async () => { + const { end, start } = event.queryStringParameters; + //url will contain the reconciliation date in path parameters, and times in the query string + const parms = { ...event.pathParameters, end, start }; + const report = await getReconciliationReportInteractor( + applicationContext, + parms, + authorizedUser, + ); - return report; - }); - }, - options, - ); + return report; + }); + }); diff --git a/web-api/src/lambdas/workitems/assignWorkItemsLambda.ts b/web-api/src/lambdas/workitems/assignWorkItemsLambda.ts index 7adae821db8..2881d284ef2 100644 --- a/web-api/src/lambdas/workitems/assignWorkItemsLambda.ts +++ b/web-api/src/lambdas/workitems/assignWorkItemsLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { assignWorkItemsInteractor } from '@web-api/business/useCases/workItems/assignWorkItemsInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,11 +8,13 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const assignWorkItemsLambda = event => +export const assignWorkItemsLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .assignWorkItemsInteractor(applicationContext, { + return await assignWorkItemsInteractor( + applicationContext, + { ...JSON.parse(event.body), - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/workitems/completeWorkItemLambda.ts b/web-api/src/lambdas/workitems/completeWorkItemLambda.ts index 02e5f404610..a3691543264 100644 --- a/web-api/src/lambdas/workitems/completeWorkItemLambda.ts +++ b/web-api/src/lambdas/workitems/completeWorkItemLambda.ts @@ -1,3 +1,5 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { completeWorkItemInteractor } from '@web-api/business/useCases/workItems/completeWorkItemInteractor'; import { genericHandler } from '../../genericHandler'; /** @@ -6,12 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const completeWorkItemLambda = event => +export const completeWorkItemLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .completeWorkItemInteractor(applicationContext, { + return await completeWorkItemInteractor( + applicationContext, + { completedMessage: JSON.parse(event.body).completedMessage, workItemId: event.pathParameters.workItemId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/workitems/getDocumentQCInboxForSectionLambda.ts b/web-api/src/lambdas/workitems/getDocumentQCInboxForSectionLambda.ts index 6581bd01ab1..668c7719021 100644 --- a/web-api/src/lambdas/workitems/getDocumentQCInboxForSectionLambda.ts +++ b/web-api/src/lambdas/workitems/getDocumentQCInboxForSectionLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getDocumentQCInboxForSectionInteractor } from '@web-api/business/useCases/workItems/getDocumentQCInboxForSectionInteractor'; /** * returns all sent work items in a particular section @@ -6,14 +8,19 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getDocumentQCInboxForSectionLambda = event => +export const getDocumentQCInboxForSectionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { section } = event.pathParameters || {}; - return await applicationContext - .getUseCases() - .getDocumentQCInboxForSectionInteractor(applicationContext, { + return await getDocumentQCInboxForSectionInteractor( + applicationContext, + { section, ...event.queryStringParameters, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/workitems/getDocumentQCInboxForUserLambda.ts b/web-api/src/lambdas/workitems/getDocumentQCInboxForUserLambda.ts index 589a5b25902..31651f93776 100644 --- a/web-api/src/lambdas/workitems/getDocumentQCInboxForUserLambda.ts +++ b/web-api/src/lambdas/workitems/getDocumentQCInboxForUserLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getDocumentQCInboxForUserInteractor } from '@web-api/business/useCases/workItems/getDocumentQCInboxForUserInteractor'; /** * returns the users inbox @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getDocumentQCInboxForUserLambda = event => +export const getDocumentQCInboxForUserLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { userId } = event.pathParameters || {}; - return await applicationContext - .getUseCases() - .getDocumentQCInboxForUserInteractor(applicationContext, { + return await getDocumentQCInboxForUserInteractor( + applicationContext, + { userId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/workitems/getDocumentQCServedForSectionLambda.ts b/web-api/src/lambdas/workitems/getDocumentQCServedForSectionLambda.ts index c0547a8fc87..ed144580a37 100644 --- a/web-api/src/lambdas/workitems/getDocumentQCServedForSectionLambda.ts +++ b/web-api/src/lambdas/workitems/getDocumentQCServedForSectionLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getDocumentQCServedForSectionInteractor } from '@web-api/business/useCases/workItems/getDocumentQCServedForSectionInteractor'; /** * returns all sent work items in a particular section @@ -6,13 +8,17 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getDocumentQCServedForSectionLambda = event => +export const getDocumentQCServedForSectionLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { section } = event.pathParameters || {}; - - return await applicationContext - .getUseCases() - .getDocumentQCServedForSectionInteractor(applicationContext, { + return await getDocumentQCServedForSectionInteractor( + applicationContext, + { section, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/workitems/getDocumentQCServedForUserLambda.ts b/web-api/src/lambdas/workitems/getDocumentQCServedForUserLambda.ts index 56493357a21..1e6f12b2433 100644 --- a/web-api/src/lambdas/workitems/getDocumentQCServedForUserLambda.ts +++ b/web-api/src/lambdas/workitems/getDocumentQCServedForUserLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getDocumentQCServedForUserInteractor } from '@web-api/business/useCases/workItems/getDocumentQCServedForUserInteractor'; /** * returns the users inbox @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getDocumentQCServedForUserLambda = event => +export const getDocumentQCServedForUserLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { userId } = event.pathParameters || {}; - return await applicationContext - .getUseCases() - .getDocumentQCServedForUserInteractor(applicationContext, { + return await getDocumentQCServedForUserInteractor( + applicationContext, + { userId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/workitems/getWorkItemLambda.ts b/web-api/src/lambdas/workitems/getWorkItemLambda.ts index b3858ba5813..766a17109d5 100644 --- a/web-api/src/lambdas/workitems/getWorkItemLambda.ts +++ b/web-api/src/lambdas/workitems/getWorkItemLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { getWorkItemInteractor } from '@web-api/business/useCases/workItems/getWorkItemInteractor'; /** * returns a single work item via the workItemId passed in the path of the url @@ -6,11 +8,13 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const getWorkItemLambda = event => +export const getWorkItemLambda = (event, authorizedUser: UnknownAuthUser) => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .getWorkItemInteractor(applicationContext, { + return await getWorkItemInteractor( + applicationContext, + { workItemId: event.pathParameters.workItemId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/lambdas/workitems/setWorkItemAsReadLambda.ts b/web-api/src/lambdas/workitems/setWorkItemAsReadLambda.ts index b9f7b35564b..1a9a1bbd177 100644 --- a/web-api/src/lambdas/workitems/setWorkItemAsReadLambda.ts +++ b/web-api/src/lambdas/workitems/setWorkItemAsReadLambda.ts @@ -1,4 +1,6 @@ +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { genericHandler } from '../../genericHandler'; +import { setWorkItemAsReadInteractor } from '@web-api/business/useCases/workItems/setWorkItemAsReadInteractor'; /** * assigns a list of work item ids to an assignee @@ -6,13 +8,18 @@ import { genericHandler } from '../../genericHandler'; * @param {object} event the AWS event object * @returns {Promise<*|undefined>} the api gateway response object containing the statusCode, body, and headers */ -export const setWorkItemAsReadLambda = event => +export const setWorkItemAsReadLambda = ( + event, + authorizedUser: UnknownAuthUser, +) => genericHandler(event, async ({ applicationContext }) => { const { workItemId } = event.pathParameters || {}; - return await applicationContext - .getUseCases() - .setWorkItemAsReadInteractor(applicationContext, { + return await setWorkItemAsReadInteractor( + applicationContext, + { workItemId, - }); + }, + authorizedUser, + ); }); diff --git a/web-api/src/middleware/apiGatewayHelper.test.ts b/web-api/src/middleware/apiGatewayHelper.test.ts index e05ab40b848..f41af22ed1a 100644 --- a/web-api/src/middleware/apiGatewayHelper.test.ts +++ b/web-api/src/middleware/apiGatewayHelper.test.ts @@ -379,7 +379,7 @@ describe('getUserFromAuthHeader', () => { Authorization: `Bearer ${token}`, }, }); - expect(user.name).toEqual(mockUser.name); + expect(user?.name).toEqual(mockUser.name); }); it('should return undefined if the user token is not a valid jwt token', () => { @@ -396,14 +396,14 @@ describe('getUserFromAuthHeader', () => { expect(user).toEqual(undefined); }); - it('returns custom:userId when it is present in the token', () => { + it('should return custom:userId when it is present in the token', () => { const user = getUserFromAuthHeader({ headers: { Authorization: `Bearer ${token}`, token, }, }); - expect(user.userId).toEqual(mockUser['custom:userId']); + expect(user?.userId).toEqual(mockUser['custom:userId']); }); describe('redirect', () => { diff --git a/web-api/src/persistence/dynamo/cases/docketNumberGenerator.ts b/web-api/src/persistence/dynamo/cases/docketNumberGenerator.ts index a041c7ce014..486ea7d8ff4 100644 --- a/web-api/src/persistence/dynamo/cases/docketNumberGenerator.ts +++ b/web-api/src/persistence/dynamo/cases/docketNumberGenerator.ts @@ -71,7 +71,7 @@ export const createDocketNumber = async ({ receivedAt, }: { applicationContext: IApplicationContext; - receivedAt: string; + receivedAt?: string; }) => { const year = receivedAt ? formatDateString(receivedAt, FORMATS.YEAR) diff --git a/web-api/src/persistence/dynamo/workitems/getDocumentQCServedForSection.test.ts b/web-api/src/persistence/dynamo/workitems/getDocumentQCServedForSection.test.ts index bf582ab9843..672e1bb3c7a 100644 --- a/web-api/src/persistence/dynamo/workitems/getDocumentQCServedForSection.test.ts +++ b/web-api/src/persistence/dynamo/workitems/getDocumentQCServedForSection.test.ts @@ -41,10 +41,6 @@ describe('getDocumentQCServedForSection', () => { }); it('invokes the persistence layer with pk of {userId}|outbox and {section}|outbox and other expected params', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - section: DOCKET_SECTION, - userId: '1805d1ab-18d0-43ec-bafb-654e83405416', - }); applicationContext.getDocumentClient.mockReturnValue({ query: queryStub, }); diff --git a/web-api/src/persistence/dynamo/workitems/getDocumentQCServedForUser.test.ts b/web-api/src/persistence/dynamo/workitems/getDocumentQCServedForUser.test.ts index f4b5ab5e459..72209bfd291 100644 --- a/web-api/src/persistence/dynamo/workitems/getDocumentQCServedForUser.test.ts +++ b/web-api/src/persistence/dynamo/workitems/getDocumentQCServedForUser.test.ts @@ -43,10 +43,6 @@ describe('getDocumentQCServedForUser', () => { }); it('should filter out the work items returned from persistence to only have served documents', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - section: DOCKET_SECTION, - userId: '1805d1ab-18d0-43ec-bafb-654e83405416', - }); applicationContext.getDocumentClient.mockReturnValue({ query: queryStub, }); diff --git a/web-api/src/persistence/dynamo/workitems/putWorkItemInOutbox.test.ts b/web-api/src/persistence/dynamo/workitems/putWorkItemInOutbox.test.ts index 1263bd2393b..827eddd3a2c 100644 --- a/web-api/src/persistence/dynamo/workitems/putWorkItemInOutbox.test.ts +++ b/web-api/src/persistence/dynamo/workitems/putWorkItemInOutbox.test.ts @@ -1,6 +1,7 @@ import { DOCKET_SECTION } from '../../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../../../../shared/src/business/test/createTestApplicationContext'; import { createISODateString } from '../../../../../shared/src/business/utilities/DateHandler'; +import { mockDocketClerkUser } from '@shared/test/mockAuthUsers'; import { putWorkItemInOutbox } from './putWorkItemInOutbox'; describe('putWorkItemInOutbox', () => { @@ -22,16 +23,14 @@ describe('putWorkItemInOutbox', () => { it('invokes the persistence layer with pk of {userId}|outbox and {section}|outbox and other expected params', async () => { const timestamp = createISODateString(); - applicationContext.getCurrentUser.mockReturnValue({ - section: DOCKET_SECTION, - userId: '1805d1ab-18d0-43ec-bafb-654e83405416', - }); + applicationContext.getDocumentClient.mockReturnValue({ get: getStub, put: putStub, }); await putWorkItemInOutbox({ applicationContext, + authorizedUser: mockDocketClerkUser, workItem: { completedAt: timestamp, workItemId: '123', diff --git a/web-api/src/persistence/dynamo/workitems/putWorkItemInOutbox.ts b/web-api/src/persistence/dynamo/workitems/putWorkItemInOutbox.ts index dfe42d9d5f1..2f9188d7216 100644 --- a/web-api/src/persistence/dynamo/workitems/putWorkItemInOutbox.ts +++ b/web-api/src/persistence/dynamo/workitems/putWorkItemInOutbox.ts @@ -1,10 +1,19 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; +import { RawWorkItem } from '@shared/business/entities/WorkItem'; +import { ServerApplicationContext } from '@web-api/applicationContext'; import { createSectionOutboxRecords } from './createSectionOutboxRecords'; import { createUserOutboxRecord } from './createUserOutboxRecord'; import { get } from '../../dynamodbClientService'; -export const putWorkItemInOutbox = async ({ applicationContext, workItem }) => { - const authorizedUser = applicationContext.getCurrentUser(); - +export const putWorkItemInOutbox = async ({ + applicationContext, + authorizedUser, + workItem, +}: { + applicationContext: ServerApplicationContext; + authorizedUser: AuthUser; + workItem: RawWorkItem; +}) => { const user = await get({ Key: { pk: `user|${authorizedUser.userId}`, diff --git a/web-api/src/persistence/dynamo/workitems/putWorkItemInUsersOutbox.test.ts b/web-api/src/persistence/dynamo/workitems/putWorkItemInUsersOutbox.test.ts index 7cc5a89218f..48fbb00ffb1 100644 --- a/web-api/src/persistence/dynamo/workitems/putWorkItemInUsersOutbox.test.ts +++ b/web-api/src/persistence/dynamo/workitems/putWorkItemInUsersOutbox.test.ts @@ -22,10 +22,6 @@ describe('putWorkItemInUsersOutbox', () => { it('invokes the persistence layer with pk of user-outbox|{userId} and section-outbox|{section} and other expected params', async () => { const timestamp = createISODateString(); - applicationContext.getCurrentUser.mockReturnValue({ - section: DOCKET_SECTION, - userId: '1805d1ab-18d0-43ec-bafb-654e83405416', - }); applicationContext.getDocumentClient.mockReturnValue({ get: getStub, put: putStub, diff --git a/web-api/src/persistence/dynamo/workitems/saveWorkItemForDocketClerkFilingExternalDocument.test.ts b/web-api/src/persistence/dynamo/workitems/saveWorkItemForDocketClerkFilingExternalDocument.test.ts index 88443632e41..35767656152 100644 --- a/web-api/src/persistence/dynamo/workitems/saveWorkItemForDocketClerkFilingExternalDocument.test.ts +++ b/web-api/src/persistence/dynamo/workitems/saveWorkItemForDocketClerkFilingExternalDocument.test.ts @@ -22,10 +22,6 @@ describe('saveWorkItemForDocketClerkFilingExternalDocument', () => { it('invokes the persistence layer 5 times to store the work item, user and section outbox records, and work item mapping record', async () => { const timestamp = createISODateString(); - applicationContext.getCurrentUser.mockReturnValue({ - section: DOCKET_SECTION, - userId: '1805d1ab-18d0-43ec-bafb-654e83405416', - }); applicationContext.getDocumentClient.mockReturnValue({ get: getStub, put: putStub, diff --git a/web-api/src/persistence/elasticsearch/getCaseInventoryReport.test.ts b/web-api/src/persistence/elasticsearch/getCaseInventoryReport.test.ts index 33d600ce06b..1b0e58e9ad1 100644 --- a/web-api/src/persistence/elasticsearch/getCaseInventoryReport.test.ts +++ b/web-api/src/persistence/elasticsearch/getCaseInventoryReport.test.ts @@ -2,7 +2,6 @@ import { CASE_STATUS_TYPES, CHIEF_JUDGE, } from '../../../../shared/src/business/entities/EntityConstants'; -import { MOCK_USERS } from '../../../../shared/src/test/mockUsers'; import { applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; import { getCaseInventoryReport } from './getCaseInventoryReport'; import { marshall } from '@aws-sdk/util-dynamodb'; @@ -35,9 +34,6 @@ describe('getCaseInventoryReport', () => { applicationContext.getConstants.mockReturnValue({ CASE_INVENTORY_MAX_PAGE_SIZE, }); - applicationContext.getCurrentUser.mockReturnValue( - MOCK_USERS['a7d90c05-f6cd-442c-a168-202db587f16f'], - ); applicationContext.getSearchClient.mockReturnValue({ search: searchSpy, }); diff --git a/web-api/src/persistence/s3/saveDocumentFromLambda.ts b/web-api/src/persistence/s3/saveDocumentFromLambda.ts index be26a0ebfc0..d3bc3501b5f 100644 --- a/web-api/src/persistence/s3/saveDocumentFromLambda.ts +++ b/web-api/src/persistence/s3/saveDocumentFromLambda.ts @@ -9,7 +9,7 @@ export const saveDocumentFromLambda = async ({ }: { applicationContext: ServerApplicationContext; contentType?: string; - document: any; + document: WithImplicitCoercion; key: string; useTempBucket?: boolean; }): Promise => { diff --git a/web-api/src/users/signUpUserLambda.ts b/web-api/src/users/signUpUserLambda.ts index 471bf13eabe..afd63568fcf 100644 --- a/web-api/src/users/signUpUserLambda.ts +++ b/web-api/src/users/signUpUserLambda.ts @@ -1,4 +1,5 @@ import { genericHandler } from '../genericHandler'; +import { signUpUserInteractor } from '@web-api/business/useCases/auth/signUpUserInteractor'; /** * creates a new user locally @@ -7,9 +8,7 @@ import { genericHandler } from '../genericHandler'; */ export const signUpUserLambda = event => genericHandler(event, async ({ applicationContext }) => { - return await applicationContext - .getUseCases() - .signUpUserInteractor(applicationContext, { - user: JSON.parse(event.body), - }); + return await signUpUserInteractor(applicationContext, { + user: JSON.parse(event.body), + }); }); diff --git a/web-api/terraform/applyables/account-specific/account-specific.tf b/web-api/terraform/applyables/account-specific/account-specific.tf index 2ee73cddd87..245b15fdfc0 100644 --- a/web-api/terraform/applyables/account-specific/account-specific.tf +++ b/web-api/terraform/applyables/account-specific/account-specific.tf @@ -16,7 +16,7 @@ terraform { backend "s3" {} required_providers { - aws = "5.63.0" + aws = "5.63.1" opensearch = { source = "opensearch-project/opensearch" version = "2.2.0" diff --git a/web-api/terraform/applyables/allColors/allColors.tf b/web-api/terraform/applyables/allColors/allColors.tf index 0c20b63b31d..d283758a1a7 100644 --- a/web-api/terraform/applyables/allColors/allColors.tf +++ b/web-api/terraform/applyables/allColors/allColors.tf @@ -17,7 +17,7 @@ terraform { } required_providers { - aws = "5.63.0" + aws = "5.63.1" } } diff --git a/web-api/terraform/applyables/blue/blue.tf b/web-api/terraform/applyables/blue/blue.tf index f1163923e34..aa5be5d6bfd 100644 --- a/web-api/terraform/applyables/blue/blue.tf +++ b/web-api/terraform/applyables/blue/blue.tf @@ -18,7 +18,7 @@ terraform { } required_providers { - aws = "5.63.0" + aws = "5.63.1" } } diff --git a/web-api/terraform/applyables/glue-cron/glue-cron-applyable.tf b/web-api/terraform/applyables/glue-cron/glue-cron-applyable.tf index e247b94287e..2b6968d69f2 100644 --- a/web-api/terraform/applyables/glue-cron/glue-cron-applyable.tf +++ b/web-api/terraform/applyables/glue-cron/glue-cron-applyable.tf @@ -7,7 +7,7 @@ terraform { } required_providers { - aws = "5.63.0" + aws = "5.63.1" } } diff --git a/web-api/terraform/applyables/green/green.tf b/web-api/terraform/applyables/green/green.tf index eeb59c3f72d..317798f3f9e 100644 --- a/web-api/terraform/applyables/green/green.tf +++ b/web-api/terraform/applyables/green/green.tf @@ -18,7 +18,7 @@ terraform { } required_providers { - aws = "5.63.0" + aws = "5.63.1" } } diff --git a/web-api/terraform/applyables/migration-cron/migration-cron-applyable.tf b/web-api/terraform/applyables/migration-cron/migration-cron-applyable.tf index 55b53b3f66d..b15a70a986f 100644 --- a/web-api/terraform/applyables/migration-cron/migration-cron-applyable.tf +++ b/web-api/terraform/applyables/migration-cron/migration-cron-applyable.tf @@ -7,7 +7,7 @@ terraform { } required_providers { - aws = "5.63.0" + aws = "5.63.1" } } diff --git a/web-api/terraform/applyables/migration/migration-applyable.tf b/web-api/terraform/applyables/migration/migration-applyable.tf index 463590ccd65..0fa0921efb8 100644 --- a/web-api/terraform/applyables/migration/migration-applyable.tf +++ b/web-api/terraform/applyables/migration/migration-applyable.tf @@ -7,7 +7,7 @@ terraform { } required_providers { - aws = "5.63.0" + aws = "5.63.1" } } diff --git a/web-api/terraform/applyables/reindex-cron/reindex-cron-applyable.tf b/web-api/terraform/applyables/reindex-cron/reindex-cron-applyable.tf index 1ac3a95eda4..4e41970283c 100644 --- a/web-api/terraform/applyables/reindex-cron/reindex-cron-applyable.tf +++ b/web-api/terraform/applyables/reindex-cron/reindex-cron-applyable.tf @@ -7,7 +7,7 @@ terraform { } required_providers { - aws = "5.63.0" + aws = "5.63.1" } } diff --git a/web-api/terraform/applyables/switch-colors-cron/switch-colors-cron-applyable.tf b/web-api/terraform/applyables/switch-colors-cron/switch-colors-cron-applyable.tf index ed71f2fb7a8..5987d1dd6b6 100644 --- a/web-api/terraform/applyables/switch-colors-cron/switch-colors-cron-applyable.tf +++ b/web-api/terraform/applyables/switch-colors-cron/switch-colors-cron-applyable.tf @@ -7,7 +7,7 @@ terraform { } required_providers { - aws = "5.63.0" + aws = "5.63.1" } } diff --git a/web-api/terraform/applyables/wait-for-workflow/wait-for-workflow-cron-applyable.tf b/web-api/terraform/applyables/wait-for-workflow/wait-for-workflow-cron-applyable.tf index 4ffbfe30cd5..d87de1bbe1f 100644 --- a/web-api/terraform/applyables/wait-for-workflow/wait-for-workflow-cron-applyable.tf +++ b/web-api/terraform/applyables/wait-for-workflow/wait-for-workflow-cron-applyable.tf @@ -7,7 +7,7 @@ terraform { } required_providers { - aws = "5.63.0" + aws = "5.63.1" } } diff --git a/web-api/terraform/modules/ci-cd/ci-cd-permissions.tf b/web-api/terraform/modules/ci-cd/ci-cd-permissions.tf index 03fda04aafc..a3558eb9a38 100644 --- a/web-api/terraform/modules/ci-cd/ci-cd-permissions.tf +++ b/web-api/terraform/modules/ci-cd/ci-cd-permissions.tf @@ -48,6 +48,7 @@ resource "aws_iam_policy" "ci_cd_policy" { "Sid": "Cognito", "Effect": "Allow", "Action": [ + "cognito-idp:AddCustomAttributes", "cognito-idp:AdminCreateUser", "cognito-idp:AdminDeleteUser", "cognito-idp:AdminDisableUser", diff --git a/web-api/terraform/modules/dynamsoft/dynamsoft.tf b/web-api/terraform/modules/dynamsoft/dynamsoft.tf index 09df081dd3c..b35552c2ded 100644 --- a/web-api/terraform/modules/dynamsoft/dynamsoft.tf +++ b/web-api/terraform/modules/dynamsoft/dynamsoft.tf @@ -10,20 +10,14 @@ resource "aws_instance" "dynamsoft" { Name = "dynamsoft-${var.environment}" environment = var.environment } - user_data = data.template_file.setup_dynamsoft.rendered - user_data_replace_on_change = true - - iam_instance_profile = "dynamsoft_s3_download_role" -} - -data "template_file" "setup_dynamsoft" { - template = file("${path.module}/setup_dynamsoft.sh") - - vars = { + user_data = templatefile("${path.module}/setup_dynamsoft.sh", { dynamsoft_s3_zip_path = var.dynamsoft_s3_zip_path dynamsoft_url = var.dynamsoft_url dynamsoft_product_keys = var.dynamsoft_product_keys - } + }) + user_data_replace_on_change = true + + iam_instance_profile = "dynamsoft_s3_download_role" } resource "aws_security_group" "dynamsoft_load_balancer_security_group" { diff --git a/web-api/terraform/modules/everything-else-deprecated/cognito.tf b/web-api/terraform/modules/everything-else-deprecated/cognito.tf index 10c3cb6b04d..fbd209bce73 100644 --- a/web-api/terraform/modules/everything-else-deprecated/cognito.tf +++ b/web-api/terraform/modules/everything-else-deprecated/cognito.tf @@ -162,7 +162,7 @@ resource "aws_cognito_user_pool_client" "client" { explicit_auth_flows = ["ADMIN_NO_SRP_AUTH", "USER_PASSWORD_AUTH"] generate_secret = false - allowed_oauth_flows_user_pool_client = true + allowed_oauth_flows_user_pool_client = false token_validity_units { access_token = "hours" @@ -173,9 +173,6 @@ resource "aws_cognito_user_pool_client" "client" { access_token_validity = 1 id_token_validity = 1 - allowed_oauth_flows = ["code", "implicit"] - allowed_oauth_scopes = ["email", "openid", "profile", "phone", "aws.cognito.signin.user.admin"] - supported_identity_providers = ["COGNITO"] user_pool_id = aws_cognito_user_pool.pool.id @@ -348,7 +345,7 @@ resource "aws_cognito_user_pool_client" "irs_client" { explicit_auth_flows = ["ADMIN_NO_SRP_AUTH", "USER_PASSWORD_AUTH"] generate_secret = false - allowed_oauth_flows_user_pool_client = true + allowed_oauth_flows_user_pool_client = false token_validity_units { access_token = "hours" id_token = "hours" @@ -358,10 +355,6 @@ resource "aws_cognito_user_pool_client" "irs_client" { access_token_validity = 1 id_token_validity = 1 - allowed_oauth_flows = ["code", "implicit"] - allowed_oauth_scopes = ["email", "openid", "profile", "phone", "aws.cognito.signin.user.admin"] - supported_identity_providers = ["COGNITO"] - user_pool_id = aws_cognito_user_pool.irs_pool.id write_attributes = [ diff --git a/web-client/integration-tests/docketClerkStandaloneRemoteTrialSession.test.ts b/web-client/integration-tests/docketClerkStandaloneRemoteTrialSession.test.ts index 0f631ab43c8..7dd65dab96d 100644 --- a/web-client/integration-tests/docketClerkStandaloneRemoteTrialSession.test.ts +++ b/web-client/integration-tests/docketClerkStandaloneRemoteTrialSession.test.ts @@ -23,7 +23,7 @@ describe('Docket clerk standalone remote trial session journey', () => { headers: { Authorization: // mocked admissions clerk user - 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFkbWlzc2lvbnNjbGVya0BleGFtcGxlLmNvbSIsIm5hbWUiOiJUZXN0IEFkbWlzc2lvbnMgQ2xlcmsiLCJyb2xlIjoiYWRtaXNzaW9uc2NsZXJrIiwic2VjdGlvbiI6ImFkbWlzc2lvbnMiLCJ1c2VySWQiOiI5ZDdkNjNiNy1kN2E1LTQ5MDUtYmE4OS1lZjcxYmYzMDA1N2YiLCJjdXN0b206cm9sZSI6ImFkbWlzc2lvbnNjbGVyayIsInN1YiI6IjlkN2Q2M2I3LWQ3YTUtNDkwNS1iYTg5LWVmNzFiZjMwMDU3ZiIsImlhdCI6MTYwOTQ0NTUyNn0.kow3pAUloDseD3isrxgtKBpcKsjMktbRBzY41c1NRqA', + 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFkbWlzc2lvbnNjbGVya0BleGFtcGxlLmNvbSIsIm5hbWUiOiJUZXN0IEFkbWlzc2lvbnMgQ2xlcmsiLCJyb2xlIjoiYWRtaXNzaW9uc2NsZXJrIiwic2VjdGlvbiI6ImFkbWlzc2lvbnMiLCJjdXN0b206dXNlcklkIjoiOWQ3ZDYzYjctZDdhNS00OTA1LWJhODktZWY3MWJmMzAwNTdmIiwiY3VzdG9tOnJvbGUiOiJhZG1pc3Npb25zY2xlcmsiLCJzdWIiOiI5ZDdkNjNiNy1kN2E1LTQ5MDUtYmE4OS1lZjcxYmYzMDA1N2YiLCJpYXQiOjE2MDk0NDU1MjZ9.0SHlDNenfsLo4GJ6aC6Utwxh6ec0NCYDG0fLhcqhYAs', 'Content-Type': 'application/json', }, timeout: 2000, diff --git a/web-client/integration-tests/helpers.ts b/web-client/integration-tests/helpers.ts index 616d67aa7e1..87f9111ee56 100644 --- a/web-client/integration-tests/helpers.ts +++ b/web-client/integration-tests/helpers.ts @@ -41,8 +41,7 @@ import jwt from 'jsonwebtoken'; import qs from 'qs'; import riotRoute from 'riot-route'; -const applicationContext = - clientApplicationContext as unknown as IApplicationContext; +const applicationContext = clientApplicationContext as any; const { CASE_TYPES_MAP, PARTY_TYPES, SERVICE_INDICATOR_TYPES } = applicationContext.getConstants(); diff --git a/web-client/integration-tests/journey/admissionsClerkMigratesPractitionerWithoutEmail.ts b/web-client/integration-tests/journey/admissionsClerkMigratesPractitionerWithoutEmail.ts index 74b3f9d69cd..42805924f67 100644 --- a/web-client/integration-tests/journey/admissionsClerkMigratesPractitionerWithoutEmail.ts +++ b/web-client/integration-tests/journey/admissionsClerkMigratesPractitionerWithoutEmail.ts @@ -12,7 +12,7 @@ const axiosInstance = axios.create({ headers: { Authorization: // mocked admissions clerk user - 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFkbWlzc2lvbnNjbGVya0BleGFtcGxlLmNvbSIsIm5hbWUiOiJUZXN0IEFkbWlzc2lvbnMgQ2xlcmsiLCJyb2xlIjoiYWRtaXNzaW9uc2NsZXJrIiwic2VjdGlvbiI6ImFkbWlzc2lvbnMiLCJ1c2VySWQiOiI5ZDdkNjNiNy1kN2E1LTQ5MDUtYmE4OS1lZjcxYmYzMDA1N2YiLCJjdXN0b206cm9sZSI6ImFkbWlzc2lvbnNjbGVyayIsInN1YiI6IjlkN2Q2M2I3LWQ3YTUtNDkwNS1iYTg5LWVmNzFiZjMwMDU3ZiIsImlhdCI6MTYwOTQ0NTUyNn0.kow3pAUloDseD3isrxgtKBpcKsjMktbRBzY41c1NRqA', + 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFkbWlzc2lvbnNjbGVya0BleGFtcGxlLmNvbSIsIm5hbWUiOiJUZXN0IEFkbWlzc2lvbnMgQ2xlcmsiLCJyb2xlIjoiYWRtaXNzaW9uc2NsZXJrIiwic2VjdGlvbiI6ImFkbWlzc2lvbnMiLCJjdXN0b206dXNlcklkIjoiOWQ3ZDYzYjctZDdhNS00OTA1LWJhODktZWY3MWJmMzAwNTdmIiwiY3VzdG9tOnJvbGUiOiJhZG1pc3Npb25zY2xlcmsiLCJzdWIiOiI5ZDdkNjNiNy1kN2E1LTQ5MDUtYmE4OS1lZjcxYmYzMDA1N2YiLCJpYXQiOjE2MDk0NDU1MjZ9.0SHlDNenfsLo4GJ6aC6Utwxh6ec0NCYDG0fLhcqhYAs', 'Content-Type': 'application/json', }, timeout: 2000, diff --git a/web-client/integration-tests/journey/chambersUserAddsOrderToCase.ts b/web-client/integration-tests/journey/chambersUserAddsOrderToCase.ts index 584b1e3c4e3..6b012050d18 100644 --- a/web-client/integration-tests/journey/chambersUserAddsOrderToCase.ts +++ b/web-client/integration-tests/journey/chambersUserAddsOrderToCase.ts @@ -48,6 +48,7 @@ export const chambersUserAddsOrderToCase = cerebralTest => { .getUtilities() .getFormattedCaseDetail({ applicationContext, + authorizedUser: cerebralTest.getState('user'), caseDetail: cerebralTest.getState('caseDetail'), }); diff --git a/web-client/integration-tests/journey/petitionsClerkAddsGenericOrderToCase.ts b/web-client/integration-tests/journey/petitionsClerkAddsGenericOrderToCase.ts index 509abc15b33..683a744f289 100644 --- a/web-client/integration-tests/journey/petitionsClerkAddsGenericOrderToCase.ts +++ b/web-client/integration-tests/journey/petitionsClerkAddsGenericOrderToCase.ts @@ -49,6 +49,7 @@ export const petitionsClerkAddsGenericOrderToCase = cerebralTest => { .getUtilities() .getFormattedCaseDetail({ applicationContext, + authorizedUser: cerebralTest.getState('user'), caseDetail: cerebralTest.getState('caseDetail'), }); diff --git a/web-client/integration-tests/journey/petitionsClerkAddsNoticeToCase.ts b/web-client/integration-tests/journey/petitionsClerkAddsNoticeToCase.ts index 8d8f25c4203..e7cdc9b722a 100644 --- a/web-client/integration-tests/journey/petitionsClerkAddsNoticeToCase.ts +++ b/web-client/integration-tests/journey/petitionsClerkAddsNoticeToCase.ts @@ -53,6 +53,7 @@ export const petitionsClerkAddsNoticeToCase = cerebralTest => { .getUtilities() .getFormattedCaseDetail({ applicationContext, + authorizedUser: cerebralTest.getState('user'), caseDetail: cerebralTest.getState('caseDetail'), }); diff --git a/web-client/integration-tests/journey/petitionsClerkAddsOrderToCase.ts b/web-client/integration-tests/journey/petitionsClerkAddsOrderToCase.ts index 15ce7c4cb56..35c4e6155fa 100644 --- a/web-client/integration-tests/journey/petitionsClerkAddsOrderToCase.ts +++ b/web-client/integration-tests/journey/petitionsClerkAddsOrderToCase.ts @@ -54,6 +54,7 @@ export const petitionsClerkAddsOrderToCase = cerebralTest => { .getUtilities() .getFormattedCaseDetail({ applicationContext, + authorizedUser: cerebralTest.getState('user'), caseDetail: cerebralTest.getState('caseDetail'), }); diff --git a/web-client/integration-tests/journey/petitionsClerkCreateOrder.ts b/web-client/integration-tests/journey/petitionsClerkCreateOrder.ts index 829b9fa62e8..1e2bc7edb37 100644 --- a/web-client/integration-tests/journey/petitionsClerkCreateOrder.ts +++ b/web-client/integration-tests/journey/petitionsClerkCreateOrder.ts @@ -50,6 +50,7 @@ export const petitionsClerkCreateOrder = cerebralTest => { .getUtilities() .getFormattedCaseDetail({ applicationContext, + authorizedUser: cerebralTest.getState('user'), caseDetail: cerebralTest.getState('caseDetail'), }); diff --git a/web-client/integration-tests/sentWorkItemsExpireAfterNDays.test.ts b/web-client/integration-tests/sentWorkItemsExpireAfterNDays.test.ts index c7c781938b5..73a53012dc6 100644 --- a/web-client/integration-tests/sentWorkItemsExpireAfterNDays.test.ts +++ b/web-client/integration-tests/sentWorkItemsExpireAfterNDays.test.ts @@ -1,7 +1,4 @@ -import { - CASE_STATUS_TYPES, - ROLES, -} from '../../shared/src/business/entities/EntityConstants'; +import { CASE_STATUS_TYPES } from '../../shared/src/business/entities/EntityConstants'; import { createApplicationContext as applicationContextFactory } from '../../web-api/src/applicationContext'; import { getFormattedDocumentQCMyOutbox, @@ -10,6 +7,7 @@ import { setupTest, uploadPetition, } from './helpers'; +import { mockPetitionsClerkUser } from '@shared/test/mockAuthUsers'; describe('verify old sent work items do not show up in the outbox', () => { const cerebralTest = setupTest(); @@ -31,11 +29,12 @@ describe('verify old sent work items do not show up in the outbox', () => { caseDetail = await uploadPetition(cerebralTest); expect(caseDetail.docketNumber).toBeDefined(); - const applicationContext = applicationContextFactory({ - role: ROLES.petitionsClerk, - section: 'petitions', + const mockUser = { + ...mockPetitionsClerkUser, userId: '3805d1ab-18d0-43ec-bafb-654e83405416', - }); + }; + + const applicationContext = applicationContextFactory(mockUser); applicationContext.environment.dynamoDbTableName = 'efcms-local'; const daysToRetrieveKey = applicationContext.getConstants().CONFIGURATION_ITEM_KEYS @@ -62,12 +61,12 @@ describe('verify old sent work items do not show up in the outbox', () => { workItemIdNPlus1 = applicationContext.getUniqueId(); workItemNPlus1Days = { - assigneeId: '3805d1ab-18d0-43ec-bafb-654e83405416', + assigneeId: mockUser.userId, assigneeName: 'Test petitionsclerk1', caseStatus: CASE_STATUS_TYPES.new, completedAt: CREATED_N_PLUS_1_DAYS_AGO, completedBy: 'Test Petitionsclerk', - completedByUserId: '3805d1ab-18d0-43ec-bafb-654e83405416', + completedByUserId: mockUser.userId, createdAt: CREATED_N_PLUS_1_DAYS_AGO, docketEntry: { createdAt: '2019-06-25T15:14:11.924Z', @@ -80,7 +79,7 @@ describe('verify old sent work items do not show up in the outbox', () => { section: 'petitions', sentBy: 'Test petitionsclerk1', sentBySection: 'petitions', - sentByUserId: '3805d1ab-18d0-43ec-bafb-654e83405416', + sentByUserId: mockUser.userId, updatedAt: '2019-06-26T16:31:17.643Z', workItemId: `${workItemIdNPlus1}`, }; @@ -101,23 +100,26 @@ describe('verify old sent work items do not show up in the outbox', () => { await applicationContext.getPersistenceGateway().putWorkItemInOutbox({ applicationContext, + authorizedUser: mockUser, workItem: workItemNPlus1Days, }); await applicationContext.getPersistenceGateway().putWorkItemInOutbox({ applicationContext, + authorizedUser: mockUser, workItem: workItemNDays, }); await applicationContext.getPersistenceGateway().putWorkItemInOutbox({ applicationContext, + authorizedUser: mockUser, workItem: workItemNMinus1Days, }); }); loginAs(cerebralTest, 'petitionsclerk@example.com'); - it('the petitionsclerk user should have the expected work items equal to or new than 7 days', async () => { + it('the petitionsclerk user should have the expected work items equal to or newer than 7 days', async () => { const myOutbox = ( await getFormattedDocumentQCMyOutbox(cerebralTest) ).filter(item => item.docketNumber === caseDetail.docketNumber); diff --git a/web-client/integration-tests/servedWorkItemsExpireAfter7Days.test.ts b/web-client/integration-tests/servedWorkItemsExpireAfter7Days.test.ts index 2d97f595855..0ada36c34ab 100644 --- a/web-client/integration-tests/servedWorkItemsExpireAfter7Days.test.ts +++ b/web-client/integration-tests/servedWorkItemsExpireAfter7Days.test.ts @@ -7,12 +7,12 @@ import { setupTest, uploadPetition, } from './helpers'; +import { mockPetitionsClerkUser } from '@shared/test/mockAuthUsers'; const { IRS_SYSTEM_SECTION, PETITIONS_SECTION, STATUS_TYPES: CASE_STATUS_TYPES, - USER_ROLES: ROLES, } = applicationContext.getConstants(); const cerebralTest = setupTest(); @@ -37,11 +37,12 @@ describe('verify old served work items do not show up in the outbox', () => { caseDetail = await uploadPetition(cerebralTest); expect(caseDetail.docketNumber).toBeDefined(); - const appContext = applicationContextFactory({ - role: ROLES.petitionsClerk, - section: PETITIONS_SECTION, + const mockUser = { + ...mockPetitionsClerkUser, userId: '3805d1ab-18d0-43ec-bafb-654e83405416', - }); + }; + + const appContext = applicationContextFactory(mockUser); appContext.environment.dynamoDbTableName = 'efcms-local'; const CREATED_8_DAYS_AGO = applicationContext @@ -59,11 +60,11 @@ describe('verify old served work items do not show up in the outbox', () => { workItemId8 = appContext.getUniqueId(); workItem8Days = { - assigneeId: '3805d1ab-18d0-43ec-bafb-654e83405416', + assigneeId: mockUser.userId, assigneeName: 'Test petitionsclerk1', caseStatus: CASE_STATUS_TYPES.new, completedAt: '2019-06-26T16:31:17.643Z', - completedByUserId: '3805d1ab-18d0-43ec-bafb-654e83405416', + completedByUserId: mockUser.userId, createdAt: CREATED_8_DAYS_AGO, docketEntry: { createdAt: '2019-06-25T15:14:11.924Z', @@ -76,7 +77,7 @@ describe('verify old served work items do not show up in the outbox', () => { section: IRS_SYSTEM_SECTION, sentBy: 'Test petitionsclerk1', sentBySection: PETITIONS_SECTION, - sentByUserId: '3805d1ab-18d0-43ec-bafb-654e83405416', + sentByUserId: mockUser.userId, updatedAt: '2019-06-26T16:31:17.643Z', workItemId: `${workItemId8}`, }; @@ -97,16 +98,19 @@ describe('verify old served work items do not show up in the outbox', () => { await appContext.getPersistenceGateway().putWorkItemInOutbox({ applicationContext: appContext, + authorizedUser: mockUser, workItem: workItem8Days, }); await appContext.getPersistenceGateway().putWorkItemInOutbox({ applicationContext: appContext, + authorizedUser: mockUser, workItem: workItem7Days, }); await appContext.getPersistenceGateway().putWorkItemInOutbox({ applicationContext: appContext, + authorizedUser: mockUser, workItem: workItem6Days, }); }); diff --git a/web-client/integration-tests/v2ApiJourney.test.ts b/web-client/integration-tests/v2ApiJourney.test.ts index 34bff835698..1b4949e5787 100644 --- a/web-client/integration-tests/v2ApiJourney.test.ts +++ b/web-client/integration-tests/v2ApiJourney.test.ts @@ -5,7 +5,6 @@ import { USTC_TZ, } from '../../shared/src/business/utilities/DateHandler'; import { PARTIES_CODES } from '../../shared/src/business/entities/EntityConstants'; -import { applicationContext } from '../../shared/src/business/test/createTestApplicationContext'; import { loginAs, setupTest } from './helpers'; import { petitionsClerkCreatesNewCase } from './journey/petitionsClerkCreatesNewCase'; import { seedEntries } from '../../web-api/storage/fixtures/seed'; @@ -201,7 +200,7 @@ describe('View and manage the deadlines of a case', () => { const docketEntries = new Array(); for (const item of seedEntries) { if (item.entityName === 'DocketEntry') { - const de = new DocketEntry(item, { applicationContext }); + const de = new DocketEntry(item, { authorizedUser: undefined }); if ( [PARTIES_CODES.BOTH, PARTIES_CODES.RESPONDENT].includes( de.servedPartiesCode ?? '', diff --git a/web-client/src/applicationContext.ts b/web-client/src/applicationContext.ts index ace8f8256ff..390fe7117f3 100644 --- a/web-client/src/applicationContext.ts +++ b/web-client/src/applicationContext.ts @@ -28,9 +28,7 @@ import { getPublicSiteUrl, getUniqueId, } from '../../shared/src/sharedAppContext'; -import { RawIrsPractitioner } from '@shared/business/entities/IrsPractitioner'; -import { RawPractitioner } from '@shared/business/entities/Practitioner'; -import { RawUser, User } from '../../shared/src/business/entities/User'; +import { User } from '../../shared/src/business/entities/User'; import { abbreviateState } from '../../shared/src/business/utilities/abbreviateState'; import { addCaseToTrialSessionInteractor } from '../../shared/src/proxies/trialSessions/addCaseToTrialSessionProxy'; import { addConsolidatedCaseInteractor } from '../../shared/src/proxies/addConsolidatedCaseProxy'; @@ -372,23 +370,6 @@ const reduce = ImageBlobReduce({ let user; let broadcastChannel; -const getCurrentUser = (): RawUser | RawPractitioner | RawIrsPractitioner => { - return user; -}; -const setCurrentUser = ( - newUser: RawUser | RawPractitioner | RawIrsPractitioner, -) => { - user = newUser; -}; - -let token; -const getCurrentUserToken = () => { - return token; -}; -const setCurrentUserToken = newToken => { - token = newToken; -}; - let forceRefreshCallback: () => {}; const allUseCases = { @@ -654,12 +635,6 @@ const applicationContext = { }, getCaseTitle: Case.getCaseTitle, getConstants: () => appConstants, - getCurrentUser, - getCurrentUserPermissions: () => { - const currentUser = getCurrentUser(); - return getUserPermissions(currentUser); - }, - getCurrentUserToken, getEnvironment, getFileReaderInstance: () => new FileReader(), getForceRefreshCallback() { @@ -822,8 +797,6 @@ const applicationContext = { return getIsFeatureEnabled(featureName, user, getEnvironment().stage); }, isPublicUser: () => false, - setCurrentUser, - setCurrentUserToken, setForceRefreshCallback(callback) { forceRefreshCallback = callback; }, diff --git a/web-client/src/applicationContextPublic.ts b/web-client/src/applicationContextPublic.ts index 2ecf613c5f2..6eaa6b508d1 100644 --- a/web-client/src/applicationContextPublic.ts +++ b/web-client/src/applicationContextPublic.ts @@ -169,8 +169,6 @@ const applicationContextPublic = { }, getCaseTitle: Case.getCaseTitle, getConstants: () => frozenConstants, - getCurrentUser: () => ({}), - getCurrentUserToken: () => null, getEnvironment, getForceRefreshCallback() { return forceRefreshCallback; diff --git a/web-client/src/persistence/s3/getDocument.ts b/web-client/src/persistence/s3/getDocument.ts index ef000d374cd..a7ac6bacc7e 100644 --- a/web-client/src/persistence/s3/getDocument.ts +++ b/web-client/src/persistence/s3/getDocument.ts @@ -1,3 +1,4 @@ +import { getCurrentUserToken } from '@shared/proxies/requests'; import { getPdfFromUrl } from './getPdfFromUrl'; const getDownloadPolicy = async ({ @@ -17,7 +18,7 @@ const getDownloadPolicy = async ({ `${applicationContext.getBaseUrl()}/case-documents/${docketNumber}/${key}/download-policy-url`, { headers: { - Authorization: `Bearer ${applicationContext.getCurrentUserToken()}`, + Authorization: `Bearer ${getCurrentUserToken()}`, }, }, ); diff --git a/web-client/src/persistence/s3/uploadDocumentFromClient.ts b/web-client/src/persistence/s3/uploadDocumentFromClient.ts index 36f774bbdfe..ff4bb4f8d2b 100644 --- a/web-client/src/persistence/s3/uploadDocumentFromClient.ts +++ b/web-client/src/persistence/s3/uploadDocumentFromClient.ts @@ -1,9 +1,11 @@ +import { getCurrentUserToken } from '@shared/proxies/requests'; + const getUploadPolicy = async ({ applicationContext, key }) => { const response = await applicationContext .getHttpClient() .get(`${applicationContext.getBaseUrl()}/documents/${key}/upload-policy`, { headers: { - Authorization: `Bearer ${applicationContext.getCurrentUserToken()}`, + Authorization: `Bearer ${getCurrentUserToken()}`, }, }); return response.data; diff --git a/web-client/src/presenter/actions/CaseAssociationRequest/canRequestAccessAction.test.ts b/web-client/src/presenter/actions/CaseAssociationRequest/canRequestAccessAction.test.ts index 59aee3f9bd9..9f78c9eeed5 100644 --- a/web-client/src/presenter/actions/CaseAssociationRequest/canRequestAccessAction.test.ts +++ b/web-client/src/presenter/actions/CaseAssociationRequest/canRequestAccessAction.test.ts @@ -1,4 +1,3 @@ -import { ROLES } from '@shared/business/entities/EntityConstants'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { canRequestAccessAction } from './canRequestAccessAction'; import { presenter } from '../../presenter'; @@ -11,10 +10,6 @@ describe('canRequestAccessAction', () => { yes: jest.fn(), }; - (applicationContext.getCurrentUser as jest.Mock).mockReturnValue({ - role: ROLES.irsPractitioner, - }); - it('should call path.yes if props.isAssociated is false or undefined', async () => { await runAction(canRequestAccessAction, { modules: { diff --git a/web-client/src/presenter/actions/CaseConsolidation/canConsolidateAction.ts b/web-client/src/presenter/actions/CaseConsolidation/canConsolidateAction.ts index e848879162d..56a5ce9f0ac 100644 --- a/web-client/src/presenter/actions/CaseConsolidation/canConsolidateAction.ts +++ b/web-client/src/presenter/actions/CaseConsolidation/canConsolidateAction.ts @@ -1,3 +1,5 @@ +import { state } from '@web-client/presenter/app.cerebral'; + /** * check to see if we can consolidate cases * @@ -9,10 +11,12 @@ */ export const canConsolidateAction = ({ applicationContext, + get, path, props, }: ActionProps) => { const { caseDetail, caseToConsolidate, confirmSelection } = props; + const user = get(state.user); if (!confirmSelection) { return path.error({ @@ -22,7 +26,7 @@ export const canConsolidateAction = ({ const results = applicationContext .getUseCases() - .canConsolidateInteractor(applicationContext, { + .canConsolidateInteractor(user, { caseToConsolidate, currentCase: caseDetail, }); diff --git a/web-client/src/presenter/actions/CorrespondenceDocument/uploadCorrespondenceFileAction.ts b/web-client/src/presenter/actions/CorrespondenceDocument/uploadCorrespondenceFileAction.ts index ffe5d005941..3c503a3fac9 100644 --- a/web-client/src/presenter/actions/CorrespondenceDocument/uploadCorrespondenceFileAction.ts +++ b/web-client/src/presenter/actions/CorrespondenceDocument/uploadCorrespondenceFileAction.ts @@ -14,13 +14,18 @@ export const uploadCorrespondenceFileAction = async ({ path, }: ActionProps) => { const { primaryDocumentFile } = get(state.form); + const user = get(state.user); try { const primaryDocumentFileId = await applicationContext .getUseCases() - .uploadCorrespondenceDocumentInteractor(applicationContext, { - documentFile: primaryDocumentFile, - }); + .uploadCorrespondenceDocumentInteractor( + applicationContext, + { + documentFile: primaryDocumentFile, + }, + user, + ); return path.success({ primaryDocumentFileId, diff --git a/web-client/src/presenter/actions/CourtIssuedDocketEntry/setDefaultServiceStampAction.test.ts b/web-client/src/presenter/actions/CourtIssuedDocketEntry/setDefaultServiceStampAction.test.ts index 2d206126bf0..06f0dcb9b11 100644 --- a/web-client/src/presenter/actions/CourtIssuedDocketEntry/setDefaultServiceStampAction.test.ts +++ b/web-client/src/presenter/actions/CourtIssuedDocketEntry/setDefaultServiceStampAction.test.ts @@ -8,16 +8,13 @@ presenter.providers.applicationContext = applicationContext; describe('setDefaultServiceStampAction', () => { it('should set default serviceStamp on form if user is a petitions clerk', async () => { - applicationContext.getCurrentUser = () => ({ - role: ROLES.petitionsClerk, - }); - const result = await runAction(setDefaultServiceStampAction, { modules: { presenter, }, state: { form: {}, + user: { role: ROLES.petitionsClerk }, }, }); @@ -27,16 +24,13 @@ describe('setDefaultServiceStampAction', () => { }); it('should not set default serviceStamp on form if user is a docket clerk', async () => { - applicationContext.getCurrentUser = () => ({ - role: ROLES.docketClerk, - }); - const result = await runAction(setDefaultServiceStampAction, { modules: { presenter, }, state: { form: {}, + user: { role: ROLES.docketClerk }, }, }); diff --git a/web-client/src/presenter/actions/CourtIssuedDocketEntry/setDefaultServiceStampAction.ts b/web-client/src/presenter/actions/CourtIssuedDocketEntry/setDefaultServiceStampAction.ts index 3991900ca77..f1fecaacfcc 100644 --- a/web-client/src/presenter/actions/CourtIssuedDocketEntry/setDefaultServiceStampAction.ts +++ b/web-client/src/presenter/actions/CourtIssuedDocketEntry/setDefaultServiceStampAction.ts @@ -8,9 +8,10 @@ import { state } from '@web-client/presenter/app.cerebral'; */ export const setDefaultServiceStampAction = ({ applicationContext, + get, store, }: ActionProps) => { - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); if (user.role === USER_ROLES.petitionsClerk) { store.set(state.form.serviceStamp, 'Served'); diff --git a/web-client/src/presenter/actions/CourtIssuedOrder/overwriteCorrespondenceFileAction.ts b/web-client/src/presenter/actions/CourtIssuedOrder/overwriteCorrespondenceFileAction.ts index 8a832c9f275..514d36f4553 100644 --- a/web-client/src/presenter/actions/CourtIssuedOrder/overwriteCorrespondenceFileAction.ts +++ b/web-client/src/presenter/actions/CourtIssuedOrder/overwriteCorrespondenceFileAction.ts @@ -15,14 +15,19 @@ export const overwriteCorrespondenceFileAction = async ({ }: ActionProps) => { const { primaryDocumentFile } = get(state.form); const docketEntryId = get(state.docketEntryId); + const user = get(state.user); try { const primaryDocumentFileId = await applicationContext .getUseCases() - .uploadCorrespondenceDocumentInteractor(applicationContext, { - documentFile: primaryDocumentFile, - keyToOverwrite: docketEntryId, - }); + .uploadCorrespondenceDocumentInteractor( + applicationContext, + { + documentFile: primaryDocumentFile, + keyToOverwrite: docketEntryId, + }, + user, + ); return path.success({ primaryDocumentFileId, diff --git a/web-client/src/presenter/actions/CourtIssuedOrder/overwriteOrderFileAction.ts b/web-client/src/presenter/actions/CourtIssuedOrder/overwriteOrderFileAction.ts index 76fb6a9f8fc..e90c065443f 100644 --- a/web-client/src/presenter/actions/CourtIssuedOrder/overwriteOrderFileAction.ts +++ b/web-client/src/presenter/actions/CourtIssuedOrder/overwriteOrderFileAction.ts @@ -15,14 +15,19 @@ export const overwriteOrderFileAction = async ({ }: ActionProps) => { const { primaryDocumentFile } = get(state.form); const documentToEdit = get(state.documentToEdit); + const user = get(state.user); try { const primaryDocumentFileId = await applicationContext .getUseCases() - .uploadOrderDocumentInteractor(applicationContext, { - documentFile: primaryDocumentFile, - fileIdToOverwrite: documentToEdit.docketEntryId, - }); + .uploadOrderDocumentInteractor( + applicationContext, + { + documentFile: primaryDocumentFile, + fileIdToOverwrite: documentToEdit.docketEntryId, + }, + user, + ); return path.success({ primaryDocumentFileId, diff --git a/web-client/src/presenter/actions/DocketEntry/uploadDocketEntryFileAction.ts b/web-client/src/presenter/actions/DocketEntry/uploadDocketEntryFileAction.ts index afacd6ef1ca..50b52721a35 100644 --- a/web-client/src/presenter/actions/DocketEntry/uploadDocketEntryFileAction.ts +++ b/web-client/src/presenter/actions/DocketEntry/uploadDocketEntryFileAction.ts @@ -10,15 +10,20 @@ export const uploadDocketEntryFileAction = async ({ fileUploadProgressMap: Record; }>) => { const docketEntryId = get(state.docketEntryId); + const user = get(state.user); const { fileUploadProgressMap } = props; try { const primaryDocumentFileId = await applicationContext .getUseCases() - .uploadDocumentInteractor(applicationContext, { - documentFile: fileUploadProgressMap.primary.file, - key: docketEntryId, - onUploadProgress: fileUploadProgressMap.primary.uploadProgress, - }); + .uploadDocumentInteractor( + applicationContext, + { + documentFile: fileUploadProgressMap.primary.file, + key: docketEntryId, + onUploadProgress: fileUploadProgressMap.primary.uploadProgress, + }, + user, + ); return path.success({ docketEntryId: primaryDocumentFileId, diff --git a/web-client/src/presenter/actions/EditDocketRecordEntry/validateDocumentAction.ts b/web-client/src/presenter/actions/EditDocketRecordEntry/validateDocumentAction.ts index 74b5d39af13..2e0e5912e05 100644 --- a/web-client/src/presenter/actions/EditDocketRecordEntry/validateDocumentAction.ts +++ b/web-client/src/presenter/actions/EditDocketRecordEntry/validateDocumentAction.ts @@ -16,12 +16,14 @@ export const validateDocumentAction = ({ }: ActionProps) => { const formMetadata = get(state.form); const editType = get(state.screenMetadata.editType); // Document, CourtIssued, NoDocument + const authorizedUser = get(state.user); - let errors = applicationContext - .getUseCases() - .validateDocumentInteractor(applicationContext, { + let errors = applicationContext.getUseCases().validateDocumentInteractor( + { document: formMetadata, - }); + }, + authorizedUser, + ); let errorDisplayOrder = ['description', 'eventCode', 'filingDate', 'index']; diff --git a/web-client/src/presenter/actions/FileDocument/setDefaultFileDocumentFormValuesAction.test.ts b/web-client/src/presenter/actions/FileDocument/setDefaultFileDocumentFormValuesAction.test.ts index 3a6de6936b6..441582362dd 100644 --- a/web-client/src/presenter/actions/FileDocument/setDefaultFileDocumentFormValuesAction.test.ts +++ b/web-client/src/presenter/actions/FileDocument/setDefaultFileDocumentFormValuesAction.test.ts @@ -18,8 +18,6 @@ describe('setDefaultFileDocumentFormValuesAction', () => { presenter.providers.applicationContext = applicationContext; it('should set fileAcrossConsolidatedGroup to false when the user is filing a document on a case that is NOT consolidated', async () => { - applicationContext.getCurrentUser.mockReturnValue(privatePractitionerUser); - const result = await runAction(setDefaultFileDocumentFormValuesAction, { modules: { presenter }, state: { @@ -28,6 +26,7 @@ describe('setDefaultFileDocumentFormValuesAction', () => { leadDocketNumber: undefined, }, form: {}, + user: privatePractitionerUser, }, }); @@ -44,8 +43,6 @@ describe('setDefaultFileDocumentFormValuesAction', () => { }); it('should set fileAcrossConsolidatedGroup to false when the user is filing on a consolidated case but the document they are filing is NOT multi-docketable', async () => { - applicationContext.getCurrentUser.mockReturnValue(privatePractitionerUser); - const result = await runAction(setDefaultFileDocumentFormValuesAction, { modules: { presenter }, state: { @@ -56,6 +53,7 @@ describe('setDefaultFileDocumentFormValuesAction', () => { form: { eventCode: NON_MULTI_DOCKETABLE_EVENT_CODES[0], }, + user: privatePractitionerUser, }, }); @@ -73,8 +71,6 @@ describe('setDefaultFileDocumentFormValuesAction', () => { }); it('should set fileAcrossConsolidatedGroup to true when the user is filing a document on a case that is consolidated and they have chosen to file a document that is multi-docketable', async () => { - applicationContext.getCurrentUser.mockReturnValue(privatePractitionerUser); - const result = await runAction(setDefaultFileDocumentFormValuesAction, { modules: { presenter }, state: { @@ -85,6 +81,7 @@ describe('setDefaultFileDocumentFormValuesAction', () => { form: { eventCode: MULTI_DOCKET_FILING_EVENT_CODES[0], }, + user: privatePractitionerUser, }, }); @@ -102,13 +99,12 @@ describe('setDefaultFileDocumentFormValuesAction', () => { }); it('should set filersMap[userId] to true when the logged in user is a petitioner', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - const result = await runAction(setDefaultFileDocumentFormValuesAction, { modules: { presenter }, state: { caseDetail: {}, form: {}, + user: petitionerUser, }, }); @@ -118,8 +114,6 @@ describe('setDefaultFileDocumentFormValuesAction', () => { }); it('should set partyIrsPractitioner to true when first IRS filing', async () => { - applicationContext.getCurrentUser.mockReturnValue(irsPractitionerUser); - const result = await runAction(setDefaultFileDocumentFormValuesAction, { modules: { presenter }, state: { @@ -129,6 +123,7 @@ describe('setDefaultFileDocumentFormValuesAction', () => { form: { eventCode: 'EA', }, + user: irsPractitionerUser, }, }); @@ -136,13 +131,12 @@ describe('setDefaultFileDocumentFormValuesAction', () => { }); it('should default the generationType to manual', async () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - const result = await runAction(setDefaultFileDocumentFormValuesAction, { modules: { presenter }, state: { caseDetail: {}, form: { generationType: undefined }, + user: petitionerUser, }, }); diff --git a/web-client/src/presenter/actions/FileDocument/setDefaultFileDocumentFormValuesAction.ts b/web-client/src/presenter/actions/FileDocument/setDefaultFileDocumentFormValuesAction.ts index d8903682474..b589da3a0a3 100644 --- a/web-client/src/presenter/actions/FileDocument/setDefaultFileDocumentFormValuesAction.ts +++ b/web-client/src/presenter/actions/FileDocument/setDefaultFileDocumentFormValuesAction.ts @@ -7,7 +7,7 @@ export const setDefaultFileDocumentFormValuesAction = ({ get, store, }: ActionProps) => { - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); diff --git a/web-client/src/presenter/actions/FileDocument/setPractitionerOnFormAction.test.ts b/web-client/src/presenter/actions/FileDocument/setPractitionerOnFormAction.test.ts index 56a3b835dc4..9e3aa56fb76 100644 --- a/web-client/src/presenter/actions/FileDocument/setPractitionerOnFormAction.test.ts +++ b/web-client/src/presenter/actions/FileDocument/setPractitionerOnFormAction.test.ts @@ -9,24 +9,22 @@ describe('setPractitionerOnFormAction', () => { presenter.providers.applicationContext = applicationContext; it('should not set state.form.practitioner when the logged in user is not a privatePractitioner', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: USER_ROLES.docketClerk, - }); - const { state } = await runAction(setPractitionerOnFormAction, { modules: { presenter }, + state: { + user: { role: USER_ROLES.docketClerk }, + }, }); expect(state.form).toBeUndefined(); }); it('should set state.form.practitioner to the logged in user when the user is a privatePractitioner', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: USER_ROLES.privatePractitioner, - }); - const { state } = await runAction(setPractitionerOnFormAction, { modules: { presenter }, + state: { + user: { role: USER_ROLES.privatePractitioner }, + }, }); expect(state.form.practitioner).toEqual([ diff --git a/web-client/src/presenter/actions/FileDocument/setPractitionerOnFormAction.ts b/web-client/src/presenter/actions/FileDocument/setPractitionerOnFormAction.ts index d827b8b8feb..61d297597a1 100644 --- a/web-client/src/presenter/actions/FileDocument/setPractitionerOnFormAction.ts +++ b/web-client/src/presenter/actions/FileDocument/setPractitionerOnFormAction.ts @@ -10,9 +10,10 @@ import { state } from '@web-client/presenter/app.cerebral'; */ export const setPractitionerOnFormAction = ({ applicationContext, + get, store, }: ActionProps) => { - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); if (user.role === USER_ROLES.privatePractitioner) { diff --git a/web-client/src/presenter/actions/FileDocument/submitCaseAssociationRequestAction.test.ts b/web-client/src/presenter/actions/FileDocument/submitCaseAssociationRequestAction.test.ts index c8b5d50c4d4..5513e92d207 100644 --- a/web-client/src/presenter/actions/FileDocument/submitCaseAssociationRequestAction.test.ts +++ b/web-client/src/presenter/actions/FileDocument/submitCaseAssociationRequestAction.test.ts @@ -8,8 +8,6 @@ import { submitCaseAssociationRequestAction } from './submitCaseAssociationReque describe('submitCaseAssociationRequestAction', () => { presenter.providers.applicationContext = applicationContext; - applicationContext.getCurrentUser.mockReturnValue(privatePractitionerUser); - it("should call submitCaseAssociationRequestInteractor when the document's event code allows for the user to be immediately associated with the case", async () => { const eventCodeAllowingImmediateAssociation = PRACTITIONER_ASSOCIATION_DOCUMENT_TYPES_MAP.filter( @@ -29,6 +27,7 @@ describe('submitCaseAssociationRequestAction', () => { eventCode: eventCodeAllowingImmediateAssociation, primaryDocumentFile: {}, }, + user: privatePractitionerUser, }, }); @@ -56,6 +55,7 @@ describe('submitCaseAssociationRequestAction', () => { eventCode: eventCodeNotAllowingImmediateAssociation, primaryDocumentFile: {}, }, + user: privatePractitionerUser, }, }); @@ -78,6 +78,7 @@ describe('submitCaseAssociationRequestAction', () => { form: { primaryDocumentFile: {}, }, + user: privatePractitionerUser, }, }); diff --git a/web-client/src/presenter/actions/FileDocument/submitCaseAssociationRequestAction.ts b/web-client/src/presenter/actions/FileDocument/submitCaseAssociationRequestAction.ts index 2556fd06a7f..2b0e1b65362 100644 --- a/web-client/src/presenter/actions/FileDocument/submitCaseAssociationRequestAction.ts +++ b/web-client/src/presenter/actions/FileDocument/submitCaseAssociationRequestAction.ts @@ -16,7 +16,7 @@ export const submitCaseAssociationRequestAction = async ({ const { PRACTITIONER_ASSOCIATION_DOCUMENT_TYPES_MAP } = applicationContext.getConstants(); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { primaryDocumentId } = props.documentsFiled; @@ -55,12 +55,14 @@ export const submitCaseAssociationRequestAction = async ({ .submitCaseAssociationRequestInteractor(applicationContext, { docketNumber, filers: documentMetadata.filers, + userId: user.userId, }); } else if (isDocumentWithPendingAssociation) { await applicationContext .getUseCases() .submitPendingCaseAssociationRequestInteractor(applicationContext, { docketNumber, + userId: user.userId, }); } diff --git a/web-client/src/presenter/actions/FileDocument/submitRespondentCaseAssociationRequestAction.test.ts b/web-client/src/presenter/actions/FileDocument/submitRespondentCaseAssociationRequestAction.test.ts index c85d8bcfb88..44c4b773b89 100644 --- a/web-client/src/presenter/actions/FileDocument/submitRespondentCaseAssociationRequestAction.test.ts +++ b/web-client/src/presenter/actions/FileDocument/submitRespondentCaseAssociationRequestAction.test.ts @@ -9,14 +9,13 @@ describe('submitRespondentCaseAssociationRequestAction', () => { presenter.providers.applicationContext = applicationContext; it('should not call submitCaseAssociationRequestInteractor when the logged in user is not an IRS practitioner', async () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - await runAction(submitRespondentCaseAssociationRequestAction, { modules: { presenter }, state: { caseDetail: { docketNumber: MOCK_CASE.docketNumber, }, + user: docketClerkUser, }, }); @@ -26,14 +25,13 @@ describe('submitRespondentCaseAssociationRequestAction', () => { }); it('should call submitCaseAssociationRequestInteractor when the logged in user is an IRS practitioner', async () => { - applicationContext.getCurrentUser.mockReturnValue(irsPractitionerUser); - await runAction(submitRespondentCaseAssociationRequestAction, { modules: { presenter }, state: { caseDetail: { docketNumber: MOCK_CASE.docketNumber, }, + user: irsPractitionerUser, }, }); @@ -46,7 +44,6 @@ describe('submitRespondentCaseAssociationRequestAction', () => { }); it('should return the updated case as props', async () => { - applicationContext.getCurrentUser.mockReturnValue(irsPractitionerUser); applicationContext .getUseCases() .submitCaseAssociationRequestInteractor.mockResolvedValue(MOCK_CASE); @@ -59,6 +56,7 @@ describe('submitRespondentCaseAssociationRequestAction', () => { caseDetail: { docketNumber: MOCK_CASE.docketNumber, }, + user: irsPractitionerUser, }, }, ); diff --git a/web-client/src/presenter/actions/FileDocument/submitRespondentCaseAssociationRequestAction.ts b/web-client/src/presenter/actions/FileDocument/submitRespondentCaseAssociationRequestAction.ts index d645796bdb6..26ffd61b09e 100644 --- a/web-client/src/presenter/actions/FileDocument/submitRespondentCaseAssociationRequestAction.ts +++ b/web-client/src/presenter/actions/FileDocument/submitRespondentCaseAssociationRequestAction.ts @@ -13,7 +13,7 @@ export const submitRespondentCaseAssociationRequestAction = async ({ }: ActionProps) => { const { docketNumber } = get(state.caseDetail); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); @@ -22,6 +22,7 @@ export const submitRespondentCaseAssociationRequestAction = async ({ .getUseCases() .submitCaseAssociationRequestInteractor(applicationContext, { docketNumber, + userId: user.userId, }); } }; diff --git a/web-client/src/presenter/actions/FileDocument/uploadExternalDocumentsAction.ts b/web-client/src/presenter/actions/FileDocument/uploadExternalDocumentsAction.ts index cdc6519f88b..1fcc705c74a 100644 --- a/web-client/src/presenter/actions/FileDocument/uploadExternalDocumentsAction.ts +++ b/web-client/src/presenter/actions/FileDocument/uploadExternalDocumentsAction.ts @@ -22,15 +22,20 @@ export const uploadExternalDocumentsAction = async ({ }>) => { const { documentMetadata, files, fileUploadProgressMap } = props; const { docketNumber } = get(state.caseDetail); + const user = get(state.user); try { const { caseDetail, docketEntryIdsAdded } = await applicationContext .getUseCases() - .uploadExternalDocumentsInteractor(applicationContext, { - documentFiles: files, - documentMetadata, - fileUploadProgressMap, - }); + .uploadExternalDocumentsInteractor( + applicationContext, + { + documentFiles: files, + documentMetadata, + fileUploadProgressMap, + }, + user, + ); for (let docketEntryId of docketEntryIdsAdded) { await addCoversheet({ diff --git a/web-client/src/presenter/actions/FileDocument/uploadOrderFileAction.ts b/web-client/src/presenter/actions/FileDocument/uploadOrderFileAction.ts index 63f5df0d220..ce35b7a9d33 100644 --- a/web-client/src/presenter/actions/FileDocument/uploadOrderFileAction.ts +++ b/web-client/src/presenter/actions/FileDocument/uploadOrderFileAction.ts @@ -12,13 +12,18 @@ export const uploadOrderFileAction = async ({ path, }: ActionProps) => { const { primaryDocumentFile } = get(state.form); + const user = get(state.user); try { const primaryDocumentFileId = await applicationContext .getUseCases() - .uploadOrderDocumentInteractor(applicationContext, { - documentFile: primaryDocumentFile, - }); + .uploadOrderDocumentInteractor( + applicationContext, + { + documentFile: primaryDocumentFile, + }, + user, + ); return path.success({ primaryDocumentFileId, diff --git a/web-client/src/presenter/actions/JudgeActivityReport/setDefaultJudgeNameBasedOnUserAction.test.ts b/web-client/src/presenter/actions/JudgeActivityReport/setDefaultJudgeNameBasedOnUserAction.test.ts index f56f1941861..1679328836c 100644 --- a/web-client/src/presenter/actions/JudgeActivityReport/setDefaultJudgeNameBasedOnUserAction.test.ts +++ b/web-client/src/presenter/actions/JudgeActivityReport/setDefaultJudgeNameBasedOnUserAction.test.ts @@ -8,8 +8,6 @@ describe('setDefaultJudgeNameBasedOnUserAction', () => { presenter.providers.applicationContext = applicationContext; it('should set state.judgeActivityReport.filters.judgeName to the last name of the current user', async () => { - applicationContext.getCurrentUser.mockReturnValue(judgeUser); - const { state } = await runAction(setDefaultJudgeNameBasedOnUserAction, { modules: { presenter, diff --git a/web-client/src/presenter/actions/Login/setTokenAction.test.ts b/web-client/src/presenter/actions/Login/setTokenAction.test.ts index 63c648dccb0..86ff8da3019 100644 --- a/web-client/src/presenter/actions/Login/setTokenAction.test.ts +++ b/web-client/src/presenter/actions/Login/setTokenAction.test.ts @@ -1,4 +1,5 @@ import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; +import { getCurrentUserToken } from '@shared/proxies/requests'; import { presenter } from '../../presenter-mock'; import { runAction } from '@web-client/presenter/test.cerebral'; import { setTokenAction } from './setTokenAction'; @@ -24,7 +25,7 @@ describe('setTokenAction,', () => { expect(state.token).toEqual(mockToken); }); - it('should call applicationContext.setCurrentUserToken with props.token', async () => { + it('should setCurrentUserToken with props.token', async () => { await runAction(setTokenAction, { modules: { presenter, @@ -35,8 +36,6 @@ describe('setTokenAction,', () => { state: {}, }); - expect(applicationContext.setCurrentUserToken.mock.calls[0][0]).toEqual( - mockToken, - ); + expect(getCurrentUserToken()).toEqual(mockToken); }); }); diff --git a/web-client/src/presenter/actions/Login/setTokenAction.ts b/web-client/src/presenter/actions/Login/setTokenAction.ts index 476dfce4d52..69c23c7491c 100644 --- a/web-client/src/presenter/actions/Login/setTokenAction.ts +++ b/web-client/src/presenter/actions/Login/setTokenAction.ts @@ -1,11 +1,11 @@ +import { setCurrentUserToken } from '@shared/proxies/requests'; import { state } from '@web-client/presenter/app.cerebral'; export const setTokenAction = ({ - applicationContext, props, store, }: ActionProps<{ idToken: string }>): void => { store.set(state.token, props.idToken); - applicationContext.setCurrentUserToken(props.idToken); + setCurrentUserToken(props.idToken); }; diff --git a/web-client/src/presenter/actions/TrialSession/canSetTrialSessionToCalendarAction.ts b/web-client/src/presenter/actions/TrialSession/canSetTrialSessionToCalendarAction.ts index b9c66ee6a2e..a9b80fe216c 100644 --- a/web-client/src/presenter/actions/TrialSession/canSetTrialSessionToCalendarAction.ts +++ b/web-client/src/presenter/actions/TrialSession/canSetTrialSessionToCalendarAction.ts @@ -14,9 +14,10 @@ export const canSetTrialSessionToCalendarAction = ({ path, }: ActionProps) => { const trialSession = get(state.trialSession); + const user = get(state.user); const { canSetAsCalendared, emptyFields, isRemote } = applicationContext .getUseCases() - .canSetTrialSessionAsCalendaredInteractor(applicationContext, { + .canSetTrialSessionAsCalendaredInteractor(user, { trialSession, }); diff --git a/web-client/src/presenter/actions/TrialSession/getTrialSessionsForJudgeAction.test.ts b/web-client/src/presenter/actions/TrialSession/getTrialSessionsForJudgeAction.test.ts index 3f2857b26ee..7bf6485a435 100644 --- a/web-client/src/presenter/actions/TrialSession/getTrialSessionsForJudgeAction.test.ts +++ b/web-client/src/presenter/actions/TrialSession/getTrialSessionsForJudgeAction.test.ts @@ -9,10 +9,6 @@ describe('getTrialSessionsForJudgeAction', () => { }); it('should invoke the interactor with the expected judge id when calling this action as a judge user', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: 'judge', - userId: '123', - }); applicationContext .getUseCases() .getTrialSessionsForJudgeInteractor.mockResolvedValue([ @@ -26,7 +22,7 @@ describe('getTrialSessionsForJudgeAction', () => { presenter, }, props: {}, - state: {}, + state: { user: { role: 'judge', userId: '123' } }, }); expect( @@ -36,9 +32,6 @@ describe('getTrialSessionsForJudgeAction', () => { }); it('should invoke the interactor with the expected judge id when calling this action as a chambers user', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: 'chambers', - }); applicationContext .getUseCases() .getTrialSessionsForJudgeInteractor.mockResolvedValue([ @@ -57,6 +50,9 @@ describe('getTrialSessionsForJudgeAction', () => { role: 'judge', userId: '123', }, + user: { + role: 'chambers', + }, }, }); diff --git a/web-client/src/presenter/actions/TrialSession/getTrialSessionsForJudgeAction.ts b/web-client/src/presenter/actions/TrialSession/getTrialSessionsForJudgeAction.ts index e654d6022f6..e9cea73bb23 100644 --- a/web-client/src/presenter/actions/TrialSession/getTrialSessionsForJudgeAction.ts +++ b/web-client/src/presenter/actions/TrialSession/getTrialSessionsForJudgeAction.ts @@ -10,7 +10,7 @@ export const getTrialSessionsForJudgeAction = async ({ applicationContext, get, }: ActionProps) => { - const { role, userId } = applicationContext.getCurrentUser(); + const { role, userId } = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); const chambersJudgeUser = get(state.judgeUser); const isChambersUser = role === USER_ROLES.chambers; diff --git a/web-client/src/presenter/actions/TrialSession/isUserAssociatedWithTrialSessionAction.test.ts b/web-client/src/presenter/actions/TrialSession/isUserAssociatedWithTrialSessionAction.test.ts index 8ba282b7062..34470fa0c9b 100644 --- a/web-client/src/presenter/actions/TrialSession/isUserAssociatedWithTrialSessionAction.test.ts +++ b/web-client/src/presenter/actions/TrialSession/isUserAssociatedWithTrialSessionAction.test.ts @@ -21,10 +21,6 @@ describe('isUserAssociatedWithTrialSessionAction', () => { }); it('should return path.yes() if the judge is associated with the trial session', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: USER_ROLES.judge, - userId: '123', - }); await runAction(isUserAssociatedWithTrialSessionAction, { modules: { presenter, @@ -33,6 +29,10 @@ describe('isUserAssociatedWithTrialSessionAction', () => { trialSession: { judge: { userId: '123' }, }, + user: { + role: USER_ROLES.judge, + userId: '123', + }, }, }); @@ -40,10 +40,6 @@ describe('isUserAssociatedWithTrialSessionAction', () => { }); it('should return path.no() if the judge is not associated with the trial session', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: USER_ROLES.judge, - userId: '234', - }); await runAction(isUserAssociatedWithTrialSessionAction, { modules: { presenter, @@ -52,6 +48,10 @@ describe('isUserAssociatedWithTrialSessionAction', () => { trialSession: { judge: { userId: '123' }, }, + user: { + role: USER_ROLES.judge, + userId: '234', + }, }, }); @@ -59,10 +59,6 @@ describe('isUserAssociatedWithTrialSessionAction', () => { }); it('should return path.no() if the user is in the chambers section and their judge is not associated with the trial session', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: USER_ROLES.chambers, - userId: '234', - }); await runAction(isUserAssociatedWithTrialSessionAction, { modules: { presenter, @@ -71,6 +67,10 @@ describe('isUserAssociatedWithTrialSessionAction', () => { trialSession: { judge: { userId: '123' }, }, + user: { + role: USER_ROLES.chambers, + userId: '234', + }, users: [{ role: USER_ROLES.judge, userId: '456' }], }, }); @@ -79,10 +79,6 @@ describe('isUserAssociatedWithTrialSessionAction', () => { }); it('should return path.yes() if the user is in the chambers section and their judge is associated with the trial session', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: USER_ROLES.chambers, - userId: '234', - }); await runAction(isUserAssociatedWithTrialSessionAction, { modules: { presenter, @@ -91,6 +87,11 @@ describe('isUserAssociatedWithTrialSessionAction', () => { trialSession: { judge: { userId: '123' }, }, + + user: { + role: USER_ROLES.chambers, + userId: '234', + }, users: [{ role: USER_ROLES.judge, userId: '123' }], }, }); @@ -99,10 +100,6 @@ describe('isUserAssociatedWithTrialSessionAction', () => { }); it('should return path.yes() if the current user is a trial clerk for this trial session', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: USER_ROLES.trialClerk, - userId: '123', - }); await runAction(isUserAssociatedWithTrialSessionAction, { modules: { presenter, @@ -111,6 +108,10 @@ describe('isUserAssociatedWithTrialSessionAction', () => { trialSession: { trialClerk: { userId: '123' }, }, + user: { + role: USER_ROLES.trialClerk, + userId: '123', + }, }, }); @@ -118,10 +119,6 @@ describe('isUserAssociatedWithTrialSessionAction', () => { }); it('should return path.no() if the current user is a trial clerk but is NOT the trial clerk for this trial session', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: USER_ROLES.trialClerk, - userId: '234', - }); await runAction(isUserAssociatedWithTrialSessionAction, { modules: { presenter, @@ -130,6 +127,10 @@ describe('isUserAssociatedWithTrialSessionAction', () => { trialSession: { trialClerk: { userId: '123' }, }, + user: { + role: USER_ROLES.trialClerk, + userId: '234', + }, }, }); diff --git a/web-client/src/presenter/actions/TrialSession/isUserAssociatedWithTrialSessionAction.ts b/web-client/src/presenter/actions/TrialSession/isUserAssociatedWithTrialSessionAction.ts index 32f472dfd8f..ec50840f8a8 100644 --- a/web-client/src/presenter/actions/TrialSession/isUserAssociatedWithTrialSessionAction.ts +++ b/web-client/src/presenter/actions/TrialSession/isUserAssociatedWithTrialSessionAction.ts @@ -14,7 +14,7 @@ export const isUserAssociatedWithTrialSessionAction = ({ path, }: ActionProps) => { const trialSession = get(state.trialSession); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); if (user.role === USER_ROLES.judge) { diff --git a/web-client/src/presenter/actions/TrialSessionWorkingCopy/prepareUserBasedHeadingAction.test.ts b/web-client/src/presenter/actions/TrialSessionWorkingCopy/prepareUserBasedHeadingAction.test.ts index 04947635f58..5f1d303ce1a 100644 --- a/web-client/src/presenter/actions/TrialSessionWorkingCopy/prepareUserBasedHeadingAction.test.ts +++ b/web-client/src/presenter/actions/TrialSessionWorkingCopy/prepareUserBasedHeadingAction.test.ts @@ -8,7 +8,6 @@ describe('prepareUserBasedHeadingAction', () => { let user; const { USER_ROLES } = applicationContext.getConstants(); - applicationContext.getCurrentUser = () => user; it.each([ [USER_ROLES.trialClerk, 'Test User - Session Copy'], @@ -26,6 +25,7 @@ describe('prepareUserBasedHeadingAction', () => { formattedTrialSessionDetails: { formattedJudge: 'Buch', }, + user, }, }); expect(result.output).toEqual({ userHeading: expected }); diff --git a/web-client/src/presenter/actions/TrialSessionWorkingCopy/prepareUserBasedHeadingAction.ts b/web-client/src/presenter/actions/TrialSessionWorkingCopy/prepareUserBasedHeadingAction.ts index b45802f20ea..f9442b36f55 100644 --- a/web-client/src/presenter/actions/TrialSessionWorkingCopy/prepareUserBasedHeadingAction.ts +++ b/web-client/src/presenter/actions/TrialSessionWorkingCopy/prepareUserBasedHeadingAction.ts @@ -11,7 +11,7 @@ export const prepareUserBasedHeadingAction = ({ applicationContext, get, }: ActionProps) => { - const currentUser = applicationContext.getCurrentUser(); + const currentUser = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); const userRole = currentUser.role; const formattedTrialSessionDetails = get(state.formattedTrialSessionDetails); diff --git a/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditSessionNoteModalStateAction.test.ts b/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditSessionNoteModalStateAction.test.ts index 89c50b44663..fb7c0b83f06 100644 --- a/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditSessionNoteModalStateAction.test.ts +++ b/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditSessionNoteModalStateAction.test.ts @@ -8,7 +8,6 @@ describe('setAddEditSessionNoteModalStateAction', () => { let user; const { USER_ROLES } = applicationContext.getConstants(); - applicationContext.getCurrentUser = () => user; it('should set the modal state', async () => { user = { role: USER_ROLES.judge }; @@ -24,6 +23,7 @@ describe('setAddEditSessionNoteModalStateAction', () => { trialSessionWorkingCopy: { sessionNotes: 'i got some notes', }, + user, }, }); @@ -46,6 +46,7 @@ describe('setAddEditSessionNoteModalStateAction', () => { trialSessionWorkingCopy: { sessionNotes: 'i got some notes', }, + user, }, }); diff --git a/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditSessionNoteModalStateAction.ts b/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditSessionNoteModalStateAction.ts index 9a9d4991f92..e1735d868b7 100644 --- a/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditSessionNoteModalStateAction.ts +++ b/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditSessionNoteModalStateAction.ts @@ -13,7 +13,7 @@ export const setAddEditSessionNoteModalStateAction = ({ get, store, }: ActionProps) => { - const currentUser = applicationContext.getCurrentUser(); + const currentUser = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); const notes = get(state.trialSessionWorkingCopy.sessionNotes); const trialSessionDetail = get(state.trialSession); diff --git a/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditUserCaseNoteModalStateFromDetailAction.test.ts b/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditUserCaseNoteModalStateFromDetailAction.test.ts index 2b0eed45bba..5644ec1430c 100644 --- a/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditUserCaseNoteModalStateFromDetailAction.test.ts +++ b/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditUserCaseNoteModalStateFromDetailAction.test.ts @@ -8,7 +8,6 @@ describe('setAddEditUserCaseNoteModalStateFromDetailAction', () => { let user; const { USER_ROLES } = applicationContext.getConstants(); - applicationContext.getCurrentUser = () => user; it('should set the modal state from caseDetail and props', async () => { user = { role: USER_ROLES.judge }; @@ -26,6 +25,7 @@ describe('setAddEditUserCaseNoteModalStateFromDetailAction', () => { docketNumberWithSuffix: '101-19L', }, judgesNote: { notes: 'i got some notes' }, + user, }, }, ); @@ -55,6 +55,7 @@ describe('setAddEditUserCaseNoteModalStateFromDetailAction', () => { docketNumberWithSuffix: '101-19', }, judgesNote: { notes: 'i got some notes' }, + user, }, }, ); diff --git a/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditUserCaseNoteModalStateFromDetailAction.ts b/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditUserCaseNoteModalStateFromDetailAction.ts index 2da6e915279..3ef4bdfca7f 100644 --- a/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditUserCaseNoteModalStateFromDetailAction.ts +++ b/web-client/src/presenter/actions/TrialSessionWorkingCopy/setAddEditUserCaseNoteModalStateFromDetailAction.ts @@ -12,7 +12,7 @@ export const setAddEditUserCaseNoteModalStateFromDetailAction = ({ get, store, }: ActionProps) => { - const currentUser = applicationContext.getCurrentUser(); + const currentUser = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); const { caseCaption, docketNumber, docketNumberWithSuffix } = get( diff --git a/web-client/src/presenter/actions/WorkItem/assignPetitionToAuthenticatedUserAction.test.ts b/web-client/src/presenter/actions/WorkItem/assignPetitionToAuthenticatedUserAction.test.ts index 0f16b51fee3..90d18800db0 100644 --- a/web-client/src/presenter/actions/WorkItem/assignPetitionToAuthenticatedUserAction.test.ts +++ b/web-client/src/presenter/actions/WorkItem/assignPetitionToAuthenticatedUserAction.test.ts @@ -7,13 +7,13 @@ describe('assignPetitionToAuthenticatedUserAction', () => { const { INITIAL_DOCUMENT_TYPES } = applicationContext.getConstants(); const { assignWorkItemsInteractor } = applicationContext.getUseCases(); + const user = { + name: 'Some One', + userId: 'abc', + }; + beforeAll(() => { presenter.providers.applicationContext = applicationContext; - - applicationContext.getCurrentUser.mockReturnValue({ - name: 'Some One', - userId: 'abc', - }); }); it('should not assign the workitem if the qc work item is not present', async () => { @@ -25,6 +25,7 @@ describe('assignPetitionToAuthenticatedUserAction', () => { caseDetail: { docketEntries: [], }, + user, }, }); @@ -45,6 +46,7 @@ describe('assignPetitionToAuthenticatedUserAction', () => { }, ], }, + user, }, }); diff --git a/web-client/src/presenter/actions/WorkItem/assignPetitionToAuthenticatedUserAction.ts b/web-client/src/presenter/actions/WorkItem/assignPetitionToAuthenticatedUserAction.ts index d45683fb4e6..9fa26148359 100644 --- a/web-client/src/presenter/actions/WorkItem/assignPetitionToAuthenticatedUserAction.ts +++ b/web-client/src/presenter/actions/WorkItem/assignPetitionToAuthenticatedUserAction.ts @@ -13,7 +13,7 @@ export const assignPetitionToAuthenticatedUserAction = async ({ }: ActionProps) => { const { INITIAL_DOCUMENT_TYPES } = applicationContext.getConstants(); const { docketEntries } = get(state.caseDetail); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const petitionDocument = docketEntries.find( document => diff --git a/web-client/src/presenter/actions/clearUserAction.test.ts b/web-client/src/presenter/actions/clearUserAction.test.ts index be2bb3ce77f..de47bec4434 100644 --- a/web-client/src/presenter/actions/clearUserAction.test.ts +++ b/web-client/src/presenter/actions/clearUserAction.test.ts @@ -1,12 +1,13 @@ import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { clearUserAction } from './clearUserAction'; +import { emptyUserState } from '@web-client/presenter/state/userState'; import { presenter } from '../presenter-mock'; import { runAction } from '@web-client/presenter/test.cerebral'; describe('clearUserAction', () => { presenter.providers.applicationContext = applicationContext; - it('should unset state.user, state.token, and state.permissions', async () => { + it('should unset state.token and state.permissions and reset state.user', async () => { const result = await runAction(clearUserAction, { modules: { presenter, @@ -18,7 +19,7 @@ describe('clearUserAction', () => { }, }); - expect(result.state.user).toBeUndefined(); + expect(result.state.user).toEqual(emptyUserState); expect(result.state.token).toBeUndefined(); expect(result.state.permissions).toBeUndefined(); }); @@ -43,15 +44,4 @@ describe('clearUserAction', () => { .key, ).toBe('token'); }); - - it('should make a call to set currentUser to null', async () => { - await runAction(clearUserAction, { - modules: { - presenter, - }, - state: {}, - }); - - expect(applicationContext.setCurrentUser).toHaveBeenCalled(); - }); }); diff --git a/web-client/src/presenter/actions/clearUserAction.ts b/web-client/src/presenter/actions/clearUserAction.ts index 852fe0bd23b..17df53387a3 100644 --- a/web-client/src/presenter/actions/clearUserAction.ts +++ b/web-client/src/presenter/actions/clearUserAction.ts @@ -1,10 +1,13 @@ +import { cloneDeep } from 'lodash'; +import { emptyUserState } from '@web-client/presenter/state/userState'; +import { setCurrentUserToken } from '@shared/proxies/requests'; import { state } from '@web-client/presenter/app.cerebral'; export const clearUserAction = async ({ applicationContext, store, }: ActionProps) => { - store.unset(state.user); + store.set(state.user, cloneDeep(emptyUserState)); store.unset(state.token); store.unset(state.permissions); @@ -19,6 +22,5 @@ export const clearUserAction = async ({ key: 'token', }); - applicationContext.setCurrentUser(null); - applicationContext.setCurrentUserToken(null); + setCurrentUserToken(''); }; diff --git a/web-client/src/presenter/actions/completeDocumentSigningAction.test.ts b/web-client/src/presenter/actions/completeDocumentSigningAction.test.ts index 6e48972f47d..1670a225773 100644 --- a/web-client/src/presenter/actions/completeDocumentSigningAction.test.ts +++ b/web-client/src/presenter/actions/completeDocumentSigningAction.test.ts @@ -57,10 +57,6 @@ describe('completeDocumentSigningAction', () => { }, }; - applicationContext.getCurrentUser.mockReturnValue({ - userId: '15adf875-8c3c-4e94-91e9-a4c1bff51291', - }); - mockPdfjsObj = { getData: jest.fn().mockResolvedValue(true), }; diff --git a/web-client/src/presenter/actions/completeMotionStampingAction.test.ts b/web-client/src/presenter/actions/completeMotionStampingAction.test.ts index e5307b6f071..87678c7b188 100644 --- a/web-client/src/presenter/actions/completeMotionStampingAction.test.ts +++ b/web-client/src/presenter/actions/completeMotionStampingAction.test.ts @@ -57,10 +57,6 @@ describe('completeMotionStampingAction', () => { }, }; - applicationContext.getCurrentUser.mockReturnValue({ - userId: '15adf875-8c3c-4e94-91e9-a4c1bff51291', - }); - global.File = jest.fn(); uploadDocumentFromClient.mockReturnValue( diff --git a/web-client/src/presenter/actions/completeWorkItemForDocumentSigningAction.ts b/web-client/src/presenter/actions/completeWorkItemForDocumentSigningAction.ts index 2f3d6c9a480..ed8bb25d6e4 100644 --- a/web-client/src/presenter/actions/completeWorkItemForDocumentSigningAction.ts +++ b/web-client/src/presenter/actions/completeWorkItemForDocumentSigningAction.ts @@ -23,7 +23,6 @@ export const completeWorkItemForDocumentSigningAction = async ({ await applicationContext .getUseCases() .completeWorkItemInteractor(applicationContext, { - userId: applicationContext.getCurrentUser().userId, workItemId: workItemIdToClose, }); } diff --git a/web-client/src/presenter/actions/countryTypeUserContactChangeAction.ts b/web-client/src/presenter/actions/countryTypeUserContactChangeAction.ts index 63541d8d72f..aedd3e29e2d 100644 --- a/web-client/src/presenter/actions/countryTypeUserContactChangeAction.ts +++ b/web-client/src/presenter/actions/countryTypeUserContactChangeAction.ts @@ -16,7 +16,7 @@ export const countryTypeUserContactChangeAction = ({ store }: ActionProps) => { 'state', 'city', ].forEach(field => { - store.unset(state.user.contact[field]); + store.unset((state.user as any).contact[field]); }); store.set(state.validationErrors.contact, {}); diff --git a/web-client/src/presenter/actions/createCaseAction.test.ts b/web-client/src/presenter/actions/createCaseAction.test.ts index 15ae2e5d018..05947c3121a 100644 --- a/web-client/src/presenter/actions/createCaseAction.test.ts +++ b/web-client/src/presenter/actions/createCaseAction.test.ts @@ -48,9 +48,6 @@ describe('createCaseAction', () => { petitionFileId: '123', stinFileId: '123', }); - applicationContext.getCurrentUser.mockReturnValue({ - email: 'petitioner1@example.com', - }); }); it('should call createCaseInteractor and addCoversheetInteractor FOUR times when there is a CDS form, and then call the success path', async () => { @@ -81,19 +78,26 @@ describe('createCaseAction', () => { await runAction(createCaseAction, { modules: { presenter }, props: { fileUploadProgressMap }, - state: { form: mockPetitionMetadata }, + state: { + form: mockPetitionMetadata, + user: { email: 'petitioner1@example.com' }, + }, }); expect(generateDocumentIds).toHaveBeenCalled(); - expect(generateDocumentIds).toHaveBeenCalledWith(expect.anything(), { - attachmentToPetitionUploadProgress: [ - fileUploadProgressMap.attachmentToPetition, - ], - corporateDisclosureUploadProgress: - fileUploadProgressMap.corporateDisclosure, - petitionUploadProgress: fileUploadProgressMap.petition, - stinUploadProgress: fileUploadProgressMap.stin, - }); + expect(generateDocumentIds).toHaveBeenCalledWith( + expect.anything(), + { + attachmentToPetitionUploadProgress: [ + fileUploadProgressMap.attachmentToPetition, + ], + corporateDisclosureUploadProgress: + fileUploadProgressMap.corporateDisclosure, + petitionUploadProgress: fileUploadProgressMap.petition, + stinUploadProgress: fileUploadProgressMap.stin, + }, + { email: 'petitioner1@example.com' }, + ); expect(createCaseInteractor).toHaveBeenCalled(); @@ -127,16 +131,23 @@ describe('createCaseAction', () => { attachmentToPetition: undefined, }, }, - state: { form: mockPetitionMetadata }, + state: { + form: mockPetitionMetadata, + user: { email: 'petitioner1@example.com' }, + }, }); expect(generateDocumentIds).toHaveBeenCalled(); - expect(generateDocumentIds).toHaveBeenCalledWith(expect.anything(), { - corporateDisclosureUploadProgress: - fileUploadProgressMap.corporateDisclosure, - petitionUploadProgress: fileUploadProgressMap.petition, - stinUploadProgress: fileUploadProgressMap.stin, - }); + expect(generateDocumentIds).toHaveBeenCalledWith( + expect.anything(), + { + corporateDisclosureUploadProgress: + fileUploadProgressMap.corporateDisclosure, + petitionUploadProgress: fileUploadProgressMap.petition, + stinUploadProgress: fileUploadProgressMap.stin, + }, + { email: 'petitioner1@example.com' }, + ); expect(createCaseInteractor).toHaveBeenCalled(); expect(createCaseInteractor).toHaveBeenCalledWith(expect.anything(), { diff --git a/web-client/src/presenter/actions/createCaseAction.ts b/web-client/src/presenter/actions/createCaseAction.ts index 74d7eccebe2..80d0404fbf8 100644 --- a/web-client/src/presenter/actions/createCaseAction.ts +++ b/web-client/src/presenter/actions/createCaseAction.ts @@ -20,7 +20,7 @@ export const createCaseAction = async ({ const form: ElectronicCreatedCaseType = omit(petitionMetadata, 'trialCities'); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); form.contactPrimary.email = user.email; let caseDetail; @@ -39,9 +39,9 @@ export const createCaseAction = async ({ corporateDisclosureFileId, petitionFileId, stinFileId, - } = await applicationContext - .getUseCases() - .generateDocumentIds(applicationContext, { + } = await applicationContext.getUseCases().generateDocumentIds( + applicationContext, + { attachmentToPetitionUploadProgress, corporateDisclosureUploadProgress: fileUploadProgressMap.corporateDisclosure as FileUploadProgressType, @@ -49,7 +49,9 @@ export const createCaseAction = async ({ fileUploadProgressMap.petition as FileUploadProgressType, stinUploadProgress: fileUploadProgressMap.stin as FileUploadProgressType, - }); + }, + user, + ); stinFile = stinFileId; diff --git a/web-client/src/presenter/actions/createCaseFromPaperAction.test.ts b/web-client/src/presenter/actions/createCaseFromPaperAction.test.ts index 6f7e2e18b3e..32efbe49246 100644 --- a/web-client/src/presenter/actions/createCaseFromPaperAction.test.ts +++ b/web-client/src/presenter/actions/createCaseFromPaperAction.test.ts @@ -54,9 +54,6 @@ describe('createCaseFromPaperAction', () => { requestForPlaceOfTrialFileId: '123', stinFileId: '123', }); - applicationContext.getCurrentUser.mockReturnValue({ - email: 'petitioner1@example.com', - }); }); it('should generate document ids for files selected, then call createCaseFromPaperInteractor with the petition metadata and ids and call the success path when finished', async () => { diff --git a/web-client/src/presenter/actions/createCaseFromPaperAction.ts b/web-client/src/presenter/actions/createCaseFromPaperAction.ts index 4d85ee009af..4ddb14b34fa 100644 --- a/web-client/src/presenter/actions/createCaseFromPaperAction.ts +++ b/web-client/src/presenter/actions/createCaseFromPaperAction.ts @@ -12,6 +12,7 @@ export const createCaseFromPaperAction = async ({ }: ActionProps<{ fileUploadProgressMap: Record; }>) => { + const user = get(state.user); const petitionMetadata: CreatedCaseType = get(state.form); const { fileUploadProgressMap } = props; let caseDetail: RawCase; @@ -31,9 +32,9 @@ export const createCaseFromPaperAction = async ({ petitionFileId, requestForPlaceOfTrialFileId, stinFileId, - } = await applicationContext - .getUseCases() - .generateDocumentIds(applicationContext, { + } = await applicationContext.getUseCases().generateDocumentIds( + applicationContext, + { applicationForWaiverOfFilingFeeUploadProgress: fileUploadProgressMap.applicationForWaiverOfFilingFee, attachmentToPetitionUploadProgress, @@ -43,7 +44,9 @@ export const createCaseFromPaperAction = async ({ requestForPlaceOfTrialUploadProgress: fileUploadProgressMap.requestForPlaceOfTrial, stinUploadProgress: fileUploadProgressMap.stin, - }); + }, + user, + ); caseDetail = await applicationContext .getUseCases() diff --git a/web-client/src/presenter/actions/createPractitionerDocumentAction.ts b/web-client/src/presenter/actions/createPractitionerDocumentAction.ts index a717950ce48..07115ddb7d7 100644 --- a/web-client/src/presenter/actions/createPractitionerDocumentAction.ts +++ b/web-client/src/presenter/actions/createPractitionerDocumentAction.ts @@ -13,12 +13,17 @@ export const createPractitionerDocumentAction = async ({ }: ActionProps) => { const { practitionerDocumentFile, ...form } = get(state.form); const { barNumber } = get(state.practitionerDetail); + const user = get(state.user); const practitionerDocumentFileId = await applicationContext .getUseCases() - .uploadOrderDocumentInteractor(applicationContext, { - documentFile: practitionerDocumentFile, - }); + .uploadOrderDocumentInteractor( + applicationContext, + { + documentFile: practitionerDocumentFile, + }, + user, + ); await applicationContext .getUseCases() diff --git a/web-client/src/presenter/actions/editPractitionerDocumentAction.ts b/web-client/src/presenter/actions/editPractitionerDocumentAction.ts index c75d2148112..1d1413c3c3d 100644 --- a/web-client/src/presenter/actions/editPractitionerDocumentAction.ts +++ b/web-client/src/presenter/actions/editPractitionerDocumentAction.ts @@ -15,17 +15,20 @@ export const editPractitionerDocumentAction = async ({ state.form, ); const { barNumber } = get(state.practitionerDetail); + const user = get(state.user); let fileName; let uploadDate; if (practitionerDocumentFile) { - await applicationContext - .getUseCases() - .uploadOrderDocumentInteractor(applicationContext, { + await applicationContext.getUseCases().uploadOrderDocumentInteractor( + applicationContext, + { documentFile: practitionerDocumentFile, fileIdToOverwrite: practitionerDocumentFileId, - }); + }, + user, + ); fileName = practitionerDocumentFile.name; uploadDate = applicationContext.getUtilities().createISODateString(); diff --git a/web-client/src/presenter/actions/formatPetitionAction.test.ts b/web-client/src/presenter/actions/formatPetitionAction.test.ts index 3da96571ddd..61146360fa6 100644 --- a/web-client/src/presenter/actions/formatPetitionAction.test.ts +++ b/web-client/src/presenter/actions/formatPetitionAction.test.ts @@ -1,6 +1,7 @@ import { CASE_TYPES_MAP } from '@shared/business/entities/EntityConstants'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { formatPetitionAction } from '@web-client/presenter/actions/formatPetitionAction'; +import { mockPetitionerUser } from '@shared/test/mockAuthUsers'; import { presenter } from '../presenter-mock'; import { runAction } from '@web-client/presenter/test.cerebral'; @@ -32,10 +33,6 @@ describe('formatPetitionAction', () => { .getUtilities() .getCaseCaption.mockImplementation(() => TEST_CASE_CAPTION); - applicationContext.getCurrentUser.mockImplementation(() => ({ - email: TEST_EMAIL, - })); - presenter.providers.applicationContext = applicationContext; }); @@ -47,6 +44,10 @@ describe('formatPetitionAction', () => { props: PROPS, state: { petitionFormatted: undefined, + user: { + ...mockPetitionerUser, + email: TEST_EMAIL, + }, }, }); @@ -82,6 +83,10 @@ describe('formatPetitionAction', () => { props: PROPS, state: { petitionFormatted: undefined, + user: { + ...mockPetitionerUser, + email: TEST_EMAIL, + }, }, }); @@ -126,6 +131,10 @@ describe('formatPetitionAction', () => { props: propsWithDisclosure, state: { petitionFormatted: undefined, + user: { + ...mockPetitionerUser, + email: TEST_EMAIL, + }, }, }); @@ -164,6 +173,10 @@ describe('formatPetitionAction', () => { props: propsWithoutIrsNotice, state: { petitionFormatted: undefined, + user: { + ...mockPetitionerUser, + email: TEST_EMAIL, + }, }, }); diff --git a/web-client/src/presenter/actions/formatPetitionAction.ts b/web-client/src/presenter/actions/formatPetitionAction.ts index d71ab160909..997b6d16d30 100644 --- a/web-client/src/presenter/actions/formatPetitionAction.ts +++ b/web-client/src/presenter/actions/formatPetitionAction.ts @@ -4,6 +4,7 @@ import { state } from '@web-client/presenter/app.cerebral'; export const formatPetitionAction = ({ applicationContext, + get, props, store, }: ActionProps) => { @@ -29,7 +30,7 @@ export const formatPetitionAction = ({ const { contactPrimary, irsNotices } = petitionInfo; - const user = applicationContext.getCurrentUser(); + const user = get(state.user); contactPrimary.email = user.email; const irsNoticesWithCaseTypes = irsNotices.map(irsNotice => { diff --git a/web-client/src/presenter/actions/getCaseAssociationAction.test.ts b/web-client/src/presenter/actions/getCaseAssociationAction.test.ts index 7088bb410c6..c4b69c976a3 100644 --- a/web-client/src/presenter/actions/getCaseAssociationAction.test.ts +++ b/web-client/src/presenter/actions/getCaseAssociationAction.test.ts @@ -1,10 +1,13 @@ -import { - CASE_STATUS_TYPES, - ROLES, -} from '../../../../shared/src/business/entities/EntityConstants'; +import { CASE_STATUS_TYPES } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { getCaseAssociationAction } from './getCaseAssociationAction'; -import { irsSuperuserUser } from '@shared/test/mockUsers'; +import { + irsPractitionerUser, + irsSuperuserUser, + petitionerUser, + petitionsClerkUser, + privatePractitionerUser, +} from '@shared/test/mockUsers'; import { presenter } from '../presenter-mock'; import { runAction } from '@web-client/presenter/test.cerebral'; @@ -19,8 +22,6 @@ describe('getCaseAssociation', () => { describe('IRS SuperUser', () => { it('should return false for isAssociated and pendingAssociation if the user is an irsSuperuser and service is not allowed on the case', async () => { - applicationContext.getCurrentUser.mockReturnValue(irsSuperuserUser); - const results = await runAction(getCaseAssociationAction, { modules: { presenter, @@ -31,6 +32,7 @@ describe('getCaseAssociation', () => { docketEntries: [{ documentType: 'Petition' }], status: CASE_STATUS_TYPES.new, }, + user: irsSuperuserUser, }, }); @@ -42,8 +44,6 @@ describe('getCaseAssociation', () => { }); it('should return true for isAssociated and false for pendingAssociation if the user is an irsSuperuser and service is allowed for the case', async () => { - applicationContext.getCurrentUser.mockReturnValue(irsSuperuserUser); - const results = await runAction(getCaseAssociationAction, { modules: { presenter, @@ -59,6 +59,7 @@ describe('getCaseAssociation', () => { ], status: CASE_STATUS_TYPES.generalDocket, }, + user: irsSuperuserUser, }, }); @@ -72,11 +73,6 @@ describe('getCaseAssociation', () => { describe('Internal user', () => { it('should return true for isAssociated and false for pendingAssociation if the user is an internal user', async () => { - applicationContext.getCurrentUser.mockReturnValueOnce({ - role: ROLES.petitionsClerk, - userId: '123', - }); - const results = await runAction(getCaseAssociationAction, { modules: { presenter, @@ -86,6 +82,7 @@ describe('getCaseAssociation', () => { caseDetail: { privatePractitioners: [{ userId: '123' }], }, + user: petitionsClerkUser, }, }); @@ -98,12 +95,6 @@ describe('getCaseAssociation', () => { }); describe('Private Practitioner, Petitioner, IRS Practitioner', () => { - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.privatePractitioner, - userId: '123', - }); - }); describe('consolidatedCases', () => {}); describe('nonConsolidatedCases', () => { it('should return that practitioner is associated', async () => { @@ -114,8 +105,11 @@ describe('getCaseAssociation', () => { props: {}, state: { caseDetail: { - privatePractitioners: [{ userId: '123' }], + privatePractitioners: [ + { userId: privatePractitionerUser.userId }, + ], }, + user: privatePractitionerUser, }, }); @@ -140,6 +134,7 @@ describe('getCaseAssociation', () => { caseDetail: { privatePractitioners: [{ userId: 'nothing' }], }, + user: privatePractitionerUser, }, }); @@ -166,6 +161,7 @@ describe('getCaseAssociation', () => { { userId: 'I am very different and not associated' }, ], }, + user: privatePractitionerUser, }, }); @@ -194,6 +190,7 @@ describe('getCaseAssociation', () => { }, ], }, + user: privatePractitionerUser, }, }); @@ -208,10 +205,6 @@ describe('getCaseAssociation', () => { applicationContext .getUseCases() .verifyPendingCaseForUserInteractor.mockReturnValue(false); - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.irsPractitioner, - userId: '789', - }); const results = await runAction(getCaseAssociationAction, { modules: { @@ -220,8 +213,9 @@ describe('getCaseAssociation', () => { props: {}, state: { caseDetail: { - irsPractitioners: [{ userId: '789' }], + irsPractitioners: [{ userId: irsPractitionerUser.userId }], }, + user: irsPractitionerUser, }, }); @@ -235,10 +229,6 @@ describe('getCaseAssociation', () => { applicationContext .getUseCases() .verifyPendingCaseForUserInteractor.mockReturnValue(true); - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.irsPractitioner, - userId: '789', - }); const results = await runAction(getCaseAssociationAction, { modules: { @@ -249,6 +239,7 @@ describe('getCaseAssociation', () => { caseDetail: { irsPractitioners: [{ userId: '123' }], }, + user: irsPractitionerUser, }, }); @@ -262,10 +253,6 @@ describe('getCaseAssociation', () => { applicationContext .getUseCases() .verifyPendingCaseForUserInteractor.mockReturnValue(false); - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '123', - }); const results = await runAction(getCaseAssociationAction, { modules: { @@ -276,10 +263,11 @@ describe('getCaseAssociation', () => { caseDetail: { petitioners: [ { - contactId: '123', + contactId: petitionerUser.userId, }, ], }, + user: petitionerUser, }, }); @@ -293,10 +281,6 @@ describe('getCaseAssociation', () => { applicationContext .getUseCases() .verifyPendingCaseForUserInteractor.mockReturnValue(true); - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: '789', - }); const results = await runAction(getCaseAssociationAction, { modules: { presenter, @@ -311,6 +295,7 @@ describe('getCaseAssociation', () => { ], userId: '123', }, + user: petitionerUser, }, }); @@ -326,12 +311,7 @@ describe('getCaseAssociation', () => { describe('with CONSOLIDATED_CASES_GROUP_ACCESS_PETITIONER feature flag', () => { describe('Feature Flag On', () => { it('isAssociated should be true when the petitioners userId exists in the consolidated group list', async () => { - const petitionerContactId = '123'; - - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: petitionerContactId, - }); + const petitionerContactId = petitionerUser.userId; const results = await runAction(getCaseAssociationAction, { modules: { @@ -356,6 +336,7 @@ describe('getCaseAssociation', () => { }, ], }, + user: petitionerUser, }, }); @@ -364,12 +345,7 @@ describe('getCaseAssociation', () => { }); it('should return true for isAssociated when and the case is not consolidated', async () => { - const petitionerContactId = '123'; - - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: petitionerContactId, - }); + const petitionerContactId = petitionerUser.userId; const results = await runAction(getCaseAssociationAction, { modules: { @@ -384,6 +360,7 @@ describe('getCaseAssociation', () => { }, ], }, + user: petitionerUser, }, }); @@ -392,12 +369,7 @@ describe('getCaseAssociation', () => { }); it('isDirectlyAssociated should be true when the id of the caseDetail petitioner matches the users id', async () => { - const petitionerContactId = '123'; - - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - userId: petitionerContactId, - }); + const petitionerContactId = petitionerUser.userId; const results = await runAction(getCaseAssociationAction, { modules: { @@ -414,6 +386,7 @@ describe('getCaseAssociation', () => { }, ], }, + user: petitionerUser, }, }); diff --git a/web-client/src/presenter/actions/getCaseAssociationAction.ts b/web-client/src/presenter/actions/getCaseAssociationAction.ts index 8b2a3c3066a..a8a8b26e802 100644 --- a/web-client/src/presenter/actions/getCaseAssociationAction.ts +++ b/web-client/src/presenter/actions/getCaseAssociationAction.ts @@ -12,7 +12,7 @@ export const getCaseAssociationAction = async ({ applicationContext, get, }: ActionProps) => { - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); @@ -68,6 +68,7 @@ export const getCaseAssociationAction = async ({ .getUseCases() .verifyPendingCaseForUserInteractor(applicationContext, { docketNumber: caseDetail.docketNumber, + userId: user.userId, }); } diff --git a/web-client/src/presenter/actions/getCompletedMessagesForSectionAction.test.ts b/web-client/src/presenter/actions/getCompletedMessagesForSectionAction.test.ts index d7350e457c2..5385c5b250b 100644 --- a/web-client/src/presenter/actions/getCompletedMessagesForSectionAction.test.ts +++ b/web-client/src/presenter/actions/getCompletedMessagesForSectionAction.test.ts @@ -2,6 +2,7 @@ import { ADC_SECTION, DOCKET_SECTION, } from '../../../../shared/src/business/entities/EntityConstants'; +import { adcUser } from '@shared/test/mockUsers'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { getCompletedMessagesForSectionAction } from './getCompletedMessagesForSectionAction'; import { presenter } from '../presenter-mock'; @@ -24,7 +25,9 @@ describe('getCompletedMessagesForSectionAction', () => { modules: { presenter, }, - state: {}, + state: { + user: {}, + }, }); expect(results.output.messages).toEqual([message]); }); @@ -45,12 +48,10 @@ describe('getCompletedMessagesForSectionAction', () => { applicationContext.getUseCases().getCompletedMessagesForSectionInteractor .mock.calls[0][1], ).toEqual({ section: DOCKET_SECTION }); - expect(applicationContext.getCurrentUser).not.toHaveBeenCalled(); }); it("retrieves completed messages for the current user's section when state.messageBoxToDisplay.section is undefined", async () => { const currentUserSection = { section: ADC_SECTION }; - applicationContext.getCurrentUser.mockReturnValue(currentUserSection); await runAction(getCompletedMessagesForSectionAction, { modules: { @@ -58,6 +59,7 @@ describe('getCompletedMessagesForSectionAction', () => { }, state: { messageBoxToDisplay: {}, + user: adcUser, }, }); @@ -65,6 +67,5 @@ describe('getCompletedMessagesForSectionAction', () => { applicationContext.getUseCases().getCompletedMessagesForSectionInteractor .mock.calls[0][1], ).toEqual(currentUserSection); - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); }); }); diff --git a/web-client/src/presenter/actions/getCompletedMessagesForSectionAction.ts b/web-client/src/presenter/actions/getCompletedMessagesForSectionAction.ts index 955098ef25e..bdc415db836 100644 --- a/web-client/src/presenter/actions/getCompletedMessagesForSectionAction.ts +++ b/web-client/src/presenter/actions/getCompletedMessagesForSectionAction.ts @@ -10,11 +10,12 @@ export const getCompletedMessagesForSectionAction = async ({ get, }: ActionProps) => { const selectedSection = get(state.messageBoxToDisplay.section); + const user = get(state.user); const messages = await applicationContext .getUseCases() .getCompletedMessagesForSectionInteractor(applicationContext, { - section: selectedSection || applicationContext.getCurrentUser().section, + section: selectedSection || user.section, }); return { messages }; diff --git a/web-client/src/presenter/actions/getCompletedMessagesForUserAction.test.ts b/web-client/src/presenter/actions/getCompletedMessagesForUserAction.test.ts index 8dd7a65332e..946ae2ec100 100644 --- a/web-client/src/presenter/actions/getCompletedMessagesForUserAction.test.ts +++ b/web-client/src/presenter/actions/getCompletedMessagesForUserAction.test.ts @@ -20,7 +20,7 @@ describe('getCompletedMessagesForUserAction', () => { modules: { presenter, }, - state: {}, + state: { user: {} }, }); expect(results.output.messages).toEqual([message]); }); diff --git a/web-client/src/presenter/actions/getCompletedMessagesForUserAction.ts b/web-client/src/presenter/actions/getCompletedMessagesForUserAction.ts index e0eb7e766a1..eebe640596d 100644 --- a/web-client/src/presenter/actions/getCompletedMessagesForUserAction.ts +++ b/web-client/src/presenter/actions/getCompletedMessagesForUserAction.ts @@ -1,3 +1,5 @@ +import { state } from '@web-client/presenter/app.cerebral'; + /** * fetches the completed messages for the user * @param {object} applicationContext object that contains all the context specific methods @@ -5,11 +7,13 @@ */ export const getCompletedMessagesForUserAction = async ({ applicationContext, + get, }: ActionProps) => { + const user = get(state.user); const messages = await applicationContext .getUseCases() .getCompletedMessagesForUserInteractor(applicationContext, { - userId: applicationContext.getCurrentUser().userId, + userId: user.userId, }); return { messages }; diff --git a/web-client/src/presenter/actions/getDefaultDraftViewerDocumentToDisplayAction.ts b/web-client/src/presenter/actions/getDefaultDraftViewerDocumentToDisplayAction.ts index c1786f1b220..41f75dc8cdb 100644 --- a/web-client/src/presenter/actions/getDefaultDraftViewerDocumentToDisplayAction.ts +++ b/web-client/src/presenter/actions/getDefaultDraftViewerDocumentToDisplayAction.ts @@ -13,6 +13,7 @@ export const getDefaultDraftViewerDocumentToDisplayAction = ({ applicationContext, get, }: ActionProps) => { + const user = get(state.user); const draftDocketEntryId = get(state.draftDocumentViewerDocketEntryId) || get(state.screenMetadata.draftDocumentViewerDocketEntryId); @@ -20,7 +21,7 @@ export const getDefaultDraftViewerDocumentToDisplayAction = ({ const caseDetail = get(state.caseDetail); const { draftDocuments } = applicationContext .getUtilities() - .formatCase(applicationContext, cloneDeep(caseDetail)); + .formatCase(applicationContext, cloneDeep(caseDetail), user); let viewerDraftDocumentToDisplay = draftDocuments[0]; diff --git a/web-client/src/presenter/actions/getDefaultViewerCorrespondenceToDisplayAction.ts b/web-client/src/presenter/actions/getDefaultViewerCorrespondenceToDisplayAction.ts index ccbe6f7aea1..169216eb2a0 100644 --- a/web-client/src/presenter/actions/getDefaultViewerCorrespondenceToDisplayAction.ts +++ b/web-client/src/presenter/actions/getDefaultViewerCorrespondenceToDisplayAction.ts @@ -16,12 +16,13 @@ export const getDefaultViewerCorrespondenceToDisplayAction = ({ }: ActionProps) => { const { correspondenceId } = props; let viewerCorrespondenceToDisplay = null; + const user = get(state.user); const caseDetail = get(state.caseDetail); const { correspondence } = applicationContext .getUtilities() - .formatCase(applicationContext, cloneDeep(caseDetail)); + .formatCase(applicationContext, cloneDeep(caseDetail), user); if (correspondenceId) { viewerCorrespondenceToDisplay = correspondence.find( diff --git a/web-client/src/presenter/actions/getDocumentQCInboxForSectionAction.test.ts b/web-client/src/presenter/actions/getDocumentQCInboxForSectionAction.test.ts index fed4145763b..f06815db9ed 100644 --- a/web-client/src/presenter/actions/getDocumentQCInboxForSectionAction.test.ts +++ b/web-client/src/presenter/actions/getDocumentQCInboxForSectionAction.test.ts @@ -1,3 +1,5 @@ +import { ADC_SECTION } from '@shared/business/entities/EntityConstants'; +import { adcUser } from '@shared/test/mockUsers'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { getDocumentQCInboxForSectionAction } from './getDocumentQCInboxForSectionAction'; import { presenter } from '../presenter-mock'; @@ -5,33 +7,15 @@ import { runAction } from '@web-client/presenter/test.cerebral'; describe('getDocumentQCInboxForSectionAction', () => { const mockWorkItems = [{ docketEntryId: 1 }, { docketEntryId: 2 }]; - const { CHIEF_JUDGE, USER_ROLES } = applicationContext.getConstants(); + const { CHIEF_JUDGE } = applicationContext.getConstants(); beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue({ - section: 'judgy section', - }); applicationContext .getUseCases() .getDocumentQCInboxForSectionInteractor.mockReturnValue(mockWorkItems); presenter.providers.applicationContext = applicationContext; }); - it('should retrieve the current user', async () => { - await runAction(getDocumentQCInboxForSectionAction, { - modules: { - presenter, - }, - state: { - judgeUser: { - name: 'A judgy person', - }, - }, - }); - - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); - }); - it('should call getDocumentQCInboxForSectionInteractor with the judge user from state', async () => { await runAction(getDocumentQCInboxForSectionAction, { modules: { @@ -41,6 +25,9 @@ describe('getDocumentQCInboxForSectionAction', () => { judgeUser: { name: 'A judgy person', }, + user: { + section: 'judgy section', + }, }, }); @@ -63,6 +50,7 @@ describe('getDocumentQCInboxForSectionAction', () => { presenter, }, state: { + user: {}, workQueueToDisplay: { section: mockSection, }, @@ -78,15 +66,11 @@ describe('getDocumentQCInboxForSectionAction', () => { }); it('should call getDocumentQCInboxForSectionInteractor with the CHIEF_JUDGE if judgeUser is not found in state and user role is adc', async () => { - applicationContext.getCurrentUser.mockReturnValueOnce({ - role: USER_ROLES.adc, - section: 'judgy section', - }); await runAction(getDocumentQCInboxForSectionAction, { modules: { presenter, }, - state: {}, + state: { user: adcUser }, }); expect( @@ -96,7 +80,7 @@ describe('getDocumentQCInboxForSectionAction', () => { judgeUser: { name: CHIEF_JUDGE, }, - section: 'judgy section', + section: ADC_SECTION, }); }); }); diff --git a/web-client/src/presenter/actions/getDocumentQCInboxForSectionAction.ts b/web-client/src/presenter/actions/getDocumentQCInboxForSectionAction.ts index 460dae40e74..bad33cae3b8 100644 --- a/web-client/src/presenter/actions/getDocumentQCInboxForSectionAction.ts +++ b/web-client/src/presenter/actions/getDocumentQCInboxForSectionAction.ts @@ -13,7 +13,7 @@ export const getDocumentQCInboxForSectionAction = async ({ const selectedSection = get(state.workQueueToDisplay.section); const { CHIEF_JUDGE, USER_ROLES } = applicationContext.getConstants(); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); let judgeUser = get(state.judgeUser); if (!judgeUser && user.role === USER_ROLES.adc) { diff --git a/web-client/src/presenter/actions/getDocumentQCInboxForUserAction.test.ts b/web-client/src/presenter/actions/getDocumentQCInboxForUserAction.test.ts index 3920cbd0b5b..b1fc3b950d4 100644 --- a/web-client/src/presenter/actions/getDocumentQCInboxForUserAction.test.ts +++ b/web-client/src/presenter/actions/getDocumentQCInboxForUserAction.test.ts @@ -8,10 +8,6 @@ describe('getDocumentQCInboxForUserAction', () => { const mockUserId = '35f77d01-df22-479c-b5a9-84edfbc876af'; beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue({ - userId: mockUserId, - }); - applicationContext .getUseCases() .getDocumentQCInboxForUserInteractor.mockReturnValue(mockWorkItems); @@ -19,21 +15,14 @@ describe('getDocumentQCInboxForUserAction', () => { presenter.providers.applicationContext = applicationContext; }); - it('should make a call to get the current user', async () => { - await runAction(getDocumentQCInboxForUserAction, { - modules: { - presenter, - }, - }); - - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); - }); - it("should make a call to getDocumentQCInboxForUserInteractor with the current user's userId", async () => { await runAction(getDocumentQCInboxForUserAction, { modules: { presenter, }, + state: { + user: { userId: mockUserId }, + }, }); expect( @@ -47,6 +36,9 @@ describe('getDocumentQCInboxForUserAction', () => { modules: { presenter, }, + state: { + user: { userId: mockUserId }, + }, }); expect(output).toEqual({ workItems: mockWorkItems }); diff --git a/web-client/src/presenter/actions/getDocumentQCInboxForUserAction.ts b/web-client/src/presenter/actions/getDocumentQCInboxForUserAction.ts index dc34316eaf2..66d330b540b 100644 --- a/web-client/src/presenter/actions/getDocumentQCInboxForUserAction.ts +++ b/web-client/src/presenter/actions/getDocumentQCInboxForUserAction.ts @@ -1,3 +1,5 @@ +import { state } from '@web-client/presenter/app.cerebral'; + /** * fetches the document qc inbox work items for a user, * @param {object} applicationContext object that contains all the context specific methods @@ -5,11 +7,13 @@ */ export const getDocumentQCInboxForUserAction = async ({ applicationContext, + get, }: ActionProps) => { + const user = get(state.user); const workItems = await applicationContext .getUseCases() .getDocumentQCInboxForUserInteractor(applicationContext, { - userId: applicationContext.getCurrentUser().userId, + userId: user.userId, }); return { workItems }; diff --git a/web-client/src/presenter/actions/getDocumentQCServedForSectionAction.test.ts b/web-client/src/presenter/actions/getDocumentQCServedForSectionAction.test.ts index cb423cbe01b..c69b36edc2e 100644 --- a/web-client/src/presenter/actions/getDocumentQCServedForSectionAction.test.ts +++ b/web-client/src/presenter/actions/getDocumentQCServedForSectionAction.test.ts @@ -8,10 +8,6 @@ describe('getDocumentQCServedForSectionAction', () => { const mockSection = 'A side section'; beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue({ - section: mockSection, - }); - applicationContext .getUseCases() .getDocumentQCServedForSectionInteractor.mockReturnValue(mockWorkItems); @@ -19,21 +15,16 @@ describe('getDocumentQCServedForSectionAction', () => { presenter.providers.applicationContext = applicationContext; }); - it('should make a call to get the current user', async () => { - await runAction(getDocumentQCServedForSectionAction, { - modules: { - presenter, - }, - }); - - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); - }); - it("should make a call to getDocumentQCServedForSectionInteractor with the current user's section", async () => { await runAction(getDocumentQCServedForSectionAction, { modules: { presenter, }, + state: { + user: { + section: mockSection, + }, + }, }); expect( @@ -49,6 +40,9 @@ describe('getDocumentQCServedForSectionAction', () => { presenter, }, state: { + user: { + section: mockSection, + }, workQueueToDisplay: { section: mockSelectedSection, }, @@ -67,6 +61,11 @@ describe('getDocumentQCServedForSectionAction', () => { modules: { presenter, }, + state: { + user: { + section: mockSection, + }, + }, }); expect(output).toEqual({ workItems: mockWorkItems }); diff --git a/web-client/src/presenter/actions/getDocumentQCServedForSectionAction.ts b/web-client/src/presenter/actions/getDocumentQCServedForSectionAction.ts index a6ae39b7024..46585b9d392 100644 --- a/web-client/src/presenter/actions/getDocumentQCServedForSectionAction.ts +++ b/web-client/src/presenter/actions/getDocumentQCServedForSectionAction.ts @@ -12,7 +12,7 @@ export const getDocumentQCServedForSectionAction = async ({ }: ActionProps) => { const selectedSection = get(state.workQueueToDisplay.section); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const workItems = await applicationContext .getUseCases() .getDocumentQCServedForSectionInteractor(applicationContext, { diff --git a/web-client/src/presenter/actions/getDocumentQCServedForUserAction.test.ts b/web-client/src/presenter/actions/getDocumentQCServedForUserAction.test.ts index a2b36233ec2..64326c49ddf 100644 --- a/web-client/src/presenter/actions/getDocumentQCServedForUserAction.test.ts +++ b/web-client/src/presenter/actions/getDocumentQCServedForUserAction.test.ts @@ -8,10 +8,6 @@ describe('getDocumentQCServedForUserAction', () => { const mockUserId = 'a2eaa4e5-e6d8-434c-973a-fe9431f84e66'; beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue({ - userId: mockUserId, - }); - applicationContext .getUseCases() .getDocumentQCServedForUserInteractor.mockReturnValue(mockWorkItems); @@ -19,21 +15,16 @@ describe('getDocumentQCServedForUserAction', () => { presenter.providers.applicationContext = applicationContext; }); - it('should make a call to get the current user', async () => { - await runAction(getDocumentQCServedForUserAction, { - modules: { - presenter, - }, - }); - - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); - }); - it("should make a call to getDocumentQCServedForUserInteractor with the current user's userId", async () => { await runAction(getDocumentQCServedForUserAction, { modules: { presenter, }, + state: { + user: { + userId: mockUserId, + }, + }, }); expect( @@ -47,6 +38,11 @@ describe('getDocumentQCServedForUserAction', () => { modules: { presenter, }, + state: { + user: { + userId: mockUserId, + }, + }, }); expect(output).toEqual({ workItems: mockWorkItems }); diff --git a/web-client/src/presenter/actions/getDocumentQCServedForUserAction.ts b/web-client/src/presenter/actions/getDocumentQCServedForUserAction.ts index d0e1dcda4cc..d1697d3368f 100644 --- a/web-client/src/presenter/actions/getDocumentQCServedForUserAction.ts +++ b/web-client/src/presenter/actions/getDocumentQCServedForUserAction.ts @@ -1,3 +1,5 @@ +import { state } from '@web-client/presenter/app.cerebral'; + /** * fetches the document qc served work items for a user. * @param {object} applicationContext object that contains all the context specific methods @@ -5,11 +7,13 @@ */ export const getDocumentQCServedForUserAction = async ({ applicationContext, + get, }: ActionProps) => { + const user = get(state.user); const workItems = await applicationContext .getUseCases() .getDocumentQCServedForUserInteractor(applicationContext, { - userId: applicationContext.getCurrentUser().userId, + userId: user.userId, }); return { workItems }; diff --git a/web-client/src/presenter/actions/getInboxMessagesForSectionAction.test.ts b/web-client/src/presenter/actions/getInboxMessagesForSectionAction.test.ts index 9ca44e24d9a..44f14241577 100644 --- a/web-client/src/presenter/actions/getInboxMessagesForSectionAction.test.ts +++ b/web-client/src/presenter/actions/getInboxMessagesForSectionAction.test.ts @@ -24,7 +24,7 @@ describe('getInboxMessagesForSectionAction', () => { modules: { presenter, }, - state: {}, + state: { user: {} }, }); expect(results.output.messages).toEqual([message]); }); @@ -38,6 +38,7 @@ describe('getInboxMessagesForSectionAction', () => { messageBoxToDisplay: { section: DOCKET_SECTION, }, + user: {}, }, }); @@ -45,12 +46,10 @@ describe('getInboxMessagesForSectionAction', () => { applicationContext.getUseCases().getInboxMessagesForSectionInteractor.mock .calls[0][1], ).toEqual({ section: DOCKET_SECTION }); - expect(applicationContext.getCurrentUser).not.toHaveBeenCalled(); }); it("retrieves inbox messages for the current user's section when state.messageBoxToDisplay.section is undefined", async () => { const currentUserSection = { section: ADC_SECTION }; - applicationContext.getCurrentUser.mockReturnValue(currentUserSection); await runAction(getInboxMessagesForSectionAction, { modules: { @@ -58,6 +57,7 @@ describe('getInboxMessagesForSectionAction', () => { }, state: { messageBoxToDisplay: {}, + user: currentUserSection, }, }); @@ -65,6 +65,5 @@ describe('getInboxMessagesForSectionAction', () => { applicationContext.getUseCases().getInboxMessagesForSectionInteractor.mock .calls[0][1], ).toEqual(currentUserSection); - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); }); }); diff --git a/web-client/src/presenter/actions/getInboxMessagesForSectionAction.ts b/web-client/src/presenter/actions/getInboxMessagesForSectionAction.ts index 8245356b3a4..59057623686 100644 --- a/web-client/src/presenter/actions/getInboxMessagesForSectionAction.ts +++ b/web-client/src/presenter/actions/getInboxMessagesForSectionAction.ts @@ -10,11 +10,12 @@ export const getInboxMessagesForSectionAction = async ({ get, }: ActionProps) => { const selectedSection = get(state.messageBoxToDisplay.section); + const user = get(state.user); const messages = await applicationContext .getUseCases() .getInboxMessagesForSectionInteractor(applicationContext, { - section: selectedSection || applicationContext.getCurrentUser().section, + section: selectedSection || user.section, }); return { messages }; diff --git a/web-client/src/presenter/actions/getInboxMessagesForUserAction.test.ts b/web-client/src/presenter/actions/getInboxMessagesForUserAction.test.ts index 7559c8e0445..1da8e8b1a55 100644 --- a/web-client/src/presenter/actions/getInboxMessagesForUserAction.test.ts +++ b/web-client/src/presenter/actions/getInboxMessagesForUserAction.test.ts @@ -20,7 +20,7 @@ describe('getInboxMessagesForUserAction', () => { modules: { presenter, }, - state: {}, + state: { user: {} }, }); expect(results.output.messages).toEqual([message]); }); diff --git a/web-client/src/presenter/actions/getInboxMessagesForUserAction.ts b/web-client/src/presenter/actions/getInboxMessagesForUserAction.ts index ec7eb1fb92e..9b1eb61be63 100644 --- a/web-client/src/presenter/actions/getInboxMessagesForUserAction.ts +++ b/web-client/src/presenter/actions/getInboxMessagesForUserAction.ts @@ -1,3 +1,5 @@ +import { state } from '@web-client/presenter/app.cerebral'; + /** * fetches the inbox messages for the user * @param {object} applicationContext object that contains all the context specific methods @@ -5,11 +7,13 @@ */ export const getInboxMessagesForUserAction = async ({ applicationContext, + get, }: ActionProps) => { + const user = get(state.user); const messages = await applicationContext .getUseCases() .getInboxMessagesForUserInteractor(applicationContext, { - userId: applicationContext.getCurrentUser().userId, + userId: user.userId, }); return { messages }; diff --git a/web-client/src/presenter/actions/getJudgeForCurrentUserAction.test.ts b/web-client/src/presenter/actions/getJudgeForCurrentUserAction.test.ts index 39bc92fa6a9..08178abb2b9 100644 --- a/web-client/src/presenter/actions/getJudgeForCurrentUserAction.test.ts +++ b/web-client/src/presenter/actions/getJudgeForCurrentUserAction.test.ts @@ -5,9 +5,6 @@ import { runAction } from '@web-client/presenter/test.cerebral'; describe('getJudgeForCurrentUserAction', () => { beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue({ - userId: '123', - }); presenter.providers.applicationContext = applicationContext; }); @@ -19,6 +16,11 @@ describe('getJudgeForCurrentUserAction', () => { modules: { presenter, }, + state: { + user: { + userId: '123', + }, + }, }); expect( applicationContext.getUseCases().getJudgeInSectionInteractor, @@ -34,6 +36,11 @@ describe('getJudgeForCurrentUserAction', () => { modules: { presenter, }, + state: { + user: { + userId: '123', + }, + }, }); expect(result.output.judgeUser).toBeUndefined(); }); diff --git a/web-client/src/presenter/actions/getJudgeForCurrentUserAction.ts b/web-client/src/presenter/actions/getJudgeForCurrentUserAction.ts index ba0f487c7bf..14e6ca7d61f 100644 --- a/web-client/src/presenter/actions/getJudgeForCurrentUserAction.ts +++ b/web-client/src/presenter/actions/getJudgeForCurrentUserAction.ts @@ -1,12 +1,15 @@ import { RawUser } from '@shared/business/entities/User'; +import { state } from '@web-client/presenter/app.cerebral'; export const getJudgeForCurrentUserAction = async ({ applicationContext, + get, }: ActionProps): Promise<{ judgeUser: RawUser }> => { + const user = get(state.user); const judgeUser = await applicationContext .getUseCases() .getJudgeInSectionInteractor(applicationContext, { - section: applicationContext.getCurrentUser().section, + section: user.section, }); return { judgeUser }; diff --git a/web-client/src/presenter/actions/getNotificationsAction.test.ts b/web-client/src/presenter/actions/getNotificationsAction.test.ts index 0bfcbc1579f..3a9366ffe64 100644 --- a/web-client/src/presenter/actions/getNotificationsAction.test.ts +++ b/web-client/src/presenter/actions/getNotificationsAction.test.ts @@ -17,6 +17,9 @@ describe('getNotificationsAction', () => { modules: { presenter, }, + state: { + user: {}, + }, }); expect( @@ -33,6 +36,9 @@ describe('getNotificationsAction', () => { judgeUser: { userId: '123', }, + state: { + user: {}, + }, }, }); @@ -43,6 +49,7 @@ describe('getNotificationsAction', () => { }); it('makes a call to fetch notifications with case services supervisor information when state.messageBoxToDisplay.section is defined', async () => { + const userId = 'this is a user id'; await runAction(getNotificationsAction, { modules: { presenter, @@ -51,6 +58,7 @@ describe('getNotificationsAction', () => { messageBoxToDisplay: { section: DOCKET_SECTION, }, + user: { userId }, }, }); @@ -59,16 +67,18 @@ describe('getNotificationsAction', () => { .calls[0][1].caseServicesSupervisorData, ).toEqual({ section: DOCKET_SECTION, - userId: 'a805d1ab-18d0-43ec-bafb-654e83405416', + userId, }); }); it('makes a call to fetch notifications with case services supervisor information when state.workQueueToDisplay.section is defined', async () => { + const userId = 'this is a user id'; await runAction(getNotificationsAction, { modules: { presenter, }, state: { + user: { userId }, workQueueToDisplay: { section: DOCKET_SECTION, }, @@ -80,7 +90,7 @@ describe('getNotificationsAction', () => { .calls[0][1].caseServicesSupervisorData, ).toEqual({ section: DOCKET_SECTION, - userId: 'a805d1ab-18d0-43ec-bafb-654e83405416', + userId, }); }); }); diff --git a/web-client/src/presenter/actions/getNotificationsAction.ts b/web-client/src/presenter/actions/getNotificationsAction.ts index 14df5bc349d..bebe58a2320 100644 --- a/web-client/src/presenter/actions/getNotificationsAction.ts +++ b/web-client/src/presenter/actions/getNotificationsAction.ts @@ -16,12 +16,14 @@ export const getNotificationsAction = async ({ get(state.messageBoxToDisplay.section) || get(state.workQueueToDisplay.section); + const user = get(state.user); + let caseServicesSupervisorData; if (sectionToDisplay) { caseServicesSupervisorData = { section: sectionToDisplay, - userId: applicationContext.getCurrentUser().userId, + userId: user.userId, }; } diff --git a/web-client/src/presenter/actions/getOutboxMessagesForSectionAction.test.ts b/web-client/src/presenter/actions/getOutboxMessagesForSectionAction.test.ts index eabff2a06f3..a1c494ceba8 100644 --- a/web-client/src/presenter/actions/getOutboxMessagesForSectionAction.test.ts +++ b/web-client/src/presenter/actions/getOutboxMessagesForSectionAction.test.ts @@ -24,7 +24,9 @@ describe('getOutboxMessagesForSectionAction', () => { modules: { presenter, }, - state: {}, + state: { + user: {}, + }, }); expect(results.output.messages).toEqual([message]); }); @@ -38,6 +40,7 @@ describe('getOutboxMessagesForSectionAction', () => { messageBoxToDisplay: { section: DOCKET_SECTION, }, + user: {}, }, }); @@ -45,12 +48,10 @@ describe('getOutboxMessagesForSectionAction', () => { applicationContext.getUseCases().getOutboxMessagesForSectionInteractor .mock.calls[0][1], ).toEqual({ section: DOCKET_SECTION }); - expect(applicationContext.getCurrentUser).not.toHaveBeenCalled(); }); it("retrieves sent messages for the current user's section when state.messageBoxToDisplay.section is undefined", async () => { const currentUserSection = { section: ADC_SECTION }; - applicationContext.getCurrentUser.mockReturnValue(currentUserSection); await runAction(getOutboxMessagesForSectionAction, { modules: { @@ -58,6 +59,7 @@ describe('getOutboxMessagesForSectionAction', () => { }, state: { messageBoxToDisplay: {}, + user: currentUserSection, }, }); @@ -65,6 +67,5 @@ describe('getOutboxMessagesForSectionAction', () => { applicationContext.getUseCases().getOutboxMessagesForSectionInteractor .mock.calls[0][1], ).toEqual(currentUserSection); - expect(applicationContext.getCurrentUser).toHaveBeenCalled(); }); }); diff --git a/web-client/src/presenter/actions/getOutboxMessagesForSectionAction.ts b/web-client/src/presenter/actions/getOutboxMessagesForSectionAction.ts index 1a83d09c416..c099d40f659 100644 --- a/web-client/src/presenter/actions/getOutboxMessagesForSectionAction.ts +++ b/web-client/src/presenter/actions/getOutboxMessagesForSectionAction.ts @@ -10,11 +10,12 @@ export const getOutboxMessagesForSectionAction = async ({ get, }: ActionProps) => { const selectedSection = get(state.messageBoxToDisplay.section); + const user = get(state.user); const messages = await applicationContext .getUseCases() .getOutboxMessagesForSectionInteractor(applicationContext, { - section: selectedSection || applicationContext.getCurrentUser().section, + section: selectedSection || user.section, }); return { messages }; diff --git a/web-client/src/presenter/actions/getOutboxMessagesForUserAction.test.ts b/web-client/src/presenter/actions/getOutboxMessagesForUserAction.test.ts index 642e7542df1..2ff90ce8ba7 100644 --- a/web-client/src/presenter/actions/getOutboxMessagesForUserAction.test.ts +++ b/web-client/src/presenter/actions/getOutboxMessagesForUserAction.test.ts @@ -20,7 +20,7 @@ describe('getOutboxMessagesForUserAction', () => { modules: { presenter, }, - state: {}, + state: { user: {} }, }); expect(results.output.messages).toEqual([message]); }); diff --git a/web-client/src/presenter/actions/getOutboxMessagesForUserAction.ts b/web-client/src/presenter/actions/getOutboxMessagesForUserAction.ts index e9be1dd3ddb..b4c7056c8c0 100644 --- a/web-client/src/presenter/actions/getOutboxMessagesForUserAction.ts +++ b/web-client/src/presenter/actions/getOutboxMessagesForUserAction.ts @@ -1,3 +1,5 @@ +import { state } from '@web-client/presenter/app.cerebral'; + /** * fetches the outbox messages for the user * @param {object} applicationContext object that contains all the context specific methods @@ -5,11 +7,13 @@ */ export const getOutboxMessagesForUserAction = async ({ applicationContext, + get, }: ActionProps) => { + const user = get(state.user); const messages = await applicationContext .getUseCases() .getOutboxMessagesForUserInteractor(applicationContext, { - userId: applicationContext.getCurrentUser().userId, + userId: user.userId, }); return { messages }; diff --git a/web-client/src/presenter/actions/getShouldMarkMessageAsReadAction.test.ts b/web-client/src/presenter/actions/getShouldMarkMessageAsReadAction.test.ts index f4c5b2cae32..923a953e929 100644 --- a/web-client/src/presenter/actions/getShouldMarkMessageAsReadAction.test.ts +++ b/web-client/src/presenter/actions/getShouldMarkMessageAsReadAction.test.ts @@ -17,9 +17,7 @@ describe('getShouldMarkMessageAsReadAction', () => { }); it('should return the markRead path if the message is unread and belongs to the current user', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - userId: '123', - }); + const userId = '123'; await runAction(getShouldMarkMessageAsReadAction, { modules: { @@ -31,21 +29,22 @@ describe('getShouldMarkMessageAsReadAction', () => { toUserId: '123', }, }, + state: { + user: { userId }, + }, }); expect(markReadStub.mock.calls.length).toEqual(1); expect(markReadStub).toHaveBeenCalledWith({ messageToMarkRead: { isRead: false, - toUserId: '123', + toUserId: userId, }, }); }); it('should return the noAction path the message is already read', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - userId: '123', - }); + const userId = '123'; await runAction(getShouldMarkMessageAsReadAction, { modules: { @@ -57,15 +56,18 @@ describe('getShouldMarkMessageAsReadAction', () => { toUserId: '123', }, }, + state: { + user: { + userId, + }, + }, }); expect(noActionStub.mock.calls.length).toEqual(1); }); it('should return the noAction path the message is not assigned to the current user', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - userId: '123', - }); + const userId = '123'; await runAction(getShouldMarkMessageAsReadAction, { modules: { @@ -77,6 +79,11 @@ describe('getShouldMarkMessageAsReadAction', () => { toUserId: '321', }, }, + state: { + user: { + userId, + }, + }, }); expect(noActionStub.mock.calls.length).toEqual(1); diff --git a/web-client/src/presenter/actions/getShouldMarkMessageAsReadAction.ts b/web-client/src/presenter/actions/getShouldMarkMessageAsReadAction.ts index 71e5935adae..ffa8ab53c4e 100644 --- a/web-client/src/presenter/actions/getShouldMarkMessageAsReadAction.ts +++ b/web-client/src/presenter/actions/getShouldMarkMessageAsReadAction.ts @@ -1,3 +1,5 @@ +import { state } from '@web-client/presenter/app.cerebral'; + /** * returns the path based on whether the message should be marked as read * @param {object} providers the providers object @@ -7,11 +9,11 @@ * @returns {object} continue path for the sequence */ export const getShouldMarkMessageAsReadAction = ({ - applicationContext, + get, path, props, }: ActionProps) => { - const { userId } = applicationContext.getCurrentUser(); + const { userId } = get(state.user); const { mostRecentMessage } = props; if (mostRecentMessage.toUserId === userId && !mostRecentMessage.isRead) { diff --git a/web-client/src/presenter/actions/getUsersInSectionAction.test.ts b/web-client/src/presenter/actions/getUsersInSectionAction.test.ts index 1b41edb5055..8beeb0613d2 100644 --- a/web-client/src/presenter/actions/getUsersInSectionAction.test.ts +++ b/web-client/src/presenter/actions/getUsersInSectionAction.test.ts @@ -53,9 +53,6 @@ describe('getUsersInSectionAction', () => { it("should retrieve all the users in the current user's section when a section is not provided", async () => { const mockSection = 'Test User Section'; - applicationContext.getCurrentUser.mockReturnValue({ - section: mockSection, - }); applicationContext .getUseCases() .getUsersInSectionInteractor.mockReturnValue([]); @@ -64,6 +61,9 @@ describe('getUsersInSectionAction', () => { modules: { presenter, }, + state: { + user: { section: mockSection }, + }, }); expect( diff --git a/web-client/src/presenter/actions/getUsersInSectionAction.ts b/web-client/src/presenter/actions/getUsersInSectionAction.ts index 065c763d6e4..8356721879e 100644 --- a/web-client/src/presenter/actions/getUsersInSectionAction.ts +++ b/web-client/src/presenter/actions/getUsersInSectionAction.ts @@ -1,10 +1,12 @@ import { RawUser } from '@shared/business/entities/User'; import { sortBy } from 'lodash'; +import { state } from '@web-client/presenter/app.cerebral'; export const getUsersInSectionAction = ({ section }: { section?: string }) => async ({ applicationContext, + get, props, }: ActionProps<{ section: string; @@ -23,7 +25,7 @@ export const getUsersInSectionAction = } if (!sectionToGet) { - const user = applicationContext.getCurrentUser(); + const user = get(state.user); sectionToGet = user.section; } diff --git a/web-client/src/presenter/actions/isInternalUserAction.test.ts b/web-client/src/presenter/actions/isInternalUserAction.test.ts index 16549faf052..34e31442a54 100644 --- a/web-client/src/presenter/actions/isInternalUserAction.test.ts +++ b/web-client/src/presenter/actions/isInternalUserAction.test.ts @@ -18,29 +18,30 @@ describe('isInternalUserAction', () => { }); it('should call path.yes if the user is an internal user', async () => { - presenter.providers.applicationContext.getCurrentUser = () => ({ - role: ROLES.docketClerk, - }); - await runAction(isInternalUserAction, { modules: { presenter, }, - state: {}, + state: { + user: { + role: ROLES.docketClerk, + }, + }, }); expect(yesStub).toHaveBeenCalled(); }); it('should call the path.no if the user is an external user', async () => { - presenter.providers.applicationContext.getCurrentUser = () => ({ - role: ROLES.petitioner, - }); await runAction(isInternalUserAction, { modules: { presenter, }, - state: {}, + state: { + user: { + role: ROLES.petitioner, + }, + }, }); expect(noStub).toHaveBeenCalled(); diff --git a/web-client/src/presenter/actions/isInternalUserAction.ts b/web-client/src/presenter/actions/isInternalUserAction.ts index 61a028d16ea..7200330b576 100644 --- a/web-client/src/presenter/actions/isInternalUserAction.ts +++ b/web-client/src/presenter/actions/isInternalUserAction.ts @@ -1,3 +1,5 @@ +import { state } from '@web-client/presenter/app.cerebral'; + /** * takes a path depending on if the user an internal user * @param {object} providers the providers object @@ -6,9 +8,10 @@ */ export const isInternalUserAction = ({ applicationContext, + get, path, }: ActionProps) => { - const user = applicationContext.getCurrentUser(); + const user = get(state.user); return applicationContext.getUtilities().isInternalUser(user.role) ? path.yes() : path.no(); diff --git a/web-client/src/presenter/actions/passAlongJudgeUserAction.test.ts b/web-client/src/presenter/actions/passAlongJudgeUserAction.test.ts index 70d6d5258fd..c3d59aea771 100644 --- a/web-client/src/presenter/actions/passAlongJudgeUserAction.test.ts +++ b/web-client/src/presenter/actions/passAlongJudgeUserAction.test.ts @@ -8,13 +8,14 @@ describe('passAlongJudgeUserAction', () => { presenter.providers.applicationContext = applicationContext; it('should call the setItemInteractor to persists the tab and form', async () => { - applicationContext.getCurrentUser.mockReturnValue(judgeUser); - const { output } = await runAction(passAlongJudgeUserAction, { modules: { presenter, }, props: {}, + state: { + user: judgeUser, + }, }); expect(output.judgeUser).toEqual(judgeUser); diff --git a/web-client/src/presenter/actions/passAlongJudgeUserAction.ts b/web-client/src/presenter/actions/passAlongJudgeUserAction.ts index 159c770eea0..04bc6d64a78 100644 --- a/web-client/src/presenter/actions/passAlongJudgeUserAction.ts +++ b/web-client/src/presenter/actions/passAlongJudgeUserAction.ts @@ -1,8 +1,9 @@ import { RawUser } from '@shared/business/entities/User'; import { cloneDeep } from 'lodash'; +import { state } from '@web-client/presenter/app.cerebral'; export const passAlongJudgeUserAction = ({ - applicationContext, + get, }: ActionProps): { judgeUser: RawUser } => { - return { judgeUser: cloneDeep(applicationContext.getCurrentUser()) }; + return { judgeUser: cloneDeep(get(state.user)) }; }; diff --git a/web-client/src/presenter/actions/runPathForUserRoleAction.test.ts b/web-client/src/presenter/actions/runPathForUserRoleAction.test.ts index 92b5d34deab..579d771a0e5 100644 --- a/web-client/src/presenter/actions/runPathForUserRoleAction.test.ts +++ b/web-client/src/presenter/actions/runPathForUserRoleAction.test.ts @@ -36,93 +36,100 @@ describe('runPathForUserRoleAction', () => { }); it('should throw an exception for unrecognized roles', async () => { - presenter.providers.applicationContext.getCurrentUser = () => ({ - role: 'bananas', - }); await expect( runAction(runPathForUserRoleAction, { modules: { presenter, }, - state: {}, + state: { + user: { + role: 'bananas', + }, + }, }), ).rejects.toThrow(); }); it('should return the petitioner path for user role petitioner', async () => { - presenter.providers.applicationContext.getCurrentUser = () => ({ - role: ROLES.petitioner, - }); await runAction(runPathForUserRoleAction, { modules: { presenter, }, - state: {}, + state: { + user: { + role: ROLES.petitioner, + }, + }, }); expect(petitionerStub.mock.calls.length).toEqual(1); }); it('should return the privatePractitioner path for user role privatePractitioner', async () => { - presenter.providers.applicationContext.getCurrentUser = () => ({ - role: ROLES.privatePractitioner, - }); await runAction(runPathForUserRoleAction, { modules: { presenter, }, - state: {}, + state: { + user: { + role: ROLES.privatePractitioner, + }, + }, }); expect(privatePractitionerStub.mock.calls.length).toEqual(1); }); it('should return the irsPractitioner path for user role irsPractitioner', async () => { - presenter.providers.applicationContext.getCurrentUser = () => ({ - role: ROLES.irsPractitioner, - }); await runAction(runPathForUserRoleAction, { modules: { presenter, }, - state: {}, + state: { + user: { + role: ROLES.irsPractitioner, + }, + }, }); expect(irsPractitionerStub.mock.calls.length).toEqual(1); }); it('should return the petitionsclerk path for user role petitionsclerk', async () => { - presenter.providers.applicationContext.getCurrentUser = () => ({ - role: ROLES.petitionsClerk, - }); await runAction(runPathForUserRoleAction, { modules: { presenter, }, - state: {}, + state: { + user: { + role: ROLES.petitionsClerk, + }, + }, }); expect(petitionsclerkStub.mock.calls.length).toEqual(1); }); it('should return the docketclerk path for user role docketclerk', async () => { - presenter.providers.applicationContext.getCurrentUser = () => ({ - role: ROLES.docketClerk, - }); await runAction(runPathForUserRoleAction, { modules: { presenter, }, - state: {}, + state: { + user: { + role: ROLES.docketClerk, + }, + }, }); expect(docketclerkStub.mock.calls.length).toEqual(1); }); it('should return the judge path for user role judge', async () => { - presenter.providers.applicationContext.getCurrentUser = () => ({ - role: ROLES.judge, - }); await runAction(runPathForUserRoleAction, { modules: { presenter, }, - state: {}, + state: { + user: { + role: ROLES.judge, + }, + }, }); expect(judgeStub.mock.calls.length).toEqual(1); }); diff --git a/web-client/src/presenter/actions/runPathForUserRoleAction.ts b/web-client/src/presenter/actions/runPathForUserRoleAction.ts index 7698bb42f24..460fbcd1253 100644 --- a/web-client/src/presenter/actions/runPathForUserRoleAction.ts +++ b/web-client/src/presenter/actions/runPathForUserRoleAction.ts @@ -1,3 +1,5 @@ +import { state } from '@web-client/presenter/app.cerebral'; + /** * get the role associated with the user * @param {object} providers the providers object @@ -5,11 +7,8 @@ * @param {object} providers.path the cerebral path object used for invoking the next path in the sequence based on the user's role * @returns {object} the path to call based on the user role */ -export const runPathForUserRoleAction = ({ - applicationContext, - path, -}: ActionProps) => { - const user = applicationContext.getCurrentUser(); +export const runPathForUserRoleAction = ({ get, path }: ActionProps) => { + const user = get(state.user); if (typeof path[user.role] !== 'function') { throw new Error(`No path available for ${JSON.stringify(user)}`); diff --git a/web-client/src/presenter/actions/saveAndSubmitCaseAction.ts b/web-client/src/presenter/actions/saveAndSubmitCaseAction.ts index e73f44f1131..52eebd0e098 100644 --- a/web-client/src/presenter/actions/saveAndSubmitCaseAction.ts +++ b/web-client/src/presenter/actions/saveAndSubmitCaseAction.ts @@ -1,4 +1,4 @@ -import { ElectronicCreatedCaseType } from '@shared/business/useCases/createCaseInteractor'; +import { ElectronicCreatedCaseType } from '@web-api/business/useCases/createCaseInteractor'; import { FileUploadProgressType, FileUploadProgressValueType, @@ -20,6 +20,8 @@ export const saveAndSubmitCaseAction = async ({ state.petitionFormatted, ); + const user = get(state.user); + let caseDetail; let stinFile; @@ -29,9 +31,9 @@ export const saveAndSubmitCaseAction = async ({ corporateDisclosureFileId, petitionFileId, stinFileId, - } = await applicationContext - .getUseCases() - .generateDocumentIds(applicationContext, { + } = await applicationContext.getUseCases().generateDocumentIds( + applicationContext, + { attachmentToPetitionUploadProgress: fileUploadProgressMap.attachmentToPetition as FileUploadProgressType[], corporateDisclosureUploadProgress: @@ -40,7 +42,9 @@ export const saveAndSubmitCaseAction = async ({ fileUploadProgressMap.petition as FileUploadProgressType, stinUploadProgress: fileUploadProgressMap.stin as FileUploadProgressType, - }); + }, + user, + ); stinFile = stinFileId; diff --git a/web-client/src/presenter/actions/setDefaultGenerationTypeAction.test.ts b/web-client/src/presenter/actions/setDefaultGenerationTypeAction.test.ts index 3a2b83924ad..2a7285d3c48 100644 --- a/web-client/src/presenter/actions/setDefaultGenerationTypeAction.test.ts +++ b/web-client/src/presenter/actions/setDefaultGenerationTypeAction.test.ts @@ -11,8 +11,6 @@ import { setDefaultGenerationTypeAction } from './setDefaultGenerationTypeAction describe('setDefaultGenerationTypeAction', () => { presenter.providers.applicationContext = applicationContext; - applicationContext.getCurrentUser.mockReturnValue(privatePractitionerUser); - it('should set the generation type to auto when the changed event code is EA', async () => { const { state } = await runAction(setDefaultGenerationTypeAction, { modules: { presenter }, @@ -27,6 +25,7 @@ describe('setDefaultGenerationTypeAction', () => { form: { generationType: GENERATION_TYPES.MANUAL, }, + user: privatePractitionerUser, }, }); @@ -47,6 +46,7 @@ describe('setDefaultGenerationTypeAction', () => { form: { generationType: GENERATION_TYPES.AUTO, }, + user: privatePractitionerUser, }, }); @@ -54,8 +54,6 @@ describe('setDefaultGenerationTypeAction', () => { }); it('should set the generation type to manual when the changed event code is NOT EA and the user is an IRS Practitioner', async () => { - applicationContext.getCurrentUser.mockReturnValueOnce(irsPractitionerUser); - const { state } = await runAction(setDefaultGenerationTypeAction, { modules: { presenter }, props: { @@ -69,6 +67,7 @@ describe('setDefaultGenerationTypeAction', () => { form: { generationType: GENERATION_TYPES.AUTO, }, + user: irsPractitionerUser, }, }); @@ -76,8 +75,6 @@ describe('setDefaultGenerationTypeAction', () => { }); it('should set the generation type to "auto"" when the changed event code is EA and the user is an IRS Practitioner with no parties having paper service', async () => { - applicationContext.getCurrentUser.mockReturnValueOnce(irsPractitionerUser); - const { state } = await runAction(setDefaultGenerationTypeAction, { modules: { presenter }, props: { @@ -91,6 +88,8 @@ describe('setDefaultGenerationTypeAction', () => { form: { generationType: GENERATION_TYPES.MANUAL, }, + + user: irsPractitionerUser, }, }); @@ -111,6 +110,7 @@ describe('setDefaultGenerationTypeAction', () => { form: { generationType: GENERATION_TYPES.AUTO, }, + user: privatePractitionerUser, }, }); @@ -118,8 +118,6 @@ describe('setDefaultGenerationTypeAction', () => { }); it('should set the generation type to manual if code is EA but a petitioner has paper', async () => { - applicationContext.getCurrentUser.mockReturnValueOnce(irsPractitionerUser); - const { state } = await runAction(setDefaultGenerationTypeAction, { modules: { presenter }, props: { @@ -137,6 +135,7 @@ describe('setDefaultGenerationTypeAction', () => { form: { generationType: GENERATION_TYPES.AUTO, }, + user: irsPractitionerUser, }, }); @@ -162,6 +161,7 @@ describe('setDefaultGenerationTypeAction', () => { form: { generationType: GENERATION_TYPES.MANUAL, }, + user: privatePractitionerUser, }, }); diff --git a/web-client/src/presenter/actions/setDefaultGenerationTypeAction.ts b/web-client/src/presenter/actions/setDefaultGenerationTypeAction.ts index 224a2f114b4..bbc46a15735 100644 --- a/web-client/src/presenter/actions/setDefaultGenerationTypeAction.ts +++ b/web-client/src/presenter/actions/setDefaultGenerationTypeAction.ts @@ -16,7 +16,7 @@ export const setDefaultGenerationTypeAction = async ({ const { GENERATION_TYPES } = applicationContext.getConstants(); const petitioners = get(state.caseDetail.petitioners); - const user = await applicationContext.getCurrentUser(); + const user = get(state.user); if (props.key === 'eventCode') { const showGenerationTypeForm = showGenerationType( diff --git a/web-client/src/presenter/actions/setSignatureNameForPdfSigningAction.test.ts b/web-client/src/presenter/actions/setSignatureNameForPdfSigningAction.test.ts index 36548e65c26..294160644a2 100644 --- a/web-client/src/presenter/actions/setSignatureNameForPdfSigningAction.test.ts +++ b/web-client/src/presenter/actions/setSignatureNameForPdfSigningAction.test.ts @@ -10,10 +10,6 @@ describe('setSignatureNameForPdfSigningAction', () => { const { ALLOWLIST_FEATURE_FLAGS, CHIEF_JUDGE } = applicationContext.getConstants(); - let user = { - section: 'colvinChambers', - }; - let judgeUser: RawUser; beforeAll(() => { @@ -28,18 +24,19 @@ describe('setSignatureNameForPdfSigningAction', () => { [ALLOWLIST_FEATURE_FLAGS.CHIEF_JUDGE_NAME.key]: 'Oscar the Grouch', }); - applicationContext.getCurrentUser.mockReturnValue(user); - presenter.providers.applicationContext = applicationContext; }); it('sets the Chief Judge for non chamber users', async () => { - user.section = 'docketclerk'; - const result = await runAction(setSignatureNameForPdfSigningAction, { modules: { presenter, }, + state: { + user: { + section: 'docketclerk', + }, + }, }); expect(result.state.pdfForSigning.nameForSigning).toEqual( 'Oscar the Grouch', @@ -50,11 +47,15 @@ describe('setSignatureNameForPdfSigningAction', () => { it('sets the chamber judge for chamber users', async () => { judgeUser.judgeFullName = 'John O. Colvin'; judgeUser.judgeTitle = 'Judge'; - user.section = 'colvinChambers'; const result = await runAction(setSignatureNameForPdfSigningAction, { modules: { presenter, }, + state: { + user: { + section: 'colvinChambers', + }, + }, }); expect(result.state.pdfForSigning.nameForSigning).toEqual('John O. Colvin'); expect(result.state.pdfForSigning.nameForSigningLine2).toEqual('Judge'); @@ -63,11 +64,15 @@ describe('setSignatureNameForPdfSigningAction', () => { it('sets special trial for special trial judge', async () => { judgeUser.judgeFullName = 'John O. Colvin'; judgeUser.judgeTitle = 'Special Trial Judge'; - user.section = 'colvinChambers'; const result = await runAction(setSignatureNameForPdfSigningAction, { modules: { presenter, }, + state: { + user: { + section: 'colvinChambers', + }, + }, }); expect(result.state.pdfForSigning.nameForSigning).toEqual('John O. Colvin'); expect(result.state.pdfForSigning.nameForSigningLine2).toEqual( diff --git a/web-client/src/presenter/actions/setSignatureNameForPdfSigningAction.ts b/web-client/src/presenter/actions/setSignatureNameForPdfSigningAction.ts index 1abdad66c57..00996476e97 100644 --- a/web-client/src/presenter/actions/setSignatureNameForPdfSigningAction.ts +++ b/web-client/src/presenter/actions/setSignatureNameForPdfSigningAction.ts @@ -8,9 +8,10 @@ import { state } from '@web-client/presenter/app.cerebral'; */ export const setSignatureNameForPdfSigningAction = async ({ applicationContext, + get, store, }: ActionProps) => { - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { ALLOWLIST_FEATURE_FLAGS, CHIEF_JUDGE } = applicationContext.getConstants(); diff --git a/web-client/src/presenter/actions/setUserAction.test.ts b/web-client/src/presenter/actions/setUserAction.test.ts index f12b62e2753..edd73185bd1 100644 --- a/web-client/src/presenter/actions/setUserAction.test.ts +++ b/web-client/src/presenter/actions/setUserAction.test.ts @@ -14,11 +14,11 @@ describe('setUserAction', () => { delete global.window; }); - it('stores the user onto the application context', async () => { + it('stores the user cerebral state', async () => { const user = { userId: 'petitioner', }; - await runAction(setUserAction, { + const { state } = await runAction(setUserAction, { modules: { presenter, }, @@ -27,9 +27,6 @@ describe('setUserAction', () => { }, state: {}, }); - expect(applicationContext.setCurrentUser.mock.calls.length).toEqual(1); - expect(applicationContext.setCurrentUser.mock.calls[0][0]).toMatchObject( - user, - ); + expect(state.user).toEqual(user); }); }); diff --git a/web-client/src/presenter/actions/setUserAction.ts b/web-client/src/presenter/actions/setUserAction.ts index 1c1055c9b68..30f55de36fa 100644 --- a/web-client/src/presenter/actions/setUserAction.ts +++ b/web-client/src/presenter/actions/setUserAction.ts @@ -5,13 +5,7 @@ import { state } from '@web-client/presenter/app.cerebral'; * @param {object} providers the providers object * @param {object} providers.store the cerebral store used for setting state.user * @param {object} providers.props the cerebral props object used for getting the props.user - * @param {object} providers.applicationContext the application context needed for getting the setCurrentUser method */ -export const setUserAction = ({ - applicationContext, - props, - store, -}: ActionProps) => { +export const setUserAction = ({ props, store }: ActionProps) => { store.set(state.user, props.user); - applicationContext.setCurrentUser(props.user); }; diff --git a/web-client/src/presenter/actions/setUserPermissionsAction.test.ts b/web-client/src/presenter/actions/setUserPermissionsAction.test.ts index a155b3449bb..461b59b7027 100644 --- a/web-client/src/presenter/actions/setUserPermissionsAction.test.ts +++ b/web-client/src/presenter/actions/setUserPermissionsAction.test.ts @@ -1,6 +1,5 @@ import { ROLES } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; -import { getUserPermissions } from '../../../../shared/src/authorization/getUserPermissions'; import { presenter } from '../presenter-mock'; import { runAction } from '@web-client/presenter/test.cerebral'; import { setUserPermissionsAction } from './setUserPermissionsAction'; @@ -13,10 +12,6 @@ describe('setUserPermissionsAction', () => { }); it('set state.permissions based on the user role', async () => { - applicationContext.getCurrentUserPermissions.mockReturnValue( - getUserPermissions(mockUser), - ); - const result = await runAction(setUserPermissionsAction, { modules: { presenter, diff --git a/web-client/src/presenter/actions/setUserPermissionsAction.ts b/web-client/src/presenter/actions/setUserPermissionsAction.ts index 3f629a4d7c0..c14b42636fe 100644 --- a/web-client/src/presenter/actions/setUserPermissionsAction.ts +++ b/web-client/src/presenter/actions/setUserPermissionsAction.ts @@ -1,3 +1,4 @@ +import { getUserPermissions } from '@shared/authorization/getUserPermissions'; import { state } from '@web-client/presenter/app.cerebral'; /** @@ -6,10 +7,8 @@ import { state } from '@web-client/presenter/app.cerebral'; * @param {object} providers.applicationContext the application context * @param {object} providers.store the cerebral store object */ -export const setUserPermissionsAction = ({ - applicationContext, - store, -}: ActionProps) => { - const userPermissions = applicationContext.getCurrentUserPermissions(); +export const setUserPermissionsAction = ({ get, store }: ActionProps) => { + const user = get(state.user); + const userPermissions = getUserPermissions(user); store.set(state.permissions, userPermissions); }; diff --git a/web-client/src/presenter/actions/startRefreshIntervalAction.ts b/web-client/src/presenter/actions/startRefreshIntervalAction.ts index b69ae2548ce..b516713c68b 100644 --- a/web-client/src/presenter/actions/startRefreshIntervalAction.ts +++ b/web-client/src/presenter/actions/startRefreshIntervalAction.ts @@ -1,3 +1,4 @@ +import { setCurrentUserToken } from '@shared/proxies/requests'; import { state } from '@web-client/presenter/app.cerebral'; export const startRefreshIntervalAction = ({ @@ -15,7 +16,7 @@ export const startRefreshIntervalAction = ({ .renewIdTokenInteractor(applicationContext); store.set(state.token, response.idToken); - applicationContext.setCurrentUserToken(response.idToken); + setCurrentUserToken(response.idToken); } }; diff --git a/web-client/src/presenter/actions/updateUserContactInformationAction.test.ts b/web-client/src/presenter/actions/updateUserContactInformationAction.test.ts index 1bf8eb28c22..f746389376f 100644 --- a/web-client/src/presenter/actions/updateUserContactInformationAction.test.ts +++ b/web-client/src/presenter/actions/updateUserContactInformationAction.test.ts @@ -18,12 +18,14 @@ describe('updateUserContactInformationAction', () => { contact: { address1: '999 Jump St' }, firmName: 'testing', }, + user: {}, }, }); expect(result.state.userContactEditProgress.inProgress).toBe(true); }); it('should call the use case to update the user contact', async () => { + const userId = 'a805d1ab-18d0-43ec-bafb-654e83405416'; await runAction(updateUserContactInformationAction, { modules: { presenter, @@ -33,6 +35,7 @@ describe('updateUserContactInformationAction', () => { contact: { address1: '999 Jump St' }, firmName: 'testing', }, + user: { userId }, }, }); expect( @@ -46,7 +49,7 @@ describe('updateUserContactInformationAction', () => { address1: '999 Jump St', }, firmName: 'testing', - userId: 'a805d1ab-18d0-43ec-bafb-654e83405416', + userId, }); }); }); diff --git a/web-client/src/presenter/actions/updateUserContactInformationAction.ts b/web-client/src/presenter/actions/updateUserContactInformationAction.ts index 9bd9c1325c8..d53bbd6b9ee 100644 --- a/web-client/src/presenter/actions/updateUserContactInformationAction.ts +++ b/web-client/src/presenter/actions/updateUserContactInformationAction.ts @@ -12,7 +12,7 @@ export const updateUserContactInformationAction = async ({ store, }: ActionProps) => { const formUser = get(state.form); - const currentUser = applicationContext.getCurrentUser(); + const currentUser = get(state.user); store.set(state.userContactEditProgress.inProgress, true); diff --git a/web-client/src/presenter/actions/updatedValidatePetitionAction.ts b/web-client/src/presenter/actions/updatedValidatePetitionAction.ts index de2ad753ef2..fd8e80ed2f0 100644 --- a/web-client/src/presenter/actions/updatedValidatePetitionAction.ts +++ b/web-client/src/presenter/actions/updatedValidatePetitionAction.ts @@ -4,7 +4,7 @@ export const updatedValidatePetitionAction = ({ applicationContext, get, path, -}: ActionProps<{}, IApplicationContext>) => { +}: ActionProps) => { const petition = get(state.petitionFormatted); const errors = applicationContext diff --git a/web-client/src/presenter/actions/validateCaseDetailAction.test.ts b/web-client/src/presenter/actions/validateCaseDetailAction.test.ts index f45747080d8..2e07ad00759 100644 --- a/web-client/src/presenter/actions/validateCaseDetailAction.test.ts +++ b/web-client/src/presenter/actions/validateCaseDetailAction.test.ts @@ -41,7 +41,7 @@ describe('validateCaseDetail', () => { }); expect( applicationContext.getUseCases().validateCaseDetailInteractor.mock - .calls[0][1].caseDetail, + .calls[0][0].caseDetail, ).toMatchObject({ docketNumber: '123-45', irsNoticeDate: '2009-10-13', diff --git a/web-client/src/presenter/actions/validateCaseDetailAction.ts b/web-client/src/presenter/actions/validateCaseDetailAction.ts index 245cef41aaa..c892d57e846 100644 --- a/web-client/src/presenter/actions/validateCaseDetailAction.ts +++ b/web-client/src/presenter/actions/validateCaseDetailAction.ts @@ -11,20 +11,22 @@ export const validateCaseDetailAction = ({ store, }: ActionProps) => { const form = get(state.form); + const user = get(state.user); let errors; if (form.isPaper) { errors = applicationContext .getUseCases() - .validatePetitionFromPaperInteractor(applicationContext, { + .validatePetitionFromPaperInteractor(user, { petition: form, }); } else { - errors = applicationContext - .getUseCases() - .validateCaseDetailInteractor(applicationContext, { + errors = applicationContext.getUseCases().validateCaseDetailInteractor( + { caseDetail: form, - }); + }, + user, + ); } errors = aggregatePetitionerErrors({ errors }); diff --git a/web-client/src/presenter/actions/validateCaseDetailsAction.test.ts b/web-client/src/presenter/actions/validateCaseDetailsAction.test.ts index 41dc0045f0a..6e9a2273905 100644 --- a/web-client/src/presenter/actions/validateCaseDetailsAction.test.ts +++ b/web-client/src/presenter/actions/validateCaseDetailsAction.test.ts @@ -43,7 +43,7 @@ describe('validateCaseDetailsAction', () => { expect( applicationContext.getUseCases().validateCaseDetailInteractor.mock - .calls[0][1].caseDetail, + .calls[0][0].caseDetail, ).toMatchObject({ petitionPaymentDate: '2019-09-06T04:00:00.000Z', petitionPaymentMethod: 'check', @@ -67,7 +67,7 @@ describe('validateCaseDetailsAction', () => { expect( applicationContext.getUseCases().validateCaseDetailInteractor.mock - .calls[0][1].caseDetail, + .calls[0][0].caseDetail, ).toMatchObject({ petitionPaymentStatus: PAYMENT_STATUS.UNPAID, }); @@ -90,7 +90,7 @@ describe('validateCaseDetailsAction', () => { expect( applicationContext.getUseCases().validateCaseDetailInteractor.mock - .calls[0][1].caseDetail, + .calls[0][0].caseDetail, ).toMatchObject({ petitionPaymentStatus: PAYMENT_STATUS.WAIVED, petitionPaymentWaivedDate: '2001-01-01T05:00:00.000Z', @@ -113,7 +113,7 @@ describe('validateCaseDetailsAction', () => { expect( applicationContext.getUseCases().validateCaseDetailInteractor.mock - .calls[0][1].caseDetail, + .calls[0][0].caseDetail, ).toMatchObject({ irsNoticeDate: '2001-01-01T05:00:00.000Z', }); @@ -133,7 +133,7 @@ describe('validateCaseDetailsAction', () => { expect( applicationContext.getUseCases().validateCaseDetailInteractor.mock - .calls[0][1].caseDetail, + .calls[0][0].caseDetail, ).toMatchObject({ preferredTrialCity: null, }); @@ -153,7 +153,7 @@ describe('validateCaseDetailsAction', () => { expect( applicationContext.getUseCases().validateCaseDetailInteractor.mock - .calls[0][1].caseDetail, + .calls[0][0].caseDetail, ).toMatchObject({ preferredTrialCity: 'Fresno, California', }); diff --git a/web-client/src/presenter/actions/validateCaseDetailsAction.ts b/web-client/src/presenter/actions/validateCaseDetailsAction.ts index 36db4e3f895..65cf0ad457b 100644 --- a/web-client/src/presenter/actions/validateCaseDetailsAction.ts +++ b/web-client/src/presenter/actions/validateCaseDetailsAction.ts @@ -9,18 +9,22 @@ export const validateCaseDetailsAction = async ({ }: ActionProps) => { const caseDetail = get(state.caseDetail); const form = get(state.form); + const user = get(state.user); let errors = await applicationContext .getUseCases() - .validateCaseDetailInteractor(applicationContext, { - caseDetail: { - ...caseDetail, - ...form, - preferredTrialCity: form.preferredTrialCity - ? form.preferredTrialCity - : null, + .validateCaseDetailInteractor( + { + caseDetail: { + ...caseDetail, + ...form, + preferredTrialCity: form.preferredTrialCity + ? form.preferredTrialCity + : null, + }, }, - }); + user, + ); if (!errors) { return path.success(); diff --git a/web-client/src/presenter/actions/validateNoteOnCaseDetailAction.test.ts b/web-client/src/presenter/actions/validateNoteOnCaseDetailAction.test.ts index c1a0def0c8f..5d08f3d8b33 100644 --- a/web-client/src/presenter/actions/validateNoteOnCaseDetailAction.test.ts +++ b/web-client/src/presenter/actions/validateNoteOnCaseDetailAction.test.ts @@ -78,7 +78,7 @@ describe('validateNoteOnCaseDetailAction', () => { expect( applicationContext.getUseCases().validateCaseDetailInteractor.mock - .calls[0][1], + .calls[0][0], ).toMatchObject({ useCaseEntity: true }); }); }); diff --git a/web-client/src/presenter/actions/validateNoteOnCaseDetailAction.ts b/web-client/src/presenter/actions/validateNoteOnCaseDetailAction.ts index e485da6b127..9dfd29d661b 100644 --- a/web-client/src/presenter/actions/validateNoteOnCaseDetailAction.ts +++ b/web-client/src/presenter/actions/validateNoteOnCaseDetailAction.ts @@ -15,13 +15,15 @@ export const validateNoteOnCaseDetailAction = ({ }: ActionProps) => { const caseDetail = get(state.caseDetail); const note = get(state.modal.notes); + const user = get(state.user); - const errors = applicationContext - .getUseCases() - .validateCaseDetailInteractor(applicationContext, { + const errors = applicationContext.getUseCases().validateCaseDetailInteractor( + { caseDetail: { ...caseDetail, caseNote: note }, useCaseEntity: true, - }); + }, + user, + ); if (!errors) { return path.success(); diff --git a/web-client/src/presenter/actions/validatePetitionFromPaperAction.ts b/web-client/src/presenter/actions/validatePetitionFromPaperAction.ts index 6ce49fa0e7c..bdc68140fa0 100644 --- a/web-client/src/presenter/actions/validatePetitionFromPaperAction.ts +++ b/web-client/src/presenter/actions/validatePetitionFromPaperAction.ts @@ -74,10 +74,11 @@ export const validatePetitionFromPaperAction = ({ path, }: ActionProps) => { const form = get(state.form); + const user = get(state.user); let errors = applicationContext .getUseCases() - .validatePetitionFromPaperInteractor(applicationContext, { + .validatePetitionFromPaperInteractor(user, { petition: form, }); diff --git a/web-client/src/presenter/actions/validateUserContactAction.test.ts b/web-client/src/presenter/actions/validateUserContactAction.test.ts index 55cb4b91cc3..6c0af36d0f3 100644 --- a/web-client/src/presenter/actions/validateUserContactAction.test.ts +++ b/web-client/src/presenter/actions/validateUserContactAction.test.ts @@ -23,7 +23,7 @@ describe('validateUserContactAction', () => { modules: { presenter, }, - state: { form: { contact: {} } }, + state: { form: { contact: {} }, user: {} }, }); expect(errorMock).toHaveBeenCalled(); }); @@ -36,7 +36,7 @@ describe('validateUserContactAction', () => { modules: { presenter, }, - state: { form: { contact: {} } }, + state: { form: { contact: {} }, user: {} }, }); expect(successMock).toHaveBeenCalled(); }); diff --git a/web-client/src/presenter/actions/validateUserContactAction.ts b/web-client/src/presenter/actions/validateUserContactAction.ts index d69e20c6078..72c61c286c2 100644 --- a/web-client/src/presenter/actions/validateUserContactAction.ts +++ b/web-client/src/presenter/actions/validateUserContactAction.ts @@ -14,7 +14,7 @@ export const validateUserContactAction = ({ path, }: ActionProps) => { const formContact = get(state.form); - const currentUser = applicationContext.getCurrentUser(); + const currentUser = get(state.user); const errors = applicationContext .getUseCases() diff --git a/web-client/src/presenter/computeds/AdvancedSearch/advancedSearchHelper.test.ts b/web-client/src/presenter/computeds/AdvancedSearch/advancedSearchHelper.test.ts index f1f4be9a917..9608dbfc24a 100644 --- a/web-client/src/presenter/computeds/AdvancedSearch/advancedSearchHelper.test.ts +++ b/web-client/src/presenter/computeds/AdvancedSearch/advancedSearchHelper.test.ts @@ -3,6 +3,7 @@ import { paginationHelper, } from './advancedSearchHelper'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; +import { docketClerk1User } from '@shared/test/mockUsers'; import { getUserPermissions } from '../../../../../shared/src/authorization/getUserPermissions'; import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../../withAppContext'; @@ -18,6 +19,7 @@ describe('advancedSearchHelper', () => { const getBaseState = user => { return { permissions: getUserPermissions(user), + user, }; }; @@ -32,9 +34,6 @@ describe('advancedSearchHelper', () => { MAX_SEARCH_RESULTS: maxSearchResultsOverride, }; }, - getCurrentUser: () => { - return globalUser; - }, }, ); @@ -50,10 +49,7 @@ describe('advancedSearchHelper', () => { }; beforeEach(() => { - globalUser = { - role: USER_ROLES.docketClerk, - userId: 'docketClerk', - }; + globalUser = docketClerk1User; }); it('returns appropriate defaults if permissions are not defined in state', () => { diff --git a/web-client/src/presenter/computeds/AdvancedSearch/practitionerSearchHelper.test.ts b/web-client/src/presenter/computeds/AdvancedSearch/practitionerSearchHelper.test.ts index 7631994e3c0..a6db9057d49 100644 --- a/web-client/src/presenter/computeds/AdvancedSearch/practitionerSearchHelper.test.ts +++ b/web-client/src/presenter/computeds/AdvancedSearch/practitionerSearchHelper.test.ts @@ -26,9 +26,6 @@ describe('practitionerSearchHelper', () => { PRACTITIONER_SEARCH_PAGE_SIZE: pageSizeOverride, }; }, - getCurrentUser: () => { - return globalUser; - }, }, ); @@ -85,9 +82,6 @@ describe('practitionerSearchHelper', () => { PRACTITIONER_SEARCH_PAGE_SIZE: pageSizeOverride, }; }, - getCurrentUser: () => { - return globalUser; - }, isPublicUser: () => true, }, ); diff --git a/web-client/src/presenter/computeds/TrialSession/addTrialSessionInformationHelper.test.ts b/web-client/src/presenter/computeds/TrialSession/addTrialSessionInformationHelper.test.ts index c94868e43cc..dbc6603e246 100644 --- a/web-client/src/presenter/computeds/TrialSession/addTrialSessionInformationHelper.test.ts +++ b/web-client/src/presenter/computeds/TrialSession/addTrialSessionInformationHelper.test.ts @@ -20,6 +20,7 @@ describe('addTrialSessionInformationHelper', () => { const result = runCompute(addTrialSessionInformationHelper, { state: { form: { proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.remote }, + user: { role: 'docketclerk' }, }, }); @@ -30,6 +31,7 @@ describe('addTrialSessionInformationHelper', () => { const result = runCompute(addTrialSessionInformationHelper, { state: { form: { sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote }, + user: { role: 'docketclerk' }, }, }); @@ -40,6 +42,7 @@ describe('addTrialSessionInformationHelper', () => { const result = runCompute(addTrialSessionInformationHelper, { state: { form: { proceedingType: 'def', sessionScope: 'abc' }, + user: { role: 'docketclerk' }, }, }); @@ -52,6 +55,7 @@ describe('addTrialSessionInformationHelper', () => { const result = runCompute(addTrialSessionInformationHelper, { state: { form: { sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote }, + user: { role: 'docketclerk' }, }, }); @@ -62,6 +66,7 @@ describe('addTrialSessionInformationHelper', () => { const result = runCompute(addTrialSessionInformationHelper, { state: { form: { sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased }, + user: { role: 'docketclerk' }, }, }); @@ -74,6 +79,7 @@ describe('addTrialSessionInformationHelper', () => { const result = runCompute(addTrialSessionInformationHelper, { state: { form: { sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote }, + user: { role: 'docketclerk' }, }, }); @@ -84,6 +90,7 @@ describe('addTrialSessionInformationHelper', () => { const result = runCompute(addTrialSessionInformationHelper, { state: { form: { sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased }, + user: { role: 'docketclerk' }, }, }); @@ -96,6 +103,7 @@ describe('addTrialSessionInformationHelper', () => { const result = runCompute(addTrialSessionInformationHelper, { state: { form: { sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote }, + user: { role: 'docketclerk' }, }, }); @@ -106,6 +114,7 @@ describe('addTrialSessionInformationHelper', () => { const result = runCompute(addTrialSessionInformationHelper, { state: { form: { sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased }, + user: { role: 'docketclerk' }, }, }); @@ -115,9 +124,11 @@ describe('addTrialSessionInformationHelper', () => { describe('sessionTypes', () => { it(`should NOT include 'Special' or 'Motion/Hearing' when form.sessionScope is ${TRIAL_SESSION_SCOPE_TYPES.standaloneRemote}`, () => { + const user = { role: 'clerkofclerk' }; const result = runCompute(addTrialSessionInformationHelper, { state: { form: { sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote }, + user, }, }); @@ -130,9 +141,11 @@ describe('addTrialSessionInformationHelper', () => { }); it(`should include 'Special' and 'Motion/Hearing' when form.sessionScope is ${TRIAL_SESSION_SCOPE_TYPES.locationBased}`, () => { + const user = { role: 'clerkofclerk' }; const result = runCompute(addTrialSessionInformationHelper, { state: { form: { sessionScope: TRIAL_SESSION_SCOPE_TYPES.locationBased }, + user, }, }); @@ -145,5 +158,17 @@ describe('addTrialSessionInformationHelper', () => { 'Motion/Hearing', ]); }); + + it("should ONLY include 'Special' or 'Motion/Hearing' trial sessions when role is docketclerk}", () => { + const user = { role: 'docketclerk' }; + const result = runCompute(addTrialSessionInformationHelper, { + state: { + form: { sessionScope: TRIAL_SESSION_SCOPE_TYPES.standaloneRemote }, + user, + }, + }); + + expect(result.sessionTypes).toEqual(['Special', 'Motion/Hearing']); + }); }); }); diff --git a/web-client/src/presenter/computeds/TrialSession/addTrialSessionInformationHelper.ts b/web-client/src/presenter/computeds/TrialSession/addTrialSessionInformationHelper.ts index 69aacb3aa1a..053875fd7db 100644 --- a/web-client/src/presenter/computeds/TrialSession/addTrialSessionInformationHelper.ts +++ b/web-client/src/presenter/computeds/TrialSession/addTrialSessionInformationHelper.ts @@ -1,3 +1,4 @@ +import { AuthUser } from '@shared/business/entities/authUser/AuthUser'; import { ClientApplicationContext } from '@web-client/applicationContext'; import { FORMATS } from '../../../../../shared/src/business/utilities/DateHandler'; import { Get } from 'cerebral'; @@ -7,7 +8,13 @@ import { state } from '@web-client/presenter/app.cerebral'; export const addTrialSessionInformationHelper = ( get: Get, applicationContext: ClientApplicationContext, -): any => { +): { + displayRemoteProceedingForm: boolean; + isStandaloneSession: boolean; + sessionTypes: string[]; + title: string; + today: string; +} => { const { SESSION_TYPES, TRIAL_SESSION_PROCEEDING_TYPES } = applicationContext.getConstants(); @@ -23,20 +30,29 @@ export const addTrialSessionInformationHelper = ( proceedingType === TRIAL_SESSION_PROCEEDING_TYPES.remote || isStandaloneSession; + const DISALLOWED_STANDALONE_SESSION_TYPES = ['Special', 'Motion/Hearing']; + const DOCKETCLERK_EDITABLE_SESSION_TYPES = ['Special', 'Motion/Hearing']; + let sessionTypes = Object.values(SESSION_TYPES); if (isStandaloneSession) { sessionTypes = sessionTypes.filter(type => { - return !['Special', 'Motion/Hearing'].includes(type); + return !DISALLOWED_STANDALONE_SESSION_TYPES.includes(type); }); } + // NOTE: what happens if isStandaloneSession is true and user is docketclerk? + const getSessionTypes = (user: AuthUser) => { + return user.role === 'docketclerk' + ? DOCKETCLERK_EDITABLE_SESSION_TYPES + : sessionTypes; + }; const today = applicationContext.getUtilities().formatNow(FORMATS.YYYYMMDD); return { displayRemoteProceedingForm, isStandaloneSession, - sessionTypes, + sessionTypes: getSessionTypes(get(state.user)), title, today, }; diff --git a/web-client/src/presenter/computeds/addCourtIssuedDocketEntryHelper.test.ts b/web-client/src/presenter/computeds/addCourtIssuedDocketEntryHelper.test.ts index f811434af3b..1bbec8ab36b 100644 --- a/web-client/src/presenter/computeds/addCourtIssuedDocketEntryHelper.test.ts +++ b/web-client/src/presenter/computeds/addCourtIssuedDocketEntryHelper.test.ts @@ -70,11 +70,10 @@ describe('addCourtIssuedDocketEntryHelper', () => { form: { generatedDocumentTitle: 'Circle of Life', }, + user, }; beforeEach(() => { - applicationContext.getCurrentUser.mockImplementation(() => user); - applicationContext.getConstants.mockImplementation(() => mockConstants); }); @@ -208,6 +207,7 @@ describe('addCourtIssuedDocketEntryHelper', () => { it('should return showSaveAndServeButton false if eventCode is found in unservable event codes list', () => { const result = runCompute(addCourtIssuedDocketEntryHelper, { state: { + ...state, caseDetail: { ...state.caseDetail, docketEntries: [ @@ -229,6 +229,7 @@ describe('addCourtIssuedDocketEntryHelper', () => { it('should return showServiceWarning true and showSaveAndServeButton false if the case can NOT allow service', () => { const result = runCompute(addCourtIssuedDocketEntryHelper, { state: { + ...state, caseDetail: { ...state.caseDetail, docketEntries: [ @@ -253,6 +254,7 @@ describe('addCourtIssuedDocketEntryHelper', () => { it('should return showServiceWarning true and showSaveAndServeButton false if eventCode is NOT found in unservable event codes list and case can NOT allow service', () => { const result = runCompute(addCourtIssuedDocketEntryHelper, { state: { + ...state, caseDetail: { ...state.caseDetail, docketEntries: [ @@ -281,6 +283,7 @@ describe('addCourtIssuedDocketEntryHelper', () => { it('should return showServiceWarning false and showSaveAndServeButton true if eventCode is NOT found in unservable event codes list and case can allow service', () => { const result = runCompute(addCourtIssuedDocketEntryHelper, { state: { + ...state, caseDetail: { ...state.caseDetail, docketEntries: [ diff --git a/web-client/src/presenter/computeds/addCourtIssuedDocketEntryHelper.ts b/web-client/src/presenter/computeds/addCourtIssuedDocketEntryHelper.ts index 4af3990dcc6..5445778df72 100644 --- a/web-client/src/presenter/computeds/addCourtIssuedDocketEntryHelper.ts +++ b/web-client/src/presenter/computeds/addCourtIssuedDocketEntryHelper.ts @@ -20,7 +20,7 @@ export const addCourtIssuedDocketEntryHelper = ( const form = get(state.form); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const eventCodes = COURT_ISSUED_EVENT_CODES; diff --git a/web-client/src/presenter/computeds/alertHelper.test.ts b/web-client/src/presenter/computeds/alertHelper.test.ts index 87b28a781d7..e60748e084b 100644 --- a/web-client/src/presenter/computeds/alertHelper.test.ts +++ b/web-client/src/presenter/computeds/alertHelper.test.ts @@ -1,12 +1,7 @@ -import { alertHelper as alertHelperComputed } from './alertHelper'; +import { alertHelper } from './alertHelper'; import { runCompute } from '@web-client/presenter/test.cerebral'; -import { withAppContextDecorator } from '../../withAppContext'; -const alertHelper = withAppContextDecorator(alertHelperComputed, { - getCurrentUser: () => ({ - userId: '123', - }), -}); +const user = {}; describe('alertHelper', () => { it('single message error alert', () => { @@ -15,6 +10,7 @@ describe('alertHelper', () => { alertError: { message: 'abc', }, + user, }, }); expect(result).toMatchObject({ @@ -29,6 +25,7 @@ describe('alertHelper', () => { const result = runCompute(alertHelper, { state: { alertError: { title: 'hello' }, + user, }, }); expect(result).toMatchObject({ @@ -41,7 +38,7 @@ describe('alertHelper', () => { it('alertError is undefined', () => { const result = runCompute(alertHelper, { - state: {}, + state: { user }, }); expect(result).toMatchObject({ showErrorAlert: false, @@ -57,6 +54,7 @@ describe('alertHelper', () => { alertError: { responseCode: 504, }, + user, }, }); expect(result).toMatchObject({ diff --git a/web-client/src/presenter/computeds/alertHelper.ts b/web-client/src/presenter/computeds/alertHelper.ts index 2e0e8ad3271..7f98c6267c9 100644 --- a/web-client/src/presenter/computeds/alertHelper.ts +++ b/web-client/src/presenter/computeds/alertHelper.ts @@ -1,4 +1,3 @@ -import { ClientApplicationContext } from '@web-client/applicationContext'; import { Get } from 'cerebral'; import { state } from '@web-client/presenter/app.cerebral'; import { uniq } from 'lodash'; @@ -10,12 +9,9 @@ const DEFAULT_ALERT_ERROR = { title: undefined, }; -export const alertHelper = ( - get: Get, - applicationContext: ClientApplicationContext, -): any => { +export const alertHelper = (get: Get): any => { const alertError = get(state.alertError) || DEFAULT_ALERT_ERROR; - const userIsIdentified = applicationContext.getCurrentUser() || false; + const userIsIdentified = get(state.token) || false; return { messagesDeduped: uniq(alertError.messages).filter(Boolean), diff --git a/web-client/src/presenter/computeds/caseAssociationRequestHelper.test.ts b/web-client/src/presenter/computeds/caseAssociationRequestHelper.test.ts index 67639f9edcf..c527e723158 100644 --- a/web-client/src/presenter/computeds/caseAssociationRequestHelper.test.ts +++ b/web-client/src/presenter/computeds/caseAssociationRequestHelper.test.ts @@ -20,6 +20,7 @@ describe('caseAssociationRequestHelper', () => { const state = { caseDetail: MOCK_CASE, form: {} as any, + user: { role: ROLES.privatePractitioner } as RawUser, validationErrors: {}, }; @@ -35,11 +36,6 @@ describe('caseAssociationRequestHelper', () => { }; beforeEach(() => { - applicationContext.getCurrentUser = () => - ({ - role: ROLES.privatePractitioner, - }) as RawUser; - state.form = { filersMap, }; @@ -108,10 +104,7 @@ describe('caseAssociationRequestHelper', () => { }); it('returns correct number of document options for user role irsPractitioner', () => { - applicationContext.getCurrentUser = () => - ({ - role: ROLES.irsPractitioner, - }) as RawUser; + state.user.role = ROLES.irsPractitioner; const result = runCompute(caseAssociationRequestHelper, { state }); expect(result.documents.length).toEqual(2); }); @@ -279,10 +272,7 @@ describe('caseAssociationRequestHelper', () => { petitioners: TEST_PETITIONERS, } as RawCase; - applicationContext.getCurrentUser = () => - ({ - role: ROLES.irsPractitioner, - }) as RawUser; + state.user.role = ROLES.irsPractitioner; const { showGenerationTypeForm } = runCompute( caseAssociationRequestHelper, { @@ -296,10 +286,6 @@ describe('caseAssociationRequestHelper', () => { state.form = { eventCode: 'O', }; - applicationContext.getCurrentUser = () => - ({ - role: ROLES.privatePractitioner, - }) as RawUser; const { showGenerationTypeForm } = runCompute( caseAssociationRequestHelper, { @@ -310,10 +296,7 @@ describe('caseAssociationRequestHelper', () => { }); it('should set showGenerationTypeForm to false when code is EA and any petitioner has paper and user is not a private practitioner', () => { - applicationContext.getCurrentUser = () => - ({ - role: ROLES.irsPractitioner, - }) as RawUser; + state.user.role = ROLES.irsPractitioner; const { showGenerationTypeForm } = runCompute( caseAssociationRequestHelper, { @@ -324,6 +307,7 @@ describe('caseAssociationRequestHelper', () => { }); it('should set showGenerationTypeForm to true when code is EA and user is a private practitioner with parties that have paper service', () => { + state.user.role = ROLES.privatePractitioner; const { showGenerationTypeForm } = runCompute( caseAssociationRequestHelper, { diff --git a/web-client/src/presenter/computeds/caseAssociationRequestHelper.ts b/web-client/src/presenter/computeds/caseAssociationRequestHelper.ts index d5c9ca85d90..ee5b570ec2f 100644 --- a/web-client/src/presenter/computeds/caseAssociationRequestHelper.ts +++ b/web-client/src/presenter/computeds/caseAssociationRequestHelper.ts @@ -39,7 +39,7 @@ export const caseAssociationRequestHelper = ( const { GENERATION_TYPES, PARTY_TYPES, USER_ROLES } = applicationContext.getConstants(); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const caseDetail = get(state.caseDetail); const form = get(state.form); diff --git a/web-client/src/presenter/computeds/caseDetailHeaderHelper.test.ts b/web-client/src/presenter/computeds/caseDetailHeaderHelper.test.ts index ee72a3497b1..2371a9e825e 100644 --- a/web-client/src/presenter/computeds/caseDetailHeaderHelper.test.ts +++ b/web-client/src/presenter/computeds/caseDetailHeaderHelper.test.ts @@ -18,24 +18,17 @@ import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../withAppContext'; describe('caseDetailHeaderHelper', () => { - let globalUser; - const getBaseState = user => { - globalUser = user; return { caseDetail: { docketEntries: [], petitioners: [] }, permissions: getUserPermissions(user), + user, }; }; const caseDetailHeaderHelper = withAppContextDecorator( caseDetailHeaderHelperComputed, - { - ...applicationContext, - getCurrentUser: () => { - return globalUser; - }, - }, + applicationContext, ); describe('hidePublicCaseInformation', () => { @@ -610,6 +603,7 @@ describe('caseDetailHeaderHelper', () => { it('should be true when the case is sealed', () => { const result = runCompute(caseDetailHeaderHelper, { state: { + ...getBaseState(privatePractitionerUser), caseDetail: { ...getBaseState(privatePractitionerUser).caseDetail, isSealed: true, diff --git a/web-client/src/presenter/computeds/caseDetailHeaderHelper.ts b/web-client/src/presenter/computeds/caseDetailHeaderHelper.ts index ebdc4b1c57b..62514ec25f8 100644 --- a/web-client/src/presenter/computeds/caseDetailHeaderHelper.ts +++ b/web-client/src/presenter/computeds/caseDetailHeaderHelper.ts @@ -42,7 +42,7 @@ export const caseDetailHeaderHelper = ( ): any => { const { USER_ROLES } = applicationContext.getConstants(); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const isExternalUser = applicationContext .getUtilities() .isExternalUser(user.role); diff --git a/web-client/src/presenter/computeds/caseDetailHelper.hasTrackedItemsPermission.test.ts b/web-client/src/presenter/computeds/caseDetailHelper.hasTrackedItemsPermission.test.ts index 9c454a74cae..53e483ce618 100644 --- a/web-client/src/presenter/computeds/caseDetailHelper.hasTrackedItemsPermission.test.ts +++ b/web-client/src/presenter/computeds/caseDetailHelper.hasTrackedItemsPermission.test.ts @@ -8,12 +8,10 @@ import { getUserPermissions } from '../../../../shared/src/authorization/getUser import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../withAppContext'; -const caseDetailHelper = withAppContextDecorator(caseDetailHelperComputed, { - ...applicationContext, - getCurrentUser: () => { - return globalUser; - }, -}); +const caseDetailHelper = withAppContextDecorator( + caseDetailHelperComputed, + applicationContext, +); let globalUser; @@ -23,6 +21,7 @@ const getBaseState = user => { currentPage: 'CaseDetailInternal', form: {}, permissions: getUserPermissions(user), + user: globalUser, }; }; diff --git a/web-client/src/presenter/computeds/caseDetailHelper.showConsolidatedCasesCard.test.ts b/web-client/src/presenter/computeds/caseDetailHelper.showConsolidatedCasesCard.test.ts index 22658aac362..9ed36eb5928 100644 --- a/web-client/src/presenter/computeds/caseDetailHelper.showConsolidatedCasesCard.test.ts +++ b/web-client/src/presenter/computeds/caseDetailHelper.showConsolidatedCasesCard.test.ts @@ -2,20 +2,18 @@ import { adcUser, irsPractitionerUser, petitionerUser, - privatePractitionerUser, } from '../../../../shared/src/test/mockUsers'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { caseDetailHelper as caseDetailHelperComputed } from './caseDetailHelper'; import { getUserPermissions } from '../../../../shared/src/authorization/getUserPermissions'; +import { privatePractitionerUser } from '@shared/test/mockUsers'; import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../withAppContext'; -const caseDetailHelper = withAppContextDecorator(caseDetailHelperComputed, { - ...applicationContext, - getCurrentUser: () => { - return globalUser; - }, -}); +const caseDetailHelper = withAppContextDecorator( + caseDetailHelperComputed, + applicationContext, +); let globalUser; @@ -23,6 +21,7 @@ const getBaseState = user => { globalUser = user; return { permissions: getUserPermissions(user), + user: globalUser, }; }; diff --git a/web-client/src/presenter/computeds/caseDetailHelper.showSealedCaseView.test.ts b/web-client/src/presenter/computeds/caseDetailHelper.showSealedCaseView.test.ts index 3ee32221d5a..5fb0d6fa6a2 100644 --- a/web-client/src/presenter/computeds/caseDetailHelper.showSealedCaseView.test.ts +++ b/web-client/src/presenter/computeds/caseDetailHelper.showSealedCaseView.test.ts @@ -9,12 +9,10 @@ import { import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../withAppContext'; -const caseDetailHelper = withAppContextDecorator(caseDetailHelperComputed, { - ...applicationContext, - getCurrentUser: () => { - return globalUser; - }, -}); +const caseDetailHelper = withAppContextDecorator( + caseDetailHelperComputed, + applicationContext, +); let globalUser; @@ -24,6 +22,7 @@ const getBaseState = user => { currentPage: 'CaseDetail', form: {}, permissions: getUserPermissions(user), + user: globalUser, }; }; diff --git a/web-client/src/presenter/computeds/caseDetailHelper.test.ts b/web-client/src/presenter/computeds/caseDetailHelper.test.ts index df07871d88f..b131fb1c961 100644 --- a/web-client/src/presenter/computeds/caseDetailHelper.test.ts +++ b/web-client/src/presenter/computeds/caseDetailHelper.test.ts @@ -15,21 +15,17 @@ import { getUserPermissions } from '../../../../shared/src/authorization/getUser import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../withAppContext'; -const caseDetailHelper = withAppContextDecorator(caseDetailHelperComputed, { - ...applicationContext, - getCurrentUser: () => { - return globalUser; - }, -}); - -let globalUser; +const caseDetailHelper = withAppContextDecorator( + caseDetailHelperComputed, + applicationContext, +); const getBaseState = user => { - globalUser = user; return { currentPage: 'CaseDetail', form: {}, permissions: getUserPermissions(user), + user, }; }; diff --git a/web-client/src/presenter/computeds/caseDetailHelper.ts b/web-client/src/presenter/computeds/caseDetailHelper.ts index e346e605a02..f986cd40e16 100644 --- a/web-client/src/presenter/computeds/caseDetailHelper.ts +++ b/web-client/src/presenter/computeds/caseDetailHelper.ts @@ -9,7 +9,7 @@ export const caseDetailHelper = ( get: Get, applicationContext: ClientApplicationContext, ): any => { - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); const permissions = get(state.permissions); const hasTrackedItemsPermission = permissions.TRACKED_ITEMS; diff --git a/web-client/src/presenter/computeds/caseDetailPractitionerSearchHelper.test.ts b/web-client/src/presenter/computeds/caseDetailPractitionerSearchHelper.test.ts index 7ba0ecfc5e8..fbe04d5f5a6 100644 --- a/web-client/src/presenter/computeds/caseDetailPractitionerSearchHelper.test.ts +++ b/web-client/src/presenter/computeds/caseDetailPractitionerSearchHelper.test.ts @@ -9,16 +9,10 @@ const caseDetailPractitionerSearchHelper = withAppContextDecorator( caseDetailPractitionerSearchHelperComputed, { ...applicationContext, - getCurrentUser: () => { - return globalUser; - }, }, ); -let globalUser; - const getBaseState = user => { - globalUser = user; return { permissions: getUserPermissions(user), }; diff --git a/web-client/src/presenter/computeds/caseDetailSubnavHelper.test.ts b/web-client/src/presenter/computeds/caseDetailSubnavHelper.test.ts index 0ef844efd18..fc5ff18769c 100644 --- a/web-client/src/presenter/computeds/caseDetailSubnavHelper.test.ts +++ b/web-client/src/presenter/computeds/caseDetailSubnavHelper.test.ts @@ -7,23 +7,16 @@ import { withAppContextDecorator } from '../../withAppContext'; const caseDetailSubnavHelper = withAppContextDecorator( caseDetailSubnavHelperComputed, - { - ...applicationContext, - getCurrentUser: () => { - return globalUser; - }, - }, + applicationContext, ); -let globalUser; - const getBaseState = user => { - globalUser = user; return { caseDetail: { docketEntries: [], }, permissions: getUserPermissions(user), + user, }; }; diff --git a/web-client/src/presenter/computeds/caseDetailSubnavHelper.ts b/web-client/src/presenter/computeds/caseDetailSubnavHelper.ts index 0ff1b27e078..54d1669809d 100644 --- a/web-client/src/presenter/computeds/caseDetailSubnavHelper.ts +++ b/web-client/src/presenter/computeds/caseDetailSubnavHelper.ts @@ -6,7 +6,7 @@ export const caseDetailSubnavHelper = ( get: Get, applicationContext: ClientApplicationContext, ): any => { - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); const isInternalUser = applicationContext .getUtilities() diff --git a/web-client/src/presenter/computeds/caseInformationHelper.showUnsealedCaseButton.test.ts b/web-client/src/presenter/computeds/caseInformationHelper.showUnsealedCaseButton.test.ts index 991d5083e58..c0bf73c1e74 100644 --- a/web-client/src/presenter/computeds/caseInformationHelper.showUnsealedCaseButton.test.ts +++ b/web-client/src/presenter/computeds/caseInformationHelper.showUnsealedCaseButton.test.ts @@ -1,44 +1,28 @@ -import { ROLES } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { caseInformationHelper as caseInformationHelperComputed } from './caseInformationHelper'; +import { docketClerkUser, petitionsClerkUser } from '@shared/test/mockUsers'; import { getUserPermissions } from '../../../../shared/src/authorization/getUserPermissions'; import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../withAppContext'; describe('caseInformationHelper', () => { - const mockPetitionsClerk = { - role: ROLES.petitionsClerk, - userId: '0dd60083-ab1f-4a43-95f8-bfbc69b48777', - }; - const mockDocketClerk = { - role: ROLES.docketClerk, - userId: 'a09053ab-58c7-4384-96a1-bd5fbe14977a', - }; - const caseInformationHelper = withAppContextDecorator( caseInformationHelperComputed, applicationContext, ); const getBaseState = user => { - mockUser = { ...user }; return { permissions: getUserPermissions(user), + user, }; }; - let mockUser; - - beforeEach(() => { - mockUser = {}; - applicationContext.getCurrentUser.mockImplementation(() => mockUser); - }); - describe('showUnsealCaseButton', () => { it('should be false when the user has UNSEAL_CASE permission and case is not already sealed', () => { const result = runCompute(caseInformationHelper, { state: { - ...getBaseState(mockDocketClerk), // has SEAL_CASE permission + ...getBaseState(docketClerkUser), // has SEAL_CASE permission caseDetail: { isSealed: false, petitioners: [], sealedDate: null }, form: {}, }, @@ -50,7 +34,7 @@ describe('caseInformationHelper', () => { it('should be true when the user has UNSEAL_CASE permission and case is already sealed', () => { const result = runCompute(caseInformationHelper, { state: { - ...getBaseState(mockDocketClerk), // has SEAL_CASE permission + ...getBaseState(docketClerkUser), // has SEAL_CASE permission caseDetail: { isSealed: true, petitioners: [], @@ -66,7 +50,7 @@ describe('caseInformationHelper', () => { it('should be false when the user does not have UNSEAL_CASE permission', () => { const result = runCompute(caseInformationHelper, { state: { - ...getBaseState(mockPetitionsClerk), // does not have SEAL_CASE permission + ...getBaseState(petitionsClerkUser), // does not have SEAL_CASE permission caseDetail: { petitioners: [], }, diff --git a/web-client/src/presenter/computeds/caseInformationHelper.test.ts b/web-client/src/presenter/computeds/caseInformationHelper.test.ts index 7f45b48a88c..edf16d58456 100644 --- a/web-client/src/presenter/computeds/caseInformationHelper.test.ts +++ b/web-client/src/presenter/computeds/caseInformationHelper.test.ts @@ -6,54 +6,30 @@ import { import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { caseInformationHelper as caseInformationHelperComputed } from './caseInformationHelper'; import { getUserPermissions } from '../../../../shared/src/authorization/getUserPermissions'; +import { + adcUser as mockAdc, + docketClerkUser as mockDocketClerk, + judgeUser as mockJudge, + petitionerUser as mockPetitioner, + petitionsClerkUser as mockPetitionsClerk, + privatePractitionerUser as mockPrivatePractitioner, +} from '@shared/test/mockUsers'; import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../withAppContext'; describe('caseInformationHelper', () => { - const mockPetitionsClerk = { - role: ROLES.petitionsClerk, - userId: '0dd60083-ab1f-4a43-95f8-bfbc69b48777', - }; - const mockDocketClerk = { - role: ROLES.docketClerk, - userId: 'a09053ab-58c7-4384-96a1-bd5fbe14977a', - }; - const mockPetitioner = { - role: ROLES.petitioner, - userId: 'f94cef8e-17b8-4504-9296-af911b32020a', - }; - const mockPrivatePractitioner = { - role: ROLES.privatePractitioner, - userId: '39f7c7ee-ab75-492a-a4ee-63755a24e845', - }; - const mockAdc = { - role: ROLES.adc, - userId: '11e15c96-6705-4083-8e10-1c20664ac1ae', - }; - const mockJudge = { - role: ROLES.judge, - userId: '12e15c96-6705-4083-8e10-1c20664ac1ae', - }; - const caseInformationHelper = withAppContextDecorator( caseInformationHelperComputed, applicationContext, ); const getBaseState = user => { - mockUser = { ...user }; return { permissions: getUserPermissions(user), + user, }; }; - let mockUser; - - beforeEach(() => { - mockUser = {}; - applicationContext.getCurrentUser.mockImplementation(() => mockUser); - }); - describe('formattedPetitioners', () => { let baseState; @@ -318,7 +294,7 @@ describe('caseInformationHelper', () => { [ROLES.docketClerk, ROLES.petitionsClerk, ROLES.admissionsClerk].forEach( role => { it('should be true when the user has permission to edit petitioner counsel and there are privatePractitioners on the case', () => { - mockUser = { ...mockDocketClerk, role }; + let mockUser = { ...mockDocketClerk, role }; const result = runCompute(caseInformationHelper, { state: { @@ -338,11 +314,9 @@ describe('caseInformationHelper', () => { ); it('should be false when the user is an internal user that does NOT have permission to edit petitioner counsel', () => { - mockUser = { ...mockAdc }; - const result = runCompute(caseInformationHelper, { state: { - ...getBaseState(mockUser), + ...getBaseState(mockAdc), caseDetail: { irsPractitioners: [{ userId: '2' }], petitioners: [], @@ -356,11 +330,9 @@ describe('caseInformationHelper', () => { }); it('should be false when there are no privatePractitioners on the case', () => { - mockUser = { ...mockDocketClerk }; - const result = runCompute(caseInformationHelper, { state: { - ...getBaseState(mockUser), + ...getBaseState(mockDocketClerk), caseDetail: { irsPractitioners: [{ userId: '2' }], petitioners: [], diff --git a/web-client/src/presenter/computeds/caseInformationHelper.ts b/web-client/src/presenter/computeds/caseInformationHelper.ts index 8861ec49f42..d011bebabe8 100644 --- a/web-client/src/presenter/computeds/caseInformationHelper.ts +++ b/web-client/src/presenter/computeds/caseInformationHelper.ts @@ -8,7 +8,7 @@ export const caseInformationHelper = ( ): any => { const { STATUS_TYPES } = applicationContext.getConstants(); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const caseDetail = get(state.caseDetail); const permissions = get(state.permissions); const isInternalUser = applicationContext diff --git a/web-client/src/presenter/computeds/caseInventoryReportHelper.test.ts b/web-client/src/presenter/computeds/caseInventoryReportHelper.test.ts index 443bbdda81d..6eb10bf14a5 100644 --- a/web-client/src/presenter/computeds/caseInventoryReportHelper.test.ts +++ b/web-client/src/presenter/computeds/caseInventoryReportHelper.test.ts @@ -3,7 +3,6 @@ import { CHIEF_JUDGE, CLOSED_CASE_STATUSES, DOCKET_NUMBER_SUFFIXES, - ROLES, } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { caseInventoryReportHelper as caseInventoryReportHelperComputed } from './caseInventoryReportHelper'; @@ -26,11 +25,6 @@ describe('caseInventoryReportHelper', () => { }, ); - applicationContext.getCurrentUser = () => ({ - role: ROLES.docketClerk, - userId: '5d66d122-8417-427b-9048-c1ba8ab1ea68', - }); - it('should return all judges from state along with Chief Judge sorted alphabetically', () => { const result = runCompute(caseInventoryReportHelper, { state: { diff --git a/web-client/src/presenter/computeds/caseInventoryReportHelper.ts b/web-client/src/presenter/computeds/caseInventoryReportHelper.ts index 9d3772ba348..7021e37fe0e 100644 --- a/web-client/src/presenter/computeds/caseInventoryReportHelper.ts +++ b/web-client/src/presenter/computeds/caseInventoryReportHelper.ts @@ -35,10 +35,11 @@ export const caseInventoryReportHelper = ( } const reportData = get(state.caseInventoryReportData.foundCases) || []; + const user = get(state.user); const formattedReportData = reportData .sort(applicationContext.getUtilities().compareCasesByDocketNumber) - .map(item => formatCase(applicationContext, item)); + .map(item => formatCase(applicationContext, item, user)); let displayedCount = resultCount < CASE_INVENTORY_PAGE_SIZE diff --git a/web-client/src/presenter/computeds/caseSearchBoxHelper.test.ts b/web-client/src/presenter/computeds/caseSearchBoxHelper.test.ts index c2a1257576e..ad9e3ccb404 100644 --- a/web-client/src/presenter/computeds/caseSearchBoxHelper.test.ts +++ b/web-client/src/presenter/computeds/caseSearchBoxHelper.test.ts @@ -1,6 +1,10 @@ -import { ROLES } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../applicationContext'; import { caseSearchBoxHelper as caseSearchBoxHelperComputed } from './caseSearchBoxHelper'; +import { + irsPractitionerUser, + irsSuperuserUser, + petitionerUser, +} from '@shared/test/mockUsers'; import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../withAppContext'; @@ -11,65 +15,40 @@ const caseSearchBoxHelper = withAppContextDecorator( describe('caseSearchBoxHelper', () => { it('should return showSearchDescription true if the user role is not irsSuperuser', () => { - applicationContext.getCurrentUser = () => ({ - role: ROLES.irsPractitioner, - userId: '5d66d122-8417-427b-9048-c1ba8ab1ea68', - }); - const result = runCompute(caseSearchBoxHelper, { - state: {}, + state: { user: irsPractitionerUser }, }); expect(result.showSearchDescription).toBe(true); }); it('should return showSearchDescription false if the user role is irsSuperuser', () => { - applicationContext.getCurrentUser = () => ({ - role: ROLES.irsSuperuser, - userId: '5d66d122-8417-427b-9048-c1ba8ab1ea68', - }); - const result = runCompute(caseSearchBoxHelper, { - state: {}, + state: { user: irsSuperuserUser }, }); expect(result.showSearchDescription).toBe(false); }); it('should return showSearchDescription false if the user role is petitioner', () => { - applicationContext.getCurrentUser = () => ({ - role: ROLES.petitioner, - userId: '5d66d122-8417-427b-9048-c1ba8ab1ea68', - }); - const result = runCompute(caseSearchBoxHelper, { - state: {}, + state: { user: petitionerUser }, }); expect(result.showSearchDescription).toBe(false); }); it('should return showAdvancedSearch true if the user role is not petitioner', () => { - applicationContext.getCurrentUser = () => ({ - role: ROLES.irsPractitioner, - userId: '5d66d122-8417-427b-9048-c1ba8ab1ea68', - }); - const result = runCompute(caseSearchBoxHelper, { - state: {}, + state: { user: irsPractitionerUser }, }); expect(result.showAdvancedSearch).toBe(true); }); it('should return showAdvancedSearch false if the user role is petitioner', () => { - applicationContext.getCurrentUser = () => ({ - role: ROLES.petitioner, - userId: '5d66d122-8417-427b-9048-c1ba8ab1ea68', - }); - const result = runCompute(caseSearchBoxHelper, { - state: {}, + state: { user: petitionerUser }, }); expect(result.showAdvancedSearch).toBe(false); diff --git a/web-client/src/presenter/computeds/caseSearchBoxHelper.ts b/web-client/src/presenter/computeds/caseSearchBoxHelper.ts index 270196c004d..f7624bfa47f 100644 --- a/web-client/src/presenter/computeds/caseSearchBoxHelper.ts +++ b/web-client/src/presenter/computeds/caseSearchBoxHelper.ts @@ -1,10 +1,11 @@ import { ClientApplicationContext } from '@web-client/applicationContext'; import { Get } from 'cerebral'; +import { state } from '@web-client/presenter/app.cerebral'; export const caseSearchBoxHelper = ( get: Get, applicationContext: ClientApplicationContext, ): any => { - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); let showSearchDescription = true; diff --git a/web-client/src/presenter/computeds/caseSearchNoMatchesHelper.test.ts b/web-client/src/presenter/computeds/caseSearchNoMatchesHelper.test.ts index d1bc7e88afa..ccb0be67604 100644 --- a/web-client/src/presenter/computeds/caseSearchNoMatchesHelper.test.ts +++ b/web-client/src/presenter/computeds/caseSearchNoMatchesHelper.test.ts @@ -1,6 +1,6 @@ -import { ROLES } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContext } from '../../applicationContext'; import { caseSearchNoMatchesHelper as caseSearchNoMatchesHelperComputed } from './caseSearchNoMatchesHelper'; +import { irsPractitionerUser, petitionerUser } from '@shared/test/mockUsers'; import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../withAppContext'; @@ -11,26 +11,16 @@ const caseSearchNoMatchesHelper = withAppContextDecorator( describe('caseSearchNoMatchesHelper', () => { it('should return showSearchByNameOption true if the user role is not petitioner', () => { - applicationContext.getCurrentUser = () => ({ - role: ROLES.irsPractitioner, - userId: '5d66d122-8417-427b-9048-c1ba8ab1ea68', - }); - const result = runCompute(caseSearchNoMatchesHelper, { - state: {}, + state: { user: irsPractitionerUser }, }); expect(result.showSearchByNameOption).toBe(true); }); it('should return showSearchByNameOption false if the user role is petitioner', () => { - applicationContext.getCurrentUser = () => ({ - role: ROLES.petitioner, - userId: '5d66d122-8417-427b-9048-c1ba8ab1ea68', - }); - const result = runCompute(caseSearchNoMatchesHelper, { - state: {}, + state: { user: petitionerUser }, }); expect(result.showSearchByNameOption).toBe(false); diff --git a/web-client/src/presenter/computeds/caseSearchNoMatchesHelper.ts b/web-client/src/presenter/computeds/caseSearchNoMatchesHelper.ts index aecb20c6295..da356c47c20 100644 --- a/web-client/src/presenter/computeds/caseSearchNoMatchesHelper.ts +++ b/web-client/src/presenter/computeds/caseSearchNoMatchesHelper.ts @@ -1,10 +1,12 @@ import { ClientApplicationContext } from '@web-client/applicationContext'; import { Get } from 'cerebral'; +import { state } from '@web-client/presenter/app.cerebral'; + export const caseSearchNoMatchesHelper = ( get: Get, applicationContext: ClientApplicationContext, ): any => { - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); let showSearchByNameOption = true; diff --git a/web-client/src/presenter/computeds/completeDocumentTypeSectionHelper.test.ts b/web-client/src/presenter/computeds/completeDocumentTypeSectionHelper.test.ts index 6a1d8573c4f..b5b11dc36d5 100644 --- a/web-client/src/presenter/computeds/completeDocumentTypeSectionHelper.test.ts +++ b/web-client/src/presenter/computeds/completeDocumentTypeSectionHelper.test.ts @@ -13,18 +13,13 @@ const completeDocumentTypeSectionHelper = withAppContextDecorator( applicationContext, ); -beforeEach(() => { - applicationContext.getCurrentUser = jest - .fn() - .mockReturnValue(privatePractitionerUser); -}); - describe('completeDocumentTypeSectionHelper', () => { it("should return an empty object given there's no caseDetail", () => { const result = runCompute(completeDocumentTypeSectionHelper, { state: { caseDetail: {}, form: {}, + user: privatePractitionerUser, }, }); @@ -47,6 +42,7 @@ describe('completeDocumentTypeSectionHelper', () => { category, documentType, }, + user: privatePractitionerUser, }, }); @@ -74,6 +70,7 @@ describe('completeDocumentTypeSectionHelper', () => { documentType: 'Motion for Leave to File', }, }, + user: privatePractitionerUser, }, }); @@ -98,6 +95,7 @@ describe('completeDocumentTypeSectionHelper', () => { form: { category, }, + user: privatePractitionerUser, }, }); @@ -123,9 +121,6 @@ describe('completeDocumentTypeSectionHelper', () => { }); it('returns an array of documentTypes for select including Entry of Appearance for IRS Practitioners on first filing', () => { - applicationContext.getCurrentUser = jest - .fn() - .mockReturnValue(irsPractitionerUser); applicationContext.getUtilities().isSealedCase = jest .fn() .mockReturnValue(false); @@ -136,6 +131,7 @@ describe('completeDocumentTypeSectionHelper', () => { docketNumber: '101-20', }, form: {}, + user: irsPractitionerUser, }, }); @@ -153,9 +149,6 @@ describe('completeDocumentTypeSectionHelper', () => { }); it('returns an array of documentTypes for select that only contains documents with canBeFirstIrsDocument for IRS Pracitioners on filing first IRS document', () => { - applicationContext.getCurrentUser = jest - .fn() - .mockReturnValue(irsPractitionerUser); applicationContext.getUtilities().isSealedCase = jest .fn() .mockReturnValue(false); @@ -166,6 +159,7 @@ describe('completeDocumentTypeSectionHelper', () => { docketNumber: '101-20', }, form: {}, + user: irsPractitionerUser, }, }); @@ -180,9 +174,6 @@ describe('completeDocumentTypeSectionHelper', () => { }); it('returns an array of documentTypes for select excluding Entry of Appearance for IRS Practitioners on non-first filing', () => { - applicationContext.getCurrentUser = jest - .fn() - .mockReturnValue(irsPractitionerUser); applicationContext.getUtilities().isSealedCase = jest .fn() .mockReturnValue(false); @@ -194,6 +185,7 @@ describe('completeDocumentTypeSectionHelper', () => { irsPractitioners: [{ thing: 'thing' }], }, form: {}, + user: irsPractitionerUser, }, }); @@ -206,10 +198,6 @@ describe('completeDocumentTypeSectionHelper', () => { }); it('returns an array of documentTypes for select excluding Entry of Appearance for IRS Practitioners on sealed case', () => { - applicationContext.getCurrentUser = jest - .fn() - .mockReturnValue(irsPractitionerUser); - const result = runCompute(completeDocumentTypeSectionHelper, { state: { caseDetail: { @@ -217,6 +205,7 @@ describe('completeDocumentTypeSectionHelper', () => { isSealed: true, }, form: {}, + user: irsPractitionerUser, }, }); diff --git a/web-client/src/presenter/computeds/completeDocumentTypeSectionHelper.ts b/web-client/src/presenter/computeds/completeDocumentTypeSectionHelper.ts index ca70a5db4c1..7d6769a8cd6 100644 --- a/web-client/src/presenter/computeds/completeDocumentTypeSectionHelper.ts +++ b/web-client/src/presenter/computeds/completeDocumentTypeSectionHelper.ts @@ -59,7 +59,7 @@ export const completeDocumentTypeSectionHelper = ( value => value.eventCode, ); - const currentUser = applicationContext.getCurrentUser(); + const currentUser = get(state.user); if (currentUser.role === USER_ROLES.irsPractitioner) { if ( Case.isFirstIrsFiling(caseDetail) && @@ -85,8 +85,8 @@ export const completeDocumentTypeSectionHelper = ( return { ...documentType, documentTitle: - applicationContext.getCurrentUser().role === - USER_ROLES.irsPractitioner && documentType.eventCode === 'EA' + get(state.user).role === USER_ROLES.irsPractitioner && + documentType.eventCode === 'EA' ? `${documentType.documentTitle} for Respondent` : documentType.documentTitle, }; diff --git a/web-client/src/presenter/computeds/contactsHelper.test.ts b/web-client/src/presenter/computeds/contactsHelper.test.ts index 3746057b680..186b179fdf8 100644 --- a/web-client/src/presenter/computeds/contactsHelper.test.ts +++ b/web-client/src/presenter/computeds/contactsHelper.test.ts @@ -1,7 +1,10 @@ import { PARTY_TYPES } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { contactsHelper as contactsHelperComputed } from './contactsHelper'; -import { privatePractitionerUser } from '../../../../shared/src/test/mockUsers'; +import { + petitionerUser, + privatePractitionerUser, +} from '../../../../shared/src/test/mockUsers'; import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../withAppContext'; @@ -16,6 +19,7 @@ describe('contactsHelper', () => { const result = runCompute(contactsHelper, { state: { form: { partyType: PARTY_TYPES.conservator }, + user: petitionerUser, }, }); @@ -33,6 +37,7 @@ describe('contactsHelper', () => { form: { partyType: undefined, }, + user: petitionerUser, }, }); @@ -45,6 +50,7 @@ describe('contactsHelper', () => { form: { partyType: PARTY_TYPES.petitioner, }, + user: petitionerUser, }, }); @@ -60,6 +66,7 @@ describe('contactsHelper', () => { form: { partyType: PARTY_TYPES.petitionerSpouse, }, + user: petitionerUser, }, }); @@ -79,18 +86,13 @@ describe('contactsHelper', () => { }); describe('user role private practitioner', () => { - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue( - privatePractitionerUser, - ); - }); - it('should validate form view information for party type Partnership (as the Tax Matters Partner)', () => { const result = runCompute(contactsHelper, { state: { form: { partyType: PARTY_TYPES.partnershipAsTaxMattersPartner, }, + user: privatePractitionerUser, }, }); @@ -108,6 +110,7 @@ describe('contactsHelper', () => { form: { partyType: PARTY_TYPES.petitioner, }, + user: privatePractitionerUser, }, }); @@ -123,6 +126,7 @@ describe('contactsHelper', () => { form: { partyType: PARTY_TYPES.petitionerSpouse, }, + user: privatePractitionerUser, }, }); @@ -146,6 +150,7 @@ describe('contactsHelper', () => { form: { partyType: undefined, }, + user: privatePractitionerUser, }, }); diff --git a/web-client/src/presenter/computeds/contactsHelper.ts b/web-client/src/presenter/computeds/contactsHelper.ts index 2a3be4f68d5..edad80df534 100644 --- a/web-client/src/presenter/computeds/contactsHelper.ts +++ b/web-client/src/presenter/computeds/contactsHelper.ts @@ -17,7 +17,7 @@ export const contactsHelper = ( applicationContext: ClientApplicationContext, ): any => { const form = get(state.form); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { PARTY_TYPES, USER_ROLES } = applicationContext.getConstants(); let contactPrimary, contactSecondary; diff --git a/web-client/src/presenter/computeds/dashboardExternalHelper.test.ts b/web-client/src/presenter/computeds/dashboardExternalHelper.test.ts index 214c6bce77b..48367a23ca0 100644 --- a/web-client/src/presenter/computeds/dashboardExternalHelper.test.ts +++ b/web-client/src/presenter/computeds/dashboardExternalHelper.test.ts @@ -1,8 +1,11 @@ -import { ROLES } from '../../../../shared/src/business/entities/EntityConstants'; -import { RawUser } from '@shared/business/entities/User'; import { applicationContext } from '../../applicationContext'; import { dashboardExternalHelper as dashboardExternalHelperComputed } from './dashboardExternalHelper'; -import { docketClerk1User } from '@shared/test/mockUsers'; +import { + docketClerk1User, + irsPractitionerUser, + petitionerUser, + privatePractitionerUser, +} from '@shared/test/mockUsers'; import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../withAppContext'; @@ -13,43 +16,33 @@ describe('dashboardExternalHelper', () => { ); it('should show "what to expect" but not case list when there are no open or closed cases', () => { - applicationContext.getCurrentUser = () => - ({ - role: ROLES.petitioner, - }) as RawUser; const result = runCompute(dashboardExternalHelper, { state: { closedCases: [], openCases: [], + user: petitionerUser, }, }); expect(result.showPetitionWelcomePage).toEqual(true); }); it('should show case list but not "what to expect" when there is an open or closed case case', () => { - applicationContext.getCurrentUser = () => - ({ - role: ROLES.petitioner, - }) as RawUser; const result = runCompute(dashboardExternalHelper, { state: { closedCases: [{ something: true }], openCases: [{ something: true }], + user: petitionerUser, }, }); expect(result.showPetitionWelcomePage).toEqual(false); }); it('should keep the showFileACase flag as false when the user role is petitioner', () => { - applicationContext.getCurrentUser = () => - ({ - role: ROLES.petitioner, - }) as RawUser; - const result = runCompute(dashboardExternalHelper, { state: { closedCases: [{ something: true }], openCases: [{ something: true }], + user: petitionerUser, }, }); @@ -57,15 +50,11 @@ describe('dashboardExternalHelper', () => { }); it('should set the showFileACase flag as true when the user role is a private practitioner', () => { - applicationContext.getCurrentUser = () => - ({ - role: ROLES.privatePractitioner, - }) as RawUser; - const result = runCompute(dashboardExternalHelper, { state: { closedCases: [{ something: true }], openCases: [{ something: true }], + user: privatePractitionerUser, }, }); @@ -73,15 +62,11 @@ describe('dashboardExternalHelper', () => { }); it('should keep the showStartButton flag as false when the user role is irs practitioner', () => { - applicationContext.getCurrentUser = () => - ({ - role: ROLES.irsPractitioner, - }) as RawUser; - const result = runCompute(dashboardExternalHelper, { state: { closedCases: [{ something: true }], openCases: [{ something: true }], + user: irsPractitionerUser, }, }); @@ -89,18 +74,14 @@ describe('dashboardExternalHelper', () => { }); it('should set the showStartButton flag as true when the user role is a private practitioner or petitioner', () => { - const userRoles = ['petitioner', 'privatePractitioner']; - - userRoles.forEach(userRole => { - applicationContext.getCurrentUser = () => - ({ - role: userRole, - }) as RawUser; + const userRoles = [petitionerUser, privatePractitionerUser]; + userRoles.forEach(user => { const result = runCompute(dashboardExternalHelper, { state: { closedCases: [{ something: true }], openCases: [{ something: true }], + user, }, }); @@ -109,18 +90,14 @@ describe('dashboardExternalHelper', () => { }); it('should set the showFilingFee to true when the user is a private practitioner or petitioner', () => { - const userRoles = ['petitioner', 'privatePractitioner']; - - userRoles.forEach(userRole => { - applicationContext.getCurrentUser = () => - ({ - role: userRole, - }) as RawUser; + const userRoles = [petitionerUser, privatePractitionerUser]; + userRoles.forEach(user => { const result = runCompute(dashboardExternalHelper, { state: { closedCases: [{ something: true }], openCases: [{ something: true }], + user, }, }); @@ -129,12 +106,11 @@ describe('dashboardExternalHelper', () => { }); it('should set the showFilingFee to false when the user is NOT a private practitioner or petitioner', () => { - applicationContext.getCurrentUser = () => docketClerk1User; - const result = runCompute(dashboardExternalHelper, { state: { closedCases: [{ something: true }], openCases: [{ something: true }], + user: docketClerk1User, }, }); diff --git a/web-client/src/presenter/computeds/dashboardExternalHelper.ts b/web-client/src/presenter/computeds/dashboardExternalHelper.ts index bef42a7d443..ac3c130a361 100644 --- a/web-client/src/presenter/computeds/dashboardExternalHelper.ts +++ b/web-client/src/presenter/computeds/dashboardExternalHelper.ts @@ -12,7 +12,7 @@ export const dashboardExternalHelper = ( showPetitionWelcomePage: boolean; } => { const { USER_ROLES } = applicationContext.getConstants(); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const openCases = get(state.openCases) || []; const closedCases = get(state.closedCases) || []; diff --git a/web-client/src/presenter/computeds/documentViewerHelper.showButtons.test.ts b/web-client/src/presenter/computeds/documentViewerHelper.showButtons.test.ts index 9b9cc03316e..44127801c2e 100644 --- a/web-client/src/presenter/computeds/documentViewerHelper.showButtons.test.ts +++ b/web-client/src/presenter/computeds/documentViewerHelper.showButtons.test.ts @@ -40,12 +40,6 @@ describe('documentViewerHelper', () => { }; }; - beforeAll(() => { - applicationContext.getCurrentUser = jest - .fn() - .mockReturnValue(docketClerkUser); - }); - describe('showCompleteQcButton', () => { const showCompleteQcButtonTests = [ { diff --git a/web-client/src/presenter/computeds/documentViewerHelper.test.ts b/web-client/src/presenter/computeds/documentViewerHelper.test.ts index e98a6e33610..336ffdd0cc3 100644 --- a/web-client/src/presenter/computeds/documentViewerHelper.test.ts +++ b/web-client/src/presenter/computeds/documentViewerHelper.test.ts @@ -30,18 +30,13 @@ describe('documentViewerHelper', () => { const getBaseState = user => { return { permissions: getUserPermissions(user), + user, viewerDocumentToDisplay: { docketEntryId: DOCKET_ENTRY_ID, }, }; }; - beforeAll(() => { - applicationContext.getCurrentUser = jest - .fn() - .mockReturnValue(docketClerkUser); - }); - it('should return an empty object if the requested docketEntryId is not found in the docket record', () => { const result = runCompute(documentViewerHelper, { state: { diff --git a/web-client/src/presenter/computeds/documentViewerHelper.ts b/web-client/src/presenter/computeds/documentViewerHelper.ts index 6441bccb281..3ff40d669ae 100644 --- a/web-client/src/presenter/computeds/documentViewerHelper.ts +++ b/web-client/src/presenter/computeds/documentViewerHelper.ts @@ -21,11 +21,13 @@ export const documentViewerHelper = ( const permissions = get(state.permissions); const viewerDocumentToDisplay = get(state.viewerDocumentToDisplay); const caseDetail = get(state.caseDetail); + const user = get(state.user); const formattedCaseDetail = applicationContext .getUtilities() .getFormattedCaseDetail({ applicationContext, + authorizedUser: user, caseDetail, }); diff --git a/web-client/src/presenter/computeds/draftDocumentViewerHelper.test.ts b/web-client/src/presenter/computeds/draftDocumentViewerHelper.test.ts index 5dcc2b92ec2..e952349e175 100644 --- a/web-client/src/presenter/computeds/draftDocumentViewerHelper.test.ts +++ b/web-client/src/presenter/computeds/draftDocumentViewerHelper.test.ts @@ -24,6 +24,7 @@ describe('draftDocumentViewerHelper', () => { const getBaseState = user => { return { permissions: getUserPermissions(user), + user, viewerDraftDocumentToDisplay: { docketEntryId: mockDocketEntryId, }, @@ -39,12 +40,6 @@ describe('draftDocumentViewerHelper', () => { isDraft: true, }; - beforeEach(() => { - applicationContext.getCurrentUser = jest - .fn() - .mockReturnValue(docketClerkUser); - }); - it('should return an object with empty strings if viewerDraftDocumentToDisplay.eventCode is not defined', () => { const result = runCompute(draftDocumentViewerHelper, { state: { @@ -118,8 +113,6 @@ describe('draftDocumentViewerHelper', () => { describe('showAddDocketEntryButton', () => { it('should return true for user role of petitionsClerk', () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(petitionsClerkUser), @@ -138,8 +131,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return true for user role of clerkOfCourt', () => { - applicationContext.getCurrentUser.mockReturnValue(clerkOfCourtUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(clerkOfCourtUser), @@ -158,8 +149,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return false for other internal user roles', () => { - applicationContext.getCurrentUser.mockReturnValue(judgeUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(judgeUser), @@ -173,8 +162,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return true for signed document', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(docketClerkUser), @@ -193,8 +180,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return false for unsigned document that requires signature', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(docketClerkUser), @@ -209,8 +194,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return showApplySignatureButton true and showRemoveSignatureButton false for an internal user and an unsigned document', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(docketClerkUser), @@ -225,8 +208,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return showApplySignatureButton false and showRemoveSignatureButton false for an external user', () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(petitionerUser), @@ -241,8 +222,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return showRemoveSignatureButton true and showApplySignatureButton false for an internal user and a signed document that is not a draft stamp order', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(docketClerkUser), @@ -263,8 +242,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return showRemoveSignatureButton false for NOT document type and internal users', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(docketClerkUser), @@ -290,8 +267,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return showRemoveSignatureButton false for NTD document type and internal users', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(docketClerkUser), @@ -317,8 +292,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return showRemoveSignatureButton false for SDEC document type and internal users', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(docketClerkUser), @@ -344,8 +317,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return showRemoveSignatureButton false for a draft stamp order', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(docketClerkUser), @@ -364,8 +335,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return showEditButtonSigned true for an internal user, a document that is signed, and is not a draft stamp order', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(docketClerkUser), @@ -385,8 +354,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return showEditButtonNotSigned true for an internal user and a document that is not signed', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(docketClerkUser), @@ -400,8 +367,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return showEditButtonSigned false for an external user', () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(petitionerUser), @@ -415,8 +380,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return showEditButtonSigned false for a draft stamp order', () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(petitionerUser), @@ -435,8 +398,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return showEditButtonNotSigned true and showEditButtonSigned false for a Notice document', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(docketClerkUser), @@ -459,8 +420,6 @@ describe('draftDocumentViewerHelper', () => { }); it('should return showEditButtonNotSigned false and showEditButtonSigned false for a Stipulated Decision document', () => { - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const result = runCompute(draftDocumentViewerHelper, { state: { ...getBaseState(docketClerkUser), diff --git a/web-client/src/presenter/computeds/draftDocumentViewerHelper.ts b/web-client/src/presenter/computeds/draftDocumentViewerHelper.ts index 3ccd90e4c91..1418f6e1302 100644 --- a/web-client/src/presenter/computeds/draftDocumentViewerHelper.ts +++ b/web-client/src/presenter/computeds/draftDocumentViewerHelper.ts @@ -15,7 +15,7 @@ export const draftDocumentViewerHelper = ( NOTICE_EVENT_CODES, STIPULATED_DECISION_EVENT_CODE, } = applicationContext.getConstants(); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const permissions = get(state.permissions); const caseDetail = get(state.caseDetail); @@ -27,6 +27,7 @@ export const draftDocumentViewerHelper = ( .getUtilities() .getFormattedCaseDetail({ applicationContext, + authorizedUser: user, caseDetail, }); diff --git a/web-client/src/presenter/computeds/fileDocumentHelper.test.ts b/web-client/src/presenter/computeds/fileDocumentHelper.test.ts index 4cfdd2d89d1..21e5b6333d5 100644 --- a/web-client/src/presenter/computeds/fileDocumentHelper.test.ts +++ b/web-client/src/presenter/computeds/fileDocumentHelper.test.ts @@ -24,8 +24,6 @@ describe('fileDocumentHelper', () => { validationErrors: {}, }; - applicationContext.getCurrentUser.mockReturnValue(docketClerkUser); - const fileDocumentHelper = withAppContextDecorator( fileDocumentHelperComputed, applicationContext, @@ -36,7 +34,11 @@ describe('fileDocumentHelper', () => { }); it('returns correct values when documentType is undefined', () => { - let testState = { ...state, form: { documentType: undefined } }; + let testState = { + ...state, + form: { documentType: undefined }, + user: docketClerkUser, + }; const expected = { isSecondaryDocumentUploadOptional: false, @@ -54,7 +56,9 @@ describe('fileDocumentHelper', () => { }); it('returns a correctly-formatted list of supporting documents', () => { - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.supportingDocumentTypeList.length > 0).toBeTruthy(); expect( @@ -64,13 +68,17 @@ describe('fileDocumentHelper', () => { it('has optional secondary document upload when motion for leave to file', () => { state.form = { documentType: 'Motion for Leave to File' }; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.isSecondaryDocumentUploadOptional).toBeTruthy(); }); it('does not show secondary inclusions if document type is motion for leave to file and a secondary document has not been selected', () => { state.form = { documentType: 'Motion for Leave to File' }; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.showSecondaryDocumentInclusionsForm).toBeFalsy(); }); @@ -79,13 +87,17 @@ describe('fileDocumentHelper', () => { documentType: 'Motion for Leave to File', secondaryDocumentFile: 'something', }; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.showSecondaryDocumentInclusionsForm).toBeTruthy(); }); it('shows primary objection if primary document type is a motion', () => { state.form = { documentType: 'Motion for Leave to File' }; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.primaryDocument.showObjection).toBeTruthy(); }); @@ -96,7 +108,9 @@ describe('fileDocumentHelper', () => { documentType: 'Motion for Continuance', }, }; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.primaryDocument.showObjection).toBeTruthy(); expect(result.secondaryDocument.showObjection).toBeFalsy(); }); @@ -109,7 +123,9 @@ describe('fileDocumentHelper', () => { }, secondaryDocumentFile: 'something', }; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.primaryDocument.showObjection).toBeTruthy(); expect(result.secondaryDocument.showObjection).toBeTruthy(); }); @@ -118,7 +134,9 @@ describe('fileDocumentHelper', () => { state.form = { documentType: 'Supplemental Brief', }; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.primaryDocument.showObjection).toBeFalsy(); expect(result.secondaryDocument.showObjection).toBeFalsy(); }); @@ -130,7 +148,9 @@ describe('fileDocumentHelper', () => { documentType: 'Supplemental Brief', }, }; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.primaryDocument.showObjection).toBeTruthy(); expect(result.secondaryDocument.showObjection).toBeFalsy(); }); @@ -142,20 +162,26 @@ describe('fileDocumentHelper', () => { secondaryDocumentFile: { some: 'file' }, }; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.showPrimaryDocumentValid).toBeTruthy(); expect(result.showSecondaryDocumentValid).toBeTruthy(); }); it('shows secondary party for petitionerSpouse or petitionerDeceasedSpouse', () => { state.caseDetail.partyType = PARTY_TYPES.petitionerSpouse; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.showSecondaryParty).toBeTruthy(); }); it('generates correctly formatted service date', () => { state.form.certificateOfServiceDate = '2012-05-31'; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.certificateOfServiceDateFormatted).toEqual('05/31/12'); }); @@ -164,20 +190,26 @@ describe('fileDocumentHelper', () => { certificateOfService: true, certificateOfServiceDate: '2012-06-30', }; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.secondaryDocument.certificateOfServiceDateFormatted).toEqual( '06/30/12', ); }); it('does not generate a formatted service date if a service date is not entered on the form', () => { - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.certificateOfServiceDateFormatted).toBeUndefined(); }); it('does not generate a formatted service date for secondary document if a service date is not entered on the form', () => { state.form.secondaryDocument = undefined; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect( result.secondaryDocument.certificateOfServiceDateFormatted, ).toBeUndefined(); @@ -186,25 +218,33 @@ describe('fileDocumentHelper', () => { it('shows Filing Includes on review page if certificateOfService is true', () => { state.form.certificateOfService = true; state.form.certificateOfServiceDate = '2018-01-01'; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.showFilingIncludes).toEqual(true); }); it('does not show Filing Includes if certOfService and attachments are false', () => { state.form.certificateOfService = false; state.form.attachments = false; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.showFilingIncludes).toEqual(false); }); it('does not show party validation error if none of the party validation errors exists', () => { - const result = runCompute(fileDocumentHelper, { state }); + const result = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.partyValidationError).toBeUndefined(); }); it('shows party validation error if any one of the party validation errors exists', () => { state.validationErrors = { filers: 'You did something bad.' }; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.partyValidationError).toEqual('You did something bad.'); }); @@ -215,7 +255,9 @@ describe('fileDocumentHelper', () => { }); it('shows Add Supporting Document button and not limit reached message when supportingDocuments is undefined', () => { - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.showAddSupportingDocuments).toBeTruthy(); expect(result.showAddSupportingDocumentsLimitReached).toBeFalsy(); }); @@ -227,7 +269,9 @@ describe('fileDocumentHelper', () => { { id: '3' }, { id: '4' }, ]; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.showAddSupportingDocuments).toBeTruthy(); expect(result.showAddSupportingDocumentsLimitReached).toBeFalsy(); }); @@ -240,7 +284,9 @@ describe('fileDocumentHelper', () => { { id: '4' }, { id: '5' }, ]; - let result: any = runCompute(fileDocumentHelper, { state }); + let result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.showAddSupportingDocuments).toBeFalsy(); expect(result.showAddSupportingDocumentsLimitReached).toBeTruthy(); state.form.supportingDocuments = [ @@ -251,14 +297,18 @@ describe('fileDocumentHelper', () => { { id: '5' }, { id: '6' }, ]; - result = runCompute(fileDocumentHelper, { state }); + result = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.showAddSupportingDocuments).toBeFalsy(); expect(result.showAddSupportingDocumentsLimitReached).toBeTruthy(); }); it('upload and free text not shown if no type selected', () => { state.form.supportingDocuments = [{ supportingDocument: '' }]; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect( result.supportingDocuments[0].showSupportingDocumentFreeText, ).toBeFalsy(); @@ -271,7 +321,9 @@ describe('fileDocumentHelper', () => { state.form.supportingDocuments = [ { supportingDocument: 'Some Document type' }, ]; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect( result.supportingDocuments[0].showSupportingDocumentFreeText, ).toBeFalsy(); @@ -284,7 +336,9 @@ describe('fileDocumentHelper', () => { state.form.supportingDocuments = [ { supportingDocument: 'Affidavit in Support' }, ]; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect( result.supportingDocuments[0].showSupportingDocumentFreeText, ).toBeTruthy(); @@ -295,7 +349,9 @@ describe('fileDocumentHelper', () => { it('filing includes is shown if attachments is true', () => { state.form.supportingDocuments = [{ attachments: true }]; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.supportingDocuments[0].showFilingIncludes).toBeTruthy(); }); @@ -306,7 +362,9 @@ describe('fileDocumentHelper', () => { certificateOfServiceDate: '2019-01-01', }, ]; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.supportingDocuments[0].showFilingIncludes).toBeTruthy(); expect( result.supportingDocuments[0].certificateOfServiceDateFormatted, @@ -315,7 +373,9 @@ describe('fileDocumentHelper', () => { describe('for secondary supporting document', () => { it('shows Add Secondary Supporting Document button and not limit reached message when secondarySupportingDocuments is undefined', () => { - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.showAddSecondarySupportingDocuments).toBeTruthy(); expect( result.showAddSecondarySupportingDocumentsLimitReached, @@ -324,7 +384,9 @@ describe('fileDocumentHelper', () => { it('does not show Add Secondary Supporting Document button or limit reached message when primary document type is Motion for Leave to File and secondary file is not selected', () => { state.form.documentType = 'Motion for Leave to File'; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.showAddSecondarySupportingDocuments).toBeFalsy(); expect( result.showAddSecondarySupportingDocumentsLimitReached, @@ -338,7 +400,9 @@ describe('fileDocumentHelper', () => { { id: '3' }, { id: '4' }, ]; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.showAddSecondarySupportingDocuments).toBeTruthy(); expect( result.showAddSecondarySupportingDocumentsLimitReached, @@ -353,7 +417,9 @@ describe('fileDocumentHelper', () => { { id: '4' }, { id: '5' }, ]; - let result: any = runCompute(fileDocumentHelper, { state }); + let result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.showAddSecondarySupportingDocuments).toBeFalsy(); expect( result.showAddSecondarySupportingDocumentsLimitReached, @@ -366,7 +432,9 @@ describe('fileDocumentHelper', () => { { id: '5' }, { id: '6' }, ]; - result = runCompute(fileDocumentHelper, { state }); + result = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect(result.showAddSecondarySupportingDocuments).toBeFalsy(); expect( result.showAddSecondarySupportingDocumentsLimitReached, @@ -375,7 +443,9 @@ describe('fileDocumentHelper', () => { it('upload and free text not shown if no type selected', () => { state.form.secondarySupportingDocuments = [{ supportingDocument: '' }]; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect( result.secondarySupportingDocuments[0].showSupportingDocumentFreeText, ).toBeFalsy(); @@ -388,7 +458,9 @@ describe('fileDocumentHelper', () => { state.form.secondarySupportingDocuments = [ { supportingDocument: 'Declaration of Undying Love' }, ]; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect( result.secondarySupportingDocuments[0].showSupportingDocumentFreeText, ).toBeFalsy(); @@ -401,7 +473,9 @@ describe('fileDocumentHelper', () => { state.form.secondarySupportingDocuments = [ { supportingDocument: 'Affidavit in Support' }, ]; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect( result.secondarySupportingDocuments[0].showSupportingDocumentFreeText, ).toBeTruthy(); @@ -412,7 +486,9 @@ describe('fileDocumentHelper', () => { it('filing includes is shown if attachments is true', () => { state.form.secondarySupportingDocuments = [{ attachments: true }]; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect( result.secondarySupportingDocuments[0].showFilingIncludes, ).toBeTruthy(); @@ -425,7 +501,9 @@ describe('fileDocumentHelper', () => { certificateOfServiceDate: '2019-01-01', }, ]; - const result: any = runCompute(fileDocumentHelper, { state }); + const result: any = runCompute(fileDocumentHelper, { + state: { ...state, user: docketClerkUser }, + }); expect( result.secondarySupportingDocuments[0].showFilingIncludes, ).toBeTruthy(); @@ -474,7 +552,7 @@ describe('fileDocumentHelper', () => { it('should be set to the names of all filing petitioners and their titles', () => { const { formattedFilingParties } = runCompute(fileDocumentHelper, { - state, + state: { ...state, user: docketClerkUser }, }); expect(formattedFilingParties).toEqual([ @@ -492,7 +570,7 @@ describe('fileDocumentHelper', () => { }; const { EARedactionAcknowledgement } = runCompute(fileDocumentHelper, { - state, + state: { ...state, user: docketClerkUser }, }); expect(EARedactionAcknowledgement).toEqual(true); @@ -505,7 +583,7 @@ describe('fileDocumentHelper', () => { }; const { EARedactionAcknowledgement } = runCompute(fileDocumentHelper, { - state, + state: { ...state, user: docketClerkUser }, }); expect(EARedactionAcknowledgement).toEqual(false); @@ -518,7 +596,7 @@ describe('fileDocumentHelper', () => { }; const { EARedactionAcknowledgement } = runCompute(fileDocumentHelper, { - state, + state: { ...state, user: docketClerkUser }, }); expect(EARedactionAcknowledgement).toEqual(false); @@ -532,7 +610,7 @@ describe('fileDocumentHelper', () => { }; const { isAutoGenerated } = runCompute(fileDocumentHelper, { - state, + state: { ...state, user: docketClerkUser }, }); expect(isAutoGenerated).toEqual(true); @@ -541,8 +619,6 @@ describe('fileDocumentHelper', () => { describe('showGenerationTypeForm', () => { it('should set showGenerationTypeForm to true if showGenerationType returns true', () => { - applicationContext.getCurrentUser.mockReturnValue(irsPractitionerUser); - state.form = { eventCode: 'EA', generationType: GENERATION_TYPES.AUTO, @@ -557,7 +633,7 @@ describe('fileDocumentHelper', () => { }; const { showGenerationTypeForm } = runCompute(fileDocumentHelper, { - state, + state: { ...state, user: irsPractitionerUser }, }); expect(showGenerationTypeForm).toEqual(true); @@ -565,10 +641,6 @@ describe('fileDocumentHelper', () => { }); describe('showPartiesFiling', () => { - beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue(irsPractitionerUser); - }); - it('should set showPartiesFiling to false if IRS practitioner is filing first IRS document', () => { state.form = { generationType: GENERATION_TYPES.AUTO, @@ -583,7 +655,7 @@ describe('fileDocumentHelper', () => { }; const { showPartiesFiling } = runCompute(fileDocumentHelper, { - state, + state: { ...state, user: irsPractitionerUser }, }); expect(showPartiesFiling).toEqual(false); @@ -608,7 +680,7 @@ describe('fileDocumentHelper', () => { }; const { showPartiesFiling } = runCompute(fileDocumentHelper, { - state, + state: { ...state, user: docketClerkUser }, }); expect(showPartiesFiling).toEqual(true); @@ -617,10 +689,6 @@ describe('fileDocumentHelper', () => { describe('showPartiesFiling', () => { it('should set showPartiesFiling to true if private practitioner is filing a document', () => { - applicationContext.getCurrentUser.mockReturnValue( - privatePractitionerUser, - ); - state.form = { generationType: GENERATION_TYPES.AUTO, }; @@ -634,7 +702,7 @@ describe('fileDocumentHelper', () => { }; const { showPartiesFiling } = runCompute(fileDocumentHelper, { - state, + state: { ...state, user: privatePractitionerUser }, }); expect(showPartiesFiling).toEqual(true); diff --git a/web-client/src/presenter/computeds/fileDocumentHelper.ts b/web-client/src/presenter/computeds/fileDocumentHelper.ts index f81d9cd372a..1e4dfdd732b 100644 --- a/web-client/src/presenter/computeds/fileDocumentHelper.ts +++ b/web-client/src/presenter/computeds/fileDocumentHelper.ts @@ -87,7 +87,7 @@ export const fileDocumentHelper = ( const EARedactionAcknowledgement = form.generationType === GENERATION_TYPES.MANUAL && form.eventCode === 'EA'; - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const showGenerationTypeForm = showGenerationType( user, form.eventCode, diff --git a/web-client/src/presenter/computeds/formattedCaseDetail.formattedClosedCases.test.ts b/web-client/src/presenter/computeds/formattedCaseDetail.formattedClosedCases.test.ts index 9ea3470c8e4..f41a779e01a 100644 --- a/web-client/src/presenter/computeds/formattedCaseDetail.formattedClosedCases.test.ts +++ b/web-client/src/presenter/computeds/formattedCaseDetail.formattedClosedCases.test.ts @@ -1,4 +1,3 @@ -import { ROLES } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { formattedClosedCases as formattedClosedCasesComputed } from './formattedCaseDetail'; import { @@ -11,13 +10,7 @@ import { withAppContextDecorator } from '../../withAppContext'; describe('formattedClosedCases', () => { const formattedClosedCases = withAppContextDecorator( formattedClosedCasesComputed, - { - ...applicationContext, - getCurrentUser: () => ({ - role: ROLES.petitionsClerk, - userId: '111', - }), - }, + applicationContext, ); it('should return formatted closed cases', () => { diff --git a/web-client/src/presenter/computeds/formattedCaseDetail.formattedOpenCases.test.ts b/web-client/src/presenter/computeds/formattedCaseDetail.formattedOpenCases.test.ts index c0acbec9b49..81347a3c776 100644 --- a/web-client/src/presenter/computeds/formattedCaseDetail.formattedOpenCases.test.ts +++ b/web-client/src/presenter/computeds/formattedCaseDetail.formattedOpenCases.test.ts @@ -1,4 +1,3 @@ -import { ROLES } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { formattedOpenCases as formattedOpenCasesComputed } from './formattedCaseDetail'; import { @@ -11,13 +10,7 @@ import { withAppContextDecorator } from '../../withAppContext'; describe('formattedOpenCases', () => { const formattedOpenCases = withAppContextDecorator( formattedOpenCasesComputed, - { - ...applicationContext, - getCurrentUser: () => ({ - role: ROLES.petitionsClerk, - userId: '111', - }), - }, + applicationContext, ); it('should return formatted open cases', () => { diff --git a/web-client/src/presenter/computeds/formattedCaseDetail.getCalendarDetailsForTrialSession.test.ts b/web-client/src/presenter/computeds/formattedCaseDetail.getCalendarDetailsForTrialSession.test.ts index 28cf341571a..ed8f43710bc 100644 --- a/web-client/src/presenter/computeds/formattedCaseDetail.getCalendarDetailsForTrialSession.test.ts +++ b/web-client/src/presenter/computeds/formattedCaseDetail.getCalendarDetailsForTrialSession.test.ts @@ -6,7 +6,6 @@ import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../withAppContext'; describe('getCalendarDetailsForTrialSession', () => { - let globalUser; const { STATUS_TYPES, USER_ROLES } = applicationContext.getConstants(); const petitionsClerkUser = { @@ -18,16 +17,13 @@ describe('getCalendarDetailsForTrialSession', () => { formattedCaseDetailComputed, { ...applicationContext, - getCurrentUser: () => { - return globalUser; - }, }, ); const getBaseState = user => { - globalUser = user; return { permissions: getUserPermissions(user), + user, }; }; diff --git a/web-client/src/presenter/computeds/formattedCaseDetail.test.ts b/web-client/src/presenter/computeds/formattedCaseDetail.test.ts index 353b1f9b19a..5f4cd755d5e 100644 --- a/web-client/src/presenter/computeds/formattedCaseDetail.test.ts +++ b/web-client/src/presenter/computeds/formattedCaseDetail.test.ts @@ -45,23 +45,19 @@ export const mockPetitioners = [ ]; describe('formattedCaseDetail', () => { - let globalUser; const { STATUS_TYPES } = applicationContext.getConstants(); const formattedCaseDetail = withAppContextDecorator( formattedCaseDetailComputed, { ...applicationContext, - getCurrentUser: () => { - return globalUser; - }, }, ); const getBaseState = user => { - globalUser = user; return { permissions: getUserPermissions(user), + user, }; }; @@ -214,6 +210,7 @@ describe('formattedCaseDetail', () => { it('should set contactTypeDisplay on a contact/petitioner', () => { const result = runCompute(formattedCaseDetail, { state: { + ...getBaseState(petitionsClerkUser), caseDetail: { ...MOCK_CASE, petitioners: [ diff --git a/web-client/src/presenter/computeds/formattedCaseDetail.ts b/web-client/src/presenter/computeds/formattedCaseDetail.ts index dcae982cd60..664a579ca64 100644 --- a/web-client/src/presenter/computeds/formattedCaseDetail.ts +++ b/web-client/src/presenter/computeds/formattedCaseDetail.ts @@ -9,7 +9,9 @@ export const formattedOpenCases = ( const { formatCase } = applicationContext.getUtilities(); const cases = get(state.openCases); - return cases.map(myCase => formatCase(applicationContext, myCase)); + const user = get(state.user); + + return cases.map(myCase => formatCase(applicationContext, myCase, user)); }; export const formattedClosedCases = ( @@ -17,9 +19,10 @@ export const formattedClosedCases = ( applicationContext: ClientApplicationContext, ): any => { const { formatCase } = applicationContext.getUtilities(); + const user = get(state.user); const cases = get(state.closedCases); - return cases.map(myCase => formatCase(applicationContext, myCase)); + return cases.map(myCase => formatCase(applicationContext, myCase, user)); }; export const getUserIsAssignedToSession = ({ @@ -82,16 +85,15 @@ export const formattedCaseDetail = ( get: Get, applicationContext: ClientApplicationContext, ): any => { - const user = applicationContext.getCurrentUser(); - const { formatCase, setServiceIndicatorsForCase } = applicationContext.getUtilities(); const caseDetail = get(state.caseDetail); + const user = get(state.user); const result = { ...setServiceIndicatorsForCase(caseDetail), - ...formatCase(applicationContext, caseDetail), + ...formatCase(applicationContext, caseDetail, user), }; result.petitioners = applicationContext diff --git a/web-client/src/presenter/computeds/formattedDashboardTrialSessions.test.ts b/web-client/src/presenter/computeds/formattedDashboardTrialSessions.test.ts index dcd3adc1dd1..3ae829fa2b6 100644 --- a/web-client/src/presenter/computeds/formattedDashboardTrialSessions.test.ts +++ b/web-client/src/presenter/computeds/formattedDashboardTrialSessions.test.ts @@ -69,9 +69,6 @@ describe('formattedDashboardTrialSessions', () => { }); it('returns the expected recent and upcoming sessions', () => { - applicationContext.getCurrentUser = () => ({ - userId: '6', - }); const result = runCompute(formattedDashboardTrialSessions, { state: { trialSessions: TRIAL_SESSIONS_LIST, @@ -82,10 +79,6 @@ describe('formattedDashboardTrialSessions', () => { }); it('returns only open trial sessions', () => { - applicationContext.getCurrentUser = () => ({ - userId: '6', - }); - const trialSessions = [...TRIAL_SESSIONS_LIST]; trialSessions.forEach(session => { session.isCalendared = false; diff --git a/web-client/src/presenter/computeds/formattedDocketEntries.test.ts b/web-client/src/presenter/computeds/formattedDocketEntries.test.ts index b93fdeeda1d..6742f25475f 100644 --- a/web-client/src/presenter/computeds/formattedDocketEntries.test.ts +++ b/web-client/src/presenter/computeds/formattedDocketEntries.test.ts @@ -44,14 +44,10 @@ describe('formattedDocketEntries', () => { formattedDocketEntriesComputed, { ...applicationContext, - getCurrentUser: () => { - return globalUser; - }, }, ); const getBaseState = user => { - globalUser = user; return { documentsSelectedForDownload: [], featureFlags: { @@ -62,11 +58,10 @@ describe('formattedDocketEntries', () => { sessionMetadata: { docketRecordFilter: DOCKET_RECORD_FILTER_OPTIONS.allDocuments, }, + user, }; }; - let globalUser; - it('does not error and returns expected empty values on empty caseDetail', () => { const result = runCompute(formattedDocketEntries, { state: { diff --git a/web-client/src/presenter/computeds/formattedDocketEntries.ts b/web-client/src/presenter/computeds/formattedDocketEntries.ts index 1beeafe4d2b..cd44210db60 100644 --- a/web-client/src/presenter/computeds/formattedDocketEntries.ts +++ b/web-client/src/presenter/computeds/formattedDocketEntries.ts @@ -203,7 +203,7 @@ export const formattedDocketEntries = ( get: Get, applicationContext: ClientApplicationContext, ): any => { - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const permissions = get(state.permissions); const { docketRecordFilter } = get(state.sessionMetadata); const { ALLOWLIST_FEATURE_FLAGS } = applicationContext.getConstants(); @@ -225,7 +225,7 @@ export const formattedDocketEntries = ( .getUtilities() .prepareDateFromString(DOCUMENT_VISIBILITY_POLICY_CHANGE_DATE) .toISO(); - const result = formatCase(applicationContext, caseDetail); + const result = formatCase(applicationContext, caseDetail, user); const documentsSelectedForDownload = get(state.documentsSelectedForDownload); result.formattedDocketEntries = applicationContext diff --git a/web-client/src/presenter/computeds/formattedMessageDetail.test.ts b/web-client/src/presenter/computeds/formattedMessageDetail.test.ts index c93a4ea791e..f9bec7135f7 100644 --- a/web-client/src/presenter/computeds/formattedMessageDetail.test.ts +++ b/web-client/src/presenter/computeds/formattedMessageDetail.test.ts @@ -56,6 +56,7 @@ describe('formattedMessageDetail', () => { messageId: '98a9dbc4-a8d1-459b-98b2-30235b596d70', }, ], + user: { ...generalUser }, }, }); @@ -105,6 +106,7 @@ describe('formattedMessageDetail', () => { messageId: '98a9dbc4-a8d1-459b-98b2-30235b596d70', }, ], + user: { ...generalUser }, }, }); @@ -139,6 +141,7 @@ describe('formattedMessageDetail', () => { { attachments: [], createdAt: '2019-03-01T21:40:46.415Z' }, { attachments: [], createdAt: '2019-04-01T21:40:46.415Z' }, ], + user: { ...generalUser }, }, }); @@ -152,6 +155,7 @@ describe('formattedMessageDetail', () => { messageDetail: [ { attachments: [], createdAt: '2019-03-01T21:40:46.415Z' }, ], + user: { ...generalUser }, }, }); @@ -168,6 +172,7 @@ describe('formattedMessageDetail', () => { { attachments: [], createdAt: '2019-03-01T21:40:46.415Z' }, { attachments: [], createdAt: '2019-04-01T21:40:46.415Z' }, ], + user: { ...generalUser }, }, }); @@ -183,6 +188,7 @@ describe('formattedMessageDetail', () => { { attachments: [], createdAt: '2019-03-01T21:40:46.415Z' }, { attachments: [], createdAt: '2019-04-01T21:40:46.415Z' }, ], + user: { ...generalUser }, }, }); @@ -213,6 +219,7 @@ describe('formattedMessageDetail', () => { messageId: '98a9dbc4-a8d1-459b-98b2-30235b596d70', }, ], + user: { ...generalUser }, }, }); @@ -273,6 +280,7 @@ describe('formattedMessageDetail', () => { createdAt: '2019-03-01T21:40:46.415Z', }, ], + user: { ...generalUser }, }, }); @@ -308,6 +316,7 @@ describe('formattedMessageDetail', () => { createdAt: '2019-03-01T21:40:46.415Z', }, ], + user: { ...generalUser }, }, }); @@ -339,6 +348,7 @@ describe('formattedMessageDetail', () => { createdAt: '2019-03-01T21:40:46.415Z', }, ], + user: { ...generalUser }, }, }); @@ -348,8 +358,6 @@ describe('formattedMessageDetail', () => { describe('showActionButtons', () => { it('should be true when message is NOT completed and user role is NOT general', () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - const result = runCompute(formattedMessageDetail, { state: { caseDetail: { @@ -371,6 +379,7 @@ describe('formattedMessageDetail', () => { messageId: '98a9dbc4-a8d1-459b-98b2-30235b596d70', }, ], + user: petitionsClerkUser, }, }); @@ -378,8 +387,6 @@ describe('formattedMessageDetail', () => { }); it('should be false when message is NOT completed and user role is general', () => { - applicationContext.getCurrentUser.mockReturnValue(generalUser); - const result = runCompute(formattedMessageDetail, { state: { caseDetail: { @@ -401,6 +408,7 @@ describe('formattedMessageDetail', () => { messageId: '98a9dbc4-a8d1-459b-98b2-30235b596d70', }, ], + user: generalUser, }, }); @@ -408,8 +416,6 @@ describe('formattedMessageDetail', () => { }); it('should be false when message is completed and user role is NOT general', () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - const result = runCompute(formattedMessageDetail, { state: { caseDetail: { @@ -431,6 +437,7 @@ describe('formattedMessageDetail', () => { messageId: '98a9dbc4-a8d1-459b-98b2-30235b596d70', }, ], + user: petitionsClerkUser, }, }); @@ -438,8 +445,6 @@ describe('formattedMessageDetail', () => { }); it('should be false when message is completed and user role is general', () => { - applicationContext.getCurrentUser.mockReturnValue(generalUser); - const result = runCompute(formattedMessageDetail, { state: { caseDetail: { @@ -461,6 +466,7 @@ describe('formattedMessageDetail', () => { messageId: '98a9dbc4-a8d1-459b-98b2-30235b596d70', }, ], + user: generalUser, }, }); diff --git a/web-client/src/presenter/computeds/formattedMessageDetail.ts b/web-client/src/presenter/computeds/formattedMessageDetail.ts index 8e45d01de41..e74d0d1abe2 100644 --- a/web-client/src/presenter/computeds/formattedMessageDetail.ts +++ b/web-client/src/presenter/computeds/formattedMessageDetail.ts @@ -34,12 +34,12 @@ export const formattedMessageDetail = ( const messageDetail = get(state.messageDetail); const caseDetail = get(state.caseDetail); const isExpanded = get(state.isExpanded); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); const { draftDocuments } = applicationContext .getUtilities() - .formatCase(applicationContext, caseDetail); + .formatCase(applicationContext, caseDetail, user); const formattedMessages = orderBy( messageDetail.map(message => diff --git a/web-client/src/presenter/computeds/formattedTrialSessionDetails.test.ts b/web-client/src/presenter/computeds/formattedTrialSessionDetails.test.ts index a8b94eab28b..5f7ac902ce3 100644 --- a/web-client/src/presenter/computeds/formattedTrialSessionDetails.test.ts +++ b/web-client/src/presenter/computeds/formattedTrialSessionDetails.test.ts @@ -8,7 +8,8 @@ import { import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { colvinsChambersUser, - judgeUser, + docketClerkUser, + trialClerkUser, } from '../../../../shared/src/test/mockUsers'; import { formattedTrialSessionDetails as formattedTrialSessionDetailsComputed } from './formattedTrialSessionDetails'; import { omit } from 'lodash'; @@ -63,6 +64,7 @@ describe('formattedTrialSessionDetails', () => { const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -77,6 +79,7 @@ describe('formattedTrialSessionDetails', () => { let result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -89,6 +92,7 @@ describe('formattedTrialSessionDetails', () => { result = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -120,6 +124,7 @@ describe('formattedTrialSessionDetails', () => { const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -134,6 +139,7 @@ describe('formattedTrialSessionDetails', () => { const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -146,6 +152,7 @@ describe('formattedTrialSessionDetails', () => { const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -163,6 +170,7 @@ describe('formattedTrialSessionDetails', () => { isCalendared: false, startDate: PAST_DATE, }, + user: trialClerkUser, }, }); expect(result).toMatchObject({ @@ -180,6 +188,7 @@ describe('formattedTrialSessionDetails', () => { const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -198,6 +207,7 @@ describe('formattedTrialSessionDetails', () => { const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -216,6 +226,7 @@ describe('formattedTrialSessionDetails', () => { const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -234,6 +245,7 @@ describe('formattedTrialSessionDetails', () => { sessionStatus: SESSION_STATUS_GROUPS.open, startDate: PAST_DATE, }, + user: trialClerkUser, }, }); expect(result).toMatchObject({ @@ -251,6 +263,7 @@ describe('formattedTrialSessionDetails', () => { const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -266,11 +279,10 @@ describe('formattedTrialSessionDetails', () => { startDate: FUTURE_DATE, }; - applicationContext.getCurrentUser.mockReturnValue(judgeUser); - const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -279,6 +291,68 @@ describe('formattedTrialSessionDetails', () => { }); }); + describe('docketClerk user canEdit', () => { + it('should be true when canEdit is true and docketClerk user is editing a Special TrialSession', () => { + mockTrialSession = { + ...TRIAL_SESSION, + sessionStatus: SESSION_STATUS_GROUPS.open, + sessionType: SESSION_TYPES.special, + startDate: FUTURE_DATE, + }; + + const result: any = runCompute(formattedTrialSessionDetails, { + state: { + trialSession: {}, + user: docketClerkUser, + }, + }); + + expect(result).toMatchObject({ + canEdit: true, + }); + }); + + it('should be true when canEdit is true and docketClerk user is editing a Motion/Hearing TrialSession', () => { + mockTrialSession = { + ...TRIAL_SESSION, + sessionStatus: SESSION_STATUS_GROUPS.open, + sessionType: SESSION_TYPES.motionHearing, + startDate: FUTURE_DATE, + }; + + const result: any = runCompute(formattedTrialSessionDetails, { + state: { + trialSession: {}, + user: docketClerkUser, + }, + }); + + expect(result).toMatchObject({ + canEdit: true, + }); + }); + + it('should be false when docketClerk user sees a non- Motion/Hearing or Special TrialSession', () => { + mockTrialSession = { + ...TRIAL_SESSION, + sessionStatus: SESSION_STATUS_GROUPS.open, + sessionType: SESSION_TYPES.hybrid, + startDate: FUTURE_DATE, + }; + + const result: any = runCompute(formattedTrialSessionDetails, { + state: { + trialSession: {}, + user: docketClerkUser, + }, + }); + + expect(result).toMatchObject({ + canEdit: false, + }); + }); + }); + it('should be false when trial session start date is in the future, it is NOT closed, the user is a chambers role', () => { mockTrialSession = { ...TRIAL_SESSION, @@ -286,11 +360,10 @@ describe('formattedTrialSessionDetails', () => { startDate: FUTURE_DATE, }; - applicationContext.getCurrentUser.mockReturnValue(colvinsChambersUser); - const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: colvinsChambersUser, }, }); @@ -309,6 +382,7 @@ describe('formattedTrialSessionDetails', () => { const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -330,6 +404,7 @@ describe('formattedTrialSessionDetails', () => { const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -347,6 +422,7 @@ describe('formattedTrialSessionDetails', () => { const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -364,6 +440,7 @@ describe('formattedTrialSessionDetails', () => { const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); expect(result.canClose).toBe(false); @@ -380,6 +457,7 @@ describe('formattedTrialSessionDetails', () => { const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -397,6 +475,7 @@ describe('formattedTrialSessionDetails', () => { const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -414,6 +493,7 @@ describe('formattedTrialSessionDetails', () => { const result: any = runCompute(formattedTrialSessionDetails, { state: { trialSession: {}, + user: trialClerkUser, }, }); @@ -433,6 +513,7 @@ describe('formattedTrialSessionDetails', () => { trialSession: { ...mockTrialSession, }, + user: trialClerkUser, }, }); @@ -454,6 +535,7 @@ describe('formattedTrialSessionDetails', () => { trialSession: { ...mockTrialSession, }, + user: trialClerkUser, }, }); @@ -475,6 +557,7 @@ describe('formattedTrialSessionDetails', () => { trialSession: { ...mockTrialSession, }, + user: trialClerkUser, }, }); @@ -494,6 +577,7 @@ describe('formattedTrialSessionDetails', () => { trialSession: { ...mockTrialSession, }, + user: trialClerkUser, }, }); @@ -514,6 +598,7 @@ describe('formattedTrialSessionDetails', () => { trialSession: { ...mockTrialSession, }, + user: trialClerkUser, }, }, ); diff --git a/web-client/src/presenter/computeds/formattedTrialSessionDetails.ts b/web-client/src/presenter/computeds/formattedTrialSessionDetails.ts index c180ea278a0..f4f17cbfb68 100644 --- a/web-client/src/presenter/computeds/formattedTrialSessionDetails.ts +++ b/web-client/src/presenter/computeds/formattedTrialSessionDetails.ts @@ -86,10 +86,13 @@ export const formattedTrialSessionDetails = ( .getUtilities() .formatNow(DATE_FORMATS.YYYYMMDD); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const isChambersUser = user.role === USER_ROLES.chambers; - const trialDateInFuture = trialDateFormatted > nowDateFormatted; + const docketClerkCanEditCheck = sessionType => { + const editableSessionTypes = ['Special', 'Motion/Hearing']; + return editableSessionTypes.includes(sessionType); + }; canDelete = trialDateInFuture && !formattedTrialSession.isCalendared; canEdit = @@ -97,6 +100,10 @@ export const formattedTrialSessionDetails = ( formattedTrialSession.sessionStatus !== SESSION_STATUS_GROUPS.closed && !isChambersUser; + if (user.role === USER_ROLES.docketClerk && canEdit) { + canEdit = docketClerkCanEditCheck(formattedTrialSession.sessionType); + } + const allCases = formattedTrialSession.caseOrder || []; const inactiveCases = allCases.filter( sessionCase => sessionCase.removedFromTrial === true, diff --git a/web-client/src/presenter/computeds/formattedTrialSessions.test.ts b/web-client/src/presenter/computeds/formattedTrialSessions.test.ts index ac69abb0f98..c30830cd766 100644 --- a/web-client/src/presenter/computeds/formattedTrialSessions.test.ts +++ b/web-client/src/presenter/computeds/formattedTrialSessions.test.ts @@ -6,6 +6,7 @@ import { import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { formatTrialSessionDisplayOptions } from './addToTrialSessionModalHelper'; import { formattedTrialSessions as formattedTrialSessionsComputed } from './formattedTrialSessions'; +import { judgeUser, petitionsClerkUser } from '@shared/test/mockUsers'; import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../withAppContext'; jest.mock('./addToTrialSessionModalHelper.ts'); @@ -20,7 +21,6 @@ const formattedTrialSessions = withAppContextDecorator( formattedTrialSessionsComputed, { ...applicationContext, - getCurrentUser: () => currentUser, }, ); @@ -29,12 +29,6 @@ const getStartOfWeek = date => { }; let nextYear; -let currentUser = {}; - -const testJudgeUser = { - role: ROLES.judge, - userId: '1', -}; const testTrialClerkUser = { role: ROLES.trialClerk, @@ -43,7 +37,7 @@ const testTrialClerkUser = { const baseState = { constants: { USER_ROLES: ROLES }, - judgeUser: testJudgeUser, + judgeUser, }; let TRIAL_SESSIONS_LIST: any[] = []; @@ -54,12 +48,11 @@ describe('formattedTrialSessions', () => { }); beforeEach(() => { - currentUser = testJudgeUser; TRIAL_SESSIONS_LIST = [ { caseOrder: [], isCalendared: true, - judge: { name: '1', userId: '1' }, + judge: { name: judgeUser.name, userId: judgeUser.userId }, proceedingType: TRIAL_SESSION_PROCEEDING_TYPES.inPerson, sessionStatus: 'Open', sessionType: SESSION_TYPES.regular, @@ -177,6 +170,7 @@ describe('formattedTrialSessions', () => { state: { ...baseState, trialSessions: TRIAL_SESSIONS_LIST, + user: judgeUser, }, }); } catch (err) { @@ -190,7 +184,7 @@ describe('formattedTrialSessions', () => { state: { ...baseState, trialSessions: TRIAL_SESSIONS_LIST, - user: testJudgeUser, + user: judgeUser, }, }); @@ -208,9 +202,11 @@ describe('formattedTrialSessions', () => { const result = runCompute(formattedTrialSessions, { state: { ...baseState, - screenMetadata: { trialSessionFilters: { judge: { userId: '1' } } }, + screenMetadata: { + trialSessionFilters: { judge: { userId: judgeUser.userId } }, + }, trialSessions: TRIAL_SESSIONS_LIST, - user: testJudgeUser, + user: judgeUser, }, }); expect(result.formattedSessions.length).toBe(1); @@ -227,7 +223,7 @@ describe('formattedTrialSessions', () => { }, }, trialSessions: TRIAL_SESSIONS_LIST, - user: testJudgeUser, + user: judgeUser, }, }); const flattenedSessions = result.formattedSessions.flatMap( @@ -242,7 +238,7 @@ describe('formattedTrialSessions', () => { ...baseState, screenMetadata: { trialSessionFilters: { judge: { userId: '' } } }, trialSessions: TRIAL_SESSIONS_LIST, - user: testJudgeUser, + user: judgeUser, }, }); expect(result.formattedSessions.length).toBe(4); @@ -261,7 +257,7 @@ describe('formattedTrialSessions', () => { trialSessionFilters: { judge: { userId: 'unassigned' } }, }, trialSessions: TRIAL_SESSIONS_LIST, - user: testJudgeUser, + user: judgeUser, }, }); @@ -278,7 +274,7 @@ describe('formattedTrialSessions', () => { ...baseState, form, trialSessions: TRIAL_SESSIONS_LIST, - user: testJudgeUser, + user: judgeUser, }, }); expect(result.sessionsByTerm.length).toEqual(0); @@ -290,7 +286,7 @@ describe('formattedTrialSessions', () => { ...baseState, form, trialSessions: TRIAL_SESSIONS_LIST, - user: testJudgeUser, + user: judgeUser, }, }); expect(result.sessionsByTerm.length).toEqual(1); @@ -302,7 +298,7 @@ describe('formattedTrialSessions', () => { ...baseState, form, trialSessions: TRIAL_SESSIONS_LIST, - user: testJudgeUser, + user: judgeUser, }, }); expect(result.sessionsByTerm.length).toEqual(0); @@ -317,7 +313,7 @@ describe('formattedTrialSessions', () => { term: 'Winter', }, trialSessions: TRIAL_SESSIONS_LIST, - user: testJudgeUser, + user: judgeUser, }, }); @@ -417,7 +413,7 @@ describe('formattedTrialSessions', () => { term: 'Winter', }, trialSessions: TRIAL_SESSIONS_LIST, - user: testJudgeUser, + user: judgeUser, }, }); @@ -433,7 +429,7 @@ describe('formattedTrialSessions', () => { }, trialSession: { trialSessionId: TRIAL_SESSIONS_LIST[1].trialSessionId }, trialSessions: TRIAL_SESSIONS_LIST, - user: testJudgeUser, + user: judgeUser, }, }); @@ -451,7 +447,7 @@ describe('formattedTrialSessions', () => { ...baseState, judgeUser: undefined, trialSessions: TRIAL_SESSIONS_LIST, - user: { role: ROLES.petitionsClerk, userId: '1' }, + user: petitionsClerkUser, }, }); @@ -463,7 +459,7 @@ describe('formattedTrialSessions', () => { userIsAssignedToSession: false, }, { - judge: { name: '1', userId: '1' }, + judge: { name: judgeUser.name, userId: judgeUser.userId }, userIsAssignedToSession: false, }, { @@ -499,7 +495,7 @@ describe('formattedTrialSessions', () => { state: { ...baseState, trialSessions: TRIAL_SESSIONS_LIST, - user: testJudgeUser, + user: judgeUser, }, }); expect(result.formattedSessions).toMatchObject([ @@ -511,7 +507,7 @@ describe('formattedTrialSessions', () => { userIsAssignedToSession: false, }, { - judge: { name: '1', userId: '1' }, + judge: { name: judgeUser.name, userId: judgeUser.userId }, userIsAssignedToSession: true, }, { @@ -577,13 +573,12 @@ describe('formattedTrialSessions', () => { }); it('sets userIsAssignedToSession true for sessions the current trial clerk user is assigned to', () => { - currentUser = testTrialClerkUser; - const result = runCompute(formattedTrialSessions, { state: { ...baseState, judgeUser: undefined, trialSessions: TRIAL_SESSIONS_LIST, + user: testTrialClerkUser, }, }); @@ -595,7 +590,7 @@ describe('formattedTrialSessions', () => { userIsAssignedToSession: false, }, { - judge: { name: '1', userId: '1' }, + judge: { name: judgeUser.name, userId: judgeUser.userId }, userIsAssignedToSession: false, }, { @@ -642,7 +637,7 @@ describe('formattedTrialSessions', () => { trialLocation: 'Jacksonville, FL', }, ], - user: { role: ROLES.petitionsClerk, userId: '1' }, + user: petitionsClerkUser, }, }); expect(result.formattedSessions).toMatchObject([ diff --git a/web-client/src/presenter/computeds/formattedTrialSessions.ts b/web-client/src/presenter/computeds/formattedTrialSessions.ts index 24834e754db..e33ec8d5669 100644 --- a/web-client/src/presenter/computeds/formattedTrialSessions.ts +++ b/web-client/src/presenter/computeds/formattedTrialSessions.ts @@ -184,7 +184,7 @@ export const formattedTrialSessions = ( ): any => { const judgeId = get(state.judgeUser.userId); const currentTrialSessionId = get(state.trialSession.trialSessionId); - const currentUser = applicationContext.getCurrentUser(); + const currentUser = get(state.user); const trialSessionFilters = pickBy( omit(get(state.screenMetadata.trialSessionFilters), 'status'), diff --git a/web-client/src/presenter/computeds/formattedWorkQueue.filterWorkItems.test.ts b/web-client/src/presenter/computeds/formattedWorkQueue.filterWorkItems.test.ts index bb4fb2e8962..e409dc5f1c2 100644 --- a/web-client/src/presenter/computeds/formattedWorkQueue.filterWorkItems.test.ts +++ b/web-client/src/presenter/computeds/formattedWorkQueue.filterWorkItems.test.ts @@ -1,5 +1,6 @@ import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { filterWorkItems } from './formattedWorkQueue'; +import { petitionsClerkUser } from '@shared/test/mockUsers'; const { DOCKET_SECTION, @@ -106,11 +107,6 @@ describe('filterWorkItems', () => { let workQueueOutbox; beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.docketClerk, - userId: '7f87f5d1-dfce-4515-a1e4-5231ceac61bb', - }); - workItemPetitionsMyDocumentQCInbox = generateWorkItem({ assigneeId: petitionsClerk1.userId, docketNumber: '100-05', @@ -201,10 +197,10 @@ describe('filterWorkItems', () => { // PETITIONS CLERK it('Returns section work items for a Petitions Clerk in Section Document QC Inbox', () => { - applicationContext.getCurrentUser.mockReturnValueOnce(petitionsClerk1); - const filtered = filterWorkItems({ applicationContext, + authorizedUser: petitionsClerkUser, + section: PETITIONS_SECTION, workItems: workQueueInbox, ...SECTION_DOCUMENT_QC_INBOX, } as any); @@ -229,9 +225,9 @@ describe('filterWorkItems', () => { }); it('Returns sent work items for a Petitions Clerk in Section Document QC Outbox', () => { - applicationContext.getCurrentUser.mockReturnValueOnce(petitionsClerk1); const filtered = filterWorkItems({ applicationContext, + authorizedUser: petitionsClerk1, workItems: workQueueOutbox, ...SECTION_DOCUMENT_QC_OUTBOX, } as any); @@ -261,9 +257,9 @@ describe('filterWorkItems', () => { // DOCKET CLERK it('Returns section work items for a Docket Clerk in Section Document QC Inbox', () => { - applicationContext.getCurrentUser.mockReturnValueOnce(docketClerk1); const filtered = filterWorkItems({ applicationContext, + authorizedUser: docketClerk1, workItems: workQueueInbox, ...SECTION_DOCUMENT_QC_INBOX, } as any); @@ -288,9 +284,9 @@ describe('filterWorkItems', () => { }); it('Returns docket section work items for an ADC in Document QC Inbox', () => { - applicationContext.getCurrentUser.mockReturnValueOnce(adc); const filtered = filterWorkItems({ applicationContext, + authorizedUser: adc, workItems: workQueueInbox, ...SECTION_DOCUMENT_QC_INBOX, } as any); @@ -302,9 +298,9 @@ describe('filterWorkItems', () => { }); it('Returns docket section work items for a Docket Clerk in My Document QC In Progress', () => { - applicationContext.getCurrentUser.mockReturnValueOnce(docketClerk1); const filtered = filterWorkItems({ applicationContext, + authorizedUser: docketClerk1, workItems: workQueueInProgress, ...MY_DOCUMENT_QC_IN_PROGRESS, } as any); @@ -313,9 +309,9 @@ describe('filterWorkItems', () => { }); it('Returns docket section work items for a Docket Clerk in Section Document QC In Progress', () => { - applicationContext.getCurrentUser.mockReturnValueOnce(docketClerk1); const filtered = filterWorkItems({ applicationContext, + authorizedUser: docketClerk1, workItems: workQueueInProgress, ...SECTION_DOCUMENT_QC_IN_PROGRESS, } as any); @@ -327,9 +323,9 @@ describe('filterWorkItems', () => { }); it('should getWorkQueueFilters with the section argument', () => { - applicationContext.getCurrentUser.mockReturnValueOnce(docketClerk1); filterWorkItems({ applicationContext, + authorizedUser: docketClerk1, section: DOCKET_SECTION, workItems: workQueueInProgress, ...SECTION_DOCUMENT_QC_IN_PROGRESS, diff --git a/web-client/src/presenter/computeds/formattedWorkQueue.getWorkItemDocumentLink.test.ts b/web-client/src/presenter/computeds/formattedWorkQueue.getWorkItemDocumentLink.test.ts index df412e40c2c..efd61de9b14 100644 --- a/web-client/src/presenter/computeds/formattedWorkQueue.getWorkItemDocumentLink.test.ts +++ b/web-client/src/presenter/computeds/formattedWorkQueue.getWorkItemDocumentLink.test.ts @@ -16,16 +16,10 @@ describe('getWorkItemDocumentLink', () => { STATUS_TYPES, } = applicationContext.getConstants(); - let globalUser; - - applicationContext.getCurrentUser = () => { - return globalUser; - }; - const getBaseState = user => { - globalUser = user; return { permissions: getUserPermissions(user), + user, }; }; @@ -65,10 +59,12 @@ describe('getWorkItemDocumentLink', () => { const documentViewLink = `/case-detail/${baseWorkItem.docketNumber}/document-view?docketEntryId=6db35185-2445-4952-9449-5479a5cadab0`; it('should return editLink as petition qc page if document is petition, case is not in progress, and user is petitionsclerk viewing a QC box', () => { - const { permissions } = getBaseState(petitionsClerkUser); + const { permissions, user: authorizedUser } = + getBaseState(petitionsClerkUser); const result = getWorkItemDocumentLink({ applicationContext, + authorizedUser, permissions, workItem: { ...baseWorkItem, @@ -92,10 +88,11 @@ describe('getWorkItemDocumentLink', () => { }); it('should return /edit-court-issued if document is court-issued and not served and user is docketclerk', () => { - const { permissions } = getBaseState(docketClerkUser); + const { permissions, user: authorizedUser } = getBaseState(docketClerkUser); const result = getWorkItemDocumentLink({ applicationContext, + authorizedUser, permissions, workItem: { ...baseWorkItem, @@ -119,10 +116,12 @@ describe('getWorkItemDocumentLink', () => { }); it('should return editLink as default document detail page if document is court-issued and not served and user is petitionsclerk viewing a QC box', () => { - const { permissions } = getBaseState(petitionsClerkUser); + const { permissions, user: authorizedUser } = + getBaseState(petitionsClerkUser); const result = getWorkItemDocumentLink({ applicationContext, + authorizedUser, permissions, workItem: { ...baseWorkItem, @@ -145,10 +144,11 @@ describe('getWorkItemDocumentLink', () => { }); it('should return /complete if work item is in progress and user is docketclerk', () => { - const { permissions } = getBaseState(docketClerkUser); + const { permissions, user: authorizedUser } = getBaseState(docketClerkUser); const result = getWorkItemDocumentLink({ applicationContext, + authorizedUser, permissions, workItem: { ...baseWorkItem, @@ -177,10 +177,11 @@ describe('getWorkItemDocumentLink', () => { }); it('should return /complete when the eventCode MISC and the isPaper is false', () => { - const { permissions } = getBaseState(docketClerkUser); + const { permissions, user: authorizedUser } = getBaseState(docketClerkUser); const result = getWorkItemDocumentLink({ applicationContext, + authorizedUser, permissions, workItem: { ...baseWorkItem, @@ -202,10 +203,11 @@ describe('getWorkItemDocumentLink', () => { }); it('should return case detail link if document is processed and user is docketclerk', () => { - const { permissions } = getBaseState(docketClerkUser); + const { permissions, user: authorizedUser } = getBaseState(docketClerkUser); const result = getWorkItemDocumentLink({ applicationContext, + authorizedUser, permissions, workItem: { ...baseWorkItem, @@ -237,10 +239,11 @@ describe('getWorkItemDocumentLink', () => { }); it('should return docket entry edit link if document is in progress and user is docketclerk', () => { - const { permissions } = getBaseState(docketClerkUser); + const { permissions, user: authorizedUser } = getBaseState(docketClerkUser); const result = getWorkItemDocumentLink({ applicationContext, + authorizedUser, permissions, workItem: { ...baseWorkItem, @@ -272,10 +275,11 @@ describe('getWorkItemDocumentLink', () => { it('should return default document view link when the document has been processed, is unservable, and the user is docketClerk', () => { const { UNSERVABLE_EVENT_CODES } = applicationContext.getConstants(); - const { permissions } = getBaseState(docketClerkUser); + const { permissions, user: authorizedUser } = getBaseState(docketClerkUser); const result = getWorkItemDocumentLink({ applicationContext, + authorizedUser, permissions, workItem: { ...baseWorkItem, @@ -304,10 +308,12 @@ describe('getWorkItemDocumentLink', () => { }); it('should return default document view link if document is in progress and user is petitionsClerk', () => { - const { permissions } = getBaseState(petitionsClerkUser); + const { permissions, user: authorizedUser } = + getBaseState(petitionsClerkUser); const result = getWorkItemDocumentLink({ applicationContext, + authorizedUser, permissions, workItem: { ...baseWorkItem, @@ -333,10 +339,11 @@ describe('getWorkItemDocumentLink', () => { }); it("should return /edit if document is an external doc that has not been qc'd and user is docketclerk", () => { - const { permissions } = getBaseState(docketClerkUser); + const { permissions, user: authorizedUser } = getBaseState(docketClerkUser); const result = getWorkItemDocumentLink({ applicationContext, + authorizedUser, permissions, workItem: { ...baseWorkItem, @@ -362,10 +369,11 @@ describe('getWorkItemDocumentLink', () => { }); it('should return editLink as /edit if the box is my inbox and user is docketClerk', () => { - const { permissions } = getBaseState(docketClerkUser); + const { permissions, user: authorizedUser } = getBaseState(docketClerkUser); const result = getWorkItemDocumentLink({ applicationContext, + authorizedUser, permissions, workItem: { ...baseWorkItem, @@ -388,10 +396,12 @@ describe('getWorkItemDocumentLink', () => { }); it('should return editLink as /review if the box is my inProgress and user is petitionsClerk', () => { - const { permissions } = getBaseState(petitionsClerkUser); + const { permissions, user: authorizedUser } = + getBaseState(petitionsClerkUser); const result = getWorkItemDocumentLink({ applicationContext, + authorizedUser, permissions, workItem: { ...baseWorkItem, @@ -418,10 +428,13 @@ describe('getWorkItemDocumentLink', () => { }); it('should return editLink as /review if the box is my inProgress and user is caseServicesSupervisor', () => { - const { permissions } = getBaseState(caseServicesSupervisorUser); + const { permissions, user: authorizedUser } = getBaseState( + caseServicesSupervisorUser, + ); const result = getWorkItemDocumentLink({ applicationContext, + authorizedUser, permissions, workItem: { ...baseWorkItem, @@ -448,10 +461,13 @@ describe('getWorkItemDocumentLink', () => { }); it('should return editLink as petition qc page if document is petition, case is not in progress, and user is caseServicesSupervisor viewing a QC box', () => { - const { permissions } = getBaseState(caseServicesSupervisorUser); + const { permissions, user: authorizedUser } = getBaseState( + caseServicesSupervisorUser, + ); const result = getWorkItemDocumentLink({ applicationContext, + authorizedUser, permissions, workItem: { ...baseWorkItem, diff --git a/web-client/src/presenter/computeds/formattedWorkQueue.test.ts b/web-client/src/presenter/computeds/formattedWorkQueue.test.ts index 839513aac31..63798539202 100644 --- a/web-client/src/presenter/computeds/formattedWorkQueue.test.ts +++ b/web-client/src/presenter/computeds/formattedWorkQueue.test.ts @@ -18,18 +18,13 @@ describe('formattedWorkQueue', () => { TRIAL_SESSION_SCOPE_TYPES, } = applicationContext.getConstants(); - let globalUser; let screenMetadata = {}; - applicationContext.getCurrentUser = () => { - return globalUser; - }; - const getBaseState = user => { - globalUser = user; return { permissions: getUserPermissions(user), screenMetadata, + user, users: [docketClerkUser, validUser], }; }; diff --git a/web-client/src/presenter/computeds/formattedWorkQueue.ts b/web-client/src/presenter/computeds/formattedWorkQueue.ts index 8fd5fcf8eec..f8a5817ccd5 100644 --- a/web-client/src/presenter/computeds/formattedWorkQueue.ts +++ b/web-client/src/presenter/computeds/formattedWorkQueue.ts @@ -2,6 +2,7 @@ import { ClientApplicationContext } from '@web-client/applicationContext'; import { DocketEntry } from '../../../../shared/src/business/entities/DocketEntry'; import { Get } from 'cerebral'; import { RawWorkItem } from '@shared/business/entities/WorkItem'; +import { UnknownAuthUser } from '@shared/business/entities/authUser/AuthUser'; import { capitalize, cloneDeep, map, memoize, orderBy } from 'lodash'; import { state } from '@web-client/presenter/app.cerebral'; @@ -249,9 +250,16 @@ const getDocketEntryEditLink = ({ export const getWorkItemDocumentLink = ({ applicationContext, + authorizedUser, permissions, workItem, workQueueToDisplay, +}: { + applicationContext: any; + permissions: any; + workItem: any; + workQueueToDisplay: any; + authorizedUser: UnknownAuthUser; }) => { const result = cloneDeep(workItem); @@ -284,8 +292,7 @@ export const getWorkItemDocumentLink = ({ if (showDocumentEditLink) { if ( permissions.DOCKET_ENTRY && - (applicationContext.getCurrentUser().role !== - USER_ROLES.caseServicesSupervisor || + (authorizedUser?.role !== USER_ROLES.caseServicesSupervisor || !formattedDocketEntry.isPetition) ) { const editLinkExtension = getDocketEntryEditLink({ @@ -317,16 +324,23 @@ export const getWorkItemDocumentLink = ({ export const filterWorkItems = ({ applicationContext, assignmentFilterValue, + authorizedUser, section, workItems, workQueueToDisplay, +}: { + applicationContext: ClientApplicationContext; + assignmentFilterValue: any; + section: any; + workItems: any; + workQueueToDisplay: any; + authorizedUser: UnknownAuthUser; }) => { - const user = applicationContext.getCurrentUser(); const { box, queue } = workQueueToDisplay; const filters = applicationContext .getUtilities() - .getWorkQueueFilters({ section, user }); + .getWorkQueueFilters({ section, user: authorizedUser }); const composedFilter = filters[queue][box]; let assignmentFilter = workItem => { @@ -358,10 +372,18 @@ export const filterWorkItems = ({ const memoizedFormatItemWithLink = memoize( ({ applicationContext, + authorizedUser, isSelected, permissions, workItem, workQueueToDisplay, + }: { + applicationContext: any; + isSelected: any; + permissions: any; + workItem: any; + workQueueToDisplay: any; + authorizedUser: UnknownAuthUser; }) => { const result = formatWorkItem({ applicationContext, @@ -370,6 +392,7 @@ const memoizedFormatItemWithLink = memoize( }); const editLink = getWorkItemDocumentLink({ applicationContext, + authorizedUser, permissions, workItem, workQueueToDisplay, @@ -393,6 +416,7 @@ export const formattedWorkQueue = ( let { assignmentFilterValue } = get(state.screenMetadata); let { STATUS_TYPES } = applicationContext.getConstants(); const users = get(state.users); + const authorizedUser = get(state.user); if (assignmentFilterValue && assignmentFilterValue.userId !== 'UA') { assignmentFilterValue = users.find( @@ -403,12 +427,14 @@ export const formattedWorkQueue = ( let workQueue = filterWorkItems({ applicationContext, assignmentFilterValue, + authorizedUser, section, workItems, workQueueToDisplay, }).map(workItem => { return memoizedFormatItemWithLink({ applicationContext, + authorizedUser, isSelected: selectedWorkItemIds.includes(workItem.workItemId), permissions, workItem, diff --git a/web-client/src/presenter/computeds/headerHelper.test.ts b/web-client/src/presenter/computeds/headerHelper.test.ts index 2b5a9ddca45..ca176f97f81 100644 --- a/web-client/src/presenter/computeds/headerHelper.test.ts +++ b/web-client/src/presenter/computeds/headerHelper.test.ts @@ -1,5 +1,7 @@ import { ROLES } from '../../../../shared/src/business/entities/EntityConstants'; -import { applicationContext } from '@shared/business/test/createTestApplicationContext'; +//import { applicationContext } from '@shared/business/test/createTestApplicationContext'; +import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; +import { emptyUserState } from '@web-client/presenter/state/userState'; import { getUserPermissions } from '../../../../shared/src/authorization/getUserPermissions'; import { headerHelper as headerHelperComputed } from './headerHelper'; import { runCompute } from '@web-client/presenter/test.cerebral'; @@ -11,13 +13,14 @@ const headerHelper = withAppContextDecorator( ); const getBaseState = user => { - applicationContext.getCurrentUser = () => user; applicationContext.getPublicSiteUrl = () => 'localhost:5678/'; return { notifications: { unreadCount: 0, }, permissions: getUserPermissions(user), + token: '283490', + user, }; }; @@ -100,9 +103,14 @@ describe('headerHelper', () => { }); it('should show trial sessions for internal users', () => { + const user = { + email: 'something@mail.com', + name: 'Jody', + userId: '77747b11-19b3-4c96-b7a1-fa6a5654e2d5', + }; internal.forEach(role => { const result = runCompute(headerHelper, { - state: getBaseState({ role }), + state: getBaseState({ role, ...user }), }); expect(result.showTrialSessions).toBeTruthy(); }); @@ -367,8 +375,9 @@ describe('headerHelper', () => { it('should be the public site url when the current user is not logged in', () => { const result = runCompute(headerHelper, { state: { - ...getBaseState(undefined), + ...getBaseState(emptyUserState), currentPage: 'Messages', + token: undefined, }, }); diff --git a/web-client/src/presenter/computeds/headerHelper.ts b/web-client/src/presenter/computeds/headerHelper.ts index 9213395f378..65e82ef2def 100644 --- a/web-client/src/presenter/computeds/headerHelper.ts +++ b/web-client/src/presenter/computeds/headerHelper.ts @@ -6,9 +6,9 @@ export const headerHelper = ( get: Get, applicationContext: ClientApplicationContext, ): any => { - const user = applicationContext.getCurrentUser(); - const userRole = user && user.role; - const isLoggedIn = !!user; + const user = get(state.user); + const userRole = user.role; + const isLoggedIn = !!get(state.token); const currentPage = get(state.currentPage) || ''; const { USER_ROLES } = applicationContext.getConstants(); const permissions = get(state.permissions); diff --git a/web-client/src/presenter/computeds/internalPetitionPartiesHelper.test.ts b/web-client/src/presenter/computeds/internalPetitionPartiesHelper.test.ts index 3860af1c430..8578f408679 100644 --- a/web-client/src/presenter/computeds/internalPetitionPartiesHelper.test.ts +++ b/web-client/src/presenter/computeds/internalPetitionPartiesHelper.test.ts @@ -3,11 +3,12 @@ import { PARTY_TYPES, } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; -import { internalPetitionPartiesHelper as internalPetitionPartiesHelperComputed } from './internalPetitionPartiesHelper'; import { + docketClerk1User, petitionerUser, petitionsClerkUser, } from '../../../../shared/src/test/mockUsers'; +import { internalPetitionPartiesHelper as internalPetitionPartiesHelperComputed } from './internalPetitionPartiesHelper'; import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../withAppContext'; @@ -24,6 +25,7 @@ describe('internalPetitionPartiesHelper', () => { PARTY_TYPES, }, form: { partyType: PARTY_TYPES.conservator }, + user: docketClerk1User, }, }); @@ -44,6 +46,7 @@ describe('internalPetitionPartiesHelper', () => { PARTY_TYPES, }, form: { partyType: PARTY_TYPES.corporation }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -62,6 +65,7 @@ describe('internalPetitionPartiesHelper', () => { PARTY_TYPES, }, form: { partyType: PARTY_TYPES.custodian }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -81,6 +85,7 @@ describe('internalPetitionPartiesHelper', () => { PARTY_TYPES, }, form: { partyType: PARTY_TYPES.donor }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -100,6 +105,7 @@ describe('internalPetitionPartiesHelper', () => { form: { partyType: PARTY_TYPES.estate, }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -122,6 +128,7 @@ describe('internalPetitionPartiesHelper', () => { form: { partyType: PARTY_TYPES.estateWithoutExecutor, }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -142,6 +149,7 @@ describe('internalPetitionPartiesHelper', () => { form: { partyType: PARTY_TYPES.guardian, }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -163,6 +171,7 @@ describe('internalPetitionPartiesHelper', () => { form: { partyType: PARTY_TYPES.nextFriendForIncompetentPerson, }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -184,6 +193,7 @@ describe('internalPetitionPartiesHelper', () => { form: { partyType: PARTY_TYPES.nextFriendForMinor, }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -205,6 +215,7 @@ describe('internalPetitionPartiesHelper', () => { form: { partyType: PARTY_TYPES.partnershipBBA, }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -226,6 +237,7 @@ describe('internalPetitionPartiesHelper', () => { form: { partyType: PARTY_TYPES.partnershipOtherThanTaxMatters, }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -247,6 +259,7 @@ describe('internalPetitionPartiesHelper', () => { form: { partyType: PARTY_TYPES.partnershipAsTaxMattersPartner, }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -268,6 +281,7 @@ describe('internalPetitionPartiesHelper', () => { form: { partyType: PARTY_TYPES.petitioner, }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -287,6 +301,7 @@ describe('internalPetitionPartiesHelper', () => { form: { partyType: PARTY_TYPES.petitionerSpouse, }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -312,6 +327,7 @@ describe('internalPetitionPartiesHelper', () => { form: { partyType: PARTY_TYPES.petitionerDeceasedSpouse, }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -335,6 +351,7 @@ describe('internalPetitionPartiesHelper', () => { form: { partyType: PARTY_TYPES.survivingSpouse, }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -356,6 +373,7 @@ describe('internalPetitionPartiesHelper', () => { form: { partyType: PARTY_TYPES.transferee, }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -375,6 +393,7 @@ describe('internalPetitionPartiesHelper', () => { form: { partyType: PARTY_TYPES.trust, }, + user: docketClerk1User, }, }); expect(result).toMatchObject({ @@ -397,27 +416,25 @@ describe('internalPetitionPartiesHelper', () => { isPaper: undefined, partyType: PARTY_TYPES.partnershipAsTaxMattersPartner, }, + user: docketClerk1User, }; it('should be false when the current user is an external user', () => { - applicationContext.getCurrentUser.mockReturnValue(petitionerUser); - const result = runCompute(internalPetitionPartiesHelper, { - state: baseState, + state: { ...baseState, user: petitionerUser }, }); expect(result.showPaperPetitionEmailFieldAndConsentBox).toEqual(false); }); it('should be true when the current user is a petitions clerk user', () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - const result = runCompute(internalPetitionPartiesHelper, { state: { ...baseState, form: { isPaper: true, }, + user: petitionsClerkUser, }, }); @@ -425,8 +442,6 @@ describe('internalPetitionPartiesHelper', () => { }); it('should be false when the e-consent feature flag is disabled', () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - const result = runCompute(internalPetitionPartiesHelper, { state: { ...baseState, @@ -434,6 +449,7 @@ describe('internalPetitionPartiesHelper', () => { [ALLOWLIST_FEATURE_FLAGS.E_CONSENT_FIELDS_ENABLED_FEATURE_FLAG.key]: false, }, + user: petitionsClerkUser, }, }); @@ -441,8 +457,6 @@ describe('internalPetitionPartiesHelper', () => { }); it('should be true when the e-consent feature flag is enabled, it is a paper petition and the current user is internal', () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - const result = runCompute(internalPetitionPartiesHelper, { state: { ...baseState, @@ -453,6 +467,7 @@ describe('internalPetitionPartiesHelper', () => { form: { isPaper: true, }, + user: petitionsClerkUser, }, }); @@ -460,8 +475,6 @@ describe('internalPetitionPartiesHelper', () => { }); it('should be false when the e-consent feature flag is enabled, and it is NOT a paper petition', () => { - applicationContext.getCurrentUser.mockReturnValue(petitionsClerkUser); - const result = runCompute(internalPetitionPartiesHelper, { state: { ...baseState, @@ -472,6 +485,7 @@ describe('internalPetitionPartiesHelper', () => { form: { isPaper: false, }, + user: petitionsClerkUser, }, }); diff --git a/web-client/src/presenter/computeds/internalPetitionPartiesHelper.ts b/web-client/src/presenter/computeds/internalPetitionPartiesHelper.ts index 123dec78be1..a5f818fd32f 100644 --- a/web-client/src/presenter/computeds/internalPetitionPartiesHelper.ts +++ b/web-client/src/presenter/computeds/internalPetitionPartiesHelper.ts @@ -211,7 +211,7 @@ export const internalPetitionPartiesHelper = ( ): any => { const { ALLOWLIST_FEATURE_FLAGS, PARTY_TYPES } = applicationContext.getConstants(); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { filingType, isPaper, partyType } = get(state.form); const E_CONSENT_FIELDS_ENABLED_FEATURE_FLAG = get( diff --git a/web-client/src/presenter/computeds/messageDocumentHelper.showApplyStampButton.test.ts b/web-client/src/presenter/computeds/messageDocumentHelper.showApplyStampButton.test.ts index 33da9427f18..c32c3a3b297 100644 --- a/web-client/src/presenter/computeds/messageDocumentHelper.showApplyStampButton.test.ts +++ b/web-client/src/presenter/computeds/messageDocumentHelper.showApplyStampButton.test.ts @@ -19,18 +19,14 @@ describe('messageDocumentHelper.showApplyStampButton', () => { const messageDocumentHelper = withAppContextDecorator( messageDocumentHelperComputed, - { - ...applicationContext, - getCurrentUser: () => { - return globalUser; - }, - }, + applicationContext, ); const getBaseState = user => { globalUser = user; return { permissions: getUserPermissions(user), + user: globalUser, }; }; diff --git a/web-client/src/presenter/computeds/messageDocumentHelper.test.ts b/web-client/src/presenter/computeds/messageDocumentHelper.test.ts index b9c6d31ee77..8e4b5b802e7 100644 --- a/web-client/src/presenter/computeds/messageDocumentHelper.test.ts +++ b/web-client/src/presenter/computeds/messageDocumentHelper.test.ts @@ -19,15 +19,10 @@ import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../withAppContext'; describe('messageDocumentHelper', () => { - let globalUser; - const messageDocumentHelper = withAppContextDecorator( messageDocumentHeperComputed, { ...applicationContext, - getCurrentUser: () => { - return globalUser; - }, }, ); @@ -62,7 +57,6 @@ describe('messageDocumentHelper', () => { }; const getBaseState = user => { - globalUser = user; return { caseDetail: { ...baseCaseDetail, @@ -73,6 +67,7 @@ describe('messageDocumentHelper', () => { }, parentMessageId: mockParentMessageId, permissions: getUserPermissions(user), + user, }; }; diff --git a/web-client/src/presenter/computeds/messageDocumentHelper.ts b/web-client/src/presenter/computeds/messageDocumentHelper.ts index edf314fb938..7db2a85a0da 100644 --- a/web-client/src/presenter/computeds/messageDocumentHelper.ts +++ b/web-client/src/presenter/computeds/messageDocumentHelper.ts @@ -23,7 +23,7 @@ export const messageDocumentHelper = ( STATUS_REPORT_ORDER_DOCUMENTS_ALLOWLIST, STIPULATED_DECISION_EVENT_CODE, } = applicationContext.getConstants(); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const permissions = get(state.permissions); const caseDetail = get(state.caseDetail); const parentMessageId = get(state.parentMessageId); @@ -125,7 +125,7 @@ export const messageDocumentHelper = ( // The variables affected by formattedDocument are showApplyStampButton and showStatusReportOrderButton. const { draftDocuments } = applicationContext .getUtilities() - .formatCase(applicationContext, caseDetail); + .formatCase(applicationContext, caseDetail, user); const formattedDocument = draftDocuments.find( doc => doc.docketEntryId === viewerDocumentToDisplayDocumentId, ); diff --git a/web-client/src/presenter/computeds/messageModalHelper.ts b/web-client/src/presenter/computeds/messageModalHelper.ts index 28cc4be40eb..5e4b5d28288 100644 --- a/web-client/src/presenter/computeds/messageModalHelper.ts +++ b/web-client/src/presenter/computeds/messageModalHelper.ts @@ -20,6 +20,7 @@ export const messageModalHelper = ( const screenMetadata = get(state.screenMetadata); const attachments = get(state.modal.form.attachments); const draftAttachments = get(state.modal.form.draftAttachments); + const user = get(state.user); const currentAttachments = [...attachments, ...draftAttachments]; const computeIsAlreadyAttached = doc => @@ -28,9 +29,11 @@ export const messageModalHelper = ( ); const { correspondence, draftDocuments, formattedDocketEntries } = - applicationContext - .getUtilities() - .getFormattedCaseDetail({ applicationContext, caseDetail }); + applicationContext.getUtilities().getFormattedCaseDetail({ + applicationContext, + authorizedUser: user, + caseDetail, + }); const documents: (RawDocketEntry & { isAlreadyAttached: boolean; diff --git a/web-client/src/presenter/computeds/messagesHelper.test.ts b/web-client/src/presenter/computeds/messagesHelper.test.ts index d24bf64d083..c6cb08e7aa8 100644 --- a/web-client/src/presenter/computeds/messagesHelper.test.ts +++ b/web-client/src/presenter/computeds/messagesHelper.test.ts @@ -11,12 +11,10 @@ import { withAppContextDecorator } from '../../withAppContext'; describe('messagesHelper', () => { let user; - const messagesHelper = withAppContextDecorator(messagesHelperComputed, { - ...applicationContext, - getCurrentUser: () => { - return user; - }, - }); + const messagesHelper = withAppContextDecorator( + messagesHelperComputed, + applicationContext, + ); beforeEach(() => { user = docketClerkUser; @@ -28,6 +26,7 @@ describe('messagesHelper', () => { messageBoxToDisplay: { queue: 'my', }, + user, }, }); expect(result.showIndividualMessages).toBeTruthy(); @@ -40,6 +39,7 @@ describe('messagesHelper', () => { messageBoxToDisplay: { queue: 'section', }, + user, }, }); expect(result.showIndividualMessages).toBeFalsy(); @@ -52,6 +52,7 @@ describe('messagesHelper', () => { messageBoxToDisplay: { queue: 'my', }, + user, }, }); @@ -62,6 +63,7 @@ describe('messagesHelper', () => { messageBoxToDisplay: { queue: 'section', }, + user, }, }); @@ -75,6 +77,7 @@ describe('messagesHelper', () => { queue: 'section', section: DOCKET_SECTION, }, + user, }, }); @@ -90,6 +93,7 @@ describe('messagesHelper', () => { }, messagesInboxCount: 5, messagesSectionCount: 3, + user, }, }); @@ -104,6 +108,7 @@ describe('messagesHelper', () => { }, messagesInboxCount: 5, messagesSectionCount: 3, + user, }, }); @@ -119,6 +124,7 @@ describe('messagesHelper', () => { messageBoxToDisplay: { queue: 'section', }, + user, }, }); @@ -133,6 +139,7 @@ describe('messagesHelper', () => { messageBoxToDisplay: { queue: 'section', }, + user, }, }); @@ -147,6 +154,7 @@ describe('messagesHelper', () => { messageBoxToDisplay: { queue: 'my', }, + user, }, }); @@ -161,6 +169,7 @@ describe('messagesHelper', () => { messageBoxToDisplay: { queue: 'section', }, + user, }, }); @@ -175,6 +184,7 @@ describe('messagesHelper', () => { messageBoxToDisplay: { queue: 'my', }, + user, }, }); @@ -190,6 +200,7 @@ describe('messagesHelper', () => { queue: 'my', section: DOCKET_SECTION, }, + user, }, }); @@ -204,6 +215,7 @@ describe('messagesHelper', () => { messageBoxToDisplay: { queue: 'my', }, + user, }, }); @@ -219,6 +231,7 @@ describe('messagesHelper', () => { queue: 'my', section: DOCKET_SECTION, }, + user, }, }); @@ -233,6 +246,7 @@ describe('messagesHelper', () => { messageBoxToDisplay: { queue: 'my', }, + user, }, }); @@ -246,6 +260,7 @@ describe('messagesHelper', () => { messageBoxToDisplay: { queue: 'my', }, + user, }, }); @@ -261,6 +276,7 @@ describe('messagesHelper', () => { queue: 'my', section: DOCKET_SECTION, }, + user, }, }); diff --git a/web-client/src/presenter/computeds/messagesHelper.ts b/web-client/src/presenter/computeds/messagesHelper.ts index 11791a0b52c..2619ecf6d42 100644 --- a/web-client/src/presenter/computeds/messagesHelper.ts +++ b/web-client/src/presenter/computeds/messagesHelper.ts @@ -7,7 +7,7 @@ export const messagesHelper = ( get: Get, applicationContext: ClientApplicationContext, ): any => { - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); const userRole = user && user.role; const isCaseServicesSupervisor = diff --git a/web-client/src/presenter/computeds/orderTypesHelper.test.ts b/web-client/src/presenter/computeds/orderTypesHelper.test.ts index d3240b15445..c9a69d412da 100644 --- a/web-client/src/presenter/computeds/orderTypesHelper.test.ts +++ b/web-client/src/presenter/computeds/orderTypesHelper.test.ts @@ -28,11 +28,10 @@ describe('orderTypesHelper', () => { }, }; }, - getCurrentUser: () => user, }); it('should return all event codes for docketclerk', () => { - const result = runCompute(orderTypesHelper, { state: {} }); + const result = runCompute(orderTypesHelper, { state: { user } }); expect(result.orderTypes).toEqual([ { code: 'Simba', documentType: 'Lion', eventCode: 'ROAR' }, @@ -44,7 +43,7 @@ describe('orderTypesHelper', () => { it('should filter out and only return type O for petitionsclerk', () => { user = petitionsClerkUser; - const result = runCompute(orderTypesHelper, { state: {} }); + const result = runCompute(orderTypesHelper, { state: { user } }); expect(result.orderTypes).toEqual([ { @@ -57,7 +56,7 @@ describe('orderTypesHelper', () => { it('should return showDocumentTitleInput true and documentTitleInputLabel if state.modal.eventCode is O', () => { const result = runCompute(orderTypesHelper, { - state: { modal: { eventCode: 'O' } }, + state: { modal: { eventCode: 'O' }, user }, }); expect(result.showDocumentTitleInput).toEqual(true); @@ -66,7 +65,7 @@ describe('orderTypesHelper', () => { it('should return showDocumentTitleInput true and documentTitleInputLabel if state.modal.eventCode is NOT', () => { const result = runCompute(orderTypesHelper, { - state: { modal: { eventCode: 'NOT' } }, + state: { modal: { eventCode: 'NOT' }, user }, }); expect(result.showDocumentTitleInput).toEqual(true); @@ -75,7 +74,7 @@ describe('orderTypesHelper', () => { it('should return showDocumentTitleInput false if state.modal.eventCode is not O or NOT', () => { const result = runCompute(orderTypesHelper, { - state: { modal: { eventCode: 'OTHER' } }, + state: { modal: { eventCode: 'OTHER' }, user }, }); expect(result.showDocumentTitleInput).toEqual(false); diff --git a/web-client/src/presenter/computeds/orderTypesHelper.ts b/web-client/src/presenter/computeds/orderTypesHelper.ts index 8e217666701..3f79178ae86 100644 --- a/web-client/src/presenter/computeds/orderTypesHelper.ts +++ b/web-client/src/presenter/computeds/orderTypesHelper.ts @@ -7,7 +7,7 @@ export const orderTypesHelper = ( applicationContext: ClientApplicationContext, ): any => { const { ORDER_TYPES_MAP, USER_ROLES } = applicationContext.getConstants(); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const eventCode = get(state.modal.eventCode); let orderTypes = ORDER_TYPES_MAP; diff --git a/web-client/src/presenter/computeds/partiesInformationHelper.formatCounsel.test.ts b/web-client/src/presenter/computeds/partiesInformationHelper.formatCounsel.test.ts index 47d5a380777..a8e7a05e3ab 100644 --- a/web-client/src/presenter/computeds/partiesInformationHelper.formatCounsel.test.ts +++ b/web-client/src/presenter/computeds/partiesInformationHelper.formatCounsel.test.ts @@ -1,5 +1,4 @@ import { ROLES } from '../../../../shared/src/business/entities/EntityConstants'; -import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { formatCounsel } from './partiesInformationHelper'; describe('partiesInformationHelper', () => { @@ -7,10 +6,7 @@ describe('partiesInformationHelper', () => { let mockIrsPractitioner; - let mockUser; - beforeEach(() => { - mockUser = {}; mockIrsPractitioner = { barNumber: 'RT1111', email: mockEmail, @@ -18,7 +14,6 @@ describe('partiesInformationHelper', () => { role: ROLES.irsPractitioner, userId: 'c6df4afc-286b-4979-92e2-b788e49dc51d', }; - applicationContext.getCurrentUser.mockImplementation(() => mockUser); }); describe('formatCounsel', () => { diff --git a/web-client/src/presenter/computeds/partiesInformationHelper.test.ts b/web-client/src/presenter/computeds/partiesInformationHelper.test.ts index 5f1317d3b19..d8c98c51ced 100644 --- a/web-client/src/presenter/computeds/partiesInformationHelper.test.ts +++ b/web-client/src/presenter/computeds/partiesInformationHelper.test.ts @@ -26,10 +26,6 @@ describe('partiesInformationHelper', () => { contactId: '25d51a3b-969e-4bb4-a932-cc9645ba888c', contactType: CONTACT_TYPES.participant, }; - let mockPetitioner; - let mockPrivatePractitioner; - let mockIrsPractitioner; - let mockUser; const partiesInformationHelper = withAppContextDecorator( partiesInformationHelperComputed, @@ -37,8 +33,6 @@ describe('partiesInformationHelper', () => { ); const getBaseState = user => { - mockUser = { ...user }; - return { featureFlags: { [ALLOWLIST_FEATURE_FLAGS.E_CONSENT_FIELDS_ENABLED_FEATURE_FLAG.key]: @@ -46,11 +40,14 @@ describe('partiesInformationHelper', () => { }, permissions: getUserPermissions(user), screenMetadata: { pendingEmails: {} }, + user, }; }; + let mockPrivatePractitioner; + let mockIrsPractitioner; + let mockPetitioner; beforeEach(() => { - mockUser = {}; mockIrsPractitioner = { barNumber: 'RT1111', email: mockEmail, @@ -72,7 +69,6 @@ describe('partiesInformationHelper', () => { role: ROLES.privatePractitioner, userId: '39f7c7ee-ab75-492a-a4ee-63755a24e845', }; - applicationContext.getCurrentUser.mockImplementation(() => mockUser); }); describe('formattedParticipants', () => { diff --git a/web-client/src/presenter/computeds/partiesInformationHelper.ts b/web-client/src/presenter/computeds/partiesInformationHelper.ts index 31584598ec0..97899e53b9b 100644 --- a/web-client/src/presenter/computeds/partiesInformationHelper.ts +++ b/web-client/src/presenter/computeds/partiesInformationHelper.ts @@ -63,7 +63,7 @@ export const partiesInformationHelper = ( const caseDetail = get(state.caseDetail); const screenMetadata = get(state.screenMetadata); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const permissions = get(state.permissions); const isExternalUser = applicationContext .getUtilities() diff --git a/web-client/src/presenter/computeds/pendingReportListHelper.test.ts b/web-client/src/presenter/computeds/pendingReportListHelper.test.ts index a0f301adf5b..6590c277515 100644 --- a/web-client/src/presenter/computeds/pendingReportListHelper.test.ts +++ b/web-client/src/presenter/computeds/pendingReportListHelper.test.ts @@ -9,7 +9,7 @@ describe('pendingReportListHelper', () => { applicationContext, ); - it('should display load more button if more results are to be loaded', () => { + it('should set showLoadMore to true when there are additional results to load', () => { const mockState = { pendingReports: { hasPendingItemsResults: true, @@ -26,7 +26,7 @@ describe('pendingReportListHelper', () => { expect(showLoadMore).toBe(true); }); - it('should hide the load more button if more results are to be loaded', () => { + it('should set showLoadMore to false when there are no additional results to load', () => { const mockState = { pendingReports: { hasPendingItemsResults: true, diff --git a/web-client/src/presenter/computeds/reportMenuHelper.test.ts b/web-client/src/presenter/computeds/reportMenuHelper.test.ts index db75f3a853c..ee390ee2bf3 100644 --- a/web-client/src/presenter/computeds/reportMenuHelper.test.ts +++ b/web-client/src/presenter/computeds/reportMenuHelper.test.ts @@ -1,5 +1,9 @@ -import { ROLES } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; +import { + colvinsChambersUser, + judgeUser, + petitionsClerkUser, +} from '@shared/test/mockUsers'; import { getUserPermissions } from '../../../../shared/src/authorization/getUserPermissions'; import { reportMenuHelper as reportMenuHeaderComputed } from './reportMenuHelper'; import { runCompute } from '@web-client/presenter/test.cerebral'; @@ -12,17 +16,17 @@ describe('reportMenuHelper', () => { ); const getBaseState = user => { - applicationContext.getCurrentUser.mockReturnValue(user); return { currentPage: 'CaseDetailInternal', permissions: getUserPermissions(user), + user, }; }; describe('showActivityReport', () => { it('should be true when the current user is a judge user', () => { const result = runCompute(reportMenuHelper, { - state: getBaseState({ role: ROLES.judge }), + state: getBaseState(judgeUser), }); expect(result.showActivityReport).toBeTruthy(); @@ -30,7 +34,7 @@ describe('reportMenuHelper', () => { it('should be true when the current user is a chambers user', () => { const result = runCompute(reportMenuHelper, { - state: getBaseState({ role: ROLES.chambers }), + state: getBaseState(colvinsChambersUser), }); expect(result.showActivityReport).toBeTruthy(); @@ -38,7 +42,7 @@ describe('reportMenuHelper', () => { it('should be false when the current user is NOT a judge or chambers user', () => { const result = runCompute(reportMenuHelper, { - state: getBaseState({ role: ROLES.petitionsClerk }), + state: getBaseState(petitionsClerkUser), }); expect(result.showActivityReport).toBeFalsy(); @@ -60,7 +64,7 @@ describe('reportMenuHelper', () => { it('should show a border under the Reports tab to indicate it is the active tab when the current page is Case Deadlines Report', () => { const result = runCompute(reportMenuHelper, { state: { - ...getBaseState({ role: ROLES.petitionsClerk }), + ...getBaseState(petitionsClerkUser), currentPage: 'CaseDeadlines', }, }); @@ -71,7 +75,7 @@ describe('reportMenuHelper', () => { it('should show a border under the Reports tab to indicate it is the active tab when the current page is the Blocked Cases Report', () => { const result = runCompute(reportMenuHelper, { state: { - ...getBaseState({ role: ROLES.petitionsClerk }), + ...getBaseState(petitionsClerkUser), currentPage: 'BlockedCasesReport', }, }); diff --git a/web-client/src/presenter/computeds/scanBatchPreviewerHelper.test.ts b/web-client/src/presenter/computeds/scanBatchPreviewerHelper.test.ts index b0b4884f415..53c215117dc 100644 --- a/web-client/src/presenter/computeds/scanBatchPreviewerHelper.test.ts +++ b/web-client/src/presenter/computeds/scanBatchPreviewerHelper.test.ts @@ -17,10 +17,6 @@ describe('scanBatchPreviewerHelper', () => { applicationContext, ); - applicationContext.getCurrentUser = () => ({ - role: applicationContext.getConstants().ROLES.privatePractitioner, - }); - beforeEach(() => { state.form = {}; }); diff --git a/web-client/src/presenter/computeds/scanHelper.test.ts b/web-client/src/presenter/computeds/scanHelper.test.ts index f8d1228e239..144a8d91ad9 100644 --- a/web-client/src/presenter/computeds/scanHelper.test.ts +++ b/web-client/src/presenter/computeds/scanHelper.test.ts @@ -1,7 +1,12 @@ +import { INITIAL_DOCUMENT_TYPES } from '../../../../shared/src/business/entities/EntityConstants'; import { - INITIAL_DOCUMENT_TYPES, - ROLES, -} from '../../../../shared/src/business/entities/EntityConstants'; + adcUser, + docketClerkUser, + irsPractitionerUser, + petitionerUser, + petitionsClerkUser, + privatePractitionerUser, +} from '@shared/test/mockUsers'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { runCompute } from '@web-client/presenter/test.cerebral'; import { scanHelper as scanHelperComputed } from './scanHelper'; @@ -20,72 +25,51 @@ describe('scanHelper', () => { ); it('sets hasScanFeature to true for petitionsclerk user roles', () => { - applicationContext.getCurrentUser = () => ({ - role: ROLES.petitionsClerk, - }); - const result = runCompute(scanHelper, { - state: stateWithEmptyFormDocuments, + state: { ...stateWithEmptyFormDocuments, user: petitionsClerkUser }, }); expect(result.hasScanFeature).toEqual(true); }); it('sets hasScanFeature to true for docketclerk user roles', () => { - applicationContext.getCurrentUser = () => ({ - role: ROLES.docketClerk, - }); - const result = runCompute(scanHelper, { - state: stateWithEmptyFormDocuments, + state: { ...stateWithEmptyFormDocuments, user: docketClerkUser }, }); expect(result.hasScanFeature).toEqual(true); }); it('sets hasScanFeature to true for adc user roles', () => { - applicationContext.getCurrentUser = () => ({ - role: ROLES.adc, - }); - const result = runCompute(scanHelper, { - state: stateWithEmptyFormDocuments, + state: { ...stateWithEmptyFormDocuments, user: adcUser }, }); expect(result.hasScanFeature).toEqual(true); }); it('sets hasScanFeature to false for petitioner user roles', () => { - applicationContext.getCurrentUser = () => ({ - role: ROLES.petitioner, - }); - const result = runCompute(scanHelper, { - state: stateWithEmptyFormDocuments, + state: { ...stateWithEmptyFormDocuments, user: petitionerUser }, }); expect(result.hasScanFeature).toEqual(false); }); it('sets hasScanFeature to false for practitioner user roles', () => { - applicationContext.getCurrentUser = () => ({ - role: ROLES.privatePractitioner, - }); - const result = runCompute(scanHelper, { - state: stateWithEmptyFormDocuments, + state: { + ...stateWithEmptyFormDocuments, + user: privatePractitionerUser, + }, }); expect(result.hasScanFeature).toEqual(false); }); it('sets hasScanFeature to false for respondent user roles', () => { - applicationContext.getCurrentUser = () => ({ - role: ROLES.irsPractitioner, - }); - const result = runCompute(scanHelper, { - state: stateWithEmptyFormDocuments, + state: { ...stateWithEmptyFormDocuments, user: irsPractitionerUser }, }); expect(result.hasScanFeature).toEqual(false); @@ -98,6 +82,7 @@ describe('scanHelper', () => { modal: { showModal: 'SelectScannerSourceModal', }, + user: petitionerUser, }, }); expect(result.showScannerSourceModal).toEqual(true); @@ -111,6 +96,7 @@ describe('scanHelper', () => { scanner: { sources: mockSources, }, + user: petitionerUser, }, }); expect(result.sources.length).toEqual(2); @@ -123,6 +109,7 @@ describe('scanHelper', () => { form: { stinFile: {}, }, + user: petitionerUser, }, }); @@ -136,6 +123,7 @@ describe('scanHelper', () => { docketEntries: [], stinFile: {}, }, + user: petitionerUser, }, }); @@ -149,6 +137,7 @@ describe('scanHelper', () => { docketEntries: [], stinFile: null, }, + user: petitionerUser, }, }); expect(result.STINFileCompleted).toEqual(false); @@ -164,6 +153,7 @@ describe('scanHelper', () => { }, ], }, + user: petitionerUser, }, }); @@ -176,6 +166,7 @@ describe('scanHelper', () => { form: { docketEntries: [], }, + user: petitionerUser, }, }); @@ -191,6 +182,7 @@ describe('scanHelper', () => { docketEntries: [], requestForPlaceOfTrialFile: {}, }, + user: petitionerUser, }, }); @@ -204,6 +196,7 @@ describe('scanHelper', () => { docketEntries: [], requestForPlaceOfTrialFile: null, }, + user: petitionerUser, }, }); expect(result.RQTFileCompleted).toEqual(false); @@ -220,6 +213,7 @@ describe('scanHelper', () => { }, ], }, + user: petitionerUser, }, }); @@ -232,6 +226,7 @@ describe('scanHelper', () => { form: { docketEntries: [], }, + user: petitionerUser, }, }); @@ -247,6 +242,7 @@ describe('scanHelper', () => { applicationForWaiverOfFilingFeeFile: {}, docketEntries: [], }, + user: petitionerUser, }, }); @@ -260,6 +256,7 @@ describe('scanHelper', () => { applicationForWaiverOfFilingFeeFile: null, docketEntries: [], }, + user: petitionerUser, }, }); expect(result.APWFileCompleted).toEqual(false); @@ -277,6 +274,7 @@ describe('scanHelper', () => { }, ], }, + user: petitionerUser, }, }); @@ -289,6 +287,7 @@ describe('scanHelper', () => { form: { docketEntries: [], }, + user: petitionerUser, }, }); @@ -304,6 +303,7 @@ describe('scanHelper', () => { docketEntries: [], petitionFile: {}, }, + user: petitionerUser, }, }); @@ -317,6 +317,7 @@ describe('scanHelper', () => { docketEntries: [], petitionFileCompleted: null, }, + user: petitionerUser, }, }); expect(result.PFileCompleted).toEqual(false); @@ -332,6 +333,7 @@ describe('scanHelper', () => { }, ], }, + user: petitionerUser, }, }); @@ -344,6 +346,7 @@ describe('scanHelper', () => { form: { docketEntries: [], }, + user: petitionerUser, }, }); @@ -359,6 +362,7 @@ describe('scanHelper', () => { corporateDisclosureFile: {}, docketEntries: [], }, + user: petitionerUser, }, }); @@ -372,6 +376,7 @@ describe('scanHelper', () => { corporateDisclosureFile: null, docketEntries: [], }, + user: petitionerUser, }, }); expect(result.DISCFileCompleted).toEqual(false); @@ -387,6 +392,7 @@ describe('scanHelper', () => { }, ], }, + user: petitionerUser, }, }); @@ -399,6 +405,7 @@ describe('scanHelper', () => { form: { docketEntries: [], }, + user: petitionerUser, }, }); @@ -414,6 +421,7 @@ describe('scanHelper', () => { attachmentToPetitionFile: {}, docketEntries: [], }, + user: petitionerUser, }, }); @@ -427,6 +435,7 @@ describe('scanHelper', () => { attachmentToPetitionFile: null, docketEntries: [], }, + user: petitionerUser, }, }); expect(result.ATPFileCompleted).toEqual(false); @@ -443,6 +452,7 @@ describe('scanHelper', () => { }, ], }, + user: petitionerUser, }, }); @@ -455,6 +465,7 @@ describe('scanHelper', () => { form: { docketEntries: [], }, + user: petitionerUser, }, }); @@ -473,6 +484,7 @@ describe('scanHelper', () => { scanner: { sources: ['sourceA, sourceB'], }, + user: petitionerUser, }, }); @@ -489,6 +501,7 @@ describe('scanHelper', () => { scanner: { sources: ['sourceA, sourceB'], }, + user: petitionerUser, }, }); @@ -505,6 +518,7 @@ describe('scanHelper', () => { scanner: { sources: ['sourceA, sourceB'], }, + user: petitionerUser, }, }); @@ -521,6 +535,7 @@ describe('scanHelper', () => { scanner: { sources: [], }, + user: petitionerUser, }, }); @@ -534,6 +549,7 @@ describe('scanHelper', () => { scanMode: 'someScanMode', scanner: 'someScanner', }, + user: petitionerUser, }, }); @@ -550,6 +566,7 @@ describe('scanHelper', () => { scanner: { sources: ['sourceA, sourceB'], }, + user: petitionerUser, }, }); diff --git a/web-client/src/presenter/computeds/scanHelper.ts b/web-client/src/presenter/computeds/scanHelper.ts index 1d0e38f1862..5ce5d8696e5 100644 --- a/web-client/src/presenter/computeds/scanHelper.ts +++ b/web-client/src/presenter/computeds/scanHelper.ts @@ -16,7 +16,7 @@ export const scanHelper = ( const { INITIAL_DOCUMENT_TYPES, SCAN_MODES } = applicationContext.getConstants(); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const formCaseDocuments = get(state.form.docketEntries); const initiateScriptLoaded = get(state.scanner.initiateScriptLoaded); const configScriptLoaded = get(state.scanner.configScriptLoaded); @@ -90,11 +90,9 @@ export const scanHelper = ( STINFileCompleted, disableModalSelect, hasLoadedScanDependencies: initiateScriptLoaded && configScriptLoaded, - hasScanFeature: !!( - user && - user.role && - applicationContext.getUtilities().isInternalUser(user.role) - ), + hasScanFeature: !!applicationContext + .getUtilities() + .isInternalUser(user.role), scanFeatureEnabled, scanModeNotSelected, scanModeOptions, diff --git a/web-client/src/presenter/computeds/startCaseHelper.test.ts b/web-client/src/presenter/computeds/startCaseHelper.test.ts index 1337faf9609..28e2ccbae5b 100644 --- a/web-client/src/presenter/computeds/startCaseHelper.test.ts +++ b/web-client/src/presenter/computeds/startCaseHelper.test.ts @@ -1,10 +1,13 @@ import { CASE_TYPES_MAP, FILING_TYPES, - ROLES, } from '../../../../shared/src/business/entities/EntityConstants'; -import { RawUser } from '@shared/business/entities/User'; import { applicationContext } from '../../applicationContext'; +import { + irsPractitionerUser, + petitionerUser, + privatePractitionerUser, +} from '@shared/test/mockUsers'; import { runCompute } from '@web-client/presenter/test.cerebral'; import { startCaseHelper as startCaseHelperComputed } from './startCaseHelper'; import { withAppContextDecorator } from '../../withAppContext'; @@ -17,17 +20,11 @@ describe('startCaseHelper', () => { applicationContext, ); - beforeAll(() => { - applicationContext.getCurrentUser = () => - ({ - role: ROLES.petitioner, - }) as RawUser; - }); - it('sets showPetitionFileValid false when the petition file is not added to the petition', () => { const result = runCompute(startCaseHelper, { state: { form: {}, + user: petitionerUser, }, }); expect(result.showPetitionFileValid).toBeFalsy(); @@ -37,6 +34,7 @@ describe('startCaseHelper', () => { const result = runCompute(startCaseHelper, { state: { form: { petitionFile: true }, + user: petitionerUser, }, }); expect(result.showPetitionFileValid).toBeTruthy(); @@ -50,6 +48,7 @@ describe('startCaseHelper', () => { partyType: true, petitionFile: true, }, + user: petitionerUser, }, }); expect(result.showCorporateDisclosure).toBeTruthy(); @@ -63,6 +62,7 @@ describe('startCaseHelper', () => { partyType: true, petitionFile: true, }, + user: petitionerUser, }, }); expect(result.showCorporateDisclosure).toBeFalsy(); @@ -74,6 +74,7 @@ describe('startCaseHelper', () => { form: { hasIrsNotice: true, }, + user: petitionerUser, }, }); expect(result.showHasIrsNoticeOptions).toBeTruthy(); @@ -86,6 +87,7 @@ describe('startCaseHelper', () => { form: { hasIrsNotice: false, }, + user: petitionerUser, }, }); expect(result.showNotHasIrsNoticeOptions).toBeTruthy(); @@ -98,38 +100,31 @@ describe('startCaseHelper', () => { form: { hasIrsNotice: false, }, + user: petitionerUser, }, }); expect(result.filingTypes).toEqual(FILING_TYPES.petitioner); }); it('returns privatePractitioner filing types if user is privatePractitioner role', () => { - applicationContext.getCurrentUser = () => - ({ - role: ROLES.privatePractitioner, - }) as RawUser; - const result = runCompute(startCaseHelper, { state: { form: { hasIrsNotice: false, }, + user: privatePractitionerUser, }, }); expect(result.filingTypes).toEqual(FILING_TYPES.privatePractitioner); }); it('returns petitioner filing types by default if user is not petitioner or privatePractitioner role', () => { - applicationContext.getCurrentUser = () => - ({ - role: ROLES.irsPractitioner, - }) as RawUser; - const result = runCompute(startCaseHelper, { state: { form: { hasIrsNotice: false, }, + user: irsPractitionerUser, }, }); expect(result.filingTypes).toEqual(FILING_TYPES.petitioner); @@ -142,6 +137,7 @@ describe('startCaseHelper', () => { contactPrimary: { name: 'Michael G. Scott' }, partyType: PARTY_TYPES.petitioner, }, + user: petitionerUser, }, }); @@ -156,6 +152,7 @@ describe('startCaseHelper', () => { contactSecondary: { name: 'Carol Stills' }, partyType: PARTY_TYPES.petitionerDeceasedSpouse, }, + user: petitionerUser, }, }); @@ -170,6 +167,7 @@ describe('startCaseHelper', () => { contactSecondary: { name: 'Carol Stills' }, partyType: PARTY_TYPES.petitionerSpouse, }, + user: petitionerUser, }, }); @@ -184,6 +182,7 @@ describe('startCaseHelper', () => { contactSecondary: { name: 'Carol Stills' }, partyType: PARTY_TYPES.petitionerDeceasedSpouse, }, + user: petitionerUser, }, }); @@ -200,6 +199,7 @@ describe('startCaseHelper', () => { contactSecondary: { name: 'Carol Stills' }, partyType: PARTY_TYPES.petitionerSpouse, }, + user: petitionerUser, }, }); @@ -215,6 +215,7 @@ describe('startCaseHelper', () => { contactPrimary: { name: '' }, partyType: PARTY_TYPES.trust, }, + user: petitionerUser, }, }); @@ -228,6 +229,7 @@ describe('startCaseHelper', () => { contactPrimary: { name: '' }, partyType: PARTY_TYPES.trust, }, + user: petitionerUser, }, }); @@ -241,6 +243,7 @@ describe('startCaseHelper', () => { contactPrimary: { name: '' }, partyType: PARTY_TYPES.trust, }, + user: petitionerUser, }, }); @@ -302,6 +305,7 @@ describe('startCaseHelper', () => { form: { caseType: 'Disclosure1', }, + user: petitionerUser, }, }); @@ -314,6 +318,7 @@ describe('startCaseHelper', () => { form: { caseType: 'Disclosure2', }, + user: petitionerUser, }, }); @@ -326,6 +331,7 @@ describe('startCaseHelper', () => { form: { caseType: CASE_TYPES_MAP.deficiency, }, + user: petitionerUser, }, }); @@ -344,6 +350,7 @@ describe('startCaseHelper', () => { }, {}, ], + user: petitionerUser, }, }); @@ -355,6 +362,7 @@ describe('startCaseHelper', () => { state: { form: {}, irsNoticeUploadFormInfo: [{}, {}], + user: petitionerUser, }, }); diff --git a/web-client/src/presenter/computeds/startCaseHelper.ts b/web-client/src/presenter/computeds/startCaseHelper.ts index 04dc399d324..0ca5a992eb8 100644 --- a/web-client/src/presenter/computeds/startCaseHelper.ts +++ b/web-client/src/presenter/computeds/startCaseHelper.ts @@ -16,7 +16,7 @@ export const startCaseHelper = ( USER_ROLES, } = applicationContext.getConstants(); const form = get(state.form); - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const showContacts = showContactsHelper(form.partyType, PARTY_TYPES); diff --git a/web-client/src/presenter/computeds/trialSessionHeaderHelper.test.ts b/web-client/src/presenter/computeds/trialSessionHeaderHelper.test.ts index 56db35a9dde..bc874858495 100644 --- a/web-client/src/presenter/computeds/trialSessionHeaderHelper.test.ts +++ b/web-client/src/presenter/computeds/trialSessionHeaderHelper.test.ts @@ -1,7 +1,11 @@ import { MOCK_TRIAL_REGULAR } from '@shared/test/mockTrial'; import { TRIAL_SESSION_SCOPE_TYPES } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; -import { judgeUser, trialClerkUser } from '@shared/test/mockUsers'; +import { + docketClerkUser, + judgeUser, + trialClerkUser, +} from '@shared/test/mockUsers'; import { runCompute } from '@web-client/presenter/test.cerebral'; import { trialSessionHeaderHelper as trialSessionHeaderHelperComputed } from './trialSessionHeaderHelper'; import { withAppContextDecorator } from '../../withAppContext'; @@ -30,7 +34,9 @@ describe('trialSessionHeaderHelper', () => { }); it('should not throw an error when state.trialSession is undefined', () => { - expect(() => runCompute(trialSessionHeaderHelper, {} as any)).not.toThrow(); + expect(() => + runCompute(trialSessionHeaderHelper, { user: {} } as any), + ).not.toThrow(); }); describe('isStandaloneSession', () => { @@ -41,7 +47,7 @@ describe('trialSessionHeaderHelper', () => { }; const { isStandaloneSession } = runCompute(trialSessionHeaderHelper, { - state: baseState, + state: { ...baseState, user: docketClerkUser }, }); expect(isStandaloneSession).toEqual(true); @@ -50,10 +56,8 @@ describe('trialSessionHeaderHelper', () => { describe('nameToDisplay', () => { it("should be the assigned judge's name when the current user is NOT a trial clerk", () => { - applicationContext.getCurrentUser.mockReturnValue(judgeUser); - const result = runCompute(trialSessionHeaderHelper, { - state: baseState, + state: { ...baseState, user: judgeUser }, }); expect(result.nameToDisplay).toBe( @@ -62,10 +66,8 @@ describe('trialSessionHeaderHelper', () => { }); it("should be the current user's name when the current user is a trial clerk", () => { - applicationContext.getCurrentUser.mockReturnValue(trialClerkUser); - const result = runCompute(trialSessionHeaderHelper, { - state: baseState, + state: { ...baseState, user: trialClerkUser }, }); expect(result.nameToDisplay).toBe(trialClerkUser.name); @@ -80,7 +82,7 @@ describe('trialSessionHeaderHelper', () => { }; const result = runCompute(trialSessionHeaderHelper, { - state: baseState, + state: { ...baseState, user: trialClerkUser }, }); expect(result.showBatchDownloadButton).toBe(false); @@ -93,7 +95,7 @@ describe('trialSessionHeaderHelper', () => { }; const result = runCompute(trialSessionHeaderHelper, { - state: baseState, + state: { ...baseState, user: trialClerkUser }, }); expect(result.showBatchDownloadButton).toBe(true); @@ -108,7 +110,7 @@ describe('trialSessionHeaderHelper', () => { }; const result = runCompute(trialSessionHeaderHelper, { - state: baseState, + state: { ...baseState, user: trialClerkUser }, }); expect(result.showPrintCalendarButton).toBe(true); @@ -128,7 +130,11 @@ describe('trialSessionHeaderHelper', () => { }; const result = runCompute(trialSessionHeaderHelper, { - state: { ...baseState, permissions: { TRIAL_SESSIONS: true } }, + state: { + ...baseState, + permissions: { TRIAL_SESSIONS: true }, + user: trialClerkUser, + }, }); expect(result.showPrintPaperServicePDFsButton).toBe(true); @@ -145,6 +151,7 @@ describe('trialSessionHeaderHelper', () => { trialSession: { judge: { userId: 'NOT_ASSIGNED' }, }, + user: trialClerkUser, }, }); @@ -152,8 +159,6 @@ describe('trialSessionHeaderHelper', () => { }); it('should be false when the user is a trial clerk, they are on the TrialSessionWorkingCopy screen, but they are not assigned to the trial session', () => { - applicationContext.getCurrentUser.mockReturnValue(trialClerkUser); - const result = runCompute(trialSessionHeaderHelper, { state: { ...baseState, @@ -161,6 +166,7 @@ describe('trialSessionHeaderHelper', () => { trialSession: { trialClerk: { userId: 'NOT_ASSIGNED' }, }, + user: trialClerkUser, }, }); @@ -168,8 +174,6 @@ describe('trialSessionHeaderHelper', () => { }); it('should be false when the user is assigned to the session but they are already on the TrialSessionDetail screen', () => { - applicationContext.getCurrentUser.mockReturnValue(trialClerkUser); - const result = runCompute(trialSessionHeaderHelper, { state: { ...baseState, @@ -177,6 +181,7 @@ describe('trialSessionHeaderHelper', () => { trialSession: { trialClerk: { userId: trialClerkUser.userId }, }, + user: trialClerkUser, }, }); @@ -184,8 +189,6 @@ describe('trialSessionHeaderHelper', () => { }); it('should be true when the user is assigned to the session and they are on the TrialSessionWorkingCopy screen', () => { - applicationContext.getCurrentUser.mockReturnValue(trialClerkUser); - const result = runCompute(trialSessionHeaderHelper, { state: { ...baseState, @@ -193,6 +196,7 @@ describe('trialSessionHeaderHelper', () => { trialSession: { trialClerk: { userId: trialClerkUser.userId }, }, + user: trialClerkUser, }, }); @@ -208,6 +212,7 @@ describe('trialSessionHeaderHelper', () => { trialSession: { judge: { userId: judgeUser.userId }, }, + user: trialClerkUser, }, }); @@ -225,6 +230,7 @@ describe('trialSessionHeaderHelper', () => { trialSession: { judge: { userId: 'NOT_ASSIGNED' }, }, + user: trialClerkUser, }, }); @@ -232,8 +238,6 @@ describe('trialSessionHeaderHelper', () => { }); it('should be false when the user is a trial clerk, they are on the TrialSessionDetail screen, but they are not assigned to the trial session', () => { - applicationContext.getCurrentUser.mockReturnValue(trialClerkUser); - const result = runCompute(trialSessionHeaderHelper, { state: { ...baseState, @@ -241,6 +245,7 @@ describe('trialSessionHeaderHelper', () => { trialSession: { trialClerk: { userId: 'NOT_ASSIGNED' }, }, + user: trialClerkUser, }, }); @@ -248,8 +253,6 @@ describe('trialSessionHeaderHelper', () => { }); it('should be false when the user is assigned to the session but they are already on the TrialSessionWorkingCopy screen', () => { - applicationContext.getCurrentUser.mockReturnValue(trialClerkUser); - const result = runCompute(trialSessionHeaderHelper, { state: { ...baseState, @@ -257,6 +260,7 @@ describe('trialSessionHeaderHelper', () => { trialSession: { trialClerk: { userId: trialClerkUser.userId }, }, + user: trialClerkUser, }, }); @@ -264,8 +268,6 @@ describe('trialSessionHeaderHelper', () => { }); it('should be true when the user is a trial clerk assigned to the session and they are on the TrialSessionDetail screen', () => { - applicationContext.getCurrentUser.mockReturnValue(trialClerkUser); - const result = runCompute(trialSessionHeaderHelper, { state: { ...baseState, @@ -273,6 +275,7 @@ describe('trialSessionHeaderHelper', () => { trialSession: { trialClerk: { userId: trialClerkUser.userId }, }, + user: trialClerkUser, }, }); @@ -288,6 +291,7 @@ describe('trialSessionHeaderHelper', () => { trialSession: { judge: { userId: judgeUser.userId }, }, + user: trialClerkUser, }, }); diff --git a/web-client/src/presenter/computeds/trialSessionHeaderHelper.ts b/web-client/src/presenter/computeds/trialSessionHeaderHelper.ts index fa3b14771ba..474ed3ad5df 100644 --- a/web-client/src/presenter/computeds/trialSessionHeaderHelper.ts +++ b/web-client/src/presenter/computeds/trialSessionHeaderHelper.ts @@ -18,7 +18,7 @@ export const trialSessionHeaderHelper = ( } => { const { USER_ROLES } = applicationContext.getConstants(); - const currentUser = applicationContext.getCurrentUser(); + const currentUser = get(state.user); const trialSession = get(state.trialSession); const judgeUser = get(state.judgeUser); diff --git a/web-client/src/presenter/computeds/trialSessionsSummaryHelper.test.ts b/web-client/src/presenter/computeds/trialSessionsSummaryHelper.test.ts index 1421581c7d7..344a46aa535 100644 --- a/web-client/src/presenter/computeds/trialSessionsSummaryHelper.test.ts +++ b/web-client/src/presenter/computeds/trialSessionsSummaryHelper.test.ts @@ -1,54 +1,40 @@ import { ROLES } from '../../../../shared/src/business/entities/EntityConstants'; +import { colvinsChambersUser, judgeUser } from '@shared/test/mockUsers'; import { runCompute } from '@web-client/presenter/test.cerebral'; import { trialSessionsSummaryHelper as trialSessionsSummaryHelperComputed } from './trialSessionsSummaryHelper'; import { withAppContextDecorator } from '../../withAppContext'; -let currentUser; - -const judgeId = '733777c2-cb31-44c6-afce-f7bc1a3f613b'; -const chambersId = 'a5ac202c-4e96-46f2-8968-2749ea845143'; - const trialSessionsSummaryHelper = withAppContextDecorator( trialSessionsSummaryHelperComputed, { getConstants: () => ({ USER_ROLES: ROLES, }), - getCurrentUser: () => currentUser, }, ); describe('trialSessionsSummaryHelper', () => { - beforeEach(() => { - currentUser = { - role: ROLES.judge, - userId: judgeId, - }; - }); - it('should return the judeUserId as the logged in user when that user is a judge', () => { const result = runCompute(trialSessionsSummaryHelper, { - state: {}, + state: { + user: judgeUser, + }, }); - expect(result.judgeUserId).toEqual(judgeId); + expect(result.judgeUserId).toEqual(judgeUser.userId); }); it('should return the judeUserId as the chambers judge associated with the logged in user', () => { - currentUser = { - role: ROLES.chambers, - userId: chambersId, - }; - const result = runCompute(trialSessionsSummaryHelper, { state: { judgeUser: { role: ROLES.judge, - userId: judgeId, + userId: judgeUser.userId, }, + user: colvinsChambersUser, }, }); - expect(result.judgeUserId).toEqual(judgeId); + expect(result.judgeUserId).toEqual(judgeUser.userId); }); }); diff --git a/web-client/src/presenter/computeds/trialSessionsSummaryHelper.ts b/web-client/src/presenter/computeds/trialSessionsSummaryHelper.ts index 9de16ce2954..fcc5ca8f46d 100644 --- a/web-client/src/presenter/computeds/trialSessionsSummaryHelper.ts +++ b/web-client/src/presenter/computeds/trialSessionsSummaryHelper.ts @@ -6,7 +6,7 @@ export const trialSessionsSummaryHelper = ( get: Get, applicationContext: ClientApplicationContext, ): any => { - const { role, userId } = applicationContext.getCurrentUser(); + const { role, userId } = get(state.user); const { USER_ROLES } = applicationContext.getConstants(); const chambersJudgeUser = get(state.judgeUser); const isChambersUser = role === USER_ROLES.chambers; diff --git a/web-client/src/presenter/computeds/updatedFilePetitionHelper.test.ts b/web-client/src/presenter/computeds/updatedFilePetitionHelper.test.ts index e83f89cefcc..9aff632750a 100644 --- a/web-client/src/presenter/computeds/updatedFilePetitionHelper.test.ts +++ b/web-client/src/presenter/computeds/updatedFilePetitionHelper.test.ts @@ -9,7 +9,6 @@ import { updatedFilePetitionHelper as updatedFilePetitionHelperComputed } from ' import { withAppContextDecorator } from '../../withAppContext'; describe('updatedFilePetitionHelper', () => { - let user; const updatedFilePetitionHelper = withAppContextDecorator( updatedFilePetitionHelperComputed, { @@ -17,16 +16,9 @@ describe('updatedFilePetitionHelper', () => { getConstants: () => { return { FILING_TYPES, PARTY_TYPES }; }, - getCurrentUser: () => { - return user; - }, }, ); - beforeEach(() => { - user = petitionerUser; - }); - describe('businessFieldNames', () => { it('should return business field names for the Corporation business type', () => { const result = runCompute(updatedFilePetitionHelper, { @@ -34,6 +26,7 @@ describe('updatedFilePetitionHelper', () => { form: { businessType: 'Corporation', }, + user: petitionerUser, }, }); expect(result.businessFieldNames).toEqual({ @@ -49,6 +42,7 @@ describe('updatedFilePetitionHelper', () => { form: { businessType: 'Partnership (as the Tax Matters Partner)', }, + user: petitionerUser, }, }); expect(result.businessFieldNames).toEqual({ @@ -64,6 +58,7 @@ describe('updatedFilePetitionHelper', () => { businessType: 'Partnership (as a partner other than Tax Matters Partner)', }, + user: petitionerUser, }, }); expect(result.businessFieldNames).toEqual({ @@ -79,6 +74,7 @@ describe('updatedFilePetitionHelper', () => { businessType: 'Partnership (as a partnership representative under BBA)', }, + user: petitionerUser, }, }); expect(result.businessFieldNames).toEqual({ @@ -90,7 +86,7 @@ describe('updatedFilePetitionHelper', () => { describe('filingOptions', () => { it('should return the filing options for petitioner', () => { const result = runCompute(updatedFilePetitionHelper, { - state: { form: {} }, + state: { form: {}, user: petitionerUser }, }); expect(result.filingOptions).toEqual([ 'Myself', @@ -123,6 +119,7 @@ describe('updatedFilePetitionHelper', () => { form: { partyType, }, + user: petitionerUser, }, }); expect(result.showContactInformationForOtherPartyType).toBeTruthy(); @@ -135,6 +132,7 @@ describe('updatedFilePetitionHelper', () => { form: { partyType: PARTY_TYPES.petitioner, }, + user: petitionerUser, }, }); expect(result.showContactInformationForOtherPartyType).toBeFalsy(); @@ -148,6 +146,7 @@ describe('updatedFilePetitionHelper', () => { form: { partyType: PARTY_TYPES.survivingSpouse, }, + user: petitionerUser, }, }); expect(result.otherContactNameLabel).toEqual({ @@ -162,6 +161,7 @@ describe('updatedFilePetitionHelper', () => { form: { partyType: PARTY_TYPES.estate, }, + user: petitionerUser, }, }); expect(result.otherContactNameLabel).toEqual({ @@ -178,6 +178,7 @@ describe('updatedFilePetitionHelper', () => { form: { partyType: PARTY_TYPES.estateWithoutExecutor, }, + user: petitionerUser, }, }); expect(result.otherContactNameLabel).toEqual({ @@ -193,6 +194,7 @@ describe('updatedFilePetitionHelper', () => { form: { partyType: PARTY_TYPES.trust, }, + user: petitionerUser, }, }); expect(result.otherContactNameLabel).toEqual({ @@ -207,6 +209,7 @@ describe('updatedFilePetitionHelper', () => { form: { partyType: PARTY_TYPES.conservator, }, + user: petitionerUser, }, }); expect(result.otherContactNameLabel).toEqual({ @@ -221,6 +224,7 @@ describe('updatedFilePetitionHelper', () => { form: { partyType: PARTY_TYPES.guardian, }, + user: petitionerUser, }, }); expect(result.otherContactNameLabel).toEqual({ @@ -235,6 +239,7 @@ describe('updatedFilePetitionHelper', () => { form: { partyType: PARTY_TYPES.custodian, }, + user: petitionerUser, }, }); expect(result.otherContactNameLabel).toEqual({ @@ -249,6 +254,7 @@ describe('updatedFilePetitionHelper', () => { form: { partyType: PARTY_TYPES.nextFriendForMinor, }, + user: petitionerUser, }, }); expect(result.otherContactNameLabel).toEqual({ @@ -263,6 +269,7 @@ describe('updatedFilePetitionHelper', () => { form: { partyType: PARTY_TYPES.nextFriendForIncompetentPerson, }, + user: petitionerUser, }, }); expect(result.otherContactNameLabel).toEqual({ @@ -277,6 +284,7 @@ describe('updatedFilePetitionHelper', () => { form: { partyType: 'unknown party', }, + user: petitionerUser, }, }); expect(result.otherContactNameLabel).toEqual({ diff --git a/web-client/src/presenter/computeds/updatedFilePetitionHelper.ts b/web-client/src/presenter/computeds/updatedFilePetitionHelper.ts index 81851ab66ae..bfb1abe3d43 100644 --- a/web-client/src/presenter/computeds/updatedFilePetitionHelper.ts +++ b/web-client/src/presenter/computeds/updatedFilePetitionHelper.ts @@ -30,7 +30,7 @@ export const updatedFilePetitionHelper = ( get: Get, applicationContext: ClientApplicationContext, ): UpdatedFilePetitionHelper => { - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const { FILING_TYPES, PARTY_TYPES } = applicationContext.getConstants(); const businessType = get(state.form.businessType); diff --git a/web-client/src/presenter/computeds/viewCounselHelper.test.ts b/web-client/src/presenter/computeds/viewCounselHelper.test.ts index e684d1b4039..1698a962678 100644 --- a/web-client/src/presenter/computeds/viewCounselHelper.test.ts +++ b/web-client/src/presenter/computeds/viewCounselHelper.test.ts @@ -3,14 +3,10 @@ import { runCompute } from '@web-client/presenter/test.cerebral'; import { viewCounselHelper as viewCounselHelperComputed } from './viewCounselHelper'; import { withAppContextDecorator } from '../../../src/withAppContext'; -let globalUser; - -const viewCounselHelper = withAppContextDecorator(viewCounselHelperComputed, { - ...applicationContext, - getCurrentUser: () => { - return globalUser; - }, -}); +const viewCounselHelper = withAppContextDecorator( + viewCounselHelperComputed, + applicationContext, +); describe('viewCounselHelper', () => { it('returns the expected state when selected work items are set', () => { diff --git a/web-client/src/presenter/computeds/workQueueHelper.test.ts b/web-client/src/presenter/computeds/workQueueHelper.test.ts index 9d2d4262682..98b401c38df 100644 --- a/web-client/src/presenter/computeds/workQueueHelper.test.ts +++ b/web-client/src/presenter/computeds/workQueueHelper.test.ts @@ -1,24 +1,23 @@ +import { DOCKET_SECTION } from '../../../../shared/src/business/entities/EntityConstants'; import { - DOCKET_SECTION, - ROLES, -} from '../../../../shared/src/business/entities/EntityConstants'; + adcUser, + caseServicesSupervisorUser, + colvinsChambersUser, + docketClerk1User, + judgeUser, + petitionsClerkUser, +} from '@shared/test/mockUsers'; import { applicationContext } from '../../applicationContext'; import { getUserPermissions } from '../../../../shared/src/authorization/getUserPermissions'; import { runCompute } from '@web-client/presenter/test.cerebral'; import { withAppContextDecorator } from '../../../src/withAppContext'; import { workQueueHelper as workQueueHelperComputed } from './workQueueHelper'; -let globalUser; - const workQueueHelper = withAppContextDecorator(workQueueHelperComputed, { ...applicationContext, - getCurrentUser: () => { - return globalUser; - }, }); const getBaseState = user => { - globalUser = user; return { permissions: getUserPermissions(user), }; @@ -26,14 +25,11 @@ const getBaseState = user => { describe('workQueueHelper', () => { it('returns the expected state when selected work items are set', () => { - const user = { - role: ROLES.petitionsClerk, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(petitionsClerkUser), selectedWorkItems: [true], + user: petitionsClerkUser, workQueueToDisplay: { box: 'inbox', queue: 'section' }, }, }); @@ -48,14 +44,11 @@ describe('workQueueHelper', () => { }); it('returns the expected state when selected work items are not set', () => { - const user = { - role: ROLES.petitionsClerk, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(petitionsClerkUser), selectedWorkItems: [], + user: petitionsClerkUser, workQueueToDisplay: { box: 'outbox', queue: 'my' }, }, }); @@ -70,14 +63,11 @@ describe('workQueueHelper', () => { }); it('returns My Document QC for workQueueTitle if showing individual non-internal work queue', () => { - const user = { - role: ROLES.petitionsClerk, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(petitionsClerkUser), selectedWorkItems: [], + user: petitionsClerkUser, workQueueToDisplay: { queue: 'my', }, @@ -89,14 +79,11 @@ describe('workQueueHelper', () => { }); it('returns Document QC for workQueueTitle if showing section non-internal work queue and current user is not a docket or petitions clerk', () => { - const user = { - role: ROLES.adc, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(adcUser), selectedWorkItems: [], + user: adcUser, workQueueToDisplay: { queue: 'section', }, @@ -108,14 +95,11 @@ describe('workQueueHelper', () => { }); it('returns Section Document QC for workQueueTitle if showing section non-internal work queue and current user is a docket clerk', () => { - const user = { - role: ROLES.docketClerk, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(docketClerk1User), selectedWorkItems: [], + user: docketClerk1User, workQueueToDisplay: { queue: 'section', }, @@ -127,15 +111,11 @@ describe('workQueueHelper', () => { }); it('should set workQueueTitle to a capitalized section specific title when the user is caseServicesSupervisor and workQueueToDisplay.section exists', () => { - const user = { - role: ROLES.caseServicesSupervisor, - userId: '117c6e9c-3940-4693-8bc8-0b2a7ed59b06', - }; - let result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(caseServicesSupervisorUser), selectedWorkItems: [], + user: caseServicesSupervisorUser, workQueueToDisplay: { queue: 'section', section: DOCKET_SECTION, @@ -147,15 +127,11 @@ describe('workQueueHelper', () => { }); it('should set workQueueTitle to "My Document QC" when the user is caseServicesSupervisor and workQueueToDisplay.section does not exist', () => { - const user = { - role: ROLES.caseServicesSupervisor, - userId: '117c6e9c-3940-4693-8bc8-0b2a7ed59b06', - }; - let result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(caseServicesSupervisorUser), selectedWorkItems: [], + user: caseServicesSupervisorUser, workQueueToDisplay: { queue: 'section', }, @@ -166,14 +142,11 @@ describe('workQueueHelper', () => { }); it('shows the start a case button when role is petitions clerk', () => { - const user = { - role: ROLES.petitionsClerk, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(petitionsClerkUser), selectedWorkItems: [], + user: petitionsClerkUser, workQueueToDisplay: { box: 'outbox', queue: 'my' }, }, }); @@ -183,14 +156,11 @@ describe('workQueueHelper', () => { }); it('does not show the start a case button when role is docket clerk', () => { - const user = { - role: ROLES.docketClerk, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(docketClerk1User), selectedWorkItems: [], + user: docketClerk1User, workQueueToDisplay: { box: 'outbox', queue: 'my' }, }, }); @@ -200,14 +170,11 @@ describe('workQueueHelper', () => { }); it('shows the case status column when role is judge', () => { - const user = { - role: ROLES.judge, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(judgeUser), selectedWorkItems: [], + user: judgeUser, workQueueToDisplay: { box: 'inbox', queue: 'my' }, }, }); @@ -215,14 +182,11 @@ describe('workQueueHelper', () => { }); it('shows the case status column when role is chambers', () => { - const user = { - role: ROLES.chambers, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(colvinsChambersUser), selectedWorkItems: [], + user: colvinsChambersUser, workQueueToDisplay: { box: 'inbox', queue: 'my' }, }, }); @@ -230,14 +194,11 @@ describe('workQueueHelper', () => { }); it('shows the from column when role is judge', () => { - const user = { - role: ROLES.judge, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(judgeUser), selectedWorkItems: [], + user: judgeUser, workQueueToDisplay: { box: 'inbox', queue: 'my' }, }, }); @@ -245,14 +206,11 @@ describe('workQueueHelper', () => { }); it('shows the from column when role is chambers', () => { - const user = { - role: ROLES.chambers, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(colvinsChambersUser), selectedWorkItems: [], + user: colvinsChambersUser, workQueueToDisplay: { box: 'inbox', queue: 'my' }, }, }); @@ -260,14 +218,11 @@ describe('workQueueHelper', () => { }); it('shows in progress petitions for a petitionsclerk', () => { - const user = { - role: ROLES.petitionsClerk, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(petitionsClerkUser), selectedWorkItems: [], + user: petitionsClerkUser, workQueueToDisplay: { box: 'inProgress', queue: 'section', @@ -280,14 +235,11 @@ describe('workQueueHelper', () => { }); it('should return expected flags when user is the case services supervisor', () => { - const user = { - role: ROLES.caseServicesSupervisor, - userId: 'ed60ccc5-798c-4f9d-afed-f68f13f7c29b', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(caseServicesSupervisorUser), selectedWorkItems: [], + user: caseServicesSupervisorUser, workQueueToDisplay: { box: 'inProgress', queue: 'section', @@ -304,15 +256,12 @@ describe('workQueueHelper', () => { }); it('returns the individualInboxCount for the work queue based on the value of state.individualInboxCount', () => { - const user = { - role: ROLES.docketClerk, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(docketClerk1User), individualInboxCount: 3, selectedWorkItems: [], + user: docketClerk1User, workQueueToDisplay: { box: 'outbox', queue: 'my' }, }, }); @@ -320,15 +269,12 @@ describe('workQueueHelper', () => { }); it('returns the individualInProgressCount for the work queue based on the value of state.individualInProgressCount', () => { - const user = { - role: ROLES.docketClerk, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(docketClerk1User), individualInProgressCount: 10, selectedWorkItems: [], + user: docketClerk1User, workQueueToDisplay: { box: 'outbox', queue: 'my' }, }, }); @@ -336,15 +282,12 @@ describe('workQueueHelper', () => { }); it('returns the sectionInboxCount for the work queue based on the value of state.sectionInboxCount', () => { - const user = { - role: ROLES.docketClerk, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(docketClerk1User), sectionInboxCount: 3, selectedWorkItems: [], + user: docketClerk1User, workQueueToDisplay: { box: 'outbox', queue: 'my' }, }, }); @@ -352,15 +295,12 @@ describe('workQueueHelper', () => { }); it('returns the sectionInProgressCount for the work queue based on the value of state.sectionInProgressCount', () => { - const user = { - role: ROLES.docketClerk, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(docketClerk1User), sectionInProgressCount: 10, selectedWorkItems: [], + user: docketClerk1User, workQueueToDisplay: { box: 'outbox', queue: 'my' }, }, }); @@ -368,18 +308,15 @@ describe('workQueueHelper', () => { }); it('should return the correct document qc queue path URL based on the box and queue type provided', () => { - const user = { - role: ROLES.docketClerk, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; const mockQueue = 'test'; const mockBox = 'my'; const result = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(docketClerk1User), sectionInProgressCount: 10, selectedWorkItems: [], + user: docketClerk1User, workQueueToDisplay: { box: 'outbox', queue: 'my' }, }, }); @@ -390,19 +327,13 @@ describe('workQueueHelper', () => { }); describe('documentQCNavigationPath', () => { - let user; - beforeEach(() => { - user = { - role: ROLES.docketClerk, - userId: '9d7fd667-42a4-4bd0-9ec7-89d2673cf8b1', - }; - }); it('should construct a path based on the queue and box values passed in', () => { const { documentQCNavigationPath } = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(docketClerk1User), sectionInProgressCount: 10, selectedWorkItems: [], + user: docketClerk1User, workQueueToDisplay: { box: 'outbox', queue: 'my' }, }, }); @@ -415,9 +346,10 @@ describe('workQueueHelper', () => { it('should construct a path based on the queue box, and section values when section is defined', () => { const { documentQCNavigationPath } = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(docketClerk1User), sectionInProgressCount: 10, selectedWorkItems: [], + user: docketClerk1User, workQueueToDisplay: { box: 'outbox', queue: 'my', @@ -436,16 +368,12 @@ describe('workQueueHelper', () => { }); it('showSwitchToMyDocQCLink should be false when the user is a case services supervisor', () => { - user = { - role: ROLES.caseServicesSupervisor, - userId: '117c6e9c-3940-4693-8bc8-0b2a7ed59b06', - }; - const { showSwitchToMyDocQCLink } = runCompute(workQueueHelper, { state: { - ...getBaseState(user), + ...getBaseState(caseServicesSupervisorUser), sectionInProgressCount: 10, selectedWorkItems: [], + user: caseServicesSupervisorUser, workQueueToDisplay: { box: 'outbox', queue: 'my', diff --git a/web-client/src/presenter/computeds/workQueueHelper.ts b/web-client/src/presenter/computeds/workQueueHelper.ts index d29e6bd65c8..b256aa4ad61 100644 --- a/web-client/src/presenter/computeds/workQueueHelper.ts +++ b/web-client/src/presenter/computeds/workQueueHelper.ts @@ -9,7 +9,7 @@ export const workQueueHelper = ( get: Get, applicationContext: ClientApplicationContext, ): any => { - const user = applicationContext.getCurrentUser(); + const user = get(state.user); const selectedWorkItems = get(state.selectedWorkItems); const workQueueToDisplay = get(state.workQueueToDisplay); const { USER_ROLES } = applicationContext.getConstants(); diff --git a/web-client/src/presenter/sequences/Pending/setPendingReportSelectedJudgeSequence.ts b/web-client/src/presenter/sequences/Pending/setPendingReportSelectedJudgeSequence.ts index 08a21738163..782bbff7405 100644 --- a/web-client/src/presenter/sequences/Pending/setPendingReportSelectedJudgeSequence.ts +++ b/web-client/src/presenter/sequences/Pending/setPendingReportSelectedJudgeSequence.ts @@ -1,3 +1,4 @@ +import { clearPendingReportsAction } from '@web-client/presenter/actions/PendingItems/clearPendingReportsAction'; import { fetchPendingItemsAction } from '../../actions/PendingItems/fetchPendingItemsAction'; import { isJudgeSelectedAction } from '../../actions/PendingItems/isJudgeSelectedAction'; import { setPendingItemsAction } from '../../actions/PendingItems/setPendingItemsAction'; @@ -8,7 +9,7 @@ export const setPendingReportSelectedJudgeSequence = [ setPendingReportSelectedJudgeAction, isJudgeSelectedAction, { - no: [], + no: [clearPendingReportsAction], yes: [ showProgressSequenceDecorator([ fetchPendingItemsAction, diff --git a/web-client/src/presenter/sequences/Public/gotoPublicPrintableDocketRecordSequence.ts b/web-client/src/presenter/sequences/Public/gotoPublicPrintableDocketRecordSequence.ts index bfe81f9e087..b4d876ab46f 100644 --- a/web-client/src/presenter/sequences/Public/gotoPublicPrintableDocketRecordSequence.ts +++ b/web-client/src/presenter/sequences/Public/gotoPublicPrintableDocketRecordSequence.ts @@ -1,7 +1,6 @@ import { clearModalStateAction } from '../../actions/clearModalStateAction'; import { generatePublicDocketRecordPdfUrlAction } from '../../actions/Public/generatePublicDocketRecordPdfUrlAction'; import { getPublicCaseAction } from '../../actions/Public/getPublicCaseAction'; -import { sequence } from 'cerebral'; import { setCaseAction } from '../../actions/setCaseAction'; import { setPdfPreviewUrlSequence } from '../setPdfPreviewUrlSequence'; import { setShowModalFactoryAction } from '../../actions/setShowModalFactoryAction'; @@ -9,9 +8,7 @@ import { setupCurrentPageAction } from '../../actions/setupCurrentPageAction'; import { showMaintenancePageDecorator } from '../../utilities/showMaintenancePageDecorator'; import { showProgressSequenceDecorator } from '../../utilities/showProgressSequenceDecorator'; -export const gotoPublicPrintableDocketRecordSequence = sequence<{ - docketNumber: string; -}>( +export const gotoPublicPrintableDocketRecordSequence = showMaintenancePageDecorator( showProgressSequenceDecorator([ clearModalStateAction, @@ -22,5 +19,4 @@ export const gotoPublicPrintableDocketRecordSequence = sequence<{ setShowModalFactoryAction('OpenPrintableDocketRecordModal'), setupCurrentPageAction('PublicCaseDetail'), ]), - ), -); + ) as unknown as (props: { docketNumber: string }) => void; diff --git a/web-client/src/presenter/sequences/chooseWorkQueueSequence.test.ts b/web-client/src/presenter/sequences/chooseWorkQueueSequence.test.ts index 1930541f29a..3b13cd16004 100644 --- a/web-client/src/presenter/sequences/chooseWorkQueueSequence.test.ts +++ b/web-client/src/presenter/sequences/chooseWorkQueueSequence.test.ts @@ -1,17 +1,13 @@ import { CerebralTest } from 'cerebral/test'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { chooseWorkQueueSequence } from '../sequences/chooseWorkQueueSequence'; +import { docketClerk1User } from '@shared/test/mockUsers'; import { presenter } from '../presenter-mock'; describe('chooseWorkQueueSequence', () => { - const { PETITIONS_SECTION } = applicationContext.getConstants(); let cerebralTest; beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue({ - role: 'petitionsclerk', - section: PETITIONS_SECTION, - }); applicationContext .getUseCases() .getDocumentQCInboxForSectionInteractor.mockReturnValue([ @@ -25,6 +21,7 @@ describe('chooseWorkQueueSequence', () => { chooseWorkQueueSequence, }; cerebralTest = CerebralTest(presenter); + cerebralTest.setState('user', docketClerk1User); }); it('should set the workQueueToDisplay to match the props passed in', async () => { diff --git a/web-client/src/presenter/sequences/gotoDashboardSequence.test.ts b/web-client/src/presenter/sequences/gotoDashboardSequence.test.ts index b9226c1d50c..3319a692933 100644 --- a/web-client/src/presenter/sequences/gotoDashboardSequence.test.ts +++ b/web-client/src/presenter/sequences/gotoDashboardSequence.test.ts @@ -1,6 +1,7 @@ import { CerebralTest } from 'cerebral/test'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { gotoDashboardSequence } from '../sequences/gotoDashboardSequence'; +import { petitionerUser } from '@shared/test/mockUsers'; import { presenter } from '../presenter-mock'; describe('gotoDashboardSequence', () => { @@ -26,6 +27,12 @@ describe('gotoDashboardSequence', () => { //set token to take 'isLoggedIn' path cerebralTest.setState('token', 'a'); + cerebralTest.setState('user', { + email: 'richard@e.mail', + name: 'richard', + role: petitionerUser.role, + userId: 'a805d1ab-18d0-43ec-bafb-654e83405416', + }); }); it('should set up state for petitioner going to dashboard', async () => { diff --git a/web-client/src/presenter/sequences/gotoMessageDetailSequence.test.ts b/web-client/src/presenter/sequences/gotoMessageDetailSequence.test.ts index 9b86bc8ec7a..b4b029ec69f 100644 --- a/web-client/src/presenter/sequences/gotoMessageDetailSequence.test.ts +++ b/web-client/src/presenter/sequences/gotoMessageDetailSequence.test.ts @@ -5,6 +5,7 @@ import { import { CerebralTest } from 'cerebral/test'; import { MOCK_CASE } from '../../../../shared/src/test/mockCase'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; +import { docketClerk1User } from '@shared/test/mockUsers'; import { gotoMessageDetailSequence } from '../sequences/gotoMessageDetailSequence'; import { presenter } from '../presenter-mock'; @@ -75,6 +76,7 @@ describe('gotoMessageDetailSequence', () => { //set token to take 'isLoggedIn' path cerebralTest.setState('token', 'a'); + cerebralTest.setState('user', docketClerk1User); }); it('should change the page to MyAccount and close the opened menu', async () => { diff --git a/web-client/src/presenter/sequences/gotoMessagesSequence.test.ts b/web-client/src/presenter/sequences/gotoMessagesSequence.test.ts index 979752514ab..ef2eb0dd875 100644 --- a/web-client/src/presenter/sequences/gotoMessagesSequence.test.ts +++ b/web-client/src/presenter/sequences/gotoMessagesSequence.test.ts @@ -1,5 +1,6 @@ import { CerebralTest } from 'cerebral/test'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; +import { docketClerk1User } from '@shared/test/mockUsers'; import { gotoMessagesSequence } from '../sequences/gotoMessagesSequence'; import { presenter } from '../presenter-mock'; @@ -34,6 +35,7 @@ describe('gotoMessagesSequence', () => { //set token to take 'isLoggedIn' path cerebralTest.setState('token', 'a'); + cerebralTest.setState('user', docketClerk1User); }); it('should change the page to MyAccount and close the opened menu', async () => { diff --git a/web-client/src/presenter/sequences/gotoPrintPaperTrialNoticesSequence.ts b/web-client/src/presenter/sequences/gotoPrintPaperTrialNoticesSequence.ts index 55b1034fdc1..f5bf23b2a05 100644 --- a/web-client/src/presenter/sequences/gotoPrintPaperTrialNoticesSequence.ts +++ b/web-client/src/presenter/sequences/gotoPrintPaperTrialNoticesSequence.ts @@ -1,19 +1,15 @@ import { getPaperServicePdfUrlAction } from '@web-client/presenter/actions/TrialSession/getPaperServicePdfUrlAction'; -import { sequence } from 'cerebral'; import { setAlertWarningAction } from '@web-client/presenter/actions/setAlertWarningAction'; import { setPdfPreviewUrlAction } from '@web-client/presenter/actions/CourtIssuedOrder/setPdfPreviewUrlAction'; import { setTrialSessionCalendarAlertWarningAction } from '@web-client/presenter/actions/TrialSession/setTrialSessionCalendarAlertWarningAction'; import { setTrialSessionIdAction } from '@web-client/presenter/actions/TrialSession/setTrialSessionIdAction'; import { setupCurrentPageAction } from '@web-client/presenter/actions/setupCurrentPageAction'; -export const gotoPrintPaperTrialNoticesSequence = sequence<{ - fileId: string; - trialSessionId: string; -}>([ +export const gotoPrintPaperTrialNoticesSequence = [ setTrialSessionCalendarAlertWarningAction, setAlertWarningAction, setTrialSessionIdAction, getPaperServicePdfUrlAction, setPdfPreviewUrlAction, setupCurrentPageAction('PrintPaperTrialNotices'), -]); +] as unknown as (props: { fileId: string; trialSessionId: string }) => void; diff --git a/web-client/src/presenter/sequences/gotoPrintablePendingReportForCaseSequence.test.ts b/web-client/src/presenter/sequences/gotoPrintablePendingReportForCaseSequence.test.ts index 81b1b51969a..7da1ae4d8a6 100644 --- a/web-client/src/presenter/sequences/gotoPrintablePendingReportForCaseSequence.test.ts +++ b/web-client/src/presenter/sequences/gotoPrintablePendingReportForCaseSequence.test.ts @@ -3,14 +3,9 @@ import { applicationContextForClient as applicationContext } from '@web-client/t import { gotoPrintablePendingReportForCaseSequence } from '../sequences/gotoPrintablePendingReportForCaseSequence'; import { presenter } from '../presenter-mock'; -const { CHAMBERS_SECTION } = applicationContext.getConstants(); - describe('gotoPrintablePendingReportForCaseSequence', () => { let cerebralTest; beforeAll(() => { - applicationContext.getCurrentUser.mockReturnValue({ - section: CHAMBERS_SECTION, - }); applicationContext .getUseCases() .generatePrintablePendingReportInteractor.mockReturnValue( diff --git a/web-client/src/presenter/sequences/gotoStartCaseWizardSequence.test.ts b/web-client/src/presenter/sequences/gotoStartCaseWizardSequence.test.ts index b3c987c06ba..0c5650b428f 100644 --- a/web-client/src/presenter/sequences/gotoStartCaseWizardSequence.test.ts +++ b/web-client/src/presenter/sequences/gotoStartCaseWizardSequence.test.ts @@ -1,10 +1,8 @@ import { CerebralTest } from 'cerebral/test'; -import { - DEFAULT_PROCEDURE_TYPE, - ROLES, -} from '../../../../shared/src/business/entities/EntityConstants'; +import { DEFAULT_PROCEDURE_TYPE } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { gotoStartCaseWizardSequence } from '../sequences/gotoStartCaseWizardSequence'; +import { petitionerUser, petitionsClerkUser } from '@shared/test/mockUsers'; import { presenter } from '../presenter-mock'; describe('gotoStartCaseWizardSequence', () => { @@ -19,9 +17,7 @@ describe('gotoStartCaseWizardSequence', () => { }); it('should set up state for an internal user going to start case form', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitionsClerk, - }); + cerebralTest.setState('user', petitionsClerkUser); await cerebralTest.runSequence('gotoStartCaseWizardSequence'); @@ -44,9 +40,7 @@ describe('gotoStartCaseWizardSequence', () => { }); it('should set up state for an external user going to start case form', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.petitioner, - }); + cerebralTest.setState('user', petitionerUser); await cerebralTest.runSequence('gotoStartCaseWizardSequence'); diff --git a/web-client/src/presenter/sequences/gotoTrialSessionDetailSequence.test.ts b/web-client/src/presenter/sequences/gotoTrialSessionDetailSequence.test.ts index 7a13191651a..9f9d36bfc6f 100644 --- a/web-client/src/presenter/sequences/gotoTrialSessionDetailSequence.test.ts +++ b/web-client/src/presenter/sequences/gotoTrialSessionDetailSequence.test.ts @@ -1,5 +1,6 @@ import { CerebralTest } from 'cerebral/test'; import { MOCK_TRIAL_INPERSON } from '../../../../shared/src/test/mockTrial'; +import { ROLES } from '@shared/business/entities/EntityConstants'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { gotoTrialSessionDetailSequence } from '../sequences/gotoTrialSessionDetailSequence'; import { presenter } from '../presenter-mock'; @@ -17,6 +18,11 @@ describe('gotoTrialSessionDetailSequence', () => { cerebralTest = CerebralTest(presenter); //set token to take 'isLoggedIn' path cerebralTest.setState('token', 'a'); + cerebralTest.setState('user', { + name: 'richard', + role: ROLES.petitioner, + userId: 'a805d1ab-18d0-43ec-bafb-654e83405416', + }); }); it('should set up state for an uncalendared session with eligible cases and case order', async () => { diff --git a/web-client/src/presenter/sequences/gotoTrialSessionWorkingCopySequence.test.ts b/web-client/src/presenter/sequences/gotoTrialSessionWorkingCopySequence.test.ts index 1f321957627..da0486350c4 100644 --- a/web-client/src/presenter/sequences/gotoTrialSessionWorkingCopySequence.test.ts +++ b/web-client/src/presenter/sequences/gotoTrialSessionWorkingCopySequence.test.ts @@ -1,15 +1,13 @@ import { CerebralTest } from 'cerebral/test'; -import { - ROLES, - TRIAL_SESSION_PROCEEDING_TYPES, -} from '../../../../shared/src/business/entities/EntityConstants'; +import { TRIAL_SESSION_PROCEEDING_TYPES } from '../../../../shared/src/business/entities/EntityConstants'; import { applicationContextForClient as applicationContext } from '@web-client/test/createClientTestApplicationContext'; import { gotoTrialSessionWorkingCopySequence } from '../sequences/gotoTrialSessionWorkingCopySequence'; +import { judgeUser } from '@shared/test/mockUsers'; import { presenter } from '../presenter-mock'; describe('gotoTrialSessionWorkingCopySequence', () => { const mockTrialSessionId = '2f731ada-0276-4eca-b518-cfedc4c496d9'; - const mockJudgeUserId = '42e55e43-2cc2-4266-96ed-8cc0400ff1ce'; + const mockJudgeUserId = judgeUser.userId; const mockTrialSession = { judge: { @@ -46,14 +44,10 @@ describe('gotoTrialSessionWorkingCopySequence', () => { //set token to take 'isLoggedIn' path cerebralTest.setState('token', 'a'); + cerebralTest.setState('user', judgeUser); }); it('should set up state for a user associated with the trial session', async () => { - applicationContext.getCurrentUser.mockReturnValue({ - role: ROLES.judge, - userId: mockJudgeUserId, - }); - applicationContext .getUseCases() .getTrialSessionDetailsInteractor.mockReturnValue(mockTrialSession); diff --git a/web-client/src/presenter/sequences/setPdfPreviewUrlSequence.ts b/web-client/src/presenter/sequences/setPdfPreviewUrlSequence.ts index 37b24430359..a399f7ff697 100644 --- a/web-client/src/presenter/sequences/setPdfPreviewUrlSequence.ts +++ b/web-client/src/presenter/sequences/setPdfPreviewUrlSequence.ts @@ -1,8 +1,7 @@ import { clearPdfPreviewUrlAction } from '../actions/CourtIssuedOrder/clearPdfPreviewUrlAction'; -import { sequence } from 'cerebral'; import { setPdfPreviewUrlAction } from '../actions/CourtIssuedOrder/setPdfPreviewUrlAction'; -export const setPdfPreviewUrlSequence = sequence([ +export const setPdfPreviewUrlSequence = [ clearPdfPreviewUrlAction, setPdfPreviewUrlAction, -]); +] as unknown as () => void; diff --git a/web-client/src/presenter/sequences/updateTrialSessionCompleteSequence.ts b/web-client/src/presenter/sequences/updateTrialSessionCompleteSequence.ts index 239e29f4dab..5d2d5a28d79 100644 --- a/web-client/src/presenter/sequences/updateTrialSessionCompleteSequence.ts +++ b/web-client/src/presenter/sequences/updateTrialSessionCompleteSequence.ts @@ -4,15 +4,11 @@ import { getCompleteTrialSessionAlertSuccessAction } from '../actions/getComplet import { hasPaperAction } from '../actions/hasPaperAction'; import { navigateToPrintPaperTrialNoticesAction } from '@web-client/presenter/actions/TrialSession/navigateToPrintPaperTrialNoticesAction'; import { navigateToTrialSessionDetailAction } from '../actions/TrialSession/navigateToTrialSessionDetailAction'; -import { sequence } from 'cerebral'; import { setAlertSuccessAction } from '../actions/setAlertSuccessAction'; import { setSaveAlertsForNavigationAction } from '../actions/setSaveAlertsForNavigationAction'; import { unsetWaitingForResponseAction } from '../actions/unsetWaitingForResponseAction'; -export const updateTrialSessionCompleteSequence = sequence<{ - fileId?: string; - hasPaper: boolean; -}>([ +export const updateTrialSessionCompleteSequence = [ unsetWaitingForResponseAction, clearModalStateAction, clearModalAction, @@ -26,4 +22,4 @@ export const updateTrialSessionCompleteSequence = sequence<{ ], paper: [navigateToPrintPaperTrialNoticesAction], }, -]); +] as unknown as (props: { fileId?: string; hasPaper: boolean }) => void; diff --git a/web-client/src/presenter/state.ts b/web-client/src/presenter/state.ts index 7934d399339..bc46747db93 100644 --- a/web-client/src/presenter/state.ts +++ b/web-client/src/presenter/state.ts @@ -62,6 +62,7 @@ import { draftDocumentViewerHelper } from './computeds/draftDocumentViewerHelper import { editDocketEntryMetaHelper } from './computeds/editDocketEntryMetaHelper'; import { editPetitionerInformationHelper } from './computeds/editPetitionerInformationHelper'; import { editStatisticFormHelper } from './computeds/editStatisticFormHelper'; +import { emptyUserState } from '@web-client/presenter/state/userState'; import { externalConsolidatedCaseGroupHelper } from './computeds/externalConsolidatedCaseGroupHelper'; import { externalUserCasesHelper } from './computeds/Dashboard/externalUserCasesHelper'; import { fileDocumentHelper } from './computeds/fileDocumentHelper'; @@ -838,7 +839,7 @@ export const baseState = { name: '', }, trialSessionWorkingCopy: cloneDeep(initialTrialSessionWorkingCopyState), - user: null as any, + user: cloneDeep(emptyUserState), userContactEditProgress: {} as { inProgress?: boolean }, users: [] as RawUser[], validationErrors: {} as Record, diff --git a/web-client/src/presenter/state/userState.ts b/web-client/src/presenter/state/userState.ts new file mode 100644 index 00000000000..4a2b95bcdf1 --- /dev/null +++ b/web-client/src/presenter/state/userState.ts @@ -0,0 +1,13 @@ +import { GetUserResponse } from '@shared/business/useCases/getUserInteractor'; +import { Role } from '@shared/business/entities/EntityConstants'; + +export const emptyUserState: GetUserResponse & { + email: string; +} = { + email: '', + entityName: '', + name: '', + role: '' as Role, + section: '', + userId: '', +}; // We know that the logged in user has an email otherwise they could not login. diff --git a/web-client/src/styles/buttons.scss b/web-client/src/styles/buttons.scss index dd32b7688c3..527330a0452 100644 --- a/web-client/src/styles/buttons.scss +++ b/web-client/src/styles/buttons.scss @@ -70,7 +70,7 @@ button:disabled { } } - &.ustc-button--unstyled { + &.ustc-button--unstyled { padding: 0.75rem 0; line-height: normal; text-align: center; diff --git a/web-client/src/styles/custom.scss b/web-client/src/styles/custom.scss index 1fad9c5aee8..c87c44e7a45 100644 --- a/web-client/src/styles/custom.scss +++ b/web-client/src/styles/custom.scss @@ -2199,6 +2199,12 @@ button.change-scanner-button { color: $color-white; font-weight: $font-semibold; text-align: center; + + button { + border: none; + background: none; + color: white; + } } .cursor-pointer { diff --git a/web-client/src/styles/forms.scss b/web-client/src/styles/forms.scss index 006921b942d..cbc85c45fab 100644 --- a/web-client/src/styles/forms.scss +++ b/web-client/src/styles/forms.scss @@ -126,7 +126,6 @@ legend { input[type='email'], input[type='number'], -input[type='tel'], input[type='text'], textarea, select { diff --git a/web-client/src/test/createClientTestApplicationContext.ts b/web-client/src/test/createClientTestApplicationContext.ts index 4ba7ba7c59c..dfb4ee53731 100644 --- a/web-client/src/test/createClientTestApplicationContext.ts +++ b/web-client/src/test/createClientTestApplicationContext.ts @@ -25,7 +25,6 @@ import { getPublicSiteUrl, getUniqueId, } from '@shared/sharedAppContext'; -import { ROLES } from '@shared/business/entities/EntityConstants'; import { User } from '@shared/business/entities/User'; import { abbreviateState } from '@shared/business/utilities/abbreviateState'; import { aggregatePartiesForService } from '@shared/business/utilities/aggregatePartiesForService'; @@ -547,17 +546,7 @@ const createTestApplicationContext = () => { ERROR_MAP_429, }; }), - getCurrentUser: jest.fn().mockImplementation(() => { - return new User({ - name: 'richard', - role: ROLES.petitioner, - userId: 'a805d1ab-18d0-43ec-bafb-654e83405416', - }); - }), getCurrentUserPermissions: jest.fn(), - getCurrentUserToken: () => { - return ''; - }, getDispatchers: jest.fn().mockReturnValue({ sendBulkTemplatedEmail: jest.fn(), sendNotificationOfSealing: jest.fn(), @@ -609,7 +598,6 @@ const createTestApplicationContext = () => { isFeatureEnabled: jest.fn(), isPublicUser: jest.fn().mockImplementation(() => false), setCurrentUser: jest.fn(), - setCurrentUserToken: jest.fn(), }; return applicationContext; }; diff --git a/web-client/src/ustc-ui/Button/PillButton.tsx b/web-client/src/ustc-ui/Button/PillButton.tsx new file mode 100644 index 00000000000..adeb64671ec --- /dev/null +++ b/web-client/src/ustc-ui/Button/PillButton.tsx @@ -0,0 +1,22 @@ +import { Icon } from '../../ustc-ui/Icon/Icon'; +import React from 'react'; + +interface PillButtonProps { + text: string; + onRemove: () => void; +} + +export const PillButton = ({ onRemove, text }: PillButtonProps) => { + return ( + + {text} + + + ); +}; diff --git a/web-client/src/ustc-ui/Pagination/Paginator.tsx b/web-client/src/ustc-ui/Pagination/Paginator.tsx index 1013c2f108a..1beb6346bc7 100644 --- a/web-client/src/ustc-ui/Pagination/Paginator.tsx +++ b/web-client/src/ustc-ui/Pagination/Paginator.tsx @@ -1,51 +1,74 @@ +import { Button } from '@web-client/ustc-ui/Button/Button'; import React from 'react'; -import ReactPaginate from 'react-paginate'; +import classNames from 'classnames'; export const Paginator = ({ - breakClassName, - forcePage, - id, - marginPagesDisplayed = 3, + currentPageIndex, onPageChange, - pageCount, - pageRangeDisplayed, + totalPages, }: { - breakClassName?: string; - marginPagesDisplayed?: number; - pageCount: number; - id?: string; - pageRangeDisplayed: number; - onPageChange: (selectedItem: { selected: number }) => void; - forcePage: number; + totalPages: number; + currentPageIndex: number; + onPageChange: (currentPage: number) => void; }) => { + let currentPage = currentPageIndex + 1; + + const nextDisabled = currentPage >= totalPages; + const previousDisabled = currentPage <= 1; + return ( - <> - - + ); }; diff --git a/web-client/src/views/AddPetitionerToCase/AddPetitionerToCase.tsx b/web-client/src/views/AddPetitionerToCase/AddPetitionerToCase.tsx index 6c46c0fa788..bdd60a26472 100644 --- a/web-client/src/views/AddPetitionerToCase/AddPetitionerToCase.tsx +++ b/web-client/src/views/AddPetitionerToCase/AddPetitionerToCase.tsx @@ -16,6 +16,8 @@ import React from 'react'; export const AddPetitionerToCase = connect( { COUNTRY_TYPES: state.constants.COUNTRY_TYPES, + closeModalAndReturnToCaseDetailSequence: + sequences.closeModalAndReturnToCaseDetailSequence, constants: state.constants, form: state.form, formCancelToggleCancelSequence: sequences.formCancelToggleCancelSequence, @@ -32,6 +34,7 @@ export const AddPetitionerToCase = connect( validationErrors: state.validationErrors, }, function AddPetitionerToCase({ + closeModalAndReturnToCaseDetailSequence, constants, COUNTRY_TYPES, form, @@ -224,7 +227,7 @@ export const AddPetitionerToCase = connect( data-testid="add-petitioner-phone" id="phone" name="contact.phone" - type="tel" + type="text" value={form.contact.phone || ''} onChange={e => { updateFormValueSequence({ @@ -296,7 +299,9 @@ export const AddPetitionerToCase = connect( {showModal === 'FormCancelModalDialog' && ( - + )} ); diff --git a/web-client/src/views/AdvancedSearch/PractitionerSearchResults.tsx b/web-client/src/views/AdvancedSearch/PractitionerSearchResults.tsx index 251ef3d7bb7..b6558a3149f 100644 --- a/web-client/src/views/AdvancedSearch/PractitionerSearchResults.tsx +++ b/web-client/src/views/AdvancedSearch/PractitionerSearchResults.tsx @@ -27,14 +27,11 @@ export const PractitionerSearchResults = connect(
{practitionerSearchHelper.showPaginator && ( { submitPractitionerNameSearchSequence({ - selectedPage: pageChange.selected, + selectedPage: pageChange, }); focusPaginatorTop(paginatorTop); }} @@ -164,14 +161,11 @@ export const PractitionerSearchResults = connect(
{practitionerSearchHelper.showPaginator && ( { submitPractitionerNameSearchSequence({ - selectedPage: pageChange.selected, + selectedPage: pageChange, }); focusPaginatorTop(paginatorTop); }} diff --git a/web-client/src/views/CaseAssociationRequest/CaseAssociationRequestWizard.tsx b/web-client/src/views/CaseAssociationRequest/CaseAssociationRequestWizard.tsx index 0abb300ca34..1d26acd17a9 100644 --- a/web-client/src/views/CaseAssociationRequest/CaseAssociationRequestWizard.tsx +++ b/web-client/src/views/CaseAssociationRequest/CaseAssociationRequestWizard.tsx @@ -6,20 +6,27 @@ import { FormCancelModalDialog } from '../FormCancelModalDialog'; import { SuccessNotification } from '../SuccessNotification'; import { Tab, Tabs } from '../../ustc-ui/Tabs/Tabs'; import { connect } from '@web-client/presenter/shared.cerebral'; -import { state } from '@web-client/presenter/app.cerebral'; +import { sequences, state } from '@web-client/presenter/app.cerebral'; import React from 'react'; export const CaseAssociationRequestWizard = connect( { + closeModalAndReturnToDashboardSequence: + sequences.closeModalAndReturnToDashboardSequence, showModal: state.modal.showModal, }, - function CaseAssociationRequestWizard({ showModal }) { + function CaseAssociationRequestWizard({ + closeModalAndReturnToDashboardSequence, + showModal, + }) { return ( <>
{showModal == 'FormCancelModalDialog' && ( - + )} diff --git a/web-client/src/views/CaseDetailEdit/ReviewSavedPetition.tsx b/web-client/src/views/CaseDetailEdit/ReviewSavedPetition.tsx index 743427cae87..12d11385555 100644 --- a/web-client/src/views/CaseDetailEdit/ReviewSavedPetition.tsx +++ b/web-client/src/views/CaseDetailEdit/ReviewSavedPetition.tsx @@ -16,6 +16,7 @@ import React from 'react'; export const ReviewSavedPetition = connect( { clearModalSequence: sequences.clearModalSequence, + closeModalAndNavigateSequence: sequences.closeModalAndNavigateSequence, constants: state.constants, form: state.form, formCancelToggleCancelSequence: sequences.formCancelToggleCancelSequence, @@ -30,6 +31,7 @@ export const ReviewSavedPetition = connect( }, function ReviewSavedPetition({ clearModalSequence, + closeModalAndNavigateSequence, constants, form, formCancelToggleCancelSequence, @@ -279,7 +281,9 @@ export const ReviewSavedPetition = connect( > )} {showModal == 'FormCancelModalDialog' && ( - + )} {showModal === 'ServeCaseToIrsErrorModal' && ( diff --git a/web-client/src/views/ColdCaseReport/ColdCaseReportList.tsx b/web-client/src/views/ColdCaseReport/ColdCaseReportList.tsx index bf9852f314b..eea560e60f4 100644 --- a/web-client/src/views/ColdCaseReport/ColdCaseReportList.tsx +++ b/web-client/src/views/ColdCaseReport/ColdCaseReportList.tsx @@ -78,13 +78,10 @@ export function ColdCaseReportList({ entries }: { entries: ColdCaseEntry[] }) { {totalPages > 1 && (
{ - setActivePage(pageChange.selected); + currentPageIndex={activePage} + totalPages={totalPages} + onPageChange={pageChange => { + setActivePage(pageChange); focusPaginatorTop(paginatorTop); }} /> @@ -161,13 +158,10 @@ export function ColdCaseReportList({ entries }: { entries: ColdCaseEntry[] }) { {totalPages > 1 && ( { - setActivePage(pageChange.selected); + currentPageIndex={activePage} + totalPages={totalPages} + onPageChange={pageChange => { + setActivePage(pageChange); focusPaginatorTop(paginatorTop); }} /> diff --git a/web-client/src/views/ContactEdit.tsx b/web-client/src/views/ContactEdit.tsx index df17eeaca49..f5af3ed7032 100644 --- a/web-client/src/views/ContactEdit.tsx +++ b/web-client/src/views/ContactEdit.tsx @@ -14,6 +14,8 @@ import React from 'react'; export const ContactEdit = connect( { COUNTRY_TYPES: state.constants.COUNTRY_TYPES, + closeModalAndReturnToCaseDetailSequence: + sequences.closeModalAndReturnToCaseDetailSequence, form: state.form, formCancelToggleCancelSequence: sequences.formCancelToggleCancelSequence, showModal: state.modal.showModal, @@ -23,6 +25,7 @@ export const ContactEdit = connect( validationErrors: state.validationErrors, }, function ContactEdit({ + closeModalAndReturnToCaseDetailSequence, COUNTRY_TYPES, form, formCancelToggleCancelSequence, @@ -104,7 +107,7 @@ export const ContactEdit = connect( data-testid="phone-number-input" id="phone" name="contact.phone" - type="tel" + type="text" value={form.contact.phone || ''} onBlur={() => { validatePetitionerSequence(); @@ -137,7 +140,9 @@ export const ContactEdit = connect(
{showModal === 'FormCancelModalDialog' && ( - + )} ); diff --git a/web-client/src/views/Correspondence/AddCorrespondenceDocument.tsx b/web-client/src/views/Correspondence/AddCorrespondenceDocument.tsx index e73ca405647..0f269dace4d 100644 --- a/web-client/src/views/Correspondence/AddCorrespondenceDocument.tsx +++ b/web-client/src/views/Correspondence/AddCorrespondenceDocument.tsx @@ -12,6 +12,8 @@ import React from 'react'; export const AddCorrespondenceDocument = connect( { + closeModalAndReturnToCaseDetailSequence: + sequences.closeModalAndReturnToCaseDetailSequence, fileDocumentHelper: state.fileDocumentHelper, form: state.form, formCancelToggleCancelSequence: sequences.formCancelToggleCancelSequence, @@ -24,6 +26,7 @@ export const AddCorrespondenceDocument = connect( validationErrors: state.validationErrors, }, function AddCorrespondenceDocument({ + closeModalAndReturnToCaseDetailSequence, form, formCancelToggleCancelSequence, showModal, @@ -37,7 +40,9 @@ export const AddCorrespondenceDocument = connect( {showModal === 'FormCancelModalDialog' && ( - + )}
diff --git a/web-client/src/views/Correspondence/EditCorrespondenceDocument.tsx b/web-client/src/views/Correspondence/EditCorrespondenceDocument.tsx index b981ba2b580..80be762341e 100644 --- a/web-client/src/views/Correspondence/EditCorrespondenceDocument.tsx +++ b/web-client/src/views/Correspondence/EditCorrespondenceDocument.tsx @@ -14,6 +14,8 @@ import React from 'react'; export const EditCorrespondenceDocument = connect( { + cancelAndNavigateToCorrespondenceSequence: + sequences.cancelAndNavigateToCorrespondenceSequence, clearExistingDocumentSequence: sequences.clearExistingDocumentSequence, editCorrespondenceDocumentSequence: sequences.editCorrespondenceDocumentSequence, @@ -28,6 +30,7 @@ export const EditCorrespondenceDocument = connect( validationErrors: state.validationErrors, }, function EditCorrespondenceDocument({ + cancelAndNavigateToCorrespondenceSequence, clearExistingDocumentSequence, editCorrespondenceDocumentSequence, form, @@ -43,7 +46,9 @@ export const EditCorrespondenceDocument = connect( <> {showModal === 'FormCancelModalDialog' && ( - + )}
diff --git a/web-client/src/views/CreateOrder/CreateOrder.tsx b/web-client/src/views/CreateOrder/CreateOrder.tsx index ce2b537d324..14bf982432f 100644 --- a/web-client/src/views/CreateOrder/CreateOrder.tsx +++ b/web-client/src/views/CreateOrder/CreateOrder.tsx @@ -16,6 +16,8 @@ import React from 'react'; export const CreateOrder = connect( { + closeModalAndReturnToCaseDetailSequence: + sequences.closeModalAndReturnToCaseDetailSequence, createOrderHelper: state.createOrderHelper, editorDelta: state.form.editorDelta, formCancelToggleCancelSequence: sequences.formCancelToggleCancelSequence, @@ -32,6 +34,7 @@ export const CreateOrder = connect( validationErrors: state.validationErrors, }, function CreateOrder({ + closeModalAndReturnToCaseDetailSequence, createOrderHelper, editorDelta, formCancelToggleCancelSequence, @@ -147,7 +150,9 @@ export const CreateOrder = connect( {showModal === 'AddDocketNumbersModal' && } {showModal === 'FormCancelModalDialog' && ( - + )} {showModal === 'EditOrderTitleModal' && } diff --git a/web-client/src/views/CreatePetitionerAccount/CreatePetitionerAccountForm.tsx b/web-client/src/views/CreatePetitionerAccount/CreatePetitionerAccountForm.tsx index c9971de0789..f3b47a340ab 100644 --- a/web-client/src/views/CreatePetitionerAccount/CreatePetitionerAccountForm.tsx +++ b/web-client/src/views/CreatePetitionerAccount/CreatePetitionerAccountForm.tsx @@ -1,11 +1,16 @@ import { Button } from '@web-client/ustc-ui/Button/Button'; import { RequirementsText } from '@web-client/views/CreatePetitionerAccount/RequirementsText'; import { connect } from '@web-client/presenter/shared.cerebral'; +import { debounce } from 'lodash'; import { sequences, state } from '@web-client/presenter/app.cerebral'; -import React, { useState } from 'react'; +import React, { useEffect, useState } from 'react'; + +const DEBOUNCE_TIME_MS = 500; export const CreatePetitionerAccountForm = connect( { + alertError: state.alertError, + alertWarning: state.alertWarning, confirmPassword: state.form.confirmPassword, createAccountHelper: state.createAccountHelper, navigateToLoginSequence: sequences.navigateToLoginSequence, @@ -18,6 +23,8 @@ export const CreatePetitionerAccountForm = connect( updateFormValueSequence: sequences.updateFormValueSequence, }, ({ + alertError, + alertWarning, confirmPassword, createAccountHelper, navigateToLoginSequence, @@ -30,6 +37,18 @@ export const CreatePetitionerAccountForm = connect( }) => { const [inFocusEmail, setInFocusEmail] = useState(true); const [inFocusName, setInFocusName] = useState(true); + const [submitDisabled, setSubmitDisabled] = useState(false); + + // Re-enabled submit button if submission was unsuccessful + useEffect(() => { + if (alertError || alertWarning) { + setSubmitDisabled(false); + } + }, [alertError, alertWarning]); + + const submitFunction = debounce(() => { + submitCreatePetitionerAccountFormSequence(); + }, DEBOUNCE_TIME_MS); return ( <> @@ -42,7 +61,8 @@ export const CreatePetitionerAccountForm = connect(
{ e.preventDefault(); - submitCreatePetitionerAccountFormSequence(); + setSubmitDisabled(true); + submitFunction(); }} >
{showModal === 'FormCancelModalDialog' && ( - + )} {showModal === 'CreateMessageModalDialog' && (
{showModal === 'FormCancelModalDialog' && ( - + )} ); diff --git a/web-client/src/views/EditPetitionerCounsel.tsx b/web-client/src/views/EditPetitionerCounsel.tsx index eab1324300b..4c6a2e2a982 100644 --- a/web-client/src/views/EditPetitionerCounsel.tsx +++ b/web-client/src/views/EditPetitionerCounsel.tsx @@ -15,6 +15,8 @@ import React from 'react'; export const EditPetitionerCounsel = connect( { + closeModalAndReturnToCaseDetailSequence: + sequences.closeModalAndReturnToCaseDetailSequence, form: state.form, formCancelToggleCancelSequence: sequences.formCancelToggleCancelSequence, formattedCaseDetail: state.formattedCaseDetail, @@ -30,6 +32,7 @@ export const EditPetitionerCounsel = connect( validationErrors: state.validationErrors, }, function EditPetitionerCounsel({ + closeModalAndReturnToCaseDetailSequence, form, formattedCaseDetail, formCancelToggleCancelSequence, @@ -151,7 +154,9 @@ export const EditPetitionerCounsel = connect( {showModal === 'FormCancelModalDialog' && ( - + )} {showModal === 'MatchingEmailFoundModal' && } {showModal === 'NoMatchingEmailFoundModal' && ( diff --git a/web-client/src/views/EditPetitionerInformationInternal.tsx b/web-client/src/views/EditPetitionerInformationInternal.tsx index 72d1e7477a1..80e22d3673e 100644 --- a/web-client/src/views/EditPetitionerInformationInternal.tsx +++ b/web-client/src/views/EditPetitionerInformationInternal.tsx @@ -23,6 +23,8 @@ import React from 'react'; export const EditPetitionerInformationInternal = connect( { COUNTRY_TYPES: state.constants.COUNTRY_TYPES, + closeModalAndReturnToCaseDetailSequence: + sequences.closeModalAndReturnToCaseDetailSequence, editPetitionerInformationHelper: state.editPetitionerInformationHelper, form: state.form, formCancelToggleCancelSequence: sequences.formCancelToggleCancelSequence, @@ -37,6 +39,7 @@ export const EditPetitionerInformationInternal = connect( validationErrors: state.validationErrors, }, function EditPetitionerInformationInternal({ + closeModalAndReturnToCaseDetailSequence, COUNTRY_TYPES, editPetitionerInformationHelper, form, @@ -181,7 +184,7 @@ export const EditPetitionerInformationInternal = connect( className="usa-input max-width-200" id="phone" name="contact.phone" - type="tel" + type="text" value={form.contact.phone || ''} onBlur={() => { validatePetitionerSequence(); @@ -354,7 +357,9 @@ export const EditPetitionerInformationInternal = connect( {showModal === 'FormCancelModalDialog' && ( - + )} {showModal === 'MatchingEmailFoundModal' && } {showModal === 'AccountUnverifiedModal' && } diff --git a/web-client/src/views/EditRespondentCounsel.tsx b/web-client/src/views/EditRespondentCounsel.tsx index ba0a96e1814..f7bcddfa3df 100644 --- a/web-client/src/views/EditRespondentCounsel.tsx +++ b/web-client/src/views/EditRespondentCounsel.tsx @@ -14,6 +14,8 @@ import React from 'react'; export const EditRespondentCounsel = connect( { + closeModalAndReturnToCaseDetailSequence: + sequences.closeModalAndReturnToCaseDetailSequence, form: state.form, formCancelToggleCancelSequence: sequences.formCancelToggleCancelSequence, openRemoveRespondentCounselModalSequence: @@ -27,6 +29,7 @@ export const EditRespondentCounsel = connect( validationErrors: state.validationErrors, }, function EditRespondentCounsel({ + closeModalAndReturnToCaseDetailSequence, form, formCancelToggleCancelSequence, openRemoveRespondentCounselModalSequence, @@ -102,7 +105,9 @@ export const EditRespondentCounsel = connect( {showModal === 'FormCancelModalDialog' && ( - + )} {showModal === 'MatchingEmailFoundModal' && } {showModal === 'NoMatchingEmailFoundModal' && ( diff --git a/web-client/src/views/EditUploadCourtIssuedDocument/EditUploadCourtIssuedDocument.tsx b/web-client/src/views/EditUploadCourtIssuedDocument/EditUploadCourtIssuedDocument.tsx index 8c6067289b3..0e452c3db6e 100644 --- a/web-client/src/views/EditUploadCourtIssuedDocument/EditUploadCourtIssuedDocument.tsx +++ b/web-client/src/views/EditUploadCourtIssuedDocument/EditUploadCourtIssuedDocument.tsx @@ -17,6 +17,8 @@ import classNames from 'classnames'; export const EditUploadCourtIssuedDocument = connect( { clearExistingDocumentSequence: sequences.clearExistingDocumentSequence, + closeModalAndReturnToCaseDetailDraftDocumentsSequence: + sequences.closeModalAndReturnToCaseDetailDraftDocumentsSequence, constants: state.constants, editUploadCourtIssuedDocumentSequence: sequences.editUploadCourtIssuedDocumentSequence, @@ -32,6 +34,7 @@ export const EditUploadCourtIssuedDocument = connect( }, function EditUploadCourtIssuedDocument({ clearExistingDocumentSequence, + closeModalAndReturnToCaseDetailDraftDocumentsSequence, constants, editUploadCourtIssuedDocumentSequence, fileDocumentHelper, @@ -47,7 +50,11 @@ export const EditUploadCourtIssuedDocument = connect( <> {showModal === 'FormCancelModalDialog' && ( - + )}
diff --git a/web-client/src/views/FileDocument/BeforeYouFileADocument.tsx b/web-client/src/views/FileDocument/BeforeYouFileADocument.tsx index 43697f89013..070f66643df 100644 --- a/web-client/src/views/FileDocument/BeforeYouFileADocument.tsx +++ b/web-client/src/views/FileDocument/BeforeYouFileADocument.tsx @@ -11,11 +11,14 @@ import React from 'react'; export const BeforeYouFileADocument = connect( { caseDetail: state.caseDetail, + closeModalAndReturnToCaseDetailSequence: + sequences.closeModalAndReturnToCaseDetailSequence, formCancelToggleCancelSequence: sequences.formCancelToggleCancelSequence, showModal: state.modal.showModal, }, function BeforeYouFileADocument({ caseDetail, + closeModalAndReturnToCaseDetailSequence, formCancelToggleCancelSequence, showModal, }) { @@ -128,7 +131,9 @@ export const BeforeYouFileADocument = connect( Cancel {showModal === 'FormCancelModalDialog' && ( - + )}
diff --git a/web-client/src/views/FileDocument/FileDocumentWizard.tsx b/web-client/src/views/FileDocument/FileDocumentWizard.tsx index 96c25724f05..9837382365d 100644 --- a/web-client/src/views/FileDocument/FileDocumentWizard.tsx +++ b/web-client/src/views/FileDocument/FileDocumentWizard.tsx @@ -8,21 +8,28 @@ import { SuccessNotification } from '../SuccessNotification'; import { Tab, Tabs } from '../../ustc-ui/Tabs/Tabs'; import { ViewAllDocuments } from './ViewAllDocuments'; import { connect } from '@web-client/presenter/shared.cerebral'; -import { state } from '@web-client/presenter/app.cerebral'; +import { sequences, state } from '@web-client/presenter/app.cerebral'; import React from 'react'; export const FileDocumentWizard = connect( { + closeModalAndReturnToDashboardSequence: + sequences.closeModalAndReturnToDashboardSequence, showModal: state.modal.showModal, }, - function FileDocumentWizard({ showModal }) { + function FileDocumentWizard({ + closeModalAndReturnToDashboardSequence, + showModal, + }) { return ( <>
{showModal == 'FormCancelModalDialog' && ( - + )} diff --git a/web-client/src/views/FileDocument/ViewAllDocumentsDesktop.tsx b/web-client/src/views/FileDocument/ViewAllDocumentsDesktop.tsx index 6a3f09e718b..ff8acfb8ace 100644 --- a/web-client/src/views/FileDocument/ViewAllDocumentsDesktop.tsx +++ b/web-client/src/views/FileDocument/ViewAllDocumentsDesktop.tsx @@ -9,6 +9,8 @@ import React from 'react'; export const ViewAllDocumentsDesktop = connect( { + closeModalAndReturnToCaseDetailSequence: + sequences.closeModalAndReturnToCaseDetailSequence, formCancelToggleCancelSequence: sequences.formCancelToggleCancelSequence, navigateBackSequence: sequences.navigateBackSequence, openCompleteSelectDocumentTypeModalSequence: @@ -19,6 +21,7 @@ export const ViewAllDocumentsDesktop = connect( viewAllDocumentsHelper: state.viewAllDocumentsHelper, }, function ViewAllDocumentsDesktop({ + closeModalAndReturnToCaseDetailSequence, formCancelToggleCancelSequence, navigateBackSequence, openCompleteSelectDocumentTypeModalSequence, @@ -100,7 +103,9 @@ export const ViewAllDocumentsDesktop = connect( Cancel {showModal === 'FormCancelModalDialog' && ( - + )} {showModal === 'CompleteSelectDocumentModalDialog' && ( diff --git a/web-client/src/views/FormCancelModalDialog.tsx b/web-client/src/views/FormCancelModalDialog.tsx index 83578e37fd6..b14add3bef0 100644 --- a/web-client/src/views/FormCancelModalDialog.tsx +++ b/web-client/src/views/FormCancelModalDialog.tsx @@ -1,18 +1,20 @@ import { ModalDialog } from './ModalDialog'; import { connect } from '@web-client/presenter/shared.cerebral'; -import { props } from 'cerebral'; import { sequences } from '@web-client/presenter/app.cerebral'; import React from 'react'; -export const FormCancelModalDialog = connect( - { - cancelSequence: sequences.dismissModalSequence, - confirmSequence: sequences[props.onCancelSequence], - useRunConfirmSequence: props.useRunConfirmSequence, - }, +type Props = { + onCancelSequence: Function; + useRunConfirmSequence?: boolean; +}; + +const deps = { cancelSequence: sequences.dismissModalSequence }; + +export const FormCancelModalDialog = connect( + deps, function FormCancelModalDialog({ cancelSequence, - confirmSequence, + onCancelSequence, useRunConfirmSequence, }) { return ( @@ -20,7 +22,7 @@ export const FormCancelModalDialog = connect( cancelLabel="No, Take Me Back" cancelSequence={cancelSequence} confirmLabel="Yes, Cancel" - confirmSequence={confirmSequence} + confirmSequence={onCancelSequence} message="If you cancel, your form selections will be lost." title="Are You Sure You Want to Cancel?" useRunConfirmSequence={useRunConfirmSequence} diff --git a/web-client/src/views/PaperFiling/PaperFiling.tsx b/web-client/src/views/PaperFiling/PaperFiling.tsx index a0d4a29c2aa..fcffbd6233d 100644 --- a/web-client/src/views/PaperFiling/PaperFiling.tsx +++ b/web-client/src/views/PaperFiling/PaperFiling.tsx @@ -18,6 +18,8 @@ import React from 'react'; export const PaperFiling = connect( { + closeModalAndReturnToCaseDetailSequence: + sequences.closeModalAndReturnToCaseDetailSequence, confirmWorkItemAlreadyCompleteSequence: sequences.confirmWorkItemAlreadyCompleteSequence, form: state.form, @@ -30,6 +32,7 @@ export const PaperFiling = connect( submitPaperFilingSequence: sequences.submitPaperFilingSequence, }, function PaperFiling({ + closeModalAndReturnToCaseDetailSequence, confirmWorkItemAlreadyCompleteSequence, form, formCancelToggleCancelSequence, @@ -119,7 +122,9 @@ export const PaperFiling = connect( Cancel {showModal === 'FormCancelModalDialog' && ( - + )}
diff --git a/web-client/src/views/Practitioners/PractitionerAddEditDocument.tsx b/web-client/src/views/Practitioners/PractitionerAddEditDocument.tsx index 999c26be67c..d4c5db72010 100644 --- a/web-client/src/views/Practitioners/PractitionerAddEditDocument.tsx +++ b/web-client/src/views/Practitioners/PractitionerAddEditDocument.tsx @@ -16,6 +16,8 @@ import classNames from 'classnames'; export const PractitionerAddEditDocument = connect( { + closeModalAndReturnToPractitionerDocumentsPageSequence: + sequences.closeModalAndReturnToPractitionerDocumentsPageSequence, constants: state.constants, documentTypes: state.constants.PRACTITIONER_DOCUMENT_TYPES, form: state.form, @@ -35,6 +37,7 @@ export const PractitionerAddEditDocument = connect( validationErrors: state.validationErrors, }, function PractitionerAddEditDocument({ + closeModalAndReturnToPractitionerDocumentsPageSequence, constants, documentTypes, form, @@ -222,7 +225,11 @@ export const PractitionerAddEditDocument = connect( {showModal === 'FormCancelModalDialog' && ( - + )}
diff --git a/web-client/src/views/Practitioners/PractitionerContactForm.tsx b/web-client/src/views/Practitioners/PractitionerContactForm.tsx index fdca63306f1..f3eab1c22cf 100644 --- a/web-client/src/views/Practitioners/PractitionerContactForm.tsx +++ b/web-client/src/views/Practitioners/PractitionerContactForm.tsx @@ -68,7 +68,7 @@ export const PractitionerContactForm = connect( data-testid="practitioner-phone-input" id="phone" name="contact.phone" - type="tel" + type="text" value={form.contact.phone || ''} onBlur={() => { onBlurValidationSequence(); @@ -94,7 +94,7 @@ export const PractitionerContactForm = connect( className="usa-input" id="additional-phone" name="additionalPhone" - type="tel" + type="text" value={form.additionalPhone || ''} onChange={e => { onChangeUpdateSequence({ diff --git a/web-client/src/views/StartCase/ContactPrimary.tsx b/web-client/src/views/StartCase/ContactPrimary.tsx index cc3ea99473e..16b80966a18 100644 --- a/web-client/src/views/StartCase/ContactPrimary.tsx +++ b/web-client/src/views/StartCase/ContactPrimary.tsx @@ -251,7 +251,7 @@ export const ContactPrimary = connect( data-testid="phone" id="phone" name="contactPrimary.phone" - type="tel" + type="text" value={data.contactPrimary.phone || ''} onBlur={() => { onBlurSequence(); diff --git a/web-client/src/views/StartCase/ContactPrimaryUpdated.tsx b/web-client/src/views/StartCase/ContactPrimaryUpdated.tsx index a160aa37035..953f5ccfa02 100644 --- a/web-client/src/views/StartCase/ContactPrimaryUpdated.tsx +++ b/web-client/src/views/StartCase/ContactPrimaryUpdated.tsx @@ -249,7 +249,7 @@ export const ContactPrimaryUpdated = connect< id="primary-phone" name="contactPrimary.phone" ref={registerRef && registerRef('contactPrimary.phone')} - type="tel" + type="text" value={addressInfo.phone || ''} onBlur={() => { handleBlur({ diff --git a/web-client/src/views/StartCase/ContactSecondary.tsx b/web-client/src/views/StartCase/ContactSecondary.tsx index f461130fe92..560eaa58a42 100644 --- a/web-client/src/views/StartCase/ContactSecondary.tsx +++ b/web-client/src/views/StartCase/ContactSecondary.tsx @@ -201,7 +201,7 @@ export const ContactSecondary = connect( data-testid="contact-secondary-phone-input" id="secondaryPhone" name="contactSecondary.phone" - type="tel" + type="text" value={data.contactSecondary.phone || ''} onBlur={() => { onBlurSequence(); diff --git a/web-client/src/views/StartCase/ContactSecondaryUpdated.tsx b/web-client/src/views/StartCase/ContactSecondaryUpdated.tsx index 3e43229c2a9..30296d66116 100644 --- a/web-client/src/views/StartCase/ContactSecondaryUpdated.tsx +++ b/web-client/src/views/StartCase/ContactSecondaryUpdated.tsx @@ -169,7 +169,7 @@ export const ContactSecondaryUpdated = connect< id="secondary-phone" name="contactSecondary.phone" ref={registerRef && registerRef('contactSecondary.phone')} - type="tel" + type="text" value={addressInfo.phone || ''} onBlur={() => { handleBlur({ diff --git a/web-client/src/views/StartCase/StartCaseWizard.tsx b/web-client/src/views/StartCase/StartCaseWizard.tsx index 6b25fe0e632..a1a5a9061d0 100644 --- a/web-client/src/views/StartCase/StartCaseWizard.tsx +++ b/web-client/src/views/StartCase/StartCaseWizard.tsx @@ -17,6 +17,8 @@ import React from 'react'; export const StartCaseWizard = connect( { + closeModalAndReturnToDashboardSequence: + sequences.closeModalAndReturnToDashboardSequence, showModal: state.modal.showModal, submitFilePetitionSequence: sequences.submitFilePetitionSequence, }, @@ -52,7 +54,7 @@ export const StartCaseWizard = connect( {showModal == 'FormCancelModalDialog' && ( )} {showModal === 'FileUploadStatusModal' && } diff --git a/web-client/src/views/StartCaseInternal/StartCaseInternal.tsx b/web-client/src/views/StartCaseInternal/StartCaseInternal.tsx index 7bffdf2b4dc..8038dd93aca 100644 --- a/web-client/src/views/StartCaseInternal/StartCaseInternal.tsx +++ b/web-client/src/views/StartCaseInternal/StartCaseInternal.tsx @@ -16,6 +16,8 @@ import React from 'react'; export const StartCaseInternal = connect( { + closeModalAndReturnToDashboardSequence: + sequences.closeModalAndReturnToDashboardSequence, documentSelectedForScan: state.currentViewMetadata.documentSelectedForScan, formCancelToggleCancelSequence: sequences.formCancelToggleCancelSequence, showModal: state.modal.showModal, @@ -25,6 +27,7 @@ export const StartCaseInternal = connect( sequences.validatePetitionFromPaperSequence, }, function StartCaseInternal({ + closeModalAndReturnToDashboardSequence, documentSelectedForScan, formCancelToggleCancelSequence, showModal, @@ -38,7 +41,9 @@ export const StartCaseInternal = connect(
{showModal === 'FormCancelModalDialog' && ( - + )}
diff --git a/web-client/src/views/StartCaseUpdated/UpdatedFilePetition.tsx b/web-client/src/views/StartCaseUpdated/UpdatedFilePetition.tsx index 3f9f3fea62c..43df3c15050 100644 --- a/web-client/src/views/StartCaseUpdated/UpdatedFilePetition.tsx +++ b/web-client/src/views/StartCaseUpdated/UpdatedFilePetition.tsx @@ -10,15 +10,21 @@ import { UpdatedFilePetitionStep5 } from '@web-client/views/StartCaseUpdated/Upd import { UpdatedFilePetitionStep6 } from '@web-client/views/StartCaseUpdated/UpdatedFilePetitionStep6'; import { UpdatedFilePetitionStep7 } from '@web-client/views/StartCaseUpdated/UpdatedFilePetitionStep7'; import { connect } from '@web-client/presenter/shared.cerebral'; -import { state } from '@web-client/presenter/app.cerebral'; +import { sequences, state } from '@web-client/presenter/app.cerebral'; import React from 'react'; export const UpdatedFilePetition = connect( { + closeModalAndReturnToDashboardSequence: + sequences.closeModalAndReturnToDashboardSequence, showModal: state.modal.showModal, stepIndicatorInfo: state.stepIndicatorInfo, }, - function UpdatedFilePetition({ showModal, stepIndicatorInfo }) { + function UpdatedFilePetition({ + closeModalAndReturnToDashboardSequence, + showModal, + stepIndicatorInfo, + }) { const { currentStep } = stepIndicatorInfo; return ( <> @@ -38,7 +44,9 @@ export const UpdatedFilePetition = connect( {currentStep === 7 && }
{showModal == 'FormCancelModalDialog' && ( - + )} ); diff --git a/web-client/src/views/StyleGuide/Forms.tsx b/web-client/src/views/StyleGuide/Forms.tsx index c28ae910eda..4aee0435b93 100644 --- a/web-client/src/views/StyleGuide/Forms.tsx +++ b/web-client/src/views/StyleGuide/Forms.tsx @@ -85,7 +85,7 @@ export const Forms = () => ( @@ -96,7 +96,7 @@ export const Forms = () => ( Error message diff --git a/web-client/src/views/TrialSessions/AddTrialSession.tsx b/web-client/src/views/TrialSessions/AddTrialSession.tsx index aed927fe95e..99b5f1973e3 100644 --- a/web-client/src/views/TrialSessions/AddTrialSession.tsx +++ b/web-client/src/views/TrialSessions/AddTrialSession.tsx @@ -12,6 +12,8 @@ import React from 'react'; export const AddTrialSession = connect( { + closeModalAndReturnToTrialSessionsSequence: + sequences.closeModalAndReturnToTrialSessionsSequence, form: state.form, formCancelToggleCancelSequence: sequences.formCancelToggleCancelSequence, showModal: state.modal.showModal, @@ -20,6 +22,7 @@ export const AddTrialSession = connect( sequences.updateTrialSessionFormDataSequence, }, function AddTrialSession({ + closeModalAndReturnToTrialSessionsSequence, form, formCancelToggleCancelSequence, showModal, @@ -38,7 +41,9 @@ export const AddTrialSession = connect( role="form" > {showModal === 'FormCancelModalDialog' && ( - + )} diff --git a/web-client/src/views/TrialSessions/EditTrialSession.tsx b/web-client/src/views/TrialSessions/EditTrialSession.tsx index 28c5eee0993..317e7647c8a 100644 --- a/web-client/src/views/TrialSessions/EditTrialSession.tsx +++ b/web-client/src/views/TrialSessions/EditTrialSession.tsx @@ -12,6 +12,8 @@ import React from 'react'; export const EditTrialSession = connect( { + closeModalAndNavigateBackSequence: + sequences.closeModalAndNavigateBackSequence, form: state.form, formCancelToggleCancelSequence: sequences.formCancelToggleCancelSequence, showModal: state.modal.showModal, @@ -20,6 +22,7 @@ export const EditTrialSession = connect( updateTrialSessionSequence: sequences.updateTrialSessionSequence, }, function EditTrialSession({ + closeModalAndNavigateBackSequence, form, formCancelToggleCancelSequence, showModal, @@ -40,7 +43,9 @@ export const EditTrialSession = connect( role="form" > {showModal === 'FormCancelModalDialog' && ( - + )} @@ -48,7 +53,7 @@ export const EditTrialSession = connect( All fields required unless otherwise noted

- + diff --git a/web-client/src/views/TrialSessions/SessionInformationForm.tsx b/web-client/src/views/TrialSessions/SessionInformationForm.tsx index 73ace76ccab..7e529d4dcc5 100644 --- a/web-client/src/views/TrialSessions/SessionInformationForm.tsx +++ b/web-client/src/views/TrialSessions/SessionInformationForm.tsx @@ -6,20 +6,28 @@ import { state } from '@web-client/presenter/app.cerebral'; import React from 'react'; import classNames from 'classnames'; -export const SessionInformationForm = connect( - { - DATE_FORMATS: state.constants.DATE_FORMATS, - TRIAL_SESSION_SCOPE_TYPES: state.constants.TRIAL_SESSION_SCOPE_TYPES, - addTrialSessionInformationHelper: state.addTrialSessionInformationHelper, - form: state.form, - formatAndUpdateDateFromDatePickerSequence: - sequences.formatAndUpdateDateFromDatePickerSequence, - formattedTrialSessions: state.formattedTrialSessions, - updateTrialSessionFormDataSequence: - sequences.updateTrialSessionFormDataSequence, - validateTrialSessionSequence: sequences.validateTrialSessionSequence, - validationErrors: state.validationErrors, - }, +type SessionInformationFormProps = { addingTrialSession: boolean }; + +const sessionInformationDeps = { + DATE_FORMATS: state.constants.DATE_FORMATS, + TRIAL_SESSION_SCOPE_TYPES: state.constants.TRIAL_SESSION_SCOPE_TYPES, + addTrialSessionInformationHelper: state.addTrialSessionInformationHelper, + form: state.form, + formatAndUpdateDateFromDatePickerSequence: + sequences.formatAndUpdateDateFromDatePickerSequence, + formattedTrialSessions: state.formattedTrialSessions, + updateTrialSessionFormDataSequence: + sequences.updateTrialSessionFormDataSequence, + user: state.user, + validateTrialSessionSequence: sequences.validateTrialSessionSequence, + validationErrors: state.validationErrors, +}; + +export const SessionInformationForm = connect< + SessionInformationFormProps, + typeof sessionInformationDeps +>( + sessionInformationDeps, function SessionInformationForm({ addingTrialSession, addTrialSessionInformationHelper, diff --git a/web-client/src/views/UploadCourtIssuedDocument/UploadCourtIssuedDocument.tsx b/web-client/src/views/UploadCourtIssuedDocument/UploadCourtIssuedDocument.tsx index 84dcb6ea41c..2c0e196c15d 100644 --- a/web-client/src/views/UploadCourtIssuedDocument/UploadCourtIssuedDocument.tsx +++ b/web-client/src/views/UploadCourtIssuedDocument/UploadCourtIssuedDocument.tsx @@ -13,6 +13,8 @@ import classNames from 'classnames'; export const UploadCourtIssuedDocument = connect( { + closeModalAndReturnToCaseDetailSequence: + sequences.closeModalAndReturnToCaseDetailSequence, constants: state.constants, fileDocumentHelper: state.fileDocumentHelper, form: state.form, @@ -26,6 +28,7 @@ export const UploadCourtIssuedDocument = connect( validationErrors: state.validationErrors, }, function UploadCourtIssuedDocument({ + closeModalAndReturnToCaseDetailSequence, constants, fileDocumentHelper, form, @@ -40,7 +43,9 @@ export const UploadCourtIssuedDocument = connect( <> {showModal === 'FormCancelModalDialog' && ( - + )}
diff --git a/web-client/src/views/UserContactEditForm.tsx b/web-client/src/views/UserContactEditForm.tsx index a59cd5fe9c0..3caebda5438 100644 --- a/web-client/src/views/UserContactEditForm.tsx +++ b/web-client/src/views/UserContactEditForm.tsx @@ -62,7 +62,7 @@ export const UserContactEditForm = connect( data-testid="phone-number-input" id="phone" name="contact.phone" - type="tel" + type="text" value={form.contact.phone || ''} onBlur={() => { validateUserContactSequence();