Skip to content

Commit

Permalink
wip for images almost there
Browse files Browse the repository at this point in the history
  • Loading branch information
SeriousHorncat committed Dec 18, 2023
1 parent af466ea commit c5d2cc6
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 42 deletions.
28 changes: 15 additions & 13 deletions backend/src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class Settings(BaseSettings):
web_base_url: str = "http://dev.cgds.uab.edu/rosalution"
mongodb_host: str = "rosalution-db"
mongodb_db: str = "rosalution_db"
rosalution_key: str
rosalution_key: str = "FJKLDFJKLSJFKLDFJKLJFKLJKLJKLFDFDS"
auth_web_failure_redirect_route: str = "/login"
oauth2_access_token_expire_minutes: int = 60 * 24 * 8 # 60 minutes * 24 hours * 8 days = 8 days
oauth2_algorithm: str = "HS256"
Expand All @@ -27,18 +27,20 @@ class Settings(BaseSettings):
cas_server_url: str = "https://padlockdev.idm.uab.edu/cas/"
cas_login_enable: bool = False

@model_validator(mode="before")
@classmethod
def rosalution_key_exists(cls, values):
"""
Verifies that the ROSALUTION_KEY environment is set and provides a more descriptive error message.
This needed to be done as a pydantic root validator to execute this before pydantics validation of
individual fields since it would fail due to the missing value.
"""
key = values.get('rosalution_key')
if not key:
raise ValueError('Environment variable "ROSALUTION_KEY" missing. App requires secret for secure encoding.')
return values
# @model_validator(mode="before")
# @classmethod
# def rosalution_key_exists(cls, values):
# """
# Verifies that the ROSALUTION_KEY environment is set and provides a more descriptive error message.
# This needed to be done as a pydantic root validator to execute this before pydantics validation of
# individual fields since it would fail due to the missing value.
# """
# print("IT SHOULD BE HERE")
# print(values)
# key = values.get('rosalution_key')
# if not key:
# raise ValueError('Environment variable "ROSALUTION_KEY" missing. App requires secret for secure encoding.')
# return values


@lru_cache()
Expand Down
8 changes: 2 additions & 6 deletions backend/src/repository/analysis_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,12 +259,8 @@ def add_section_image(self, analysis_name: str, section_name: str, field_name: s
if content_row["field"] and content_row["field"] == field_name:
content_row["value"].append({'file_id': str(file_id)})

self.collection.find_one_and_update(
{"name": analysis_name},
{'$set': updated_document},
)

return updated_section
return self.collection.find_one_and_update({"name": analysis_name}, {'$set': updated_document},
return_document=ReturnDocument.AFTER)

def update_section_image(
self, analysis_name: str, section_name: str, field_name: str, file_id: str, file_id_old: str
Expand Down
38 changes: 32 additions & 6 deletions backend/src/routers/analysis_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ def update_analysis_sections(
analysis_name: str,
row_type: SectionRowType,
updated_sections: List[Section],
upload_file: UploadFile = File(None),
repositories=Depends(database),
authorized=Security(get_authorization, scopes=["write"]) #pylint: disable=unused-argument
):
Expand All @@ -122,20 +123,40 @@ def update_analysis_sections(
updated_analysis_model = Analysis(**updated_analysis)
return updated_analysis_model.sections

updated_analysis = None
section = updated_sections[0]

if row_type not in (SectionRowType.IMAGE, SectionRowType.DOCUMENT, SectionRowType.LINK):
raise HTTPException(status_code=422, detail=f"'Unsupported 'row_type': {row_type}.")

if row_type in (SectionRowType.IMAGE, SectionRowType.DOCUMENT):
print("Will be adding image or document")

try:
new_file_object_id = add_file_to_bucket_repository(upload_file, repositories["bucket"])
except Exception as exception:
raise HTTPException(status_code=500, detail=str(exception)) from exception

# # TODO - Is this only used for document adding and not image adding?
# field_value_file = {
# "name": upload_file.filename,
# "attachment_id": str(new_file_object_id),
# "type": "file",
# "comments": "" #removed the comments attribute?
# }

if row_type == SectionRowType.DOCUMENT:
print("Will be adding document")

if row_type == SectionRowType.IMAGE:
print("Will be adding image")
updated_analysis = repositories["analysis"].add_section_image(
analysis_name, section.header, section["fieldName"], new_file_object_id
)

if row_type == SectionRowType.LINK:
print("will be adding link")
if row_type in (SectionRowType.LINK):
print("Will be adding link")

print("ADDING TYPE NOT SUPPORTED YET, IN PROGRESS")
return []
updated_analysis_model = Analysis(**updated_analysis)
return updated_analysis_model.sections


def update_analysis_sections_text_fields(analysis_name, updated_sections: List[Section], analysis_repository):
Expand All @@ -149,6 +170,11 @@ def update_analysis_sections_text_fields(analysis_name, updated_sections: List[S
analysis_name, section.header, field_name, {"value": field_value}
)

def add_file_to_bucket_repository(file_to_save, bucket_repository):
"""Saves the 'file_to_save' within the bucket repository and returns the files new uuid."""
return bucket_repository.save_file(
file_to_save.file, file_to_save.filename, file_to_save.content_type
)

@router.put("/{analysis_name}/section/attach/file")
def attach_animal_model_system_report(
Expand Down
19 changes: 9 additions & 10 deletions backend/tests/unit/repository/test_analysis_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,24 +187,23 @@ def test_add_image_to_pedigree_section(analysis_collection, empty_pedigree):
expected = read_test_fixture("analysis-CPAM0002.json")

analysis_collection.add_section_image("CPAM0002", "Pedigree", "Pedigree", "63505be22888347cf1c275db")
analysis_collection.collection.find_one_and_update.assert_called_with({"name": "CPAM0002"}, {"$set": expected})
analysis_collection.collection.find_one_and_update.assert_called_with({"name": "CPAM0002"}, {"$set": expected}, return_document=ReturnDocument.AFTER)


def test_add_an_additional_image_to_pedigree_section(analysis_collection):
""" Tests adding another image to the pedigree section of the CPAM0002 analysis """

analysis_collection.collection.find_one.return_value = read_test_fixture("analysis-CPAM0002.json")

expected = {
'header': 'Pedigree', 'attachment_field': 'Pedigree', 'content': [{
'type': 'images-dataset', 'field': 'Pedigree', 'value': [{"file_id": "63505be22888347cf1c275db"},
{"file_id": "second-fake-file-id"}]
}]
}

actual = analysis_collection.add_section_image("CPAM0002", "Pedigree", "Pedigree", "second-fake-file-id")
analysis_collection.add_section_image("CPAM0002", "Pedigree", "Pedigree", "second-fake-file-id")

assert actual == expected
analysis_collection.collection.find_one_and_update.assert_called_once()
updated_analysis = analysis_collection.collection.find_one_and_update.call_args_list[0][0][1]['$set']
actual_updated_pedigree_section = (
next(filter(lambda x: x["header"] == "Pedigree", updated_analysis['sections']), None)
)
assert len(actual_updated_pedigree_section['content']) == 1
assert len(actual_updated_pedigree_section['content'][0]['value']) == 2


def test_update_existing_image_in_pedigree_section(analysis_collection):
Expand Down
21 changes: 18 additions & 3 deletions frontend/src/models/analyses.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,28 @@ export default {
return await Requests.getImage(url);
},

/**

Check failure on line 96 in frontend/src/models/analyses.js

View workflow job for this annotation

GitHub Actions / nodejs-ci (20.8)

Expected indentation of 2 spaces but found 4
* Attaches {@link image} to {@link field} within {@link sectionName}
* the analysis {@link analysisName}.
* @param {string} analysisName The unique name of the analysis to update
* @param {string} sectionName The name of the section within the analysis
* @param {string} field The identifiying field within the section
* @param {File} image the image data to be uploaded

Check failure on line 102 in frontend/src/models/analyses.js

View workflow job for this annotation

GitHub Actions / nodejs-ci (20.8)

Trailing spaces not allowed
* @return {Object[]} Array of all of the sections in the analysis
*/
async attachSectionImage(analysisName, sectionName, field, image) {
const url = `/rosalution/api/analysis/${analysisName}/section/attach/image`;
const url = `/rosalution/api/analysis/${analysisName}/sections?row_type=text`;

const section = {
'header': sectionName,
'content': [],
};
section.content.push({
'field_name': field,
});
const attachmentForm = {
'upload_file': image,
'section_name': sectionName,
'field_name': field,
'updated_sections': [section],
};

return await Requests.postForm(url, attachmentForm);
Expand Down
14 changes: 10 additions & 4 deletions frontend/src/views/AnalysisView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -231,17 +231,23 @@ export default {
attachment.data,
);
const updatedSection = this.sectionsList.find((section) => {
const sectionToUpdate = this.sectionsList.find((section) => {
return section.header == sectionName;
});
const updatedField = updatedSection.content.find((row) => {
const fieldToUpdate = sectionToUpdate.content.find((row) => {
return row.field == field;
});
updatedField.value.push({file_id: updatedSectionImage['image_id']});
const updatedField = updatedSectionImage.find((section) => {
return section.header == sectionName;
})?.content.find((row) => {
row.field == field

Check failure on line 245 in frontend/src/views/AnalysisView.vue

View workflow job for this annotation

GitHub Actions / nodejs-ci (20.8)

Missing semicolon
});
fieldToUpdate.value = updatedField.value;
this.replaceAnalysisSection(updatedSection);
this.replaceAnalysisSection(sectionToUpdate);
} catch (error) {
await notificationDialog.title('Failure').confirmText('Ok').alert(error);
}
Expand Down

0 comments on commit c5d2cc6

Please sign in to comment.