-
Notifications
You must be signed in to change notification settings - Fork 1
PRMP-587 Get document review by id #862
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import json | ||
|
|
||
| from enums.feature_flags import FeatureFlags | ||
| from enums.lambda_error import LambdaError | ||
| from enums.logging_app_interaction import LoggingAppInteraction | ||
| from services.feature_flags_service import FeatureFlagService | ||
| from services.get_document_review_service import GetDocumentReviewService | ||
| from utils.audit_logging_setup import LoggingService | ||
| from utils.decorators.ensure_env_var import ensure_environment_variables | ||
| from utils.decorators.handle_lambda_exceptions import handle_lambda_exceptions | ||
| from utils.decorators.override_error_check import override_error_check | ||
| from utils.decorators.set_audit_arg import set_request_context_for_logging | ||
| from utils.decorators.validate_patient_id import validate_patient_id | ||
| from utils.lambda_exceptions import GetDocumentReviewException | ||
| from utils.lambda_response import ApiGatewayResponse | ||
| from utils.request_context import request_context | ||
|
|
||
| logger = LoggingService(__name__) | ||
|
|
||
|
|
||
| @set_request_context_for_logging | ||
| @validate_patient_id | ||
| @ensure_environment_variables( | ||
| names=[ | ||
| "DOCUMENT_REVIEW_DYNAMODB_NAME", | ||
| "PRESIGNED_ASSUME_ROLE", | ||
| "EDGE_REFERENCE_TABLE", | ||
| "CLOUDFRONT_URL", | ||
| ] | ||
| ) | ||
| @override_error_check | ||
| @handle_lambda_exceptions | ||
| def lambda_handler(event, context): | ||
| request_context.app_interaction = LoggingAppInteraction.GET_REVIEW_DOCUMENTS.value | ||
|
|
||
| logger.info("Get Document Review handler has been triggered") | ||
| feature_flag_service = FeatureFlagService() | ||
| upload_lambda_enabled_flag_object = feature_flag_service.get_feature_flags_by_flag( | ||
steph-torres-nhs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| FeatureFlags.UPLOAD_DOCUMENT_ITERATION_3_ENABLED | ||
| ) | ||
|
|
||
| if not upload_lambda_enabled_flag_object[FeatureFlags.UPLOAD_DOCUMENT_ITERATION_3_ENABLED]: | ||
| logger.info("Feature flag not enabled, event will not be processed") | ||
| raise GetDocumentReviewException(404, LambdaError.FeatureFlagDisabled) | ||
|
|
||
| # Extract patient_id from query string parameters | ||
| query_params = event.get("queryStringParameters", {}) | ||
| patient_id = query_params.get("patientId", "") | ||
|
|
||
| if not patient_id: | ||
| logger.error("Missing patient_id in query string parameters") | ||
| raise GetDocumentReviewException( | ||
| 400, LambdaError.DocumentReferenceMissingParameters | ||
| ) | ||
|
|
||
| # Extract id from path parameters | ||
| path_params = event.get("pathParameters", {}) | ||
| document_id = path_params.get("id") | ||
|
|
||
| if not document_id: | ||
| logger.error("Missing id in path parameters") | ||
| raise GetDocumentReviewException( | ||
| 400, LambdaError.DocumentReferenceMissingParameters | ||
| ) | ||
|
|
||
| request_context.patient_nhs_no = patient_id | ||
|
|
||
| logger.info( | ||
| f"Retrieving document review for patient_id: {patient_id}, document_id: {document_id}" | ||
| ) | ||
|
|
||
| # Get document review service | ||
| document_review_service = GetDocumentReviewService() | ||
| document_review = document_review_service.get_document_review( | ||
| patient_id=patient_id, document_id=document_id | ||
| ) | ||
|
|
||
| if document_review: | ||
| logger.info( | ||
| "Document review retrieved successfully", | ||
| {"Result": "Successful document review retrieval"}, | ||
| ) | ||
| return ApiGatewayResponse( | ||
| 200, json.dumps(document_review), "GET" | ||
| ).create_api_gateway_response() | ||
| else: | ||
| logger.error( | ||
| "Document review not found", | ||
| {"Result": "No document review available"}, | ||
| ) | ||
| return ApiGatewayResponse( | ||
| 404, | ||
| LambdaError.DocumentReferenceNotFound.create_error_body(), | ||
| "GET", | ||
| ).create_api_gateway_response() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| import os | ||
| import uuid | ||
| from datetime import datetime, timezone | ||
| from typing import Optional | ||
|
|
||
| from enums.lambda_error import LambdaError | ||
| from services.base.s3_service import S3Service | ||
| from services.document_upload_review_service import DocumentUploadReviewService | ||
| from utils.audit_logging_setup import LoggingService | ||
| from utils.exceptions import DynamoServiceException | ||
| from utils.lambda_exceptions import GetDocumentReviewException | ||
| from utils.utilities import format_cloudfront_url | ||
|
|
||
| logger = LoggingService(__name__) | ||
|
|
||
|
|
||
| class GetDocumentReviewService: | ||
| """ | ||
| Service for retrieving document reviews. | ||
| """ | ||
|
|
||
| def __init__(self): | ||
| presigned_assume_role = os.getenv("PRESIGNED_ASSUME_ROLE") | ||
| self.s3_service = S3Service(custom_aws_role=presigned_assume_role) | ||
| self.document_review_service = DocumentUploadReviewService() | ||
| self.cloudfront_table_name = os.environ.get("EDGE_REFERENCE_TABLE") | ||
| self.cloudfront_url = os.environ.get("CLOUDFRONT_URL") | ||
|
|
||
| def get_document_review(self, patient_id: str, document_id: str) -> Optional[dict]: | ||
| """Retrieve a document review for a given patient and document. | ||
|
|
||
| Args: | ||
| patient_id: The patient ID (NHS number). | ||
| document_id: The document ID to retrieve. | ||
|
|
||
| Returns: | ||
| Dictionary containing the document review details, or None if not found. | ||
| """ | ||
| try: | ||
| logger.info( | ||
| f"Fetching document review for patient_id: {patient_id}, document_id: {document_id}" | ||
| ) | ||
|
|
||
| document_review_item = self.document_review_service.get_item(document_id) | ||
|
|
||
| if not document_review_item: | ||
| logger.info(f"No document review found for document_id: {document_id}") | ||
| return None | ||
|
|
||
| if document_review_item.nhs_number != patient_id: | ||
| logger.warning( | ||
| f"Document {document_id} does not belong to patient {patient_id}" | ||
| ) | ||
| return None | ||
|
|
||
| if document_review_item.files: | ||
| for file_detail in document_review_item.files: | ||
| presigned_url = self.create_cloudfront_presigned_url( | ||
| file_detail.file_location | ||
| ) | ||
| file_detail.presigned_url = presigned_url | ||
|
|
||
| document_review = document_review_item.model_dump( | ||
| by_alias=True, | ||
| include={ | ||
| "id": True, | ||
| "upload_date": True, | ||
| "files": {"__all__": {"file_name": True, "presigned_url": True}}, | ||
| "document_snomed_code_type": True, | ||
| }, | ||
| ) | ||
|
|
||
| logger.info( | ||
| f"Successfully retrieved document review for document_id: {document_id}" | ||
| ) | ||
|
|
||
| return document_review | ||
|
|
||
| except DynamoServiceException as e: | ||
| logger.error( | ||
| f"{LambdaError.DocRefClient.to_str()}: {str(e)}", | ||
| {"Result": "Failed to retrieve document review"}, | ||
| ) | ||
| raise GetDocumentReviewException(500, LambdaError.DocRefClient) | ||
| except Exception as e: | ||
| logger.error( | ||
| f"Unexpected error retrieving document review: {str(e)}", | ||
| {"Result": "Failed to retrieve document review"}, | ||
| ) | ||
| raise GetDocumentReviewException(500, LambdaError.DocRefClient) | ||
|
|
||
| def create_cloudfront_presigned_url(self, file_location: str) -> str: | ||
| """Create a CloudFront obfuscated pre-signed URL for a file. | ||
|
|
||
| Args: | ||
| file_location: The S3 file key/location. | ||
|
|
||
| Returns: | ||
| CloudFront URL that obfuscates the actual pre-signed URL. | ||
| """ | ||
| s3_bucket_name, file_key = file_location.removeprefix("s3://").split("/", 1) | ||
| presign_url_response = self.s3_service.create_download_presigned_url( | ||
| s3_bucket_name=s3_bucket_name, | ||
| file_key=file_key, | ||
| ) | ||
|
|
||
| presigned_id = "review/" + str(uuid.uuid4()) | ||
|
|
||
| deletion_date = datetime.now(timezone.utc) | ||
| ttl_half_an_hour_in_seconds = self.s3_service.presigned_url_expiry | ||
| dynamo_item_ttl = int(deletion_date.timestamp() + ttl_half_an_hour_in_seconds) | ||
|
|
||
| self.document_review_service.dynamo_service.create_item( | ||
| self.cloudfront_table_name, | ||
| { | ||
| "ID": f"{presigned_id}", | ||
| "presignedUrl": presign_url_response, | ||
| "TTL": dynamo_item_ttl, | ||
| }, | ||
| ) | ||
|
|
||
| return format_cloudfront_url(presigned_id, self.cloudfront_url) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.