Skip to content

Commit

Permalink
Merge branch 'main' into PRMDR-316
Browse files Browse the repository at this point in the history
  • Loading branch information
carlsmith101 committed Nov 2, 2023
2 parents 6e10afc + c0fee42 commit 0b9b654
Show file tree
Hide file tree
Showing 20 changed files with 495 additions and 197 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ import { LG_RECORD_STAGE } from '../../../pages/lloydGeorgeRecordPage/LloydGeorg
import { DOCUMENT_TYPE } from '../../../types/pages/UploadDocumentsPage/types';
import axios from 'axios/index';
import { USER_ROLE } from '../../../types/generic/roles';
import { BrowserRouter } from 'react-router-dom';
import * as ReactRouter from 'react-router';
import { createMemoryHistory } from 'history';
import { routes } from '../../../types/generic/routes';

jest.mock('axios');

Expand Down Expand Up @@ -42,7 +44,7 @@ describe('DeleteAllDocumentsStage', () => {

await waitFor(async () => {
expect(
screen.getByText('Are you sure you want to permanently delete files for:'),
screen.getByText('Are you sure you want to permanently delete files for:')
).toBeInTheDocument();
});

Expand Down Expand Up @@ -95,7 +97,7 @@ describe('DeleteAllDocumentsStage', () => {

await waitFor(async () => {
expect(
screen.getByText('Are you sure you want to permanently delete files for:'),
screen.getByText('Are you sure you want to permanently delete files for:')
).toBeInTheDocument();
});

Expand Down Expand Up @@ -137,11 +139,70 @@ describe('DeleteAllDocumentsStage', () => {
expect(screen.getByText('Deletion complete')).toBeInTheDocument();
});
});

it('renders a service error when service is down', async () => {
const errorResponse = {
response: {
status: 500,
message: 'Client Error.',
},
};
mockedAxios.delete.mockImplementation(() => Promise.reject(errorResponse));

renderComponent(USER_ROLE.PCSE, DOCUMENT_TYPE.ALL);

expect(screen.getByRole('radio', { name: 'Yes' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Continue' })).toBeInTheDocument();

act(() => {
userEvent.click(screen.getByRole('radio', { name: 'Yes' }));
userEvent.click(screen.getByRole('button', { name: 'Continue' }));
});

await waitFor(() => {
expect(
screen.getByText('Sorry, the service is currently unavailable.')
).toBeInTheDocument();
});
});
});

describe('Navigation', () => {
it('navigates to home page when API call returns 403', async () => {
const history = createMemoryHistory({
initialEntries: ['/example'],
initialIndex: 1,
});

const errorResponse = {
response: {
status: 403,
message: 'Forbidden',
},
};
mockedAxios.delete.mockImplementation(() => Promise.reject(errorResponse));

renderComponent(USER_ROLE.PCSE, DOCUMENT_TYPE.ALL, history);

expect(history.location.pathname).toBe('/example');

expect(screen.getByRole('radio', { name: 'Yes' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Continue' })).toBeInTheDocument();

act(() => {
userEvent.click(screen.getByRole('radio', { name: 'Yes' }));
userEvent.click(screen.getByRole('button', { name: 'Continue' }));
});

await waitFor(() => {
expect(history.location.pathname).toBe(routes.HOME);
});
});
});
});

const TestApp = (
props: Omit<Props, 'setStage' | 'setIsDeletingDocuments' | 'setDownloadStage'>,
props: Omit<Props, 'setStage' | 'setIsDeletingDocuments' | 'setDownloadStage'>
) => {
return (
<DeleteDocumentsStage
Expand All @@ -153,7 +214,15 @@ const TestApp = (
);
};

const renderComponent = (userType: USER_ROLE, docType: DOCUMENT_TYPE) => {
const homeRoute = '/example';
const renderComponent = (
userType: USER_ROLE,
docType: DOCUMENT_TYPE,
history = createMemoryHistory({
initialEntries: [homeRoute],
initialIndex: 1,
})
) => {
const auth: Session = {
auth: buildUserAuth(),
isLoggedIn: true,
Expand All @@ -167,10 +236,10 @@ const renderComponent = (userType: USER_ROLE, docType: DOCUMENT_TYPE) => {
};

render(
<BrowserRouter>
<ReactRouter.Router navigator={history} location={homeRoute}>
<SessionProvider sessionOverride={auth}>
<TestApp {...props} />
</SessionProvider>
</BrowserRouter>,
</ReactRouter.Router>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import ServiceError from '../../layout/serviceErrorBox/ServiceErrorBox';
import { SUBMISSION_STATE } from '../../../types/pages/documentSearchResultsPage/types';
import { USER_ROLE } from '../../../types/generic/roles';
import { formatNhsNumber } from '../../../helpers/utils/formatNhsNumber';
import { AxiosError } from 'axios';
import { routes } from '../../../types/generic/routes';
import { useNavigate } from 'react-router-dom';

export type Props = {
docType: DOCUMENT_TYPE;
Expand Down Expand Up @@ -45,6 +48,7 @@ function DeleteDocumentsStage({
const [deletionStage, setDeletionStage] = useState(SUBMISSION_STATE.INITIAL);
const baseUrl = useBaseAPIUrl();
const baseHeaders = useBaseAPIHeaders();
const navigate = useNavigate();

const nhsNumber: string = patientDetails?.nhsNumber || '';
const formattedNhsNumber = formatNhsNumber(nhsNumber);
Expand All @@ -64,39 +68,29 @@ function DeleteDocumentsStage({
</>
);

const deleteDocumentsFor = (type: DOCUMENT_TYPE) =>
deleteAllDocuments({
docType: type,
nhsNumber: nhsNumber,
baseUrl,
baseHeaders,
});

const handleYesOption = async () => {
setDeletionStage(SUBMISSION_STATE.PENDING);
let documentPromises: Array<Promise<DeleteResponse>> = [];

if (docType === DOCUMENT_TYPE.LLOYD_GEORGE) {
documentPromises = [deleteDocumentsFor(DOCUMENT_TYPE.LLOYD_GEORGE)];
} else if (docType === DOCUMENT_TYPE.ALL) {
documentPromises = [
deleteDocumentsFor(DOCUMENT_TYPE.LLOYD_GEORGE),
deleteDocumentsFor(DOCUMENT_TYPE.ARF),
];
}
try {
Promise.all(documentPromises).then((responses) => {
const hasSucceeded = !responses.some((res) => res.status === 403);
const response: DeleteResponse = await deleteAllDocuments({
docType: docType,
nhsNumber: nhsNumber,
baseUrl,
baseHeaders,
});

if (hasSucceeded) {
setDeletionStage(SUBMISSION_STATE.SUCCEEDED);
if (response.status === 200) {
setDeletionStage(SUBMISSION_STATE.SUCCEEDED);

if (setDownloadStage) {
setDownloadStage(DOWNLOAD_STAGE.FAILED);
}
if (setDownloadStage) {
setDownloadStage(DOWNLOAD_STAGE.FAILED);
}
});
}
} catch (e) {
const error = e as AxiosError;
if (error.response?.status === 403) {
navigate(routes.HOME);
}
setDeletionStage(SUBMISSION_STATE.FAILED);
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ describe('LloydGeorgeRecordDetails', () => {
const actionLinkStrings = [
{ label: 'See all files', expectedStage: LG_RECORD_STAGE.SEE_ALL },
{ label: 'Download all files', expectedStage: LG_RECORD_STAGE.DOWNLOAD_ALL },
{ label: 'Delete a selection of files', expectedStage: LG_RECORD_STAGE.DELETE_ANY },
{ label: 'Delete all files', expectedStage: LG_RECORD_STAGE.DELETE_ALL },
{ label: 'Delete file', expectedStage: LG_RECORD_STAGE.DELETE_ONE },
];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@ function LloydGeorgeRecordDetails({
handler: () => setStage(LG_RECORD_STAGE.DOWNLOAD_ALL),
},
{
label: 'Delete a selection of files',
key: 'delete-any-files-link',
handler: () => setStage(LG_RECORD_STAGE.DELETE_ANY),
label: 'Delete all files',
key: 'delete-all-files-link',
handler: () => setStage(LG_RECORD_STAGE.DELETE_ALL),
},
{
label: 'Delete file',
Expand Down
4 changes: 2 additions & 2 deletions app/src/pages/lloydGeorgeRecordPage/LloydGeorgeRecordPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export enum LG_RECORD_STAGE {
RECORD = 0,
DOWNLOAD_ALL = 1,
SEE_ALL = 2,
DELETE_ANY = 3,
DELETE_ALL = 3,
DELETE_ONE = 4,
}
function LloydGeorgeRecordPage() {
Expand Down Expand Up @@ -97,7 +97,7 @@ function LloydGeorgeRecordPage() {
/>
)
);
case LG_RECORD_STAGE.DELETE_ANY:
case LG_RECORD_STAGE.DELETE_ALL:
return (
patientDetails && (
<DeleteDocumentsStage
Expand Down
21 changes: 9 additions & 12 deletions lambdas/enums/supported_document_types.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
from enum import Enum
from typing import List


class SupportedDocumentTypes(Enum):
ARF = "ARF", "#arf"
LG = "LG", "#lg"

def __init__(self, field_name, field_alias):
self.field_name = field_name
self.field_alias = field_alias
ARF = "ARF"
LG = "LG"
ALL = "ALL"

@staticmethod
def list():
return [SupportedDocumentTypes.ARF, SupportedDocumentTypes.LG]

@staticmethod
def list_names():
return [SupportedDocumentTypes.ARF.name, SupportedDocumentTypes.LG.name]
def list_names() -> List[str]:
return [str(doc_type.value) for doc_type in SupportedDocumentTypes.list()]

@staticmethod
def get_from_field_name(enum_value):
for supported_document_type in SupportedDocumentTypes.list():
if supported_document_type.name == enum_value:
return supported_document_type
def get_from_field_name(value: str):
if value in SupportedDocumentTypes.list_names():
return value
return None
3 changes: 1 addition & 2 deletions lambdas/handlers/bulk_upload_report_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

from boto3.dynamodb.conditions import Attr
from botocore.exceptions import ClientError

from services.dynamo_service import DynamoDBService
from services.s3_service import S3Service
from utils.decorators.ensure_env_var import ensure_environment_variables
Expand Down Expand Up @@ -62,7 +61,7 @@ def get_dynamodb_report_items(
bulk_upload_table_name, filter_expression=filter_time
)

if not "Items" in db_response:
if "Items" not in db_response:
return None
items = db_response["Items"]
while "LastEvaluatedKey" in db_response:
Expand Down
4 changes: 2 additions & 2 deletions lambdas/handlers/create_document_reference_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def lambda_handler(event, context):

document_reference: NHSDocumentReference

if document_type == SupportedDocumentTypes.LG:
if document_type == SupportedDocumentTypes.LG.value:
document_reference = NHSDocumentReference(
nhs_number=nhs_number,
s3_bucket_name=lg_s3_bucket_name,
Expand All @@ -106,7 +106,7 @@ def lambda_handler(event, context):
file_name=document.fileName,
)
lg_documents.append(document_reference)
elif document_type == SupportedDocumentTypes.ARF:
elif document_type == SupportedDocumentTypes.ARF.value:
document_reference = NHSDocumentReference(
nhs_number=nhs_number,
s3_bucket_name=arf_s3_bucket_name,
Expand Down
Loading

0 comments on commit 0b9b654

Please sign in to comment.