diff --git a/.github/workflows/build_and_upload.yml b/.github/workflows/build_and_upload.yml
new file mode 100644
index 00000000..a64ef6aa
--- /dev/null
+++ b/.github/workflows/build_and_upload.yml
@@ -0,0 +1,58 @@
+# This workflow will build a Java project with Maven
+# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
+
+name: Java CI with Maven
+
+on:
+ push:
+ branches:
+ - master
+ workflow_dispatch:
+env:
+ ORG_NAME: BahmniIndiaDistro
+ EVENT_TYPE: hip-module-trigger
+
+jobs:
+ build:
+ name: build and upload hip omod
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: Set up JDK 1.8
+ uses: actions/setup-java@v1
+ with:
+ java-version: 1.8
+ - name: Cache Maven packages
+ uses: actions/cache@v2
+ with:
+ path: ~/.m2
+ key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
+ restore-keys: ${{ runner.os }}-m2-
+ - name: Build with Maven
+ run: mvn clean install
+ - run: mkdir staging && cp omod/target/*.omod staging
+ - uses: actions/upload-artifact@v2
+ with:
+ name: Package
+ path: staging
+
+ trigger-dependent-repos:
+ name: Trigger Workflows
+ needs: build
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ dependent-repos: [ 'bahmni-india-package' ]
+ steps:
+ - name: Create repository_dispatch
+ env:
+ REPOSITORY_NAME: ${{ matrix.dependent-repos }}
+ run: |
+ trigger_result=$(curl -s -o trigger_response.txt -w "%{http_code}" -X POST -H "Accept: application/vnd.github.v3+json" -H 'authorization: Bearer ${{ secrets.BAHMNI_PAT }}' https://api.github.com/repos/${ORG_NAME}/${REPOSITORY_NAME}/dispatches -d '{"event_type":"'"${EVENT_TYPE}"'"}')
+ if [ $trigger_result == 204 ];then
+ echo "Trigger to $ORG_NAME/$REPOSITORY_NAME Success"
+ else
+ echo "Trigger to $ORG_NAME/$REPOSITORY_NAME Failed"
+ cat trigger_response.txt
+ exit 1
+ fi
diff --git a/.gitignore b/.gitignore
index 320b19a9..ddfdd4f0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,8 +3,10 @@
.project
.classpath
target
-
+.idea
+*.DS_Store
# Package Files #
*.jar
*.war
*.ear
+*.iml
diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index 4c25686e..00000000
--- a/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,274 +0,0 @@
-#Tue Feb 08 13:16:22 EST 2011
-eclipse.preferences.version=1
-org.eclipse.jdt.core.codeComplete.argumentPrefixes=
-org.eclipse.jdt.core.codeComplete.argumentSuffixes=
-org.eclipse.jdt.core.codeComplete.fieldPrefixes=
-org.eclipse.jdt.core.codeComplete.fieldSuffixes=
-org.eclipse.jdt.core.codeComplete.localPrefixes=
-org.eclipse.jdt.core.codeComplete.localSuffixes=
-org.eclipse.jdt.core.codeComplete.staticFieldPrefixes=
-org.eclipse.jdt.core.codeComplete.staticFieldSuffixes=
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
-org.eclipse.jdt.core.compiler.compliance=1.5
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
-org.eclipse.jdt.core.compiler.processAnnotations=disabled
-org.eclipse.jdt.core.compiler.source=1.5
-org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
-org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
-org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16
-org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16
-org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=20
-org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=19
-org.eclipse.jdt.core.formatter.alignment_for_assignment=0
-org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16
-org.eclipse.jdt.core.formatter.alignment_for_compact_if=16
-org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80
-org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0
-org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16
-org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16
-org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=20
-org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=18
-org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16
-org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=0
-org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16
-org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=0
-org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=20
-org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=18
-org.eclipse.jdt.core.formatter.blank_lines_after_imports=1
-org.eclipse.jdt.core.formatter.blank_lines_after_package=1
-org.eclipse.jdt.core.formatter.blank_lines_before_field=1
-org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=1
-org.eclipse.jdt.core.formatter.blank_lines_before_imports=1
-org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1
-org.eclipse.jdt.core.formatter.blank_lines_before_method=1
-org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1
-org.eclipse.jdt.core.formatter.blank_lines_before_package=0
-org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1
-org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1
-org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line
-org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line
-org.eclipse.jdt.core.formatter.comment.clear_blank_lines=false
-org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=true
-org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=true
-org.eclipse.jdt.core.formatter.comment.format_block_comments=false
-org.eclipse.jdt.core.formatter.comment.format_comments=true
-org.eclipse.jdt.core.formatter.comment.format_header=false
-org.eclipse.jdt.core.formatter.comment.format_html=true
-org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true
-org.eclipse.jdt.core.formatter.comment.format_line_comments=false
-org.eclipse.jdt.core.formatter.comment.format_source_code=false
-org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true
-org.eclipse.jdt.core.formatter.comment.indent_root_tags=true
-org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert
-org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert
-org.eclipse.jdt.core.formatter.comment.line_length=100
-org.eclipse.jdt.core.formatter.compact_else_if=true
-org.eclipse.jdt.core.formatter.continuation_indentation=2
-org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2
-org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false
-org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true
-org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true
-org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true
-org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true
-org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true
-org.eclipse.jdt.core.formatter.indent_empty_lines=true
-org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true
-org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true
-org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true
-org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true
-org.eclipse.jdt.core.formatter.indentation.size=4
-org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert
-org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert
-org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert
-org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=insert
-org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=insert
-org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert
-org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert
-org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert
-org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert
-org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert
-org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert
-org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert
-org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert
-org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert
-org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert
-org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert
-org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert
-org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert
-org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert
-org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert
-org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert
-org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert
-org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert
-org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert
-org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert
-org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert
-org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert
-org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert
-org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert
-org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert
-org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert
-org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert
-org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert
-org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert
-org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert
-org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert
-org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert
-org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false
-org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false
-org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false
-org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false
-org.eclipse.jdt.core.formatter.lineSplit=125
-org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false
-org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false
-org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
-org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1
-org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true
-org.eclipse.jdt.core.formatter.tabulation.char=tab
-org.eclipse.jdt.core.formatter.tabulation.size=4
-org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=true
-org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true
diff --git a/.settings/org.eclipse.jdt.ui.prefs b/.settings/org.eclipse.jdt.ui.prefs
deleted file mode 100644
index 56d6d2d0..00000000
--- a/.settings/org.eclipse.jdt.ui.prefs
+++ /dev/null
@@ -1,10 +0,0 @@
-#Thu Nov 13 13:26:19 EST 2008
-eclipse.preferences.version=1
-formatter_profile=_OpenMRS Formatter
-formatter_settings_version=11
-org.eclipse.jdt.ui.exception.name=e
-org.eclipse.jdt.ui.gettersetter.use.is=true
-org.eclipse.jdt.ui.javadoc=true
-org.eclipse.jdt.ui.keywordthis=false
-org.eclipse.jdt.ui.overrideannotation=true
-org.eclipse.jdt.ui.text.custom_code_templates=/**\n * @return the ${bare_field_name}\n *//**\n * @param ${param} the ${bare_field_name} to set\n *//**\n * ${tags}\n *//**\n * The contents of this file are subject to the OpenMRS Public License\n * Version 1.0 (the "License"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n * http\://license.openmrs.org\n *\n * Software distributed under the License is distributed on an "AS IS"\n * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the\n * License for the specific language governing rights and limitations\n * under the License.\n *\n * Copyright (C) OpenMRS, LLC. All Rights Reserved.\n *//**\n *\n * ${tags}\n *//**\n * \n *//**\n * Auto generated method comment\n * \n * ${tags}\n *//**\n * ${see_to_overridden}\n *//**\n * ${tags}\n * ${see_to_target}\n */${filecomment}\n${package_declaration}\n\n${typecomment}\n${type_declaration}\n\n\n\n// ${todo} Auto-generated catch block\nlog.error("Error generated", ${exception_var});// ${todo} Auto-generated method stub\n${body_statement}${body_statement}\n// ${todo} Auto-generated constructor stubreturn ${field};${field} \= ${param};/**\n * @return the ${bare_field_name}\n *//**\n * @param ${param} the ${bare_field_name} to set\n *//**\n * ${tags}\n *//**\n * \n *//**\n * @author ${user}\n *\n * ${tags}\n *//**\n * \n *//**\n * ${tags}\n *//* (non-Jsdoc)\n * ${see_to_overridden}\n *//**\n * ${tags}\n * ${see_to_target}\n */${filecomment}\n${package_declaration}\n\n${typecomment}\n${type_declaration}\n// ${todo} Auto-generated catch block\n${exception_var}.printStackTrace();// ${todo} Auto-generated function stub\n${body_statement}${body_statement}\n// ${todo} Auto-generated constructor stubreturn ${field};${field} \= ${param};
diff --git a/.settings/org.maven.ide.eclipse.prefs b/.settings/org.maven.ide.eclipse.prefs
deleted file mode 100644
index 1fd430ec..00000000
--- a/.settings/org.maven.ide.eclipse.prefs
+++ /dev/null
@@ -1,9 +0,0 @@
-#Tue Feb 08 13:15:09 EST 2011
-activeProfiles=
-eclipse.preferences.version=1
-fullBuildGoals=process-test-resources
-includeModules=true
-resolveWorkspaceProjects=true
-resourceFilterGoals=process-resources resources\:testResources
-skipCompilerPlugin=true
-version=1
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 00000000..14b45289
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2022 Thoughtworks Technologies India Private limited
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
index 3cd1155b..c46b3018 100644
--- a/README.md
+++ b/README.md
@@ -1,25 +1,18 @@
-openmrs-module-basicmodule
+openmrs-module-hipmodule
==========================
-A demonstration module for new OpenMRS module developers
+HIP module for exposing HIP specific features from OpenMRS.
Description
-----------
-This is a very basic module which can be used as a starting point in creating a new module.
+This module is supporting the HIP service with all necessary endpoints exposed that are required by the HIP service.
Building from Source
--------------------
-You will need to have Java 1.6+ and Maven 2.x+ installed. Use the command 'mvn package' to
-compile and package the module. The .omod file will be in the omod/target folder.
+You will need to have Java 1.6+ and Maven 2.x+ installed.
+You need to install the OpenMrs module SDK from https://github.com/openmrs/openmrs-sdk (see Readme for installation instructions)
-Alternatively you can add the snippet provided in the [Creating Modules](https://wiki.openmrs.org/x/cAEr) page to your
-omod/pom.xml and use the mvn command:
-
- mvn package -P deploy-web -D deploy.path="../../openmrs-1.8.x/webapp/src/main/webapp"
-
-It will allow you to deploy any changes to your web
-resources such as jsp or js files without re-installing the module. The deploy path says
-where OpenMRS is deployed.
+Use the command `mvn clean install` to build the module, the .omod file will be in the omod/target folder.
Installation
------------
@@ -30,3 +23,32 @@ If uploads are not allowed from the web (changable via a runtime property), you
into the ~/.OpenMRS/modules folder. (Where ~/.OpenMRS is assumed to be the Application
Data Directory that the running openmrs is currently using.) After putting the file in there
simply restart OpenMRS/tomcat and the module will be loaded and started.
+
+Configure values
+------------
+## Vagrant setup
+
+You can configure values like, say location, concept and attribute names. you can check **api/src/main/java/org/bahmni/module/hip/Config.java** to know what are the values you can configure and default values.
+
+### One time setup
+
+1. create a file. For example, created `env_file` in `/etc/openmrs/` directory.
+2. To create conf file for openmrs service,`systemctl edit openmrs`. It will open blank file. paste the following lines in it
+```
+[Service]
+EnvironmentFile=/etc/openmrs/env_file
+```
+Note: You need to specify your created file path from 1st step in `EnvironmentFile` variable
+
+### To configure values
+
+You need to add values to the `env_file`. For example, if you need to specify custom values for Location and Phone Number attribute.
+```
+LOCATION=your_location
+PHONE_NUMBER=your_phoneNumber_attribute_name
+```
+Note: Attribute Name should be exactly same as enum keys from **api/src/main/java/org/bahmni/module/hip/Config.java**
+
+## Docker setup
+
+You can add values to the openmrs Environment variables, specifying same attribute name.
\ No newline at end of file
diff --git a/api/basicmodule-api.iml b/api/basicmodule-api.iml
new file mode 100644
index 00000000..75fc53ef
--- /dev/null
+++ b/api/basicmodule-api.iml
@@ -0,0 +1,85 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/api/pom.xml b/api/pom.xml
index 388a1dae..f1fe6327 100644
--- a/api/pom.xml
+++ b/api/pom.xml
@@ -2,13 +2,44 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
- org.openmrs.module
- basicmodule
+ org.bahmni.module
+ hipmodule
0.1-SNAPSHOT
- basicmodule-api
+ hipmodule-api
jar
- Basic Module API
- API project for Basic Module
+ HIP Module API
+ API project for HIP Module
+
+
+
+ org.openmrs.api
+ openmrs-api
+ 2.4.2
+ provided
+
+
+ org.openmrs.module
+ emrapi-api
+ provided
+
+
+ org.openmrs.module
+ emrapi-omod
+ provided
+
+
+ org.projectlombok
+ lombok
+ 1.18.10
+ provided
+
+
+ org.openmrs.module
+ episodes-api
+ 1.0-SNAPSHOT
+ compile
+
+
diff --git a/api/src/main/java/org/openmrs/module/basicmodule/BasicModuleActivator.java b/api/src/main/java/org/bahmni/module/hip/BasicModuleActivator.java
similarity index 93%
rename from api/src/main/java/org/openmrs/module/basicmodule/BasicModuleActivator.java
rename to api/src/main/java/org/bahmni/module/hip/BasicModuleActivator.java
index a5672c55..cbda086c 100644
--- a/api/src/main/java/org/openmrs/module/basicmodule/BasicModuleActivator.java
+++ b/api/src/main/java/org/bahmni/module/hip/BasicModuleActivator.java
@@ -11,31 +11,32 @@
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
-package org.openmrs.module.basicmodule;
+package org.bahmni.module.hip;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.module.BaseModuleActivator;
+import org.openmrs.module.ModuleActivator;
/**
* This class contains the logic that is run every time this module is either started or shutdown
*/
public class BasicModuleActivator extends BaseModuleActivator {
-
+
private Log log = LogFactory.getLog(this.getClass());
-
+
/**
* @see org.openmrs.module.Activator#startup()
*/
public void startup() {
log.info("Starting Basic Module");
}
-
+
/**
* @see org.openmrs.module.Activator#shutdown()
*/
public void shutdown() {
log.info("Shutting down Basic Module");
}
-
+
}
diff --git a/api/src/main/java/org/bahmni/module/hip/Config.java b/api/src/main/java/org/bahmni/module/hip/Config.java
new file mode 100644
index 00000000..b03cf59b
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/Config.java
@@ -0,0 +1,61 @@
+package org.bahmni.module.hip;
+
+public enum Config {
+
+
+ PATIENT_DOCUMENTS_PATH("/home/bahmni/document_images/"),
+ LOCATION("Bahmni Clinic"),
+
+ //attribute name
+ PHONE_NUMBER("phoneNumber"),
+
+ //identifier type
+ ABHA_ADDRESS("ABHA Address"),
+ ABHA_NUMBER("ABHA Number"),
+
+ //encounterType
+ CONSULTATION("Consultation"),
+ PATIENT_DOCUMENT("Patient Document"),
+ RADIOLOGY_TYPE( "RADIOLOGY"),
+ ORDER_TYPE("Order"),
+
+ //concepts
+ DOCUMENT_TYPE("Document"),
+ RADIOLOGY_REPORT("Radiology Report"),
+ CHIEF_COMPLAINT( "Chief Complaint"),
+ PROCEDURE_NOTES( "Procedure Notes"),
+ DISCHARGE_SUMMARY( "Discharge Summary"),
+ CODED_DIAGNOSIS( "Coded Diagnosis"),
+ NON_CODED_DIAGNOSIS( "Non-coded Diagnosis"),
+ LAB_REPORT( "LAB_REPORT"),
+ RADIOLOGY_ORDER( "Radiology Order"),
+ LAB_ORDER( "Lab Order"),
+ IMAGE("Image"),
+ PATIENT_VIDEO("Patient Video"),
+ CONCEPT_DETAILS_CONCEPT_CLASS("Concept Details"),
+ CHIEF_COMPLAINT_CODED("Chief Complaint Coded"),
+ SIGN_SYMPTOM_DURATION("Sign/symptom duration"),
+ CHIEF_COMPLAINT_DURATION("Chief Complaint Duration"),
+
+ //Physical_Examination_Ignoring_Form_List
+ Forms_To_Ignore_In_Physical_Examination("Discharge Summary, Death Note, Delivery Note, Opioid Substitution Therapy - Intake, Opportunistic Infection, " +
+ "Safe Abortion, ECG Notes, Operative Notes, USG Notes, Procedure Notes,Triage Reference, History and Examination, Visit Diagnoses, Patient Video"),
+
+
+ PROP_HFR_ID("bahmniHip.healthFacilityRegistryId"),
+ PROP_HFR_NAME( "bahmniHip.healthFacilityName"),
+ PROP_HFR_SYSTEM( "bahmniHip.healthFacilitySystem"),
+ PROP_HFR_URL( "bahmniHip.healthFacilityUrl");
+
+
+ private final String value;
+
+ Config(String val) {
+ value = val;
+ }
+
+ public String getValue() {
+ return System.getenv().getOrDefault(name(),this.value);
+ }
+
+}
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/CareContextRepository.java b/api/src/main/java/org/bahmni/module/hip/api/dao/CareContextRepository.java
new file mode 100644
index 00000000..48a81dc9
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/CareContextRepository.java
@@ -0,0 +1,13 @@
+package org.bahmni.module.hip.api.dao;
+
+import org.bahmni.module.hip.model.PatientCareContext;
+import org.openmrs.Patient;
+
+import java.util.List;
+
+public interface CareContextRepository {
+ List getPatientCareContext(String patientUuid);
+
+ List getNewPatientCareContext(Patient patient);
+
+}
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/Constants.java b/api/src/main/java/org/bahmni/module/hip/api/dao/Constants.java
new file mode 100644
index 00000000..a4eee283
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/Constants.java
@@ -0,0 +1,8 @@
+package org.bahmni.module.hip.api.dao;
+
+public class Constants {
+
+ public static final String VISIT_TYPE = "VISIT_TYPE";
+ public static final String PROGRAM = "PROGRAM";
+ public static final String ORDER_ACTION = "DISCONTINUE";
+}
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/ConsultationDao.java b/api/src/main/java/org/bahmni/module/hip/api/dao/ConsultationDao.java
new file mode 100644
index 00000000..abd5515e
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/ConsultationDao.java
@@ -0,0 +1,18 @@
+package org.bahmni.module.hip.api.dao;
+
+import org.openmrs.Obs;
+import org.openmrs.Order;
+import org.openmrs.Patient;
+import org.openmrs.Visit;
+
+import java.util.Date;
+import java.util.List;
+
+public interface ConsultationDao {
+ List getChiefComplaints(Visit visit);
+ List getChiefComplaintForProgram(String programName, Date fromDate, Date toDate, Patient patient);
+ List getPhysicalExamination(Visit visit);
+ List getOrders(Visit visit);
+ List getOrdersForProgram(String programName, Date fromDate, Date toDate, Patient patient);
+ List getPhysicalExaminationForProgram(String programName, Date fromDate, Date toDate, Patient patient);
+}
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/DiagnosticReportDao.java b/api/src/main/java/org/bahmni/module/hip/api/dao/DiagnosticReportDao.java
new file mode 100644
index 00000000..60ae92db
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/DiagnosticReportDao.java
@@ -0,0 +1,14 @@
+package org.bahmni.module.hip.api.dao;
+
+import org.openmrs.Encounter;
+import org.openmrs.Obs;
+import org.openmrs.Order;
+import org.openmrs.Visit;
+
+import java.util.List;
+import java.util.Map;
+
+public interface DiagnosticReportDao {
+ Map> getAllUnorderedUploadsForVisit(String patientUUID, Visit visit);
+ Map> getAllOrderedTestUploads(String patientUUID,Visit visit);
+}
\ No newline at end of file
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/DischargeSummaryDao.java b/api/src/main/java/org/bahmni/module/hip/api/dao/DischargeSummaryDao.java
new file mode 100644
index 00000000..a017abea
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/DischargeSummaryDao.java
@@ -0,0 +1,15 @@
+package org.bahmni.module.hip.api.dao;
+
+import org.openmrs.Obs;
+import org.openmrs.Patient;
+import org.openmrs.Visit;
+
+import java.util.Date;
+import java.util.List;
+
+public interface DischargeSummaryDao {
+ List getCarePlan(Visit visit);
+ List getProcedures(Visit visit);
+ List getProceduresForProgram(String programName, Date fromDate, Date toDate, Patient patient);
+ List getCarePlanForProgram(String programName, Date fromDate, Date toDate, Patient patient);
+}
\ No newline at end of file
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/EncounterDao.java b/api/src/main/java/org/bahmni/module/hip/api/dao/EncounterDao.java
new file mode 100644
index 00000000..b2206cb1
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/EncounterDao.java
@@ -0,0 +1,19 @@
+package org.bahmni.module.hip.api.dao;
+
+import org.openmrs.Encounter;
+import org.openmrs.Obs;
+import org.openmrs.Order;
+import org.openmrs.Visit;
+
+import java.util.Date;
+import java.util.List;
+
+public interface EncounterDao {
+
+ List GetEpisodeEncounterIds();
+ List GetOrdersForVisit(Visit visit);
+ List GetEncountersForVisit(Visit visit, String encounterType);
+ List GetAllObsForVisit(Visit visit, String encounterType, String conceptName);
+ List GetEncounterIdsForProgramForPrescriptions(String patientUUID, String program, String programEnrollmentID, Date fromDate, Date toDate) ;
+ List GetEncounterIdsForProgramForDiagnosticReport(String patientUUID, String program, String programEnrollmentID, Date fromDate, Date toDate);
+}
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/ExistingPatientDao.java b/api/src/main/java/org/bahmni/module/hip/api/dao/ExistingPatientDao.java
new file mode 100644
index 00000000..ec072b3a
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/ExistingPatientDao.java
@@ -0,0 +1,16 @@
+package org.bahmni.module.hip.api.dao;
+
+import org.openmrs.Patient;
+
+import java.util.List;
+
+public interface ExistingPatientDao {
+ String getPatientUuidWithHealthId(String healthId);
+
+ List getPatientsWithPhoneNumber(String phoneNumber);
+
+ String getPhoneNumber(Integer patientId);
+
+ String getPatientHealthIdWithPatientId(Integer patientId);
+
+}
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/HipVisitDao.java b/api/src/main/java/org/bahmni/module/hip/api/dao/HipVisitDao.java
new file mode 100644
index 00000000..cb5f8306
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/HipVisitDao.java
@@ -0,0 +1,14 @@
+package org.bahmni.module.hip.api.dao;
+
+import org.openmrs.Patient;
+import org.openmrs.Visit;
+
+import java.util.Date;
+import java.util.List;
+
+public interface HipVisitDao {
+
+ List GetVisitIdsForProgramForLabResults(String patientUUID, String program, String programEnrollmentID, Date fromDate, Date toDate);
+ List GetVisitIdsForVisitForLabResults(String patientUUID, String visit, Date visitStartDate) ;
+ Visit getPatientVisit(Patient patient, String visitType, Date visitStartDate);
+}
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/OPConsultDao.java b/api/src/main/java/org/bahmni/module/hip/api/dao/OPConsultDao.java
new file mode 100644
index 00000000..042ec250
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/OPConsultDao.java
@@ -0,0 +1,21 @@
+package org.bahmni.module.hip.api.dao;
+
+import org.openmrs.Encounter;
+import org.openmrs.Obs;
+import org.openmrs.Patient;
+import org.openmrs.Visit;
+import org.openmrs.module.emrapi.conditionslist.Condition;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+public interface OPConsultDao {
+ Map> getMedicalHistoryConditions(Visit visit);
+ List getMedicalHistoryDiagnosis(Visit visit);
+ List getProcedures(Visit visit);
+ List getProceduresForProgram(String programName, Date fromDate, Date toDate, Patient patient);
+ Map> getMedicalHistoryConditionsForProgram(String programName, Date fromDate, Date toDate, Patient patient);
+ List getMedicalHistoryDiagnosisForProgram(String programName, Date fromDate, Date toDate, Patient patient);
+ Map> getPatientDocumentsForVisit(Visit visit);
+}
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/PrescriptionOrderDao.java b/api/src/main/java/org/bahmni/module/hip/api/dao/PrescriptionOrderDao.java
new file mode 100644
index 00000000..d57dc6eb
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/PrescriptionOrderDao.java
@@ -0,0 +1,15 @@
+package org.bahmni.module.hip.api.dao;
+
+import org.openmrs.DrugOrder;
+import org.openmrs.OrderType;
+import org.openmrs.Patient;
+import org.openmrs.Visit;
+
+import java.util.Date;
+import java.util.List;
+
+public interface PrescriptionOrderDao {
+ List getDrugOrders(Visit visit);
+ List getDrugOrdersForProgram(Patient patient, Date fromDate, Date toDate, OrderType orderType, String program, String programEnrollmentId);
+
+}
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/impl/CareContextRepositoryImpl.java b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/CareContextRepositoryImpl.java
new file mode 100644
index 00000000..6ab6255b
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/CareContextRepositoryImpl.java
@@ -0,0 +1,131 @@
+package org.bahmni.module.hip.api.dao.impl;
+
+import org.bahmni.module.hip.api.dao.CareContextRepository;
+import org.bahmni.module.hip.api.dao.EncounterDao;
+import org.bahmni.module.hip.model.PatientCareContext;
+import org.hibernate.Query;
+import org.hibernate.SessionFactory;
+import org.openmrs.Encounter;
+import org.openmrs.Patient;
+import org.openmrs.PatientProgram;
+import org.openmrs.Visit;
+import org.openmrs.api.PatientService;
+import org.openmrs.api.ProgramWorkflowService;
+import org.openmrs.api.VisitService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static org.bahmni.module.hip.api.dao.Constants.PROGRAM;
+import static org.bahmni.module.hip.api.dao.Constants.VISIT_TYPE;
+
+@Repository
+public class CareContextRepositoryImpl implements CareContextRepository {
+ private SessionFactory sessionFactory;
+ private PatientService patientService;
+ private VisitService visitService;
+ private ProgramWorkflowService programWorkflowService;
+ private EncounterDao encounterDao;
+
+
+ @Autowired
+ public CareContextRepositoryImpl(SessionFactory sessionFactory, PatientService patientService, VisitService visitService, ProgramWorkflowService programWorkflowService, EncounterDao encounterDao) {
+ this.sessionFactory = sessionFactory;
+ this.patientService = patientService;
+ this.visitService = visitService;
+ this.programWorkflowService = programWorkflowService;
+ this.encounterDao = encounterDao;
+ }
+
+ @Override
+ public List getPatientCareContext(String patientUuid) {
+ List careContexts = new ArrayList<>();
+ Patient patient = patientService.getPatientByUuid(patientUuid);
+ List visits = getAllVisitForPatient(patient);
+ List patientPrograms = getAllPrograms(patient);
+ for (Visit visit: visits) {
+ careContexts.add(getPatientCareContext(visit));
+ }
+ for (PatientProgram program: patientPrograms) {
+ careContexts.add(getPatientCareContext(program));
+ }
+ return careContexts;
+ }
+
+
+ @Override
+ public List getNewPatientCareContext(Patient patient) {
+ List careContexts = new ArrayList<>();
+ List visits = getAllVisitForPatient(patient);
+ List patientPrograms = getAllPrograms(patient);
+ Visit visit = !visits.isEmpty() ? visits.get(0) : null;
+ PatientProgram program = !patientPrograms.isEmpty() ? patientPrograms.get(0) : null;
+ if(visit == null && program != null)
+ careContexts.add(getPatientCareContext(program));
+ else if(visit != null && program == null)
+ careContexts.add(getPatientCareContext(visit));
+ else if(visit != null && program != null) {
+ if (program.getDateCreated().before(visit.getStartDatetime()))
+ careContexts.add(getPatientCareContext(visit));
+ else
+ careContexts.add(getPatientCareContext(program));
+ }
+ return careContexts;
+ }
+
+ private PatientCareContext getPatientCareContext(Visit visit) {
+ return new PatientCareContext(VISIT_TYPE,
+ visit.getVisitType().getName().concat(" / ").concat(visit.getStartDatetime().toString()),
+ visit.getCreator().getPersonName().getFullName());
+ }
+
+ private PatientCareContext getPatientCareContext(PatientProgram program) {
+ return new PatientCareContext(PROGRAM,
+ program.getProgram().getName(),
+ getProgramEnrollementId(program.getPatientProgramId()).get(0));
+ }
+
+ private List getEpisodeIds() {
+ Query query = this.sessionFactory.getCurrentSession().createSQLQuery("select\n" +
+ "\t\tepisode_id\n" +
+ "\tfrom\n" +
+ "\t\tepisode_encounter\n");
+ return query.list();
+ }
+
+ private List getProgramEnrollementId(Integer patientProgramId) {
+ Query query = this.sessionFactory.getCurrentSession().createSQLQuery("SELECT\n" +
+ " value_reference FROM patient_program_attribute WHERE patient_program_id = :patientProgramId\n");
+ query.setParameter("patientProgramId", patientProgramId);
+ return query.list();
+ }
+
+ private List getAllVisitForPatient(Patient patient){
+ List visits = new ArrayList<>();
+ for (Visit visit: visitService.getVisitsByPatient(patient)) {
+ Set encounters = visit.getEncounters().stream()
+ .filter(encounter -> !encounterDao.GetEpisodeEncounterIds().contains(encounter.getEncounterId()))
+ .collect(Collectors.toSet());
+ if(!encounters.isEmpty())
+ visits.add(visit);
+ }
+ return visits;
+ }
+
+ private List getAllPrograms(Patient patient){
+ List programs = new ArrayList<>();
+ List episodeIds = getEpisodeIds();
+ Set patientPrograms = new HashSet<>(programWorkflowService.getPatientPrograms(patient, null, null, null, null, null, false));
+ for (PatientProgram program: patientPrograms) {
+ if(episodeIds.contains(program.getId()))
+ programs.add(program);
+ }
+ return programs;
+ }
+
+}
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/impl/ConsultationDaoImpl.java b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/ConsultationDaoImpl.java
new file mode 100644
index 00000000..0d012065
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/ConsultationDaoImpl.java
@@ -0,0 +1,145 @@
+package org.bahmni.module.hip.api.dao.impl;
+
+import org.bahmni.module.hip.Config;
+import org.bahmni.module.hip.api.dao.ConsultationDao;
+import org.bahmni.module.hip.api.dao.EncounterDao;
+import org.openmrs.Encounter;
+import org.openmrs.Obs;
+import org.openmrs.Order;
+import org.openmrs.Patient;
+import org.openmrs.PatientProgram;
+import org.openmrs.Visit;
+import org.openmrs.api.ObsService;
+import org.openmrs.api.OrderService;
+import org.openmrs.api.ProgramWorkflowService;
+import org.openmrs.module.episodes.Episode;
+import org.openmrs.module.episodes.service.EpisodeService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static org.bahmni.module.hip.api.dao.Constants.ORDER_ACTION;
+
+@Repository
+public class ConsultationDaoImpl implements ConsultationDao {
+
+ public static final ArrayList ORDER_TYPES = new ArrayList() {{
+ add(Config.LAB_ORDER.getValue());
+ add(Config.RADIOLOGY_ORDER.getValue());
+ }};
+ private final ProgramWorkflowService programWorkflowService;
+ private final EpisodeService episodeService;
+ private final EncounterDao encounterDao;
+ private final ObsService obsService;
+ private final OrderService orderService;
+
+ @Autowired
+ public ConsultationDaoImpl(ObsService obsService, OrderService orderService, ProgramWorkflowService programWorkflowService, EpisodeService episodeService, EncounterDao encounterDao) {
+ this.obsService = obsService;
+ this.orderService = orderService;
+ this.programWorkflowService = programWorkflowService;
+ this.episodeService = episodeService;
+ this.encounterDao = encounterDao;
+ }
+
+ @Override
+ public List getChiefComplaints(Visit visit) {
+ List chiefComplaintObsMap = encounterDao.GetAllObsForVisit(visit,Config.CONSULTATION.getValue(),Config.CHIEF_COMPLAINT.getValue())
+ .stream().filter(o -> o.getValueCoded() != null && o.getConcept().getName().getLocalePreferred())
+ .collect(Collectors.toList());
+ return chiefComplaintObsMap;
+ }
+
+ @Override
+ public List getChiefComplaintForProgram(String programName, Date fromDate, Date toDate, Patient patient) {
+ List obs = getAllObs(programName, fromDate, toDate, patient);
+ List obsSet = new ArrayList<>();
+ for (Obs o : obs) {
+ if (Objects.equals(o.getEncounter().getEncounterType().getName(), Config.CONSULTATION.getValue())
+ && Objects.equals(o.getConcept().getName().getName(), Config.CHIEF_COMPLAINT.getValue())
+ && o.getValueCoded() != null
+ && o.getConcept().getName().getLocalePreferred()) {
+ obsSet.add(o);
+ }
+ }
+ return obsSet;
+ }
+
+ public List getAllObs(String programName, Date fromDate, Date toDate, Patient patient) {
+ List patientPrograms = programWorkflowService.getPatientPrograms(patient, programWorkflowService.getProgramByName(programName), fromDate, toDate, null, null, false);
+ Set patientProgramSet = new HashSet<>(patientPrograms);
+ List obs = new ArrayList<>();
+ for (PatientProgram patientProgram : patientProgramSet) {
+ Episode episode = episodeService.getEpisodeForPatientProgram(patientProgram);
+ Set encounterSet = episode.getEncounters();
+ for (Encounter encounter : encounterSet) {
+ obs.addAll(encounter.getAllObs());
+ }
+ }
+ return obs;
+ }
+
+ @Override
+ public List getPhysicalExamination(Visit visit) {
+ final String[] formNames = Config.Forms_To_Ignore_In_Physical_Examination.getValue().split("\\s*,\\s*");
+ List physicalExaminationObsMap = encounterDao.GetAllObsForVisit(visit,Config.CONSULTATION.getValue(),null)
+ .stream().filter(o -> o.getValueCoded() == null
+ && o.getObsGroup() == null
+ && !Arrays.asList(formNames).contains(o.getConcept().getName().getName()) )
+ .collect(Collectors.toList());
+ return physicalExaminationObsMap;
+ }
+
+ @Override
+ public List getOrders(Visit visit) {
+ return encounterDao.GetOrdersForVisit(visit).stream()
+ .filter(order -> order.getDateStopped() == null && !Objects.equals(order.getAction().toString(), ORDER_ACTION))
+ .filter(order -> ORDER_TYPES.contains(order.getOrderType().getName()))
+ .collect(Collectors.toList());
+ }
+
+ @Override
+ public List getOrdersForProgram(String programName, Date fromDate, Date toDate, Patient patient) {
+ List orderSet = new ArrayList<>();
+ List patientPrograms = programWorkflowService.getPatientPrograms(patient, programWorkflowService.getProgramByName(programName), fromDate, toDate, null, null, false);
+ Set patientProgramSet = new HashSet<>(patientPrograms);
+ for (PatientProgram patientProgram : patientProgramSet) {
+ Episode episode = episodeService.getEpisodeForPatientProgram(patientProgram);
+ Set encounterSet = episode.getEncounters();
+ for (Encounter encounter : encounterSet) {
+ for (Order order : encounter.getOrders()) {
+ if (order.getDateStopped() == null && !Objects.equals(order.getAction().toString(), ORDER_ACTION) && ORDER_TYPES.contains(order.getOrderType().getName())) {
+ orderSet.add(order);
+ }
+ }
+ }
+ }
+ return orderSet;
+ }
+
+ @Override
+ public List getPhysicalExaminationForProgram(String programName, Date fromDate, Date toDate, Patient patient) {
+ final String[] formNames = Config.Forms_To_Ignore_In_Physical_Examination.getValue().split("\\s*,\\s*");
+ List physicalExaminationObsMap = new ArrayList<>();
+ List obs = getAllObs(programName, fromDate, toDate, patient);
+ for (Obs o : obs) {
+ if (Objects.equals(o.getEncounter().getEncounterType().getName(), Config.CONSULTATION.getValue())
+ && o.getValueCoded() == null
+ && o.getConcept().getName().getLocalePreferred()
+ && o.getObsGroup() == null
+ && !Arrays.asList(formNames).contains(o.getConcept().getName().getName())) {
+ physicalExaminationObsMap.add(o);
+ }
+ }
+ return physicalExaminationObsMap;
+ }
+}
+
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/impl/DiagnosticReportDaoImpl.java b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/DiagnosticReportDaoImpl.java
new file mode 100644
index 00000000..1c12c5f7
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/DiagnosticReportDaoImpl.java
@@ -0,0 +1,115 @@
+package org.bahmni.module.hip.api.dao.impl;
+
+import org.bahmni.module.hip.Config;
+import org.bahmni.module.hip.api.dao.DiagnosticReportDao;
+import org.hibernate.Query;
+import org.hibernate.SessionFactory;
+import org.openmrs.Concept;
+import org.openmrs.Encounter;
+import org.openmrs.Obs;
+import org.openmrs.Person;
+import org.openmrs.Visit;
+import org.openmrs.api.ConceptService;
+import org.openmrs.api.EncounterService;
+import org.openmrs.api.ObsService;
+import org.openmrs.api.PatientService;
+import org.openmrs.api.PersonService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+
+
+@Repository
+public class DiagnosticReportDaoImpl implements DiagnosticReportDao {
+
+ private SessionFactory sessionFactory;
+ private PersonService personService;
+ private ObsService obsService;
+ private ConceptService conceptService;
+ private EncounterService encounterService;
+ private PatientService patientService;
+
+
+ @Autowired
+ public DiagnosticReportDaoImpl(PersonService personService, ObsService obsService,
+ ConceptService conceptService, EncounterService encounterService,
+ SessionFactory sessionFactory, PatientService patientService)
+ {
+ this.obsService = obsService;
+ this.personService = personService;
+ this.conceptService = conceptService;
+ this.encounterService = encounterService;
+ this.sessionFactory = sessionFactory;
+ this.patientService = patientService;
+ }
+
+
+ private List getAllObsForDiagnosticReports(String patientUUID, Boolean linkedWithOrder) {
+ Person person = personService.getPersonByUuid(patientUUID);
+ Concept concept = conceptService.getConcept(Config.LAB_REPORT.getValue());
+ List obs = obsService.getObservationsByPersonAndConcept(person,concept);
+ if(linkedWithOrder)
+ return obs.stream().filter(o -> o.getOrder() != null).collect(Collectors.toList());
+ return obs.stream().filter(o -> o.getOrder() == null).collect(Collectors.toList());
+ }
+
+ @Override
+ public Map> getAllUnorderedUploadsForVisit(String patientUUID, Visit visit){
+ Map> labReportsMap = new HashMap<>();;
+ List labReports = getAllObsForDiagnosticReports(patientUUID,false);
+ List encounters = encounterService.getEncountersByVisit(visit,false);
+ if(encounters.size() != 0) {
+ List nextEncounters = encounterService.getEncountersByPatient(patientService.getPatientByUuid(patientUUID)).stream().filter(e ->
+ encounters.get(encounters.size() - 1).getId() < e.getId()
+ ).collect(Collectors.toList());
+ for (Obs obs : labReports) {
+ for (Encounter encounter : encounters) {
+ Encounter nextEncounter;
+ Date nextEncounterDate = nextEncounters.size() != 0 ? nextEncounters.get(0).getDateCreated() : new Date();
+ if (encounters.indexOf(encounter) < (encounters.size() - 1)) {
+ nextEncounter = encounterService.getEncounter(encounters.get(encounters.indexOf(encounter) + 1).getId());
+ nextEncounterDate = nextEncounter.getDateCreated();
+ }
+ if (obs.getDateCreated().equals(encounter.getDateCreated()) || (obs.getDateCreated().before(nextEncounterDate) && obs.getDateCreated().after(encounter.getDateCreated()))) {
+ if (labReportsMap.containsKey(encounter)) {
+ labReportsMap.get(encounter).add(obs);
+ } else {
+ labReportsMap.put(encounter, new ArrayList() {{
+ add(obs);
+ }});
+ }
+ }
+ }
+ }
+ }
+ return labReportsMap;
+ }
+
+ @Override
+ public Map> getAllOrderedTestUploads(String patientUuid,Visit visit) {
+ Map> documentObs = new HashMap<>();
+ List obsList = getAllObsForDiagnosticReports(patientUuid,true);
+ List encounters = encounterService.getEncountersByVisit(visit,false);
+
+ for (Obs obs : obsList) {
+ Encounter orderEncounter = obs.getOrder().getEncounter();
+ if(encounters.contains(orderEncounter)) {
+ if (documentObs.containsKey(orderEncounter)) {
+ documentObs.get(orderEncounter).add(obs);
+ } else {
+ documentObs.put(orderEncounter, new ArrayList() {{
+ add(obs);
+ }});
+ }
+ }
+ }
+ return documentObs;
+ }
+}
\ No newline at end of file
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/impl/DischargeSummaryDaoImpl.java b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/DischargeSummaryDaoImpl.java
new file mode 100644
index 00000000..4c4d7e82
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/DischargeSummaryDaoImpl.java
@@ -0,0 +1,101 @@
+package org.bahmni.module.hip.api.dao.impl;
+
+import org.bahmni.module.hip.Config;
+import org.bahmni.module.hip.api.dao.DischargeSummaryDao;
+import org.bahmni.module.hip.api.dao.EncounterDao;
+import org.openmrs.Encounter;
+import org.openmrs.Obs;
+import org.openmrs.Patient;
+import org.openmrs.PatientProgram;
+import org.openmrs.Visit;
+import org.openmrs.api.ObsService;
+import org.openmrs.api.ProgramWorkflowService;
+import org.openmrs.module.episodes.Episode;
+import org.openmrs.module.episodes.service.EpisodeService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+
+@Repository
+public class DischargeSummaryDaoImpl implements DischargeSummaryDao {
+
+ private final ObsService obsService;
+ private final ProgramWorkflowService programWorkflowService;
+ private final EpisodeService episodeService;
+ private final EncounterDao encounterDao;
+
+ @Autowired
+ public DischargeSummaryDaoImpl(ObsService obsService, ProgramWorkflowService programWorkflowService, EpisodeService episodeService, EncounterDao encounterDao) {
+ this.obsService = obsService;
+ this.programWorkflowService = programWorkflowService;
+ this.episodeService = episodeService;
+ this.encounterDao = encounterDao;
+ }
+
+ @Override
+ public List getCarePlan(Visit visit) {
+ List carePlanObs = encounterDao.GetAllObsForVisit(visit, Config.CONSULTATION.getValue(), Config.DISCHARGE_SUMMARY.getValue()).stream()
+ .filter(obs -> obs.getConcept().getName().getLocalePreferred())
+ .collect(Collectors.toList());
+
+ return carePlanObs;
+ }
+
+ @Override
+ public List getCarePlanForProgram(String programName, Date fromDate, Date toDate, Patient patient) {
+ List patientPrograms = programWorkflowService.getPatientPrograms(patient,programWorkflowService.getProgramByName(programName), fromDate, toDate,null,null,false);
+ Set patientProgramSet = new HashSet<>(patientPrograms);
+ List carePlanObs= new ArrayList<>();
+ for (PatientProgram patientProgram: patientProgramSet) {
+ Episode episode = episodeService.getEpisodeForPatientProgram(patientProgram);
+ Set encounterSet = episode.getEncounters();
+ for (Encounter encounter : encounterSet) {
+ for (Obs o : encounter.getAllObs()) {
+ if (Config.DISCHARGE_SUMMARY.getValue().equals(o.getConcept().getName().getName())
+ && o.getConcept().getName().getLocalePreferred()) {
+ carePlanObs.add(o);
+ }
+ }
+ }
+ }
+ return carePlanObs;
+ }
+
+ @Override
+ public List getProcedures(Visit visit) {
+ List proceduresObsMap = encounterDao.GetAllObsForVisit(visit,Config.CONSULTATION.getValue(), Config.PROCEDURE_NOTES.getValue()).stream()
+ .filter(obs -> obs.getObsGroup() == null)
+ .collect(Collectors.toList());
+ return proceduresObsMap;
+ }
+
+ @Override
+ public List getProceduresForProgram(String programName, Date fromDate, Date toDate, Patient patient) {
+ List patientPrograms = programWorkflowService.getPatientPrograms(patient,programWorkflowService.getProgramByName(programName), fromDate, toDate,null,null,false);
+ Set patientProgramSet = new HashSet<>(patientPrograms);
+ List proceduresObsSet= new ArrayList<>();
+ for (PatientProgram patientProgram: patientProgramSet) {
+ Episode episode = episodeService.getEpisodeForPatientProgram(patientProgram);
+ Set encounterSet = episode.getEncounters();
+ for (Encounter encounter : encounterSet) {
+ for (Obs o : encounter.getAllObs()) {
+ if (Objects.equals(o.getEncounter().getEncounterType().getName(), Config.CONSULTATION.getValue())
+ && o.getObsGroup() == null
+ && Objects.equals(o.getConcept().getName().getName(), Config.PROCEDURE_NOTES.getValue())
+ ) {
+ proceduresObsSet.add(o);
+ }
+ }
+ }
+ }
+ return proceduresObsSet;
+ }
+}
\ No newline at end of file
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/impl/EncounterDaoImpl.java b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/EncounterDaoImpl.java
new file mode 100644
index 00000000..79950796
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/EncounterDaoImpl.java
@@ -0,0 +1,200 @@
+package org.bahmni.module.hip.api.dao.impl;
+
+import org.bahmni.module.hip.Config;
+import org.bahmni.module.hip.api.dao.EncounterDao;
+import org.hibernate.Query;
+import org.hibernate.SessionFactory;
+import org.openmrs.Encounter;
+import org.openmrs.Obs;
+import org.openmrs.Order;
+import org.openmrs.Visit;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+
+
+@Repository
+public class EncounterDaoImpl implements EncounterDao {
+
+ private SessionFactory sessionFactory;
+
+ @Autowired
+ public EncounterDaoImpl(SessionFactory sessionFactory) {
+ this.sessionFactory = sessionFactory;
+ }
+
+ private String sqlGetEpisodeEncounterIds = "select\n" +
+ "\t\tencounter_id\n" +
+ "\tfrom\n" +
+ "\t\tepisode_encounter\n";
+
+ private String sqlGetEncounterIdsForProgramForPrescriptions = "SELECT\n" +
+ " le.encounter_id\n" +
+ "FROM\n" +
+ " patient_program AS pp\n" +
+ " INNER JOIN program AS p ON pp.program_id = p.program_id\n" +
+ " INNER JOIN (\n" +
+ " SELECT\n" +
+ " ee.episode_id,\n" +
+ " ee.encounter_id,\n" +
+ " epp.patient_program_id,\n" +
+ " v.date_started\n" +
+ " FROM\n" +
+ " episode_encounter AS ee\n" +
+ " INNER JOIN episode_patient_program AS epp ON ee.episode_id = epp.episode_id\n" +
+ " INNER JOIN encounter AS e ON e.encounter_id = ee.encounter_id\n" +
+ " INNER JOIN visit AS v ON v.visit_id = e.visit_id\n" +
+ " ) AS le ON le.patient_program_id = pp.patient_program_id\n" +
+ "WHERE\n" +
+ " p.name = :programName\n" +
+ " AND pp.patient_id = (\n" +
+ " SELECT\n" +
+ " person_id\n" +
+ " FROM\n" +
+ " person AS p2\n" +
+ " WHERE\n" +
+ " p2.uuid = :patientUUID\n" +
+ " )\n" +
+ " AND pp.patient_program_id IN (\n" +
+ " SELECT\n" +
+ " patient_program_id\n" +
+ " FROM\n" +
+ " program_attribute_type AS pat\n" +
+ " INNER JOIN patient_program_attribute AS ppa ON pat.program_attribute_type_id = ppa.attribute_type_id\n" +
+ " WHERE\n" +
+ " name = \"ID_Number\"\n" +
+ " AND value_reference = :programEnrollmentId\n" +
+ " )\n" +
+ " AND le.date_started BETWEEN :fromDate AND :toDate ;\n";
+
+ private String sqlGetEncounterIdsForProgramForDiagnosticReports = "SELECT\n" +
+ " res.encounter_id\n" +
+ "FROM\n" +
+ " (\n" +
+ " SELECT\n" +
+ " *\n" +
+ " from(\n" +
+ " SELECT\n" +
+ " o.encounter_id,\n" +
+ " p.uuid AS person_uuid,\n" +
+ " p2.name AS pro_name,\n" +
+ " ppa.value_reference,\n" +
+ " pp.date_enrolled,\n" +
+ " o.concept_id AS obs_concept_id,\n" +
+ " o.value_text,\n" +
+ " o.void_reason AS obs_void_reason\n" +
+ " from\n" +
+ " obs o\n" +
+ " inner join person p on p.person_id = o.person_id\n" +
+ " inner join patient_program pp on pp.patient_id = p.person_id\n" +
+ " inner join program p2 on p2.program_id = pp.program_id\n" +
+ " inner join patient_program_attribute ppa on ppa.patient_program_id = pp.patient_program_id\n" +
+ " where\n" +
+ " encounter_id in (\n" +
+ " SELECT\n" +
+ " encounter_id\n" +
+ " from\n" +
+ " encounter e\n" +
+ " inner join encounter_type as et on et.encounter_type_id = e.encounter_type\n" +
+ " where\n" +
+ " (\n" +
+ " et.name = '" + Config.RADIOLOGY_TYPE.getValue() + "'\n" +
+ " or et.name = '" + Config.PATIENT_DOCUMENT.getValue() + "'\n" +
+ " )\n" +
+ " and visit_id in (\n" +
+ " SELECT\n" +
+ " visit_id\n" +
+ " from\n" +
+ " encounter e2\n" +
+ " inner join episode_encounter ee on e2.encounter_id = ee.encounter_id\n" +
+ " )\n" +
+ " )\n" +
+ " ) as t\n" +
+ " INNER JOIN concept_name AS cn ON cn.concept_id = t.obs_concept_id\n" +
+ " WHERE\n" +
+ " name = '" + Config.DOCUMENT_TYPE.getValue() + "'\n" +
+ " and obs_void_reason is null\n" +
+ " and person_uuid = :patientUUID\n" +
+ " and pro_name = :programName\n" +
+ " and value_reference = :programEnrollmentId\n" +
+ " ) as res\n" +
+ " inner join encounter as e on e.encounter_id = res.encounter_id\n" +
+ " inner join visit as v on v.visit_id = e.visit_id\n" +
+ "where\n" +
+ " date_started between :fromDate\n" +
+ " and :toDate ;\n";
+
+ @Override
+ public List GetEpisodeEncounterIds() {
+
+ Query query = this.sessionFactory.getCurrentSession().createSQLQuery(sqlGetEpisodeEncounterIds);
+ return query.list();
+ }
+
+ @Override
+ public List GetEncountersForVisit(Visit visit, String encounterType) {
+ List episodeEncounters = GetEpisodeEncounterIds();
+ List encounters = visit.getEncounters().stream()
+ .filter(encounter -> !episodeEncounters.contains(encounter.getId()))
+ .filter(encounter -> Objects.equals(encounter.getEncounterType().getName(), encounterType))
+ .collect(Collectors.toList());
+ return encounters;
+ }
+
+ @Override
+ public List GetAllObsForVisit(Visit visit, String encounterType, String conceptName) {
+ List observations = new ArrayList<>();
+ List encounters = GetEncountersForVisit(visit,encounterType);
+ for (Encounter encounter : encounters) {
+ if(conceptName == null)
+ observations.addAll(encounter.getAllObs());
+ observations.addAll(encounter.getAllObs().stream()
+ .filter(o -> Objects.equals(o.getConcept().getName().getName(), conceptName))
+ .collect(Collectors.toList()));
+ }
+ return observations;
+ }
+
+ @Override
+ public List GetOrdersForVisit(Visit visit) {
+ List episodeEncounters = GetEpisodeEncounterIds();
+ List encounters = visit.getEncounters().stream()
+ .filter(encounter -> !episodeEncounters.contains(encounter.getId()))
+ .collect(Collectors.toList());
+ List orderList = new ArrayList<>();
+ for (Encounter encounter: encounters) {
+ orderList.addAll(encounter.getOrders());
+ }
+ return orderList;
+ }
+
+ @Override
+ public List GetEncounterIdsForProgramForPrescriptions(String patientUUID, String program, String programEnrollmentID, Date fromDate, Date toDate) {
+ Query query = this.sessionFactory.getCurrentSession().createSQLQuery(sqlGetEncounterIdsForProgramForPrescriptions);
+ query.setParameter("patientUUID", patientUUID);
+ query.setParameter("programName", program);
+ query.setParameter("programEnrollmentId", programEnrollmentID);
+ query.setParameter("fromDate", fromDate);
+ query.setParameter("toDate", toDate);
+
+ return query.list();
+ }
+
+ @Override
+ public List GetEncounterIdsForProgramForDiagnosticReport(String patientUUID, String program, String programEnrollmentID, Date fromDate, Date toDate) {
+ Query query = this.sessionFactory.getCurrentSession().createSQLQuery(sqlGetEncounterIdsForProgramForDiagnosticReports);
+ query.setParameter("patientUUID", patientUUID);
+ query.setParameter("programName", program);
+ query.setParameter("programEnrollmentId", programEnrollmentID);
+ query.setParameter("fromDate", fromDate);
+ query.setParameter("toDate", toDate);
+
+ return query.list();
+ }
+}
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/impl/ExistingPatientDaoImpl.java b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/ExistingPatientDaoImpl.java
new file mode 100644
index 00000000..e26eb92d
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/ExistingPatientDaoImpl.java
@@ -0,0 +1,74 @@
+package org.bahmni.module.hip.api.dao.impl;
+
+import org.bahmni.module.hip.Config;
+import org.bahmni.module.hip.api.dao.ExistingPatientDao;
+import org.hibernate.Criteria;
+import org.hibernate.Query;
+import org.hibernate.SessionFactory;
+import org.hibernate.criterion.Restrictions;
+import org.openmrs.Patient;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+
+@Repository
+public class ExistingPatientDaoImpl implements ExistingPatientDao {
+
+ private final SessionFactory sessionFactory;
+
+ @Autowired
+ public ExistingPatientDaoImpl(SessionFactory sessionFactory) {
+ this.sessionFactory = sessionFactory;
+ }
+
+
+ @Override
+ public String getPatientUuidWithHealthId(String healthId) {
+ String getPatientWithHealthIdQuery = "SELECT p.uuid FROM person AS p INNER JOIN \n" +
+ "\t\t\t\t patient_identifier AS pi ON p.person_id = pi.patient_id \n" +
+ "\t\t\t\t WHERE identifier = :healthId ;";
+ Query query = this.sessionFactory.openSession().createSQLQuery(getPatientWithHealthIdQuery);
+ query.setParameter("healthId", healthId);
+ List patientUuids = query.list();
+ return patientUuids.size() > 0 ? patientUuids.get(0) : null;
+ }
+
+ @Override
+ public List getPatientsWithPhoneNumber(String phoneNumber) {
+ Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(Patient.class);
+ criteria.createCriteria("attributes", "pa")
+ .add(Restrictions.like("pa.value", "%" + phoneNumber));
+ return criteria.list();
+ }
+
+ @Override
+ public String getPhoneNumber(Integer patientId) {
+ String getPatientPhoneNumberWithPatientIdQuery =
+ " SELECT value FROM person_attribute INNER JOIN person_attribute_type ON" +
+ " person_attribute.person_attribute_type_id = person_attribute_type.person_attribute_type_id " +
+ "where person_id = :patientId and name = \"phoneNumber\";";
+ Query query = this.sessionFactory.openSession().createSQLQuery(getPatientPhoneNumberWithPatientIdQuery);
+ query.setParameter("patientId", patientId);
+ List phoneNumbers = query.list();
+ return phoneNumbers.size() > 0 ? phoneNumbers.get(0) : null;
+ }
+
+ @Override
+ public String getPatientHealthIdWithPatientId(Integer patientId) {
+ String getPatientHealthId = "select\n" +
+ "\tpi.identifier\n" +
+ "from\n" +
+ "\tpatient_identifier as pi\n" +
+ "inner join patient_identifier_type as piy on\n" +
+ "\tpi.identifier_type = piy.patient_identifier_type_id\n" +
+ "where\n" +
+ "\tpi.patient_id = :patientId\n" +
+ "\tand piy.name = :healthId ;";
+ Query query = this.sessionFactory.openSession().createSQLQuery(getPatientHealthId);
+ query.setParameter("patientId", patientId);
+ query.setParameter("healthId", Config.ABHA_ADDRESS.getValue());
+ List healthIds = query.list();
+ return healthIds.size() > 0 ? healthIds.get(0) : null;
+ }
+}
\ No newline at end of file
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/impl/HipVisitDaoImpl.java b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/HipVisitDaoImpl.java
new file mode 100644
index 00000000..127b7fe3
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/HipVisitDaoImpl.java
@@ -0,0 +1,78 @@
+package org.bahmni.module.hip.api.dao.impl;
+
+import org.bahmni.module.hip.api.dao.HipVisitDao;
+import org.hibernate.Query;
+import org.hibernate.SessionFactory;
+import org.openmrs.Patient;
+import org.openmrs.Visit;
+import org.openmrs.api.VisitService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+
+import java.util.Date;
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Repository
+public class HipVisitDaoImpl implements HipVisitDao {
+
+ private SessionFactory sessionFactory;
+ private VisitService visitService;
+
+ @Autowired
+ public HipVisitDaoImpl(SessionFactory sessionFactory, VisitService visitService) {
+ this.sessionFactory = sessionFactory;
+ this.visitService = visitService;
+ }
+
+ private String sqlGetVisitIdsForVisitForLabResults =
+ "select distinct e.visit_id\n" +
+ "from visit as v join visit_type as vt on v.visit_type_id = vt.visit_type_id\n" +
+ "join encounter e on e.visit_id = v.visit_id\n" +
+ "where \n" +
+ " vt.name = :visit \n" +
+ " and v.date_started = :visitStartDate \n" +
+ " and e.visit_id not in (select e1.visit_id from encounter as e1 inner join episode_encounter on episode_encounter.encounter_id = e1.encounter_id) \n" +
+ "and v.patient_id in (select person_id from person as p2 where p2.uuid = :patientUUID) ;" ;
+
+ private String sqlGetVisitIdsForProgramForLabResults = "\n" +
+ "select distinct e.visit_id from encounter as e, patient_program_attribute as ppa, visit as v, patient_program pp, program p where \n" +
+ "p.name = :programName and \n" +
+ "pp.program_id = p.program_id and pp.patient_id = v.patient_id\n" +
+ "and ppa.value_reference = :programEnrollmentId and ppa.attribute_type_id = 1 and\n" +
+ " v.date_started between :fromDate and :toDate and\n" +
+ "e.visit_id in (select e1.visit_id from encounter as e1 inner join episode_encounter on episode_encounter.encounter_id = e1.encounter_id) \n" +
+ "and v.patient_id in (select person_id from person as p2 where p2.uuid = :patientUUID) ;";
+
+
+
+ @Override
+ public List GetVisitIdsForProgramForLabResults(String patientUUID, String program, String programEnrollmentID, Date fromDate, Date toDate) {
+ Query query = this.sessionFactory.getCurrentSession().createSQLQuery(sqlGetVisitIdsForProgramForLabResults);
+ query.setParameter("patientUUID", patientUUID);
+ query.setParameter("programName", program);
+ query.setParameter("programEnrollmentId", programEnrollmentID);
+ query.setParameter("fromDate", fromDate);
+ query.setParameter("toDate", toDate);
+
+ return query.list();
+ }
+
+ @Override
+ public List GetVisitIdsForVisitForLabResults(String patientUUID, String visit, Date visitStartDate) {
+
+ Query query = this.sessionFactory.getCurrentSession().createSQLQuery(sqlGetVisitIdsForVisitForLabResults);
+ query.setParameter("patientUUID", patientUUID);
+ query.setParameter("visit", visit);
+ query.setParameter("visitStartDate",new java.sql.Timestamp(visitStartDate.getTime()));
+ return query.list();
+ }
+
+ @Override
+ public Visit getPatientVisit(Patient patient, String visitType, Date visitStartDate){
+ Visit visit = visitService.getVisitsByPatient(patient)
+ .stream().filter(obj -> obj.getStartDatetime().getTime() == visitStartDate.getTime())
+ .filter(obj -> obj.getVisitType().getName().equals(visitType)).collect(Collectors.toList()).get(0);
+ return visit;
+ }
+}
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/impl/OPConsultDaoImpl.java b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/OPConsultDaoImpl.java
new file mode 100644
index 00000000..505bb612
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/OPConsultDaoImpl.java
@@ -0,0 +1,278 @@
+package org.bahmni.module.hip.api.dao.impl;
+import org.bahmni.module.hip.Config;
+import org.bahmni.module.hip.api.dao.EncounterDao;
+import org.bahmni.module.hip.api.dao.OPConsultDao;
+import org.openmrs.Concept;
+import org.openmrs.ConditionClinicalStatus;
+import org.openmrs.Encounter;
+import org.openmrs.Obs;
+import org.openmrs.Patient;
+import org.openmrs.PatientProgram;
+import org.openmrs.Visit;
+import org.openmrs.api.EncounterService;
+import org.openmrs.api.ObsService;
+import org.openmrs.api.ProgramWorkflowService;
+import org.openmrs.api.context.Context;
+import org.openmrs.module.emrapi.conditionslist.Condition;
+import org.openmrs.module.episodes.Episode;
+import org.openmrs.module.episodes.service.EpisodeService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+
+import org.openmrs.api.ConditionService;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+
+@Repository
+public class OPConsultDaoImpl implements OPConsultDao {
+
+ private final ObsService obsService;
+ private final ConditionService conditionService;
+ private final EncounterService encounterService;
+ private final ProgramWorkflowService programWorkflowService;
+ private final EpisodeService episodeService;
+ private final EncounterDao encounterDao;
+
+
+ @Autowired
+ public OPConsultDaoImpl(ObsService obsService, ConditionService conditionService, EncounterService encounterService, ProgramWorkflowService programWorkflowService, EpisodeService episodeService, EncounterDao encounterDao) {
+ this.obsService = obsService;
+ this.conditionService = conditionService;
+ this.encounterService = encounterService;
+ this.programWorkflowService = programWorkflowService;
+ this.episodeService = episodeService;
+ this.encounterDao = encounterDao;
+ }
+
+
+ @Override
+ public Map> getMedicalHistoryConditions(Visit visit) {
+ final String conditionStatusHistoryOf = "HISTORY_OF";
+ final String conditionStatusActive = "ACTIVE";
+ List encounters = encounterDao.GetEncountersForVisit(visit, Config.CONSULTATION.getValue());
+ if(encounters.size() == 0)
+ return new HashMap<>();
+ List conditions = conditionService.getActiveConditions(visit.getPatient())
+ .stream()
+ .filter(condition -> condition.getClinicalStatus().name().equals(conditionStatusActive) ||
+ condition.getClinicalStatus().name().equals(conditionStatusHistoryOf))
+
+ .collect(Collectors.toList());
+ List emrapiconditions = new ArrayList<>();
+ for(org.openmrs.Condition condition : conditions){
+ org.openmrs.module.emrapi.conditionslist.Condition emrapicondition = convertCoreConditionToEmrapiCondition(condition);
+ emrapiconditions.add(emrapicondition);
+ }
+
+ Map> encounterConditionsMap = new HashMap<>();
+ List nextEncounters = encounterService.getEncountersByPatient(visit.getPatient()).stream().filter(e ->
+ encounters.get(encounters.size()-1).getId() < e.getId()
+ ).collect(Collectors.toList());
+ for(Condition condition : emrapiconditions) {
+ for (Encounter encounter: encounters) {
+ Encounter nextEncounter;
+ Date nextEncounterDate = nextEncounters.size() != 0 ? nextEncounters.get(0).getDateCreated() : new Date();
+ if(encounters.indexOf(encounter) < (encounters.size() - 1)){
+ nextEncounter = encounterService.getEncounter(encounters.get(encounters.indexOf(encounter)+1).getId());
+ nextEncounterDate = nextEncounter.getDateCreated();
+ }
+ if(condition.getDateCreated().equals(encounter.getDateCreated()) || (condition.getDateCreated().before(nextEncounterDate) && condition.getDateCreated().after(encounter.getDateCreated()))){
+ if (encounterConditionsMap.containsKey(encounter)) {
+ encounterConditionsMap.get(encounter).add(condition);
+ } else {
+ encounterConditionsMap.put(encounter, new ArrayList() {{
+ add(condition);
+ }});
+ }
+ }
+ }
+ }
+ return encounterConditionsMap;
+ }
+
+
+ @Override
+ public List getMedicalHistoryDiagnosis(Visit visit) {
+ List medicalHistoryDiagnosisObsMap = encounterDao.GetAllObsForVisit(visit, Config.CONSULTATION.getValue(), Config.CODED_DIAGNOSIS.getValue());
+ medicalHistoryDiagnosisObsMap.addAll(encounterDao.GetAllObsForVisit(visit, Config.CONSULTATION.getValue(), Config.NON_CODED_DIAGNOSIS.getValue()));
+ return medicalHistoryDiagnosisObsMap;
+ }
+
+ @Override
+ public List getProcedures(Visit visit) {
+ List proceduresObsMap = encounterDao.GetAllObsForVisit(visit, Config.CONSULTATION.getValue(), Config.PROCEDURE_NOTES.getValue()).stream()
+ .filter(o -> !o.getVoided())
+ .collect(Collectors.toList());
+
+ return proceduresObsMap;
+ }
+
+ @Override
+ public List getProceduresForProgram(String programName, Date fromDate, Date toDate, Patient patient) {
+ List patientPrograms = programWorkflowService.getPatientPrograms(patient,programWorkflowService.getProgramByName(programName), fromDate, toDate,null,null,false);
+ Set patientProgramSet = new HashSet<>(patientPrograms);
+ List proceduresObsSet= new ArrayList<>();
+ for (PatientProgram patientProgram: patientProgramSet) {
+ Episode episode = episodeService.getEpisodeForPatientProgram(patientProgram);
+ Set encounterSet = episode.getEncounters();
+ for (Encounter encounter : encounterSet) {
+ for (Obs o : encounter.getAllObs()) {
+ if (Objects.equals(o.getEncounter().getEncounterType().getName(), Config.CONSULTATION.getValue())
+ && !o.getVoided()
+ && Objects.equals(o.getConcept().getName().getName(), Config.PROCEDURE_NOTES.getValue())
+ ) {
+ proceduresObsSet.add(o);
+ }
+ }
+ }
+ }
+ return proceduresObsSet;
+ }
+
+ @Override
+ public Map> getMedicalHistoryConditionsForProgram(String programName, Date fromDate, Date toDate, Patient patient) {
+ final String conditionStatusHistoryOf = "HISTORY_OF";
+ final String conditionStatusActive = "ACTIVE";
+ List patientPrograms = programWorkflowService.getPatientPrograms(patient,programWorkflowService.getProgramByName(programName), fromDate, toDate,null,null,false);
+ List encounterList = new ArrayList<>();
+ Set patientProgramSet = new HashSet<>(patientPrograms);
+ for (PatientProgram patientProgram: patientProgramSet) {
+ Episode episode = episodeService.getEpisodeForPatientProgram(patientProgram);
+ encounterList.addAll(episode.getEncounters());
+ }
+ List encounters = encounterList
+ .stream()
+ .filter(encounter -> Objects.equals(encounter.getEncounterType().getName(), "Consultation"))
+ .collect(Collectors.toList());
+ List conditions = conditionService.getActiveConditions(patient)
+ .stream()
+ .filter(condition -> condition.getClinicalStatus().name().equals(conditionStatusActive) ||
+ condition.getClinicalStatus().name().equals(conditionStatusHistoryOf))
+ .collect(Collectors.toList());
+
+ List emrapiconditions = new ArrayList<>();
+ for(org.openmrs.Condition condition : conditions){
+ org.openmrs.module.emrapi.conditionslist.Condition emrapicondition = convertCoreConditionToEmrapiCondition(condition);
+ emrapiconditions.add(emrapicondition);
+ }
+
+ Map> encounterConditionsMap = new HashMap<>();
+
+ for(Condition condition : emrapiconditions){
+ for(Encounter encounter : encounters){
+ Encounter nextEncounter;
+ Date nextEncounterDate = new Date();
+ if(encounters.indexOf(encounter) < (encounters.size() - 1)){
+ nextEncounter = encounterService.getEncounter(encounters.get(encounters.indexOf(encounter)+1).getId());
+ nextEncounterDate = nextEncounter.getDateCreated();
+ }
+ if(condition.getDateCreated().equals(encounter.getDateCreated()) || condition.getDateCreated().after(encounter.getDateCreated()) && condition.getDateCreated().before(nextEncounterDate)) {
+ if(encounterConditionsMap.containsKey(encounter)) {
+ encounterConditionsMap.get(encounter).add(condition);
+ } else {
+ encounterConditionsMap.put(encounter, new ArrayList() {{
+ add(condition);
+ }});
+ }
+ }
+ }
+ }
+ return encounterConditionsMap;
+ }
+
+ @Override
+ public List getMedicalHistoryDiagnosisForProgram(String programName, Date fromDate, Date toDate, Patient patient) {
+ List patientPrograms = programWorkflowService.getPatientPrograms(patient,programWorkflowService.getProgramByName(programName), fromDate, toDate,null,null,false);
+ Set patientProgramSet = new HashSet<>(patientPrograms);
+ List obsSet= new ArrayList<>();
+ for (PatientProgram patientProgram: patientProgramSet) {
+ Episode episode = episodeService.getEpisodeForPatientProgram(patientProgram);
+ Set encounterSet = episode.getEncounters();
+ for (Encounter encounter: encounterSet) {
+ for(Obs o : encounter.getAllObs()){
+ if(Objects.equals(o.getEncounter().getEncounterType().getName(), Config.CONSULTATION.getValue())
+ && Objects.equals(o.getConcept().getName().getName(), Config.CODED_DIAGNOSIS.getValue())
+ && o.getValueCoded() != null
+ && o.getConcept().getName().getLocalePreferred())
+ {
+ obsSet.add(o);
+ }
+ }
+ }
+ }
+ return obsSet;
+ }
+
+ public Map> getPatientDocumentsForVisit(Visit visit){
+ List patientObs = encounterDao.GetAllObsForVisit(visit, Config.PATIENT_DOCUMENT.getValue(),null)
+ .stream().filter(o -> !o.getConcept().getName().getName().equals(Config.DOCUMENT_TYPE.getValue()) ).collect(Collectors.toList());
+ patientObs.addAll(encounterDao.GetAllObsForVisit(visit, Config.CONSULTATION.getValue(), Config.IMAGE.getValue()));
+ patientObs.addAll(encounterDao.GetAllObsForVisit(visit, Config.CONSULTATION.getValue(), Config.PATIENT_VIDEO.getValue()));
+ HashMap> encounterListMap = new HashMap<>();
+ for (Obs obs: patientObs) {
+ Encounter encounter = obs.getEncounter();
+ if(!encounterListMap.containsKey(encounter))
+ encounterListMap.put(encounter, new ArrayList(){{ add(obs); }});
+ else
+ encounterListMap.get(encounter).add(obs);
+ }
+ return encounterListMap;
+ }
+
+ private org.openmrs.module.emrapi.conditionslist.Condition convertCoreConditionToEmrapiCondition(org.openmrs.Condition coreCondition) {
+ org.openmrs.module.emrapi.conditionslist.Condition cListCondition = new org.openmrs.module.emrapi.conditionslist.Condition();
+ Concept concept;
+
+ if (coreCondition.getCondition().getCoded() != null) {
+ concept = Context.getConceptService()
+ .getConceptByUuid(coreCondition.getCondition().getCoded().getUuid());
+
+ if(coreCondition.getCondition().getSpecificName() == null) {
+ coreCondition.getCondition().setSpecificName(coreCondition.getCondition().getCoded().getName(Context.getLocale()));
+ }
+ } else {
+ concept = new Concept();
+ }
+
+ cListCondition.setUuid(coreCondition.getUuid());
+ cListCondition.setConcept(concept);
+ cListCondition.setAdditionalDetail(coreCondition.getAdditionalDetail());
+ cListCondition.setPatient(coreCondition.getPatient());
+ cListCondition.setConditionNonCoded(coreCondition.getCondition().getNonCoded());
+ cListCondition.setOnsetDate(coreCondition.getOnsetDate());
+ cListCondition.setVoided(coreCondition.getVoided());
+ cListCondition.setVoidReason(coreCondition.getVoidReason());
+ cListCondition.setEndDate(coreCondition.getEndDate());
+ cListCondition.setCreator(coreCondition.getCreator());
+ cListCondition.setDateCreated(coreCondition.getDateCreated());
+ cListCondition.setStatus(convertClinicalStatus(coreCondition.getClinicalStatus()));
+ if (coreCondition.getPreviousVersion() != null) {
+ cListCondition.setPreviousCondition(convertCoreConditionToEmrapiCondition(coreCondition.getPreviousVersion()));
+ }
+
+ return cListCondition;
+ }
+
+ private Condition.Status convertClinicalStatus(ConditionClinicalStatus clinicalStatus) {
+ Condition.Status convertedStatus = Condition.Status.ACTIVE;
+
+ if (clinicalStatus == ConditionClinicalStatus.ACTIVE) {
+ convertedStatus = Condition.Status.ACTIVE;
+ } else if (clinicalStatus == ConditionClinicalStatus.INACTIVE) {
+ convertedStatus = Condition.Status.INACTIVE;
+ } else if (clinicalStatus == ConditionClinicalStatus.HISTORY_OF) {
+ convertedStatus = Condition.Status.HISTORY_OF;
+ }
+
+ return convertedStatus;
+ }
+}
diff --git a/api/src/main/java/org/bahmni/module/hip/api/dao/impl/PrescriptionOrderDaoImpl.java b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/PrescriptionOrderDaoImpl.java
new file mode 100644
index 00000000..81e3cf16
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/api/dao/impl/PrescriptionOrderDaoImpl.java
@@ -0,0 +1,60 @@
+package org.bahmni.module.hip.api.dao.impl;
+
+import org.bahmni.module.hip.api.dao.EncounterDao;
+import org.bahmni.module.hip.api.dao.PrescriptionOrderDao;
+import org.hibernate.Criteria;
+import org.hibernate.SessionFactory;
+import org.hibernate.criterion.Restrictions;
+import org.openmrs.DrugOrder;
+import org.openmrs.Order;
+import org.openmrs.OrderType;
+import org.openmrs.Patient;
+import org.openmrs.Visit;
+import org.openmrs.api.OrderService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Repository
+public class PrescriptionOrderDaoImpl implements PrescriptionOrderDao {
+ private SessionFactory sessionFactory;
+ private EncounterDao encounterDao;
+ private final OrderService orderService;
+
+ @Autowired
+ public PrescriptionOrderDaoImpl(SessionFactory sessionFactory, EncounterDao encounterDao, OrderService orderService) {
+ this.sessionFactory = sessionFactory;
+ this.encounterDao = encounterDao;
+ this.orderService = orderService;
+ }
+
+ public List getDrugOrders(Visit visit) {
+ List orderLists = encounterDao.GetOrdersForVisit(visit).stream()
+ .filter(order -> order.getOrderType().getUuid().equals(OrderType.DRUG_ORDER_TYPE_UUID))
+ .map(order -> (DrugOrder) order)
+ .collect(Collectors.toList());
+
+ return orderLists;
+ }
+
+ public List getDrugOrdersForProgram(Patient patient, Date fromDate, Date toDate, OrderType orderType, String program, String programEnrollmentId) {
+
+ Integer [] encounterIds = encounterDao.GetEncounterIdsForProgramForPrescriptions(patient.getUuid(), program, programEnrollmentId, fromDate, toDate).toArray(new Integer[0]);
+ if(encounterIds.length == 0)
+ return new ArrayList< DrugOrder > ();
+ Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(Order.class);
+ criteria.createCriteria("encounter", "e")
+ .createCriteria("visit", "v");
+ criteria.add(Restrictions.eq("patient", patient));
+ criteria.add(Restrictions.eq("orderType", orderType));
+ criteria.add(Restrictions.eq("voided", false));
+ criteria.add(Restrictions.in( "e.encounterId", encounterIds));
+ criteria.add(Restrictions.between("dateCreated", fromDate, toDate));
+ return criteria.list();
+ }
+
+}
diff --git a/api/src/main/java/org/bahmni/module/hip/model/PatientCareContext.java b/api/src/main/java/org/bahmni/module/hip/model/PatientCareContext.java
new file mode 100644
index 00000000..58605fd3
--- /dev/null
+++ b/api/src/main/java/org/bahmni/module/hip/model/PatientCareContext.java
@@ -0,0 +1,22 @@
+package org.bahmni.module.hip.model;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
+@NoArgsConstructor
+@Setter
+@Getter
+@Builder
+@AllArgsConstructor
+public class PatientCareContext {
+ private String careContextType;
+ private String careContextName;
+ private String careContextReference;
+
+ public String getCareContextName() {
+ return careContextName;
+ }
+}
diff --git a/api/src/main/resources/liquibase.xml b/api/src/main/resources/liquibase.xml
index 0fa49c63..3666d543 100644
--- a/api/src/main/resources/liquibase.xml
+++ b/api/src/main/resources/liquibase.xml
@@ -1,40 +1,133 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
+
+
+
+
+
+
+ SELECT COUNT(*) FROM users where username = 'admin'
+
+
+ Populate username for admin user
+
+
+ system_id='admin'
+
+
+
+
+
+ select count(*) from patient_identifier_type where name='ABHA Number'
+
+ Adding ABHA Number Identifier type
+
+ insert into patient_identifier_type( name, description,creator, uuid, uniqueness_behavior, location_behavior, date_created) Select 'ABHA Number','Health Id identifier type',creator,uuid(),'UNIQUE','NOT_USED',now() from users where username='admin';
+
+
+
+
+
+ select count(*) from patient_identifier_type where name='ABHA Number'
+ select count(*) from global_property where property = 'bahmni.extraPatientIdentifierTypes' and property_value LIKE CONCAT('%', (Select uuid from patient_identifier_type where name = 'ABHA Number'))
+
+ Updating global property for ABHA Number
+
+ update global_property set property_value=(SELECT CONCAT(IF(ISNULL(property_value),'',CONCAT(property_value,',')),uuid) from patient_identifier_type where name = 'ABHA Number') where property = 'bahmni.extraPatientIdentifierTypes';
+
+
+
+
+
+ select count(*) from patient_identifier_type where name='ABHA Address'
+
+ Adding ABHA Address Identifier type
+
+ insert into patient_identifier_type( name, description,creator, uuid, uniqueness_behavior, location_behavior, date_created) Select 'ABHA Address','PHR Address identifier type',creator,uuid(),'UNIQUE','NOT_USED',now() from users where username='admin';
+
+
+
+
+
+ select count(*) from patient_identifier_type where name='ABHA Address'
+ select count(*) from global_property where property = 'bahmni.extraPatientIdentifierTypes' and property_value LIKE CONCAT('%', (Select uuid from patient_identifier_type where name = 'ABHA Address'))
+
+ Updating global property for ABHA address
+
+ update global_property set property_value=(SELECT CONCAT(IF(ISNULL(property_value),'',CONCAT(property_value,',')),uuid) from patient_identifier_type where name = 'ABHA Address') where property = 'bahmni.extraPatientIdentifierTypes';
+
+
+
+
+
+
+ select count(*) from global_property where property = 'mrs.genders' and property_value='{"M":"Male", "F":"Female","O":"Other"}'
+
+
+ Adding Undisclosed to gender
+
+ update global_property set property_value='{"M":"Male", "F":"Female","O":"Other", "U":"Undisclosed"}' where property = 'mrs.genders';
+
+
+
+
+
+ select count(*) from global_property where property='abdm.encounterTypesToBeIgnored'
+
+ Adding global property for encounter types to be ignored
+
+ insert into global_property(property,description,property_value,uuid) values('abdm.encounterTypesToBeIgnored','Encounter types to be ignored for hip atomfeeds','ADMISSION,REG,TRANSFER,VALIDATION NOTES',uuid());
+
+
+
+
+
+ select count(*) from global_property where property='abdm.formFieldsToBeIgnored'
+
+ Adding global property for form fields to be ignored
+
+ insert into global_property(property,description,property_value,uuid) values('abdm.formFieldsToBeIgnored','Form fields to be ignored for hip atomfeeds','',uuid());
+
+
+
+
+
+ select count(*) from global_property where property='abdm.conceptsTypesToBeIgnored'
+
+ Adding global property for concept types to be ignored
+
+ insert into global_property(property,description,property_value,uuid) values('abdm.conceptsTypesToBeIgnored','Concept types to be ignored for hip atomfeeds','',uuid());
+
+
+
+
+ select count(*) from privilege where privilege='app:abdm'
+
+ Adding new privilage for ABDM services
+
+ insert into privilege(privilege,description,uuid) values('app:abdm','privilege to view abdm services',uuid());
+
+
+
+
+ select count(*) from role where role='ABDM'
+
+ Adding new role for ABDM services
+
+ insert into role(role,description,uuid) values('ABDM','Will have full access to abdm services',uuid());
+
+
+
+
+ select count(*) from role where role='ABDM'
+ select count(*) from privilege where privilege='app:abdm'
+
+ Providing abdm privilege to ABDM role
+
+ insert into role_privilege(role,privilege) values('ABDM','app:abdm');
+
+
+
+
diff --git a/basicmodule.iml b/basicmodule.iml
new file mode 100644
index 00000000..f409c0ea
--- /dev/null
+++ b/basicmodule.iml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/omod/basicmodule-omod.iml b/omod/basicmodule-omod.iml
new file mode 100644
index 00000000..1a0706ef
--- /dev/null
+++ b/omod/basicmodule-omod.iml
@@ -0,0 +1,121 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/omod/docs/dev-setup.md b/omod/docs/dev-setup.md
new file mode 100644
index 00000000..85165471
--- /dev/null
+++ b/omod/docs/dev-setup.md
@@ -0,0 +1,230 @@
+### Important links for reference:
+- [OPENMRS WIKI](https://wiki.openmrs.org/)
+- [FHIR](https://hl7.org/FHIR/documentation.html)
+- [SBX healthID creation](https://healthidsbx.ndhm.gov.in/)
+- [HIU](https://dev.ndhm.gov.in/hiu#/)
+- [PHR/NDHM Architecture](https://sandbox.ndhm.gov.in/docs/building_blocks)
+- [HIP API Standards](https://sandbox.ndhm.gov.in/swagger/ndhm-hip.yaml)
+
+
+## Services:
+Clone the basic 5 services:
+- [OMOD-HIP](https://github.com/Bahmni-Covid19/openmrs-module-hip.git)
+- [Hip Service](https://github.com/Bahmni-Covid19/hip-service)
+- [BahmniApps](https://github.com/Bahmni-Covid19/openmrs-module-bahmniapps)
+- [Ndhm-React](https://github.com/Bahmni-Covid19/ndhm-react)
+- [Default-config](https://github.com/Bahmni-Covid19/default-config)
+
+Others can be found here : [Bahmni-Covid19](https://github.com/Bahmni-Covid19/)
+
+### Setup Bahmni using Vagrant:
+
+1. Install [Virtualbox](https://www.virtualbox.org/wiki/Downloads)
+2. Install [Vagrant](https://www.vagrantup.com/downloads.html)
+3. Clone the `bahmni-vagrant` repo from github inside a folder called `bahmni`
+
+ ```
+ mkdir bahmni
+ cd bahmni
+ git clone https://github.com/Bahmni/bahmni-vagrant.git
+ cd bahmni-vagrant
+ ```
+
+4. Replace the contents of the `Vagrantfile` in `bahmni-vagrant` with the following:
+
+ ```
+ Vagrant.configure(2) do |config|
+ config.vm.box = "bento/centos-7.6"
+ config.vm.box_check_update = true
+ config.ssh.insert_key = false
+ config.vm.network "private_network", ip: "192.168.33.10"
+ config.vm.network "forwarded_port", guest: 3306, host: 3306
+ config.vm.network "forwarded_port", guest: 8000, host: 8000
+ config.vm.network "forwarded_port", guest: 80, host: 80
+
+ config.vm.synced_folder "..", "/bahmni", :owner => "vagrant"
+ config.vm.provider "virtualbox" do |v|
+ v.customize ["modifyvm", :id, "--memory", 3092, "--cpus", 2, "--name", "Bahmni-RPM"]
+ end
+ end
+ ```
+
+5. Make vagrant up and open vagrant
+
+ ```
+ vagrant up && vagrant ssh
+ ```
+
+6. Now, inside the vagrant box set up a local Bahmni instance by using this document
+(Note: install the version 0.92 provided in the [link](https://bahmni.atlassian.net/wiki/spaces/BAH/pages/33128505/Install+Bahmni+on+CentOS))
+
+7. Open [bahmni-emr-login](https://192.168.33.10/bahmni/home/index.html#/login), you should see bahmni up and running.
+ - Username: superman
+ - Password: Admin123
+
+### Prerequisites for OMOD-HIP:
+
+- Download following jars and fhir
+ - [jackson-core-2.10.0.jar](https://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-core/2.10.0/jackson-core-2.10.0.jar)
+ - [jackson-annotations-2.10.0.jar](https://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-annotations/2.10.0/jackson-annotations-2.10.0.jar)
+ - [jackson-databind-2.10.0.jar](https://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.10.0/jackson-databind-2.10.0.jar)
+ - [fhir2-omod-1.0.0-SNAPSHOT.omod](https://drive.google.com/drive/folders/180cdYOWqBU5vffZnzdRy5PsyEPvn3Ti5)
+- Copy all files to `bahmni` folder
+- Open vagrant and paste the files
+
+ ```
+ cd bahmni-vagrant
+ vagrant ssh
+ cp /bahmni/jackson-core-2.10.0.jar /opt/openmrs/openmrs/WEB-INF/lib/
+ cp /bahmni/jackson-annotations-2.10.0.jar /opt/openmrs/openmrs/WEB-INF/lib/
+ cp /bahmni/jackson-databind-2.10.0.jar /opt/openmrs/openmrs/WEB-INF/lib/
+ cp /bahmni/fhir2-omod-1.0.0-SNAPSHOT.omod /opt/openmrs/modules/
+ ```
+- Restart openmrs `systemctl restart openmrs`
+
+- Ensure that the module is successfully loaded by navigating through [openmrs](http://192.168.33.10/openmrs)
+ - username: superman
+ - password: Admin123
+ - Click on `Administration` -> `Manage Modules` under `Modules`
+- You can also check the log file for any errors/exceptions: `vi /opt/openmrs/openmrs.log`
+ in vagrant.
+
+### Setting up the OMOD-HIP
+
+(Make sure `bahmni` folder is created and `bahmni vagrant` is setup inside `bahmni`)
+1. Clone OMOD-HIP
+
+ ```
+ cd bahmni
+ git clone https://github.com/Bahmni-Covid19/openmrs-module-hip.git
+ ```
+
+2. Run the steps to build .omod file
+
+ ```
+ cd openmrs-module-hip
+ mvn clean install
+ ```
+
+3. Move the newly build omod to vagrant and overwrite it and restart OMOD with the new omod
+
+ ```
+ vagrant ssh
+ sudo su
+ cp /bahmni/openmrs-module-hip/omod/target/hipmodule-omod-0.1-SNAPSHOT.omod /opt/openmrs/modules/
+ systemctl restart openmrs
+ ```
+
+4. (Optional) Check log file to see if any errors occurred inside vagrant
+
+ ```
+ vi /opt/openmrs/openmrs.log
+
+ ```
+### Installations:
+
+Please make sure following are done before proceeding forward
+- [Yarn](https://classic.yarnpkg.com/en/)
+- [Node.js(v10.11.0)](https://classic.yarnpkg.com/en/)
+- [Maven](https://maven.apache.org/)
+- [Ruby v2.1 (or above)](https://www.ruby-lang.org/en/documentation/installation/)
+- [Compass](http://compass-style.org/install/) to compile the SCSS files.
+- Install Firefox to run tests for `bahmni-apps`
+
+### Setting up Bahmni-Apps
+
+1. Clone bahmni-apps
+
+ ```
+ cd bahmni
+ git clone https://github.com/Bahmni-Covid19/openmrs-module-bahmniapps.git
+ cd openmrs-module-bahmniapps
+ ```
+
+2. Change branch to stream1/master (which is the current working master for Hip stream)
+
+ ```
+ git checkout stream1/master
+ ```
+
+3. Run following to build the project
+ ```
+ cd /ui
+ yarn install
+ yarn default
+ ```
+### Setting up ndhm-react (verify-btn pop-up)
+
+1. Clone ndhm-react
+
+ ```
+ cd bahmni
+ git clone https://github.com/Bahmni-Covid19/ndhm-react.git
+ cd ndhm-react
+ ```
+
+2. In main branch run following to build project
+
+ ```
+ yarn install
+ yarn build
+ ```
+
+### Setting up default-config
+
+1. Clone default-config
+
+ ```
+ cd bahmni
+ git clone https://github.com/Bahmni-Covid19/default-config.git
+ cd default-config
+ ```
+2. Change branch to stream1/master (which is the current working master for Hip stream)
+
+ ```
+ git checkout stream1/master
+ ```
+3. Browse to this file `openmrs/apps/registration/extension.json` and change host to localhost in `NDHMIdentifierLookup`,`extensionParams`
+
+ ```
+ "hipUrl" : "http://localhost:9052",
+ "bahmniUrl": "https://192.168.33.10/openmrs/ws/rest/v1/hip"
+ ```
+
+## Linking the repos inside your local vagrant
+
+1. Go inside local vagrant
+
+ ```
+ cd bahmni-vagrant
+ vagrant ssh
+ cd /var/www/
+ ll
+ ```
+ you will see bahmniapps and bahmni_config being linked already to older versions, we will unlink and link to our local repos
+2. Unlink old links
+
+ ```
+ unlink bahmniapps
+ unlink bahmni_config
+ ```
+
+3. Link new build repositories
+
+ ```
+ ln -s /bahmni/ndhm-react/build ndhm
+ ln -s /bahmni/default-config bahmni_config
+ ln -s /bahmni/openmrs-module-bahmniapps/ui/app bahmniapps
+ ```
+
+4. Change config setting for `ndhm` redirection
+
+ ```
+ vi /etc/httpd/conf.d/ssl.conf
+ ```
+
+5. Search for Alias by typing `/Alias` and after this line `Alias /implementer-interface /var/www/implementer_interface` add
+
+ ```
+ Alias /ndhm /var/www/ndhm
+ ```
diff --git a/omod/pom.xml b/omod/pom.xml
index 184afcfa..fd1dcd6f 100644
--- a/omod/pom.xml
+++ b/omod/pom.xml
@@ -1,43 +1,215 @@
- 4.0.0
-
- org.openmrs.module
- basicmodule
- 0.1-SNAPSHOT
-
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ 4.0.0
+
+ org.bahmni.module
+ hipmodule
+ 0.1-SNAPSHOT
+
- basicmodule-omod
- jar
- Basic Module OMOD
- OpenMRS module project for Basic Module
+ hipmodule-omod
+ jar
+ HIP Module OMOD
+ OpenMRS module project for HIP Module
+
+
+ repo.mybahmni.org
+ bahmni-artifactory-snapshots
+ https://oss.sonatype.org/content/repositories/snapshots
+
+ always
+
+
+
+ repo.mybahmni.org-release
+ bahmni-artifactory-release
+ https://oss.sonatype.org/content/repositories/release
+
+
-
+
+
+ org.openmrs.api
+ openmrs-api
+ ${openMRSVersion}
+ jar
+ provided
+
+
+ javax.servlet
+ servlet-api
+
+
+
+
org.openmrs.module
- basicmodule-api
- ${project.parent.version}
-
-
- org.openmrs.web
- openmrs-web
- provided
-
-
-
-
- ${project.parent.artifactId}-${project.parent.version}
-
-
-
- org.openmrs.maven.plugins
- maven-openmrs-plugin
-
-
- org.apache.maven.plugins
- maven-dependency-plugin
-
-
-
+ episodes-api
+ 1.0-SNAPSHOT
+ provided
+
+
+ org.bahmni.module
+ hipmodule-api
+ 0.1-SNAPSHOT
+
+
+ org.openmrs.web
+ openmrs-web
+ provided
+ ${openMRSVersion}
+
+
+ org.openmrs.module
+ webservices.rest-omod
+ provided
+
+
+ org.openmrs.module
+ fhir2-omod
+ ${fhir2ModuleVersion}
+ provided
+
+
+
+ org.bahmni.module
+ bahmnicore-api
+ 0.94-SNAPSHOT
+ provided
+
+
+ rome
+ rome
+
+
+
+
+
+ org.bahmni.module
+ bahmni-commons-api
+
+
+
+ org.projectlombok
+ lombok
+ 1.18.10
+ provided
+
+
+
+ javax.servlet
+ javax.servlet-api
+ 3.0.1
+ provided
+
+
+
+
+
+
+
+
+ javax.xml.bind
+ jaxb-api
+ 2.3.0
+ test
+
+
+ com.fasterxml.jackson.core
+ jackson-core
+ 2.10.1
+ test
+
+
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ 2.1.10.RELEASE
+
+
+ org.springframework.boot
+ spring-boot-starter-logging
+
+
+ test
+
+
+ javax.xml.bind
+ jaxb-api
+ 2.3.0
+ test
+
+
+ org.openmrs.module
+ emrapi-api
+ provided
+
+
+ org.openmrs.module
+ emrapi-omod
+ provided
+
+
+
+
+ ${project.artifactId}-${project.version}
+
+
+
+ org.openmrs.maven.plugins
+ maven-openmrs-plugin
+ true
+
+
+ init
+ initialize
+
+ initialize-module
+
+
+
+ pack
+ package
+
+ package-module
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-dependency-plugin
+
+
+ Expand moduleApplicationContext and messages
+
+ unpack-dependencies
+
+ generate-resources
+
+ ${project.parent.groupId}
+ ${project.parent.artifactId}-api
+ true
+ **/*
+ ${project.build.directory}/classes
+
+
+
+ org.apache.maven.pluginsmaven-compiler-plugin1111
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+ 8
+ 8
+
+
+
+
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/client/ClientError.java b/omod/src/main/java/org/bahmni/module/hip/web/client/ClientError.java
new file mode 100644
index 00000000..5e09bbe0
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/client/ClientError.java
@@ -0,0 +1,54 @@
+package org.bahmni.module.hip.web.client;
+
+import org.bahmni.module.hip.web.client.model.ErrorCode;
+import lombok.Getter;
+import lombok.ToString;
+
+import java.util.HashMap;
+
+@Getter
+@ToString
+public class ClientError {
+ private static HashMap errorMap = new HashMap<>();
+ private Integer code;
+ private String message;
+
+ public ClientError(Integer code, String message) {
+ this.code = code;
+ this.message = message;
+ }
+
+ public static ClientError invalidPatientId() {
+ return new ClientError(ErrorCode.BAD_REQUEST.getValue(), "Invalid patient id");
+ }
+
+ public static ClientError noPatientFound() {
+ return new ClientError(ErrorCode.PATIENT_ID_NOT_FOUND.getValue(), "No patient found");
+ }
+
+ public static ClientError noPatientIdProvided() {
+ return new ClientError(ErrorCode.NO_PATIENT_ID_SUPPLIED.getValue(), "No Patient ID supplied");
+ }
+ public static ClientError noVisitTypeProvided(){
+ return new ClientError(ErrorCode.NO_VISIT_TYPE_SUPPLIED.getValue(),"No Visit type is supplied");
+ }
+ public static ClientError noVisitStartDateProvided(){
+ return new ClientError(ErrorCode.NO_VISIT_START_DATE_SUPPLIED.getValue(),"No Visit start date is supplied");
+ }
+ public static ClientError invalidVisitType(){
+ return new ClientError(ErrorCode.INVALID_VISIT_TYPE.getValue(),"Visit Type is invalid");
+ }
+ public static ClientError noProgramNameProvided(){
+ return new ClientError(ErrorCode.NO_PROGRAM_NAME_SUPPLIED.getValue(),"No program name supplied");
+ }
+ public static ClientError noProgramIDProvided(){
+ return new ClientError(ErrorCode.NO_PROGRAM_ID_SUPPLIED.getValue(),"No patient's program enrollment id supplied");
+ }
+ public static ClientError invalidProgramName(){
+ return new ClientError(ErrorCode.INVALID_PROGRAM_NAME.getValue(),"Program specified does not exist");
+ }
+ public static ClientError patientIdentifierNotFound(){
+ return new ClientError(ErrorCode.PATIENT_IDENTIFIER_NOT_FOUND.getValue(),"Patient identifier not found");
+ }
+
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/client/model/Error.java b/omod/src/main/java/org/bahmni/module/hip/web/client/model/Error.java
new file mode 100644
index 00000000..6a716d64
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/client/model/Error.java
@@ -0,0 +1,19 @@
+package org.bahmni.module.hip.web.client.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+@AllArgsConstructor
+@Builder
+@NoArgsConstructor
+@Data
+public class Error {
+ private ErrorCode code;
+ private String message;
+}
+
+
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/client/model/ErrorCode.java b/omod/src/main/java/org/bahmni/module/hip/web/client/model/ErrorCode.java
new file mode 100644
index 00000000..a218a97e
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/client/model/ErrorCode.java
@@ -0,0 +1,39 @@
+package org.bahmni.module.hip.web.client.model;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+
+import java.util.Arrays;
+
+public enum ErrorCode {
+ UNKNOWN_ERROR_OCCURRED(1500),
+ BAD_REQUEST(1501),
+ PATIENT_ID_NOT_FOUND(1502),
+ NO_PATIENT_ID_SUPPLIED (1503),
+ NO_VISIT_TYPE_SUPPLIED(1504),
+ INVALID_VISIT_TYPE(1505),
+ NO_PROGRAM_NAME_SUPPLIED (1506),
+ NO_PROGRAM_ID_SUPPLIED(1507),
+ INVALID_PROGRAM_NAME(1508),
+ PATIENT_IDENTIFIER_NOT_FOUND(1509),
+ NO_VISIT_START_DATE_SUPPLIED(1510);
+ private final int value;
+
+ ErrorCode(int val) {
+ value = val;
+ }
+
+ // Adding @JsonValue annotation that tells the 'value' to be of integer type while de-serializing.
+ @JsonValue
+ public int getValue() {
+ return value;
+ }
+
+ @JsonCreator
+ public static ErrorCode getNameByValue(int value) {
+ return Arrays.stream(ErrorCode.values())
+ .filter(errorCode -> errorCode.value == value)
+ .findAny()
+ .orElse(ErrorCode.UNKNOWN_ERROR_OCCURRED);
+ }
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/client/model/ErrorRepresentation.java b/omod/src/main/java/org/bahmni/module/hip/web/client/model/ErrorRepresentation.java
new file mode 100644
index 00000000..14bcf144
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/client/model/ErrorRepresentation.java
@@ -0,0 +1,16 @@
+package org.bahmni.module.hip.web.client.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+@AllArgsConstructor
+@Builder
+@NoArgsConstructor
+@Data
+public class ErrorRepresentation {
+ private Error error;
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/client/model/RespError.java b/omod/src/main/java/org/bahmni/module/hip/web/client/model/RespError.java
new file mode 100644
index 00000000..0b2ea3bd
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/client/model/RespError.java
@@ -0,0 +1,19 @@
+package org.bahmni.module.hip.web.client.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import java.io.Serializable;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+@AllArgsConstructor
+@Builder
+@NoArgsConstructor
+@Data
+public class RespError implements Serializable {
+ private Integer code;
+ private String message;
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/client/model/Status.java b/omod/src/main/java/org/bahmni/module/hip/web/client/model/Status.java
new file mode 100644
index 00000000..256f4b2e
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/client/model/Status.java
@@ -0,0 +1,7 @@
+package org.bahmni.module.hip.web.client.model;
+
+public enum Status {
+ DEACTIVATED,
+ REACTIVATED,
+ DELETED
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/config/OpenMRSConfig.java b/omod/src/main/java/org/bahmni/module/hip/web/config/OpenMRSConfig.java
new file mode 100644
index 00000000..96186288
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/config/OpenMRSConfig.java
@@ -0,0 +1,21 @@
+package org.bahmni.module.hip.web.config;
+
+import org.openmrs.api.OrderService;
+import org.openmrs.api.PatientService;
+import org.openmrs.api.context.Context;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class OpenMRSConfig {
+
+ @Bean
+ public PatientService patientService() {
+ return Context.getPatientService();
+ }
+
+ @Bean
+ public OrderService orderService() {
+ return Context.getOrderService();
+ }
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/controller/BundledMedicationRequestController.java b/omod/src/main/java/org/bahmni/module/hip/web/controller/BundledMedicationRequestController.java
new file mode 100644
index 00000000..d97f9ce4
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/controller/BundledMedicationRequestController.java
@@ -0,0 +1,54 @@
+package org.bahmni.module.hip.web.controller;
+
+import org.bahmni.module.hip.web.client.ClientError;
+import org.bahmni.module.hip.web.service.BundleMedicationRequestService;
+import org.bahmni.module.hip.web.service.ValidationService;
+import org.hl7.fhir.r4.model.Bundle;
+import org.openmrs.module.webservices.rest.web.RestConstants;
+import org.openmrs.module.webservices.rest.web.v1_0.controller.BaseRestController;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
+
+import static org.bahmni.module.hip.web.model.serializers.BundleSerializer.serializeBundle;
+
+@Validated
+@RestController
+@RequestMapping(value = "/rest/" + RestConstants.VERSION_1 + "/hip")
+public class BundledMedicationRequestController extends BaseRestController {
+ private final BundleMedicationRequestService bundledMedicationRequestService;
+ private final ValidationService validationService;
+
+ @Autowired
+ public BundledMedicationRequestController(BundleMedicationRequestService bundledMedicationRequestService, ValidationService validationService) {
+ this.bundledMedicationRequestService = bundledMedicationRequestService;
+ this.validationService = validationService;
+ }
+
+ @RequestMapping(method = RequestMethod.GET, value = "/medication", produces = MediaType.APPLICATION_JSON_VALUE)
+ public @ResponseBody
+ ResponseEntity> getBundledMedicationRequestFor(@RequestParam(required = false) String patientId,
+ @RequestParam(required = false) String visitType) {
+
+ if (patientId == null || patientId.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noPatientIdProvided());
+ if (visitType == null || visitType.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noVisitTypeProvided());
+ if (!validationService.isValidVisit(visitType))
+ return ResponseEntity.badRequest().body(ClientError.invalidVisitType());
+ if (!validationService.isValidPatient(patientId))
+ return ResponseEntity.badRequest().body(ClientError.invalidPatientId());
+ Bundle bundle = bundledMedicationRequestService.bundleMedicationRequestsFor(patientId, visitType);
+ return ResponseEntity.ok()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .body(serializeBundle(bundle));
+ }
+
+}
\ No newline at end of file
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/controller/CareContextController.java b/omod/src/main/java/org/bahmni/module/hip/web/controller/CareContextController.java
new file mode 100644
index 00000000..88656f49
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/controller/CareContextController.java
@@ -0,0 +1,62 @@
+package org.bahmni.module.hip.web.controller;
+
+import org.bahmni.module.hip.web.client.ClientError;
+import org.bahmni.module.hip.web.service.CareContextService;
+import org.bahmni.module.hip.web.service.ValidationService;
+import org.openmrs.module.webservices.rest.web.RestConstants;
+import org.openmrs.module.webservices.rest.web.v1_0.controller.BaseRestController;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
+
+@RequestMapping(value = "/rest/" + RestConstants.VERSION_1 + "/hip")
+@RestController
+public class CareContextController extends BaseRestController {
+ private final CareContextService careContextService;
+ private final ValidationService validationService;
+
+ @Autowired
+ public CareContextController(CareContextService careContextService, ValidationService validationService) {
+ this.careContextService = careContextService;
+ this.validationService = validationService;
+ }
+
+ @RequestMapping(method = RequestMethod.GET, value = "/careContext", produces = MediaType.APPLICATION_JSON_VALUE)
+ public @ResponseBody
+ ResponseEntity> getCareContextForPatient(@RequestParam(required = false) String patientUuid) {
+ if (patientUuid == null || patientUuid.trim().isEmpty()) {
+ return ResponseEntity.badRequest().body(ClientError.noPatientIdProvided());
+ }
+ if (!validationService.isValidPatient(patientUuid))
+ return ResponseEntity.badRequest().body(ClientError.invalidPatientId());
+ Object careContextForPatient = careContextService.careContextForPatient(patientUuid);
+ if (careContextForPatient.equals(false)) {
+ return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ClientError.noPatientFound());
+ }
+ return ResponseEntity.ok(careContextForPatient);
+ }
+
+ @RequestMapping(method = RequestMethod.GET, value = "/careContext/new", produces = MediaType.APPLICATION_JSON_VALUE)
+ public @ResponseBody
+ ResponseEntity> getNewCareContextForPatient(@RequestParam(required = false) String patientUuid) {
+ if (patientUuid == null || patientUuid.trim().isEmpty()) {
+ return ResponseEntity.badRequest().body(ClientError.noPatientIdProvided());
+ }
+ if (!validationService.isValidPatient(patientUuid))
+ return ResponseEntity.badRequest().body(ClientError.invalidPatientId());
+ Object careContextForPatient = careContextService.newCareContextsForPatient(patientUuid);
+ if (careContextForPatient.equals(false)) {
+ return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ClientError.noPatientFound());
+ }
+ return ResponseEntity.ok()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .body(careContextForPatient);
+ }
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/controller/DiagnosticReportController.java b/omod/src/main/java/org/bahmni/module/hip/web/controller/DiagnosticReportController.java
new file mode 100644
index 00000000..dac59373
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/controller/DiagnosticReportController.java
@@ -0,0 +1,105 @@
+package org.bahmni.module.hip.web.controller;
+
+import org.bahmni.module.hip.web.client.ClientError;
+import org.bahmni.module.hip.web.model.BundledDiagnosticReportResponse;
+import org.bahmni.module.hip.web.model.DateRange;
+import org.bahmni.module.hip.web.model.DiagnosticReportBundle;
+import org.bahmni.module.hip.web.service.DiagnosticReportService;
+import org.bahmni.module.hip.web.service.ValidationService;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.openmrs.module.webservices.rest.web.RestConstants;
+import org.openmrs.module.webservices.rest.web.v1_0.controller.BaseRestController;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.bahmni.module.hip.web.utils.DateUtils.isDateBetweenDateRange;
+import static org.bahmni.module.hip.web.utils.DateUtils.parseDate;
+import static org.bahmni.module.hip.web.utils.DateUtils.parseDateTime;
+
+@RequestMapping(value = "/rest/" + RestConstants.VERSION_1 + "/hip/diagnosticReports")
+@RestController
+public class DiagnosticReportController extends BaseRestController {
+ private final DiagnosticReportService diagnosticReportService;
+ private final ValidationService validationService;
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @Autowired
+ public DiagnosticReportController(DiagnosticReportService diagnosticReportService, ValidationService validationService) {
+ this.diagnosticReportService = diagnosticReportService;
+ this.validationService = validationService;
+ }
+
+ @RequestMapping(method = RequestMethod.GET, value = "/visit", produces = MediaType.APPLICATION_JSON_VALUE)
+ public @ResponseBody
+ ResponseEntity> getDiagnosticReportsForVisit(@RequestParam String patientId,
+ @RequestParam String visitType,
+ @RequestParam String visitStartDate,
+ @RequestParam String fromDate,
+ @RequestParam String toDate) throws ParseException, IOException {
+ if (patientId == null || patientId.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noPatientIdProvided());
+ if (visitType == null || visitType.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noVisitTypeProvided());
+ if (visitStartDate == null || visitStartDate.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noVisitTypeProvided());
+ if (!validationService.isValidVisit(visitType))
+ return ResponseEntity.badRequest().body(ClientError.invalidVisitType());
+ if (!validationService.isValidPatient(patientId))
+ return ResponseEntity.badRequest().body(ClientError.invalidPatientId());
+
+ List diagnosticReportBundle = new ArrayList<>();
+ if(isDateBetweenDateRange(visitStartDate,fromDate,toDate)) {
+ diagnosticReportBundle = diagnosticReportService.getDiagnosticReportsForVisit(patientId, visitType, parseDateTime(visitStartDate));
+
+ diagnosticReportBundle.addAll(diagnosticReportService.getLabResultsForVisits(patientId, visitType, parseDateTime(visitStartDate)));
+ }
+ return ResponseEntity.ok()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .body(mapper.writeValueAsString(new BundledDiagnosticReportResponse(diagnosticReportBundle)));
+ }
+
+ @RequestMapping(method = RequestMethod.GET, value = "/program", produces = MediaType.APPLICATION_JSON_VALUE)
+ public @ResponseBody
+ ResponseEntity> getDiagnosticReportsForProgram(
+ @RequestParam String patientId,
+ @RequestParam String fromDate,
+ @RequestParam String toDate,
+ @RequestParam String programName,
+ @RequestParam String programEnrollmentId
+ ) throws ParseException, IOException {
+ programName = URLDecoder.decode(programName, "UTF-8");
+ if (patientId == null || patientId.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noPatientIdProvided());
+ if (programName == null || programName.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noVisitTypeProvided());
+ if (!validationService.isValidProgram(programName))
+ return ResponseEntity.badRequest().body(ClientError.invalidProgramName());
+ if (!validationService.isValidPatient(patientId))
+ return ResponseEntity.badRequest().body(ClientError.invalidPatientId());
+ List diagnosticReportBundles =
+ diagnosticReportService.getDiagnosticReportsForProgram(patientId, new DateRange(parseDate(fromDate),
+ parseDate(toDate)), programName, programEnrollmentId);
+
+ diagnosticReportBundles.addAll(
+ diagnosticReportService.getLabResultsForPrograms(patientId, new DateRange(parseDate(fromDate),
+ parseDate(toDate)), programName, programEnrollmentId) );
+
+ return ResponseEntity.ok()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .body(mapper.writeValueAsString(new BundledDiagnosticReportResponse(diagnosticReportBundles)));
+ }
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/controller/DischargeSummaryController.java b/omod/src/main/java/org/bahmni/module/hip/web/controller/DischargeSummaryController.java
new file mode 100644
index 00000000..846f6fb2
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/controller/DischargeSummaryController.java
@@ -0,0 +1,106 @@
+package org.bahmni.module.hip.web.controller;
+
+import org.bahmni.module.hip.web.client.ClientError;
+import org.bahmni.module.hip.web.model.BundledDischargeSummaryResponse;
+import org.bahmni.module.hip.web.model.DateRange;
+import org.bahmni.module.hip.web.model.DischargeSummaryBundle;
+import org.bahmni.module.hip.web.service.DischargeSummaryService;
+import org.bahmni.module.hip.web.service.ValidationService;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.openmrs.module.webservices.rest.web.RestConstants;
+import org.openmrs.module.webservices.rest.web.v1_0.controller.BaseRestController;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RequestParam;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.bahmni.module.hip.web.utils.DateUtils.isDateBetweenDateRange;
+import static org.bahmni.module.hip.web.utils.DateUtils.parseDate;
+import static org.bahmni.module.hip.web.utils.DateUtils.parseDateTime;
+
+@RequestMapping(value = "/rest/" + RestConstants.VERSION_1 + "/hip/dischargeSummary")
+@RestController
+public class DischargeSummaryController extends BaseRestController {
+
+ private final ValidationService validationService;
+ private final DischargeSummaryService dischargeSummaryService;
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @Autowired
+ public DischargeSummaryController(ValidationService validationService, DischargeSummaryService dischargeSummaryService) {
+ this.validationService = validationService;
+ this.dischargeSummaryService = dischargeSummaryService;
+ }
+
+ @RequestMapping(method = RequestMethod.GET, value = "/visit", produces = MediaType.APPLICATION_JSON_VALUE)
+ public @ResponseBody
+ ResponseEntity> getDischargeSummaryForVisit(@RequestParam String patientId,
+ @RequestParam String visitType,
+ @RequestParam String visitStartDate,
+ @RequestParam String fromDate,
+ @RequestParam String toDate) throws ParseException, IOException {
+
+ if (patientId == null || patientId.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noPatientIdProvided());
+ if (visitType == null || visitType.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noVisitTypeProvided());
+ if (visitStartDate == null || visitStartDate.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noVisitTypeProvided());
+ if (!validationService.isValidVisit(visitType))
+ return ResponseEntity.badRequest().body(ClientError.invalidVisitType());
+ if (!validationService.isValidPatient(patientId))
+ return ResponseEntity.badRequest().body(ClientError.invalidPatientId());
+
+ List dischargeSummaryBundle = new ArrayList<>();
+ if(isDateBetweenDateRange(visitStartDate,fromDate,toDate)) {
+ dischargeSummaryBundle = dischargeSummaryService.getDischargeSummaryForVisit(patientId, visitType, parseDateTime(visitStartDate));
+ }
+ return ResponseEntity.ok()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .body(mapper.writeValueAsString(new BundledDischargeSummaryResponse(dischargeSummaryBundle)));
+ }
+
+ @RequestMapping(method = RequestMethod.GET, value = "/program", produces = MediaType.APPLICATION_JSON_VALUE)
+ public @ResponseBody
+ ResponseEntity> getDischargeSummaryForProgram(
+ @RequestParam String patientId,
+ @RequestParam String fromDate,
+ @RequestParam String toDate,
+ @RequestParam String programName,
+ @RequestParam String programEnrollmentId
+ ) throws ParseException, IOException {
+ programName = URLDecoder.decode(programName, "UTF-8");
+ if (patientId == null || patientId.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noPatientIdProvided());
+ if (programName == null || programName.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noProgramNameProvided());
+ if (!validationService.isValidProgram(programName))
+ return ResponseEntity.badRequest().body(ClientError.invalidProgramName());
+ if (!validationService.isValidPatient(patientId))
+ return ResponseEntity.badRequest().body(ClientError.invalidPatientId());
+ List dischargeSummaryBundle =
+ dischargeSummaryService.getDischargeSummaryForProgram(patientId, new DateRange(parseDate(fromDate), parseDate(toDate)), programName, programEnrollmentId);
+ return ResponseEntity.ok()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .body(mapper.writeValueAsString(new BundledDischargeSummaryResponse(dischargeSummaryBundle)));
+ }
+}
+
+
+
+
+
+
+
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/controller/HipControllerAdvice.java b/omod/src/main/java/org/bahmni/module/hip/web/controller/HipControllerAdvice.java
new file mode 100644
index 00000000..317d0bca
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/controller/HipControllerAdvice.java
@@ -0,0 +1,48 @@
+package org.bahmni.module.hip.web.controller;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.bahmni.module.hip.web.exception.RequestParameterMissingException;
+import org.bahmni.module.hip.web.model.ErrorResponse;
+import org.openmrs.module.webservices.rest.web.v1_0.controller.BaseRestController;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.ResponseStatus;
+
+@ControllerAdvice
+public class HipControllerAdvice extends BaseRestController {
+
+ private static Logger logger = LogManager.getLogger(HipControllerAdvice.class);
+
+ @ResponseStatus(HttpStatus.BAD_REQUEST)
+ @ExceptionHandler(RequestParameterMissingException.class)
+ public @ResponseBody
+ ErrorResponse missingRequestParameter(Exception ex) {
+ return new ErrorResponse(ex.getMessage());
+ }
+
+ @ResponseBody
+ @ResponseStatus(HttpStatus.BAD_REQUEST)
+ @ExceptionHandler(IllegalArgumentException.class)
+ public String illegalArgumentException(Exception ex) {
+ return ex.getMessage();
+ }
+
+// @ResponseBody
+// @ResponseStatus(HttpStatus.BAD_REQUEST)
+// @ExceptionHandler(Exception.class)
+// public ErrorResponse genericException(Exception ex) {
+// logger.error(ex.getMessage(), ex);
+// return new ErrorResponse(ex.getMessage());
+// }
+
+ @ResponseBody
+ @ResponseStatus(HttpStatus.BAD_REQUEST)
+ @ExceptionHandler(NumberFormatException.class)
+ public ErrorResponse numberFormatException(Exception ex) {
+ logger.error(ex.getMessage(), ex);
+ return new ErrorResponse(ex.getMessage());
+ }
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/controller/OPConsultController.java b/omod/src/main/java/org/bahmni/module/hip/web/controller/OPConsultController.java
new file mode 100644
index 00000000..269e8635
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/controller/OPConsultController.java
@@ -0,0 +1,94 @@
+package org.bahmni.module.hip.web.controller;
+
+import org.bahmni.module.hip.web.client.ClientError;
+import org.bahmni.module.hip.web.model.BundledOPConsultResponse;
+import org.bahmni.module.hip.web.model.DateRange;
+import org.bahmni.module.hip.web.model.OPConsultBundle;
+import org.bahmni.module.hip.web.service.OPConsultService;
+import org.bahmni.module.hip.web.service.ValidationService;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.openmrs.module.webservices.rest.web.RestConstants;
+import org.openmrs.module.webservices.rest.web.v1_0.controller.BaseRestController;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.bahmni.module.hip.web.utils.DateUtils.isDateBetweenDateRange;
+import static org.bahmni.module.hip.web.utils.DateUtils.parseDate;
+import static org.bahmni.module.hip.web.utils.DateUtils.parseDateTime;
+
+@RequestMapping(value = "/rest/" + RestConstants.VERSION_1 + "/hip/opConsults")
+@RestController
+public class OPConsultController extends BaseRestController {
+ private final OPConsultService opConsultService;
+ private final ValidationService validationService;
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @Autowired
+ public OPConsultController(OPConsultService opConsultService, ValidationService validationService) {
+ this.opConsultService = opConsultService;
+ this.validationService = validationService;
+ }
+
+ @RequestMapping(method = RequestMethod.GET, value = "/visit", produces = MediaType.APPLICATION_JSON_VALUE)
+ public @ResponseBody
+ ResponseEntity> getOpconsultForVisit(@RequestParam String patientId,
+ @RequestParam String visitType,
+ @RequestParam String visitStartDate,
+ @RequestParam String fromDate,
+ @RequestParam String toDate) throws ParseException, IOException {
+ if (patientId == null || patientId.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noPatientIdProvided());
+ if (visitType == null || visitType.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noVisitTypeProvided());
+ if (visitStartDate == null || visitStartDate.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noVisitTypeProvided());
+ if (!validationService.isValidVisit(visitType))
+ return ResponseEntity.badRequest().body(ClientError.invalidVisitType());
+ if (!validationService.isValidPatient(patientId))
+ return ResponseEntity.badRequest().body(ClientError.invalidPatientId());
+ List opConsultBundle = new ArrayList<>();
+ if(isDateBetweenDateRange(visitStartDate,fromDate,toDate))
+ opConsultBundle = opConsultService.getOpConsultsForVisit(patientId,visitType,parseDateTime(visitStartDate));
+
+
+ return ResponseEntity.ok()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .body(mapper.writeValueAsString(new BundledOPConsultResponse(opConsultBundle)));
+ }
+
+ @RequestMapping(method = RequestMethod.GET, value = "/program", produces = MediaType.APPLICATION_JSON_VALUE)
+ public @ResponseBody
+ ResponseEntity> getOpConsultForProgram(
+ @RequestParam String patientId,
+ @RequestParam String fromDate,
+ @RequestParam String toDate,
+ @RequestParam String programName,
+ @RequestParam String programEnrollmentId)
+ throws ParseException, IOException {
+ programName = URLDecoder.decode(programName, "UTF-8");
+ if (patientId == null || patientId.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noPatientIdProvided());
+ if (programName == null || programName.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noProgramNameProvided());
+ if (!validationService.isValidProgram(programName))
+ return ResponseEntity.badRequest().body(ClientError.invalidProgramName());
+ if (!validationService.isValidPatient(patientId))
+ return ResponseEntity.badRequest().body(ClientError.invalidPatientId());
+ List opConsultBundle =
+ opConsultService.getOpConsultsForProgram(patientId, new DateRange(parseDate(fromDate), parseDate(toDate)), programName, programEnrollmentId);
+
+ return ResponseEntity.ok()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .body(mapper.writeValueAsString(new BundledOPConsultResponse(opConsultBundle)));
+ }
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/controller/PatientController.java b/omod/src/main/java/org/bahmni/module/hip/web/controller/PatientController.java
new file mode 100644
index 00000000..fdf3661d
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/controller/PatientController.java
@@ -0,0 +1,95 @@
+package org.bahmni.module.hip.web.controller;
+
+import org.bahmni.module.hip.web.client.ClientError;
+import org.bahmni.module.hip.web.client.model.Error;
+import org.bahmni.module.hip.web.client.model.ErrorCode;
+import org.bahmni.module.hip.web.client.model.ErrorRepresentation;
+import org.bahmni.module.hip.web.model.ExistingPatient;
+import org.bahmni.module.hip.web.model.Location;
+import org.bahmni.module.hip.web.service.ExistingPatientService;
+import org.bahmni.module.hip.web.service.ValidationService;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.openmrs.Patient;
+import org.openmrs.module.webservices.rest.web.RestConstants;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.CookieValue;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Set;
+
+@RequestMapping(value = "/rest/" + RestConstants.VERSION_1 + "/hip")
+@RestController
+public class PatientController {
+ private final ExistingPatientService existingPatientService;
+ private final ValidationService validationService;
+
+ @Autowired
+ public PatientController(ExistingPatientService existingPatientService, ValidationService validationService) {
+ this.existingPatientService = existingPatientService;
+ this.validationService = validationService;
+ }
+
+ @RequestMapping(method = RequestMethod.GET, value = "/existingPatients", produces = MediaType.APPLICATION_JSON_VALUE)
+ public @ResponseBody
+ ResponseEntity> getExistingPatients(@RequestParam(required = false) String patientName,
+ @RequestParam String patientYearOfBirth,
+ @RequestParam String patientGender,
+ @RequestParam String phoneNumber,
+ @CookieValue(name = "bahmni.user.location") String location) throws IOException {
+ String locationUuid = new ObjectMapper().readValue(location,Location.class).getUuid();
+ Set matchingPatients = existingPatientService.getMatchingPatients(locationUuid,phoneNumber,patientName,
+ Integer.parseInt(patientYearOfBirth), patientGender);
+ if (matchingPatients.size() == 0) {
+ return ResponseEntity.ok().body(new ErrorRepresentation(new Error(
+ ErrorCode.PATIENT_ID_NOT_FOUND, "No patient found")));
+ }
+ List existingPatients = existingPatientService.getMatchingPatientDetails(matchingPatients);
+ return ResponseEntity.ok()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .body(existingPatients);
+ }
+
+ @RequestMapping(method = RequestMethod.GET, value = "/existingPatients/{healthId}")
+ @ResponseBody
+ public ResponseEntity> getExistingPatientsWithHealthId(@PathVariable String healthId) {
+ String patientUuid = existingPatientService.getPatientWithHealthId(healthId);
+ if (patientUuid != null) {
+ return ResponseEntity.ok()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .body(patientUuid);
+ }
+ else {
+ return ResponseEntity.ok()
+ .body(new ErrorRepresentation(new Error(ErrorCode.PATIENT_ID_NOT_FOUND, "No patient found")));
+ }
+ }
+
+ @RequestMapping(method = RequestMethod.GET, value = "/existingPatients/status", produces = MediaType.APPLICATION_JSON_VALUE)
+ public @ResponseBody
+ ResponseEntity> perform(@RequestParam String healthId, @RequestParam String action) {
+ if(!validationService.isValidHealthId(healthId)) {
+ return ResponseEntity.ok().body(ClientError.patientIdentifierNotFound());
+ }
+ existingPatientService.perform(healthId, action);
+ return ResponseEntity.ok().body("");
+ }
+
+ @RequestMapping(method = RequestMethod.GET, value = "/existingPatients/IdDeactivationStatus/{patientUuid}")
+ @ResponseBody
+ public ResponseEntity> getIdentifierStatus(@PathVariable String patientUuid) {
+ boolean isHealthIdVoided = existingPatientService.isHealthIdVoided(patientUuid);
+ return ResponseEntity.ok()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .body(isHealthIdVoided);
+ }
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/controller/PrescriptionController.java b/omod/src/main/java/org/bahmni/module/hip/web/controller/PrescriptionController.java
new file mode 100644
index 00000000..5baf6224
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/controller/PrescriptionController.java
@@ -0,0 +1,93 @@
+package org.bahmni.module.hip.web.controller;
+
+import org.bahmni.module.hip.web.client.ClientError;
+import org.bahmni.module.hip.web.model.BundledPrescriptionResponse;
+import org.bahmni.module.hip.web.model.DateRange;
+import org.bahmni.module.hip.web.model.PrescriptionBundle;
+import org.bahmni.module.hip.web.service.PrescriptionService;
+import org.bahmni.module.hip.web.service.ValidationService;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.openmrs.module.webservices.rest.web.RestConstants;
+import org.openmrs.module.webservices.rest.web.v1_0.controller.BaseRestController;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.bahmni.module.hip.web.utils.DateUtils.isDateBetweenDateRange;
+import static org.bahmni.module.hip.web.utils.DateUtils.parseDate;
+import static org.bahmni.module.hip.web.utils.DateUtils.parseDateTime;
+
+@RequestMapping(value = "/rest/" + RestConstants.VERSION_1 + "/hip/prescriptions")
+@RestController
+public class PrescriptionController extends BaseRestController {
+ private final PrescriptionService prescriptionService;
+ private final ValidationService validationService;
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @Autowired
+ public PrescriptionController(PrescriptionService prescriptionService, ValidationService validationService) {
+ this.prescriptionService = prescriptionService;
+ this.validationService = validationService;
+ }
+
+ @RequestMapping(method = RequestMethod.GET, value = "/visit", produces = MediaType.APPLICATION_JSON_VALUE)
+ public @ResponseBody
+ ResponseEntity> getPrescriptionForVisit(
+ @RequestParam String patientId,
+ @RequestParam String fromDate,
+ @RequestParam String toDate,
+ @RequestParam String visitType,
+ @RequestParam String visitStartDate
+ ) throws ParseException, IOException {
+ if (patientId == null || patientId.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noPatientIdProvided());
+ if (visitType == null || visitType.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noVisitTypeProvided());
+ if (visitStartDate == null || visitStartDate.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noVisitTypeProvided());
+ if (!validationService.isValidVisit(visitType))
+ return ResponseEntity.badRequest().body(ClientError.invalidVisitType());
+ if (!validationService.isValidPatient(patientId))
+ return ResponseEntity.badRequest().body(ClientError.invalidPatientId());
+ List prescriptionBundle = new ArrayList<>();
+ if(isDateBetweenDateRange(visitStartDate,fromDate,toDate))
+ prescriptionBundle = prescriptionService.getPrescriptions(patientId, visitType, parseDateTime(visitStartDate));
+ return ResponseEntity.ok()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .body(mapper.writeValueAsString(new BundledPrescriptionResponse(prescriptionBundle)));
+ }
+
+ @RequestMapping(method = RequestMethod.GET, value = "/program", produces = MediaType.APPLICATION_JSON_VALUE)
+ public @ResponseBody
+ ResponseEntity> getPrescriptionForProgram(
+ @RequestParam String patientId,
+ @RequestParam String fromDate,
+ @RequestParam String toDate,
+ @RequestParam String programName,
+ @RequestParam String programEnrollmentId
+ ) throws ParseException, IOException {
+ programName = URLDecoder.decode(programName, "UTF-8");
+ if (patientId == null || patientId.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noPatientIdProvided());
+ if (programName == null || programName.isEmpty())
+ return ResponseEntity.badRequest().body(ClientError.noProgramNameProvided());
+ if (!validationService.isValidProgram(programName))
+ return ResponseEntity.badRequest().body(ClientError.invalidProgramName());
+ if (!validationService.isValidPatient(patientId))
+ return ResponseEntity.badRequest().body(ClientError.invalidPatientId());
+ List prescriptionBundle =
+ prescriptionService.getPrescriptionsForProgram(patientId, new DateRange(parseDate(fromDate), parseDate(toDate)), programName, programEnrollmentId);
+ return ResponseEntity.ok()
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .body(mapper.writeValueAsString(new BundledPrescriptionResponse(prescriptionBundle)));
+ }
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/exception/NoMedicationFoundException.java b/omod/src/main/java/org/bahmni/module/hip/web/exception/NoMedicationFoundException.java
new file mode 100644
index 00000000..358d5e6b
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/exception/NoMedicationFoundException.java
@@ -0,0 +1,8 @@
+package org.bahmni.module.hip.web.exception;
+
+public class NoMedicationFoundException extends RuntimeException {
+
+ public NoMedicationFoundException(String patientId) {
+ super("No Medication found for Patient" + patientId);
+ }
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/exception/RequestParameterMissingException.java b/omod/src/main/java/org/bahmni/module/hip/web/exception/RequestParameterMissingException.java
new file mode 100644
index 00000000..ea9a0f29
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/exception/RequestParameterMissingException.java
@@ -0,0 +1,15 @@
+package org.bahmni.module.hip.web.exception;
+
+public class RequestParameterMissingException extends RuntimeException {
+
+ private String parameterName;
+
+ public RequestParameterMissingException(String parameterName) {
+ this.parameterName = parameterName;
+ }
+
+ @Override
+ public String getMessage() {
+ return parameterName + " is mandatory request parameter";
+ }
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/model/BundledDiagnosticReportResponse.java b/omod/src/main/java/org/bahmni/module/hip/web/model/BundledDiagnosticReportResponse.java
new file mode 100644
index 00000000..e870cdd2
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/model/BundledDiagnosticReportResponse.java
@@ -0,0 +1,15 @@
+package org.bahmni.module.hip.web.model;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.Setter;
+
+import java.util.List;
+
+@AllArgsConstructor
+@Getter
+@Setter
+public class BundledDiagnosticReportResponse {
+ private List diagnosticReports;
+}
+
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/model/BundledDischargeSummaryResponse.java b/omod/src/main/java/org/bahmni/module/hip/web/model/BundledDischargeSummaryResponse.java
new file mode 100644
index 00000000..b2f35767
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/model/BundledDischargeSummaryResponse.java
@@ -0,0 +1,14 @@
+package org.bahmni.module.hip.web.model;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.Setter;
+
+import java.util.List;
+
+@AllArgsConstructor
+@Getter
+@Setter
+public class BundledDischargeSummaryResponse {
+ private List dischargeSummary;
+}
\ No newline at end of file
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/model/BundledOPConsultResponse.java b/omod/src/main/java/org/bahmni/module/hip/web/model/BundledOPConsultResponse.java
new file mode 100644
index 00000000..344c2ed0
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/model/BundledOPConsultResponse.java
@@ -0,0 +1,14 @@
+package org.bahmni.module.hip.web.model;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.Setter;
+
+import java.util.List;
+
+@AllArgsConstructor
+@Getter
+@Setter
+public class BundledOPConsultResponse {
+ private List opConsults;
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/model/BundledPrescriptionResponse.java b/omod/src/main/java/org/bahmni/module/hip/web/model/BundledPrescriptionResponse.java
new file mode 100644
index 00000000..ba1b4357
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/model/BundledPrescriptionResponse.java
@@ -0,0 +1,14 @@
+package org.bahmni.module.hip.web.model;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.Setter;
+
+import java.util.List;
+
+@AllArgsConstructor
+@Getter
+@Setter
+public class BundledPrescriptionResponse {
+ private List prescriptions;
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/model/CareContext.java b/omod/src/main/java/org/bahmni/module/hip/web/model/CareContext.java
new file mode 100644
index 00000000..b45e208b
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/model/CareContext.java
@@ -0,0 +1,11 @@
+package org.bahmni.module.hip.web.model;
+
+import lombok.Builder;
+import lombok.Data;
+
+@Builder
+@Data
+public class CareContext {
+ String careContextReference;
+ String careContextType;
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/model/DateRange.java b/omod/src/main/java/org/bahmni/module/hip/web/model/DateRange.java
new file mode 100644
index 00000000..8f89c134
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/model/DateRange.java
@@ -0,0 +1,13 @@
+package org.bahmni.module.hip.web.model;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+import java.util.Date;
+
+@AllArgsConstructor
+@Getter
+public class DateRange {
+ Date from;
+ Date to;
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/model/DiagnosticReportBundle.java b/omod/src/main/java/org/bahmni/module/hip/web/model/DiagnosticReportBundle.java
new file mode 100644
index 00000000..117fbb68
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/model/DiagnosticReportBundle.java
@@ -0,0 +1,18 @@
+package org.bahmni.module.hip.web.model;
+
+import lombok.Builder;
+import lombok.Getter;
+import lombok.Setter;
+import org.bahmni.module.hip.web.model.serializers.FhirBundleSerializer;
+import org.codehaus.jackson.map.annotate.JsonSerialize;
+import org.hl7.fhir.r4.model.Bundle;
+
+@Getter
+@Setter
+@Builder
+public class DiagnosticReportBundle {
+ private CareContext careContext;
+
+ @JsonSerialize(using = FhirBundleSerializer.class)
+ private Bundle bundle;
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/model/DischargeSummaryBundle.java b/omod/src/main/java/org/bahmni/module/hip/web/model/DischargeSummaryBundle.java
new file mode 100644
index 00000000..9a2daec6
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/model/DischargeSummaryBundle.java
@@ -0,0 +1,18 @@
+package org.bahmni.module.hip.web.model;
+
+import lombok.Builder;
+import lombok.Getter;
+import lombok.Setter;
+import org.bahmni.module.hip.web.model.serializers.FhirBundleSerializer;
+import org.codehaus.jackson.map.annotate.JsonSerialize;
+import org.hl7.fhir.r4.model.Bundle;
+
+@Getter
+@Setter
+@Builder
+public class DischargeSummaryBundle {
+ private CareContext careContext;
+
+ @JsonSerialize(using = FhirBundleSerializer.class)
+ private Bundle bundle;
+}
\ No newline at end of file
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/model/DrugOrders.java b/omod/src/main/java/org/bahmni/module/hip/web/model/DrugOrders.java
new file mode 100644
index 00000000..a87fdcef
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/model/DrugOrders.java
@@ -0,0 +1,54 @@
+package org.bahmni.module.hip.web.model;
+
+import org.openmrs.DrugOrder;
+import org.openmrs.Encounter;
+import org.springframework.util.CollectionUtils;
+
+import javax.validation.constraints.NotNull;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class DrugOrders {
+
+ private List openMRSDrugOrders;
+
+ public DrugOrders(@NotNull List openMRSDrugOrders) {
+ this.openMRSDrugOrders = openMRSDrugOrders;
+ }
+
+ public Boolean isEmpty(){
+ return CollectionUtils.isEmpty(openMRSDrugOrders);
+ }
+
+ public Map groupByEncounter(){
+ return groupByEncounterUUID()
+ .values()
+ .stream()
+ .map(DrugOrders::new)
+ .collect(Collectors.toMap(DrugOrders::firstEncounter, drugOrders -> drugOrders));
+ }
+
+ public int size() {
+ return openMRSDrugOrders.size();
+ }
+
+ private Map> groupByEncounterUUID(){
+ return openMRSDrugOrders
+ .stream()
+ .collect(Collectors.groupingBy(order -> order.getEncounter().getUuid()));
+ }
+
+ private Encounter firstEncounter() {
+ return openMRSDrugOrders.get(0).getEncounter();
+ }
+
+ Stream stream(){
+ return openMRSDrugOrders.stream();
+ }
+
+ public List getOpenMRSDrugOrders() {
+ return openMRSDrugOrders;
+ }
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/model/ErrorResponse.java b/omod/src/main/java/org/bahmni/module/hip/web/model/ErrorResponse.java
new file mode 100644
index 00000000..f5b9ac71
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/model/ErrorResponse.java
@@ -0,0 +1,27 @@
+package org.bahmni.module.hip.web.model;
+
+public class ErrorResponse {
+ private String errMessage;
+
+ public ErrorResponse() {
+ }
+
+ @Override
+ public String toString() {
+ return "ErrorResponse{" +
+ "errMessage='" + errMessage + '\'' +
+ '}';
+ }
+
+ public ErrorResponse(String errMessage) {
+ this.errMessage = errMessage;
+ }
+
+ public String getErrMessage() {
+ return errMessage;
+ }
+
+ public void setErrMessage(String errMessage) {
+ this.errMessage = errMessage;
+ }
+}
\ No newline at end of file
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/model/ExistingPatient.java b/omod/src/main/java/org/bahmni/module/hip/web/model/ExistingPatient.java
new file mode 100644
index 00000000..a1fc4261
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/model/ExistingPatient.java
@@ -0,0 +1,19 @@
+package org.bahmni.module.hip.web.model;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Getter;
+import lombok.Setter;
+
+@Builder
+@Getter
+@Setter
+@AllArgsConstructor
+public class ExistingPatient {
+ String name;
+ String dateOfBirth;
+ String address;
+ String gender;
+ String uuid;
+ String phoneNumber;
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/model/FhirDiagnosticReport.java b/omod/src/main/java/org/bahmni/module/hip/web/model/FhirDiagnosticReport.java
new file mode 100644
index 00000000..26c05339
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/model/FhirDiagnosticReport.java
@@ -0,0 +1,135 @@
+package org.bahmni.module.hip.web.model;
+
+import org.bahmni.module.hip.Config;
+import org.bahmni.module.hip.web.service.FHIRResourceMapper;
+import org.bahmni.module.hip.web.service.FHIRUtils;
+import org.hl7.fhir.r4.model.Bundle;
+import org.hl7.fhir.r4.model.Composition;
+import org.hl7.fhir.r4.model.DiagnosticReport;
+import org.hl7.fhir.r4.model.Encounter;
+import org.hl7.fhir.r4.model.Observation;
+import org.hl7.fhir.r4.model.Patient;
+import org.hl7.fhir.r4.model.Practitioner;
+import org.hl7.fhir.r4.model.Reference;
+import org.openmrs.EncounterProvider;
+import org.openmrs.Obs;
+
+import java.util.Date;
+import java.util.List;
+import java.util.UUID;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+
+public class FhirDiagnosticReport {
+ private final List diagnosticReports;
+ private final Date visitTimestamp;
+ private final Integer encounterID;
+ private final Encounter encounter;
+ private final List practitioners;
+ private final Patient patient;
+ private final Reference patientReference;
+ private final List obs;
+
+ private FhirDiagnosticReport(Date visitDateTime,
+ List diagnosticReports,
+ Integer encounterID,
+ Encounter encounter,
+ List practitioners,
+ Patient patient,
+ Reference patientReference,
+ List obs) {
+ this.visitTimestamp = visitDateTime;
+ this.diagnosticReports = diagnosticReports;
+ this.encounterID = encounterID;
+ this.encounter = encounter;
+ this.practitioners = practitioners;
+ this.patient = patient;
+ this.patientReference = patientReference;
+ this.obs = obs;
+ }
+
+
+ public Bundle bundleDiagnosticReport(String webUrl) {
+ String bundleID = String.format("PR-%d", encounterID);
+ Bundle bundle = FHIRUtils.createBundle(visitTimestamp, bundleID, webUrl);
+
+ FHIRUtils.addToBundleEntry(bundle, compositionFrom(webUrl), false);
+ FHIRUtils.addToBundleEntry(bundle, practitioners, false);
+ FHIRUtils.addToBundleEntry(bundle, patient, false);
+ FHIRUtils.addToBundleEntry(bundle, obs, false);
+ FHIRUtils.addToBundleEntry(bundle, encounter, false);
+ FHIRUtils.addToBundleEntry(bundle, diagnosticReports, false);
+ return bundle;
+ }
+
+ public static FhirDiagnosticReport fromOpenMrsDiagnosticReport(OpenMrsDiagnosticReport openMrsDiagnosticReport,
+ FHIRResourceMapper fhirResourceMapper) {
+
+ Patient patient = fhirResourceMapper.mapToPatient(openMrsDiagnosticReport.getPatient());
+ Reference patientReference = FHIRUtils.getReferenceToResource(patient);
+ Encounter encounter = fhirResourceMapper.mapToEncounter(openMrsDiagnosticReport.getEncounter());
+ Date visitDateTime = openMrsDiagnosticReport.getEncounter().getVisit().getStartDatetime();
+ Integer encounterId = openMrsDiagnosticReport.getEncounter().getId();
+ List practitioners = getPractitionersFrom(fhirResourceMapper, openMrsDiagnosticReport.getEncounterProviders());
+ List observationNotDocumentType = openMrsDiagnosticReport.getEncounter().getAllObs().stream()
+ .filter(obs -> (!obs.getConcept().getName().getName().equals(Config.DOCUMENT_TYPE.getValue()))).collect(Collectors.toList());
+ List observations = observationNotDocumentType.stream()
+ .map(fhirResourceMapper::mapToObs).collect(Collectors.toList());
+ List diagnosticReports = observationNotDocumentType.stream()
+ .map(fhirResourceMapper::mapToDiagnosticReport).collect(Collectors.toList());
+ List diagnosticReportList = diagnosticReports.stream()
+ .peek(diagnosticReport -> {
+ diagnosticReport.setResultsInterpreter(practitioners.stream().map(FHIRUtils::getReferenceToResource)
+ .collect(Collectors.toList()));
+ diagnosticReport.setSubject(FHIRUtils.getReferenceToResource(patient));
+ diagnosticReport.setResult(observations.stream().map(FHIRUtils::getReferenceToResource)
+ .collect(Collectors.toList()));
+ }).collect(Collectors.toList());
+ return new FhirDiagnosticReport(visitDateTime, diagnosticReportList, encounterId, encounter, practitioners,
+ patient, patientReference, observations);
+ }
+
+ private Composition compositionFrom(String webURL) {
+ Composition composition = initializeComposition(visitTimestamp, webURL);
+ Composition.SectionComponent compositionSection = composition.addSection();
+
+ practitioners
+ .forEach(practitioner -> composition
+ .addAuthor().setResource(practitioner).setDisplay(FHIRUtils.getDisplay(practitioner)));
+
+ composition
+ .setEncounter(FHIRUtils.getReferenceToResource(encounter))
+ .setSubject(patientReference);
+
+ compositionSection
+ .setTitle("Diagnostic Report")
+ .setCode(FHIRUtils.getDiagnosticReportType());
+
+ diagnosticReports
+ .stream()
+ .map(FHIRUtils::getReferenceToResource)
+ .forEach(compositionSection::addEntry);
+
+ return composition;
+ }
+
+ private Composition initializeComposition(Date encounterTimestamp, String webURL) {
+ Composition composition = new Composition();
+
+ composition.setId(UUID.randomUUID().toString());
+ composition.setDate(encounterTimestamp);
+ composition.setIdentifier(FHIRUtils.getIdentifier(composition.getId(), webURL, "document"));
+ composition.setStatus(Composition.CompositionStatus.FINAL);
+ composition.setType(FHIRUtils.getDiagnosticReportType());
+ composition.setTitle("Diagnostic Report");
+ return composition;
+ }
+
+ private static List getPractitionersFrom(FHIRResourceMapper fhirResourceMapper, Set encounterProviders) {
+ return encounterProviders
+ .stream()
+ .map(fhirResourceMapper::mapToPractitioner)
+ .collect(Collectors.toList());
+ }
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/model/FhirDischargeSummary.java b/omod/src/main/java/org/bahmni/module/hip/web/model/FhirDischargeSummary.java
new file mode 100644
index 00000000..2554122e
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/model/FhirDischargeSummary.java
@@ -0,0 +1,245 @@
+package org.bahmni.module.hip.web.model;
+
+import org.bahmni.module.hip.web.service.FHIRResourceMapper;
+import org.bahmni.module.hip.web.service.FHIRUtils;
+import org.hl7.fhir.r4.model.Encounter;
+import org.hl7.fhir.r4.model.Practitioner;
+import org.hl7.fhir.r4.model.Condition;
+import org.hl7.fhir.r4.model.Patient;
+import org.hl7.fhir.r4.model.MedicationRequest;
+import org.hl7.fhir.r4.model.Medication;
+import org.hl7.fhir.r4.model.Reference;
+import org.hl7.fhir.r4.model.Observation;
+import org.hl7.fhir.r4.model.CarePlan;
+import org.hl7.fhir.r4.model.DocumentReference;
+import org.hl7.fhir.r4.model.Bundle;
+import org.hl7.fhir.r4.model.Composition;
+import org.hl7.fhir.r4.model.Procedure;
+import org.hl7.fhir.r4.model.ServiceRequest;
+import org.openmrs.EncounterProvider;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.ArrayList;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+public class FhirDischargeSummary {
+
+ private final Date visitTimestamp;
+ private final Integer encounterID;
+ private final Encounter encounter;
+ private final List practitioners;
+ private final List chiefComplaints;
+ private final Patient patient;
+ private final List medicationRequests;
+ private final List medications;
+ private final List medicalHistory;
+ private final Reference patientReference;
+ private final List observations;
+ private final List carePlan;
+ private final List patientDocuments;
+ private final Procedure procedures;
+ private final List serviceRequest;
+
+ public FhirDischargeSummary(Integer encounterID,
+ Encounter encounter,
+ Date visitTimestamp,
+ List practitioners,
+ Reference patientReference,
+ List chiefComplaints,
+ List medicationRequests,
+ List medications,
+ List medicalHistory,
+ Patient patient,
+ List carePlan,
+ List observations,
+ List patientDocuments,
+ Procedure procedures,
+ List serviceRequest){
+ this.visitTimestamp = visitTimestamp;
+ this.encounterID = encounterID;
+ this.encounter = encounter;
+ this.chiefComplaints = chiefComplaints;
+ this.practitioners = practitioners;
+ this.medicationRequests = medicationRequests;
+ this.medications = medications;
+ this.medicalHistory = medicalHistory;
+ this.patient = patient;
+ this.patientReference = patientReference;
+ this.carePlan = carePlan;
+ this.observations = observations;
+ this.patientDocuments = patientDocuments;
+ this.procedures = procedures;
+ this.serviceRequest = serviceRequest;
+ }
+ public static FhirDischargeSummary fromOpenMrsDischargeSummary(OpenMrsDischargeSummary openMrsDischargeSummary, FHIRResourceMapper fhirResourceMapper){
+ Patient patient = fhirResourceMapper.mapToPatient(openMrsDischargeSummary.getPatient());
+ Reference patientReference = FHIRUtils.getReferenceToResource(patient);
+ Encounter encounter = fhirResourceMapper.mapToEncounter(openMrsDischargeSummary.getEncounter());
+ Date visitDatetime = openMrsDischargeSummary.getEncounter().getVisit().getStartDatetime();
+ Integer encounterId = openMrsDischargeSummary.getEncounter().getId();
+ List practitioners = getPractitionersFrom(fhirResourceMapper, openMrsDischargeSummary.getEncounter().getEncounterProviders());
+ List carePlans = openMrsDischargeSummary.getCarePlanObs().stream().
+ map(fhirResourceMapper::mapToCarePlan).collect(Collectors.toList());
+ List chiefComplaints = new ArrayList<>();
+ for(int i=0;i medicationRequestsList = openMrsDischargeSummary.getDrugOrders().stream().
+ map(fhirResourceMapper::mapToMedicationRequest).collect(Collectors.toList());
+ List medications = openMrsDischargeSummary.getDrugOrders().stream().map(fhirResourceMapper::mapToMedication).
+ filter(medication -> !Objects.isNull(medication)).collect(Collectors.toList());
+ List fhirMedicalHistoryList = new ArrayList<>();
+ for(int i=0;i physicalExaminations = openMrsDischargeSummary.getPhysicalExaminationObs().stream().
+ map(fhirResourceMapper::mapToObs).collect(Collectors.toList());
+ List patientDocuments = openMrsDischargeSummary.getPatientDocuments().stream().
+ map(fhirResourceMapper::mapToDocumentDocumentReference).collect(Collectors.toList());
+ Procedure procedures = openMrsDischargeSummary.getProcedure() != null ?
+ fhirResourceMapper.mapToProcedure(openMrsDischargeSummary.getProcedure()) : null;
+ List serviceRequest = openMrsDischargeSummary.getOrders().stream().
+ map(fhirResourceMapper::mapToOrder).collect(Collectors.toList());
+
+ return new FhirDischargeSummary(encounterId, encounter, visitDatetime, practitioners, patientReference, chiefComplaints, medicationRequestsList, medications, fhirMedicalHistoryList, patient, carePlans, physicalExaminations, patientDocuments, procedures, serviceRequest);
+ }
+
+ public Bundle bundleDischargeSummary(String webUrl){
+ String bundleID = String.format("PR-%d", encounterID);
+ Bundle bundle = FHIRUtils.createBundle(visitTimestamp, bundleID, webUrl);
+ FHIRUtils.addToBundleEntry(bundle, compositionFrom(webUrl), false);
+ FHIRUtils.addToBundleEntry(bundle, practitioners, false);
+ FHIRUtils.addToBundleEntry(bundle, medicationRequests, false);
+ FHIRUtils.addToBundleEntry(bundle, chiefComplaints, false);
+ FHIRUtils.addToBundleEntry(bundle, medications, false);
+ FHIRUtils.addToBundleEntry(bundle, medicalHistory, false);
+ FHIRUtils.addToBundleEntry(bundle, patient, false);
+ FHIRUtils.addToBundleEntry(bundle, encounter, false);
+ FHIRUtils.addToBundleEntry(bundle, carePlan, false);
+ FHIRUtils.addToBundleEntry(bundle, observations, false);
+ if (procedures != null) FHIRUtils.addToBundleEntry(bundle, procedures, false);
+ FHIRUtils.addToBundleEntry(bundle, patientDocuments, false);
+ FHIRUtils.addToBundleEntry(bundle, serviceRequest, false);
+ return bundle;
+ }
+
+ private Composition compositionFrom(String webURL) {
+ Composition composition = initializeComposition(visitTimestamp, webURL);
+ composition
+ .setEncounter(FHIRUtils.getReferenceToResource(encounter))
+ .setSubject(patientReference);
+
+ practitioners
+ .forEach(practitioner -> composition
+ .addAuthor().setResource(practitioner).setDisplay(FHIRUtils.getDisplay(practitioner)));
+
+ if (carePlan.size() > 0) {
+ Composition.SectionComponent physicalExaminationsCompositionSection = composition.addSection();
+ physicalExaminationsCompositionSection
+ .setTitle("Care Plan")
+ .setCode(FHIRUtils.getCarePlanType());
+ carePlan
+ .stream()
+ .map(FHIRUtils::getReferenceToResource)
+ .forEach(physicalExaminationsCompositionSection::addEntry);
+ }
+
+ if(medicationRequests.size() > 0){
+ Composition.SectionComponent medicationRequestsCompositionSection = composition.addSection();
+ medicationRequestsCompositionSection
+ .setTitle("Medication request")
+ .setCode(FHIRUtils.getPrescriptionType());
+ medicationRequests
+ .stream()
+ .map(FHIRUtils::getReferenceToResource)
+ .forEach(medicationRequestsCompositionSection::addEntry);
+ }
+
+ if (chiefComplaints.size() > 0){
+ Composition.SectionComponent chiefComplaintsCompositionSection = composition.addSection();
+ chiefComplaintsCompositionSection
+ .setTitle("Chief complaint")
+ .setCode(FHIRUtils.getChiefComplaintType());
+ chiefComplaints
+ .stream()
+ .map(FHIRUtils::getReferenceToResource)
+ .forEach(chiefComplaintsCompositionSection::addEntry);
+ }
+
+ if (medicalHistory.size() > 0) {
+ Composition.SectionComponent medicalHistoryCompositionSection = composition.addSection();
+ medicalHistoryCompositionSection
+ .setTitle("Medical history")
+ .setCode(FHIRUtils.getMedicalHistoryType());
+ medicalHistory
+ .stream()
+ .map(FHIRUtils::getReferenceToResource)
+ .forEach(medicalHistoryCompositionSection::addEntry);
+ }
+
+ if (observations.size() > 0) {
+ Composition.SectionComponent physicalExaminationsCompositionSection = composition.addSection();
+ physicalExaminationsCompositionSection
+ .setTitle("Physical examination")
+ .setCode(FHIRUtils.getPhysicalExaminationType());
+ observations
+ .stream()
+ .map(FHIRUtils::getReferenceToResource)
+ .forEach(physicalExaminationsCompositionSection::addEntry);
+ }
+
+ if (patientDocuments.size() > 0) {
+ Composition.SectionComponent patientDocumentsCompositionSection = composition.addSection();
+ patientDocumentsCompositionSection
+ .setTitle("Patient Document")
+ .setCode(FHIRUtils.getPatientDocumentType());
+ patientDocuments
+ .stream()
+ .map(FHIRUtils::getReferenceToResource)
+ .forEach(patientDocumentsCompositionSection::addEntry);
+ }
+
+ if (procedures != null) {
+ Composition.SectionComponent procedureCompositionSection = composition.addSection();
+ procedureCompositionSection
+ .setTitle("Procedure")
+ .setCode(FHIRUtils.getProcedureType());
+
+ procedureCompositionSection.addEntry(FHIRUtils.getReferenceToResource(procedures));
+ }
+
+ if (serviceRequest.size() > 0) {
+ Composition.SectionComponent serviceRequestCompositionSection = composition.addSection();
+ serviceRequestCompositionSection
+ .setTitle("Order")
+ .setCode(FHIRUtils.getOrdersType());
+ serviceRequest.stream()
+ .map(FHIRUtils::getReferenceToResource)
+ .forEach(serviceRequestCompositionSection::addEntry);
+ }
+
+ return composition;
+ }
+
+ private Composition initializeComposition(Date visitTimestamp, String webURL) {
+ Composition composition = new Composition();
+ composition.setId(UUID.randomUUID().toString());
+ composition.setDate(visitTimestamp);
+ composition.setIdentifier(FHIRUtils.getIdentifier(composition.getId(), webURL, "Composition"));
+ composition.setStatus(Composition.CompositionStatus.FINAL);
+ composition.setType(FHIRUtils.getOPConsultType());
+ composition.setTitle("Discharge Summary Document");
+ return composition;
+ }
+
+ private static List getPractitionersFrom(FHIRResourceMapper fhirResourceMapper, Set encounterProviders) {
+ return encounterProviders
+ .stream()
+ .map(fhirResourceMapper::mapToPractitioner)
+ .collect(Collectors.toList());
+ }
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/model/FhirLabResult.java b/omod/src/main/java/org/bahmni/module/hip/web/model/FhirLabResult.java
new file mode 100644
index 00000000..6d4dee14
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/model/FhirLabResult.java
@@ -0,0 +1,170 @@
+package org.bahmni.module.hip.web.model;
+
+import org.bahmni.module.hip.Config;
+import org.bahmni.module.hip.web.service.FHIRResourceMapper;
+import org.bahmni.module.hip.web.service.FHIRUtils;
+import org.hl7.fhir.r4.model.Attachment;
+import org.hl7.fhir.r4.model.Bundle;
+import org.hl7.fhir.r4.model.CodeableConcept;
+import org.hl7.fhir.r4.model.Coding;
+import org.hl7.fhir.r4.model.Composition;
+import org.hl7.fhir.r4.model.DiagnosticReport;
+import org.hl7.fhir.r4.model.Encounter;
+import org.hl7.fhir.r4.model.Observation;
+import org.hl7.fhir.r4.model.Patient;
+import org.hl7.fhir.r4.model.Practitioner;
+import org.hl7.fhir.r4.model.Quantity;
+import org.hl7.fhir.r4.model.Reference;
+import org.hl7.fhir.r4.model.StringType;
+import org.openmrs.Obs;
+import org.openmrs.module.bahmniemrapi.laborder.contract.LabOrderResult;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.stream.Collectors;
+
+
+public class FhirLabResult {
+
+ private final Patient patient;
+ private final Encounter encounter;
+ private final Date visitTime;
+ private final List report;
+ private final List results;
+ private final List practitioners;
+
+ public FhirLabResult(Patient patient, String panelName, Encounter encounter, Date visitTime, List report, List results, List practitioners) {
+ this.patient = patient;
+ this.encounter = encounter;
+ this.visitTime = visitTime;
+ this.report = report;
+ this.results = results;
+ this.practitioners = practitioners;
+ }
+
+ public Bundle bundleLabResults (String webUrl, FHIRResourceMapper fhirResourceMapper) {
+ String bundleID = String.format("LR-%s", encounter.getId());
+
+ Bundle bundle = FHIRUtils.createBundle(visitTime, bundleID, webUrl);
+
+ FHIRUtils.addToBundleEntry(bundle, compositionFrom(webUrl), false);
+
+ FHIRUtils.addToBundleEntry(bundle, encounter, false);
+ FHIRUtils.addToBundleEntry(bundle, practitioners, false);
+ FHIRUtils.addToBundleEntry(bundle, patient, false);
+ FHIRUtils.addToBundleEntry(bundle, report, false);
+ FHIRUtils.addToBundleEntry(bundle, results, false);
+ return bundle;
+
+ }
+
+ public static FhirLabResult fromOpenMrsLabResults(OpenMrsLabResults labresult, FHIRResourceMapper fhirResourceMapper) {
+ List reportList = new ArrayList<>();
+ List practitioners = labresult.getEncounterProviders().stream().map(fhirResourceMapper::mapToPractitioner).collect(Collectors.toList());
+
+ Patient patient = fhirResourceMapper.mapToPatient(labresult.getPatient());
+
+ for(Map.Entry> report : labresult.getLabOrderResults().entrySet()) {
+ DiagnosticReport reports = new DiagnosticReport();
+ LabOrderResult firstresult = (report.getValue() != null && report.getValue().size() != 0) ? report.getValue().get(0) : new LabOrderResult();
+ String testName = report.getKey().getObsGroup().getConcept().getName().getName();
+ reports.setCode(new CodeableConcept().setText(testName).addCoding(new Coding().setDisplay(testName)));
+ try {
+ reports.setPresentedForm(getAttachments(report.getKey(),testName));
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ reports.setId(firstresult.getOrderUuid() != null ? firstresult.getOrderUuid() : UUID.randomUUID().toString());
+ reports.setStatus(DiagnosticReport.DiagnosticReportStatus.FINAL);
+ reports.setSubject(FHIRUtils.getReferenceToResource(patient));
+ reports.setResultsInterpreter(practitioners.stream().map(FHIRUtils::getReferenceToResource).collect(Collectors.toList()));
+
+ List results = new ArrayList<>();
+
+ if(report.getValue() != null) report.getValue().stream().forEach(result -> FhirLabResult.mapToObsFromLabResult(result, patient, reports, results));
+ reportList.add(reports);
+
+ }
+
+ FhirLabResult fhirLabResult = new FhirLabResult(fhirResourceMapper.mapToPatient( labresult.getPatient()), null,
+ fhirResourceMapper.mapToEncounter( labresult.getEncounter() ),
+ labresult.getEncounter().getVisit().getStartDatetime(), reportList, new ArrayList<>(), practitioners);
+
+ return fhirLabResult;
+ }
+
+ private static void mapToObsFromLabResult(LabOrderResult result, Patient patient, DiagnosticReport report, List observations) {
+
+ Observation obs = new Observation();
+
+ obs.setId(result.getTestUuid());
+ obs.setCode(new CodeableConcept().setText( result.getTestName( )));
+ try {
+ float f = result.getResult()!=null? Float.parseFloat(result.getResult()): (float) 0;
+ obs.setValue(new Quantity().setValue(f).setUnit(result.getTestUnitOfMeasurement()));
+ } catch (NumberFormatException | NullPointerException ex) {
+ obs.setValue(new StringType().setValue(result.getResult()));
+ }
+ obs.setStatus(Observation.ObservationStatus.FINAL);
+
+ report.addResult(FHIRUtils.getReferenceToResource(obs));
+
+ observations.add(obs);
+ }
+
+ private Composition compositionFrom(String webURL) {
+ Composition composition = initializeComposition(visitTime, webURL);
+ Composition.SectionComponent compositionSection = composition.addSection();
+ Reference patientReference = FHIRUtils.getReferenceToResource(patient);
+
+ practitioners
+ .forEach(practitioner -> composition
+ .addAuthor().setResource(practitioner).setDisplay(FHIRUtils.getDisplay(practitioner)));
+ composition
+ .setEncounter(FHIRUtils.getReferenceToResource(encounter))
+ .setSubject(patientReference);
+
+ compositionSection
+ .setTitle("Diagnostic Report")
+ .setCode(FHIRUtils.getDiagnosticReportType());
+
+ report.stream()
+ .map(FHIRUtils::getReferenceToResource)
+ .forEach(compositionSection::addEntry);
+
+
+ return composition;
+ }
+
+ private Composition initializeComposition(Date visitTimestamp, String webURL) {
+ Composition composition = new Composition();
+
+ composition.setId(UUID.randomUUID().toString());
+ composition.setDate(visitTimestamp);
+ composition.setIdentifier(FHIRUtils.getIdentifier(composition.getId(), webURL, "document"));
+ composition.setStatus(Composition.CompositionStatus.FINAL);
+ composition.setType(FHIRUtils.getDiagnosticReportType());
+ composition.setTitle("Diagnostic Report");
+ return composition;
+ }
+
+ private static List getAttachments(Obs obs,String testNmae) throws IOException {
+ List attachments = new ArrayList<>();
+
+ Attachment attachment = new Attachment();
+ attachment.setContentType(FHIRUtils.getTypeOfTheObsDocument(obs.getValueText()));
+ byte[] fileContent = Files.readAllBytes(new File(Config.PATIENT_DOCUMENTS_PATH.getValue() + obs.getValueText()).toPath());
+ attachment.setData(fileContent);
+ attachment.setTitle("LAB REPORT : " + testNmae);
+ attachments.add(attachment);
+
+ return attachments;
+ }
+}
diff --git a/omod/src/main/java/org/bahmni/module/hip/web/model/FhirOPConsult.java b/omod/src/main/java/org/bahmni/module/hip/web/model/FhirOPConsult.java
new file mode 100644
index 00000000..130d91ff
--- /dev/null
+++ b/omod/src/main/java/org/bahmni/module/hip/web/model/FhirOPConsult.java
@@ -0,0 +1,228 @@
+package org.bahmni.module.hip.web.model;
+
+import org.bahmni.module.hip.web.service.FHIRResourceMapper;
+import org.bahmni.module.hip.web.service.FHIRUtils;
+import org.hl7.fhir.r4.model.Condition;
+import org.hl7.fhir.r4.model.Encounter;
+import org.hl7.fhir.r4.model.Practitioner;
+import org.hl7.fhir.r4.model.Patient;
+import org.hl7.fhir.r4.model.Reference;
+import org.hl7.fhir.r4.model.Observation;
+import org.hl7.fhir.r4.model.MedicationRequest;
+import org.hl7.fhir.r4.model.Medication;
+import org.hl7.fhir.r4.model.Procedure;
+import org.hl7.fhir.r4.model.DocumentReference;
+import org.hl7.fhir.r4.model.Bundle;
+import org.hl7.fhir.r4.model.Composition;
+import org.hl7.fhir.r4.model.ServiceRequest;
+
+import org.openmrs.EncounterProvider;
+import java.util.List;
+import java.util.Date;
+import java.util.Objects;
+import java.util.UUID;
+import java.util.Set;
+import java.util.ArrayList;
+import java.util.stream.Collectors;
+
+public class FhirOPConsult {
+ private final List chiefComplaints;
+ private final List medicalHistory;
+ private final Date visitTimeStamp;
+ private final Integer encounterID;
+ private final Encounter encounter;
+ private final List practitioners;
+ private final Patient patient;
+ private final Reference patientReference;
+ private final List observations;
+ private final List medicationRequests;
+ private final List medications;
+ private final Procedure procedure;
+ private final List patientDocuments;
+ private final List serviceRequest;
+
+ public FhirOPConsult(List chiefComplaints,
+ List medicalHistory, Date visitTimeStamp,
+ Integer encounterID,
+ Encounter encounter,
+ List practitioners,
+ Patient patient,
+ Reference patientReference,
+ List observations,
+ List medicationRequests,
+ List medications,
+ Procedure procedure,
+ List patientDocuments,
+ List serviceRequest) {
+ this.chiefComplaints = chiefComplaints;
+ this.medicalHistory = medicalHistory;
+ this.visitTimeStamp = visitTimeStamp;
+ this.encounterID = encounterID;
+ this.encounter = encounter;
+ this.practitioners = practitioners;
+ this.patient = patient;
+ this.patientReference = patientReference;
+ this.observations = observations;
+ this.medicationRequests = medicationRequests;
+ this.medications = medications;
+ this.procedure = procedure;
+ this.patientDocuments = patientDocuments;
+ this.serviceRequest = serviceRequest;
+ }
+
+ public Bundle bundleOPConsult(String webUrl) {
+ String bundleID = String.format("PR-%d", encounterID);
+ Bundle bundle = FHIRUtils.createBundle(visitTimeStamp, bundleID, webUrl);
+ FHIRUtils.addToBundleEntry(bundle, compositionFrom(webUrl), false);
+ FHIRUtils.addToBundleEntry(bundle, practitioners, false);
+ FHIRUtils.addToBundleEntry(bundle, patient, false);
+ FHIRUtils.addToBundleEntry(bundle, encounter, false);
+ FHIRUtils.addToBundleEntry(bundle, chiefComplaints, false);
+ FHIRUtils.addToBundleEntry(bundle, medicalHistory, false);
+ FHIRUtils.addToBundleEntry(bundle, observations, false);
+ FHIRUtils.addToBundleEntry(bundle, medicationRequests, false);
+ FHIRUtils.addToBundleEntry(bundle, medications, false);
+ FHIRUtils.addToBundleEntry(bundle, serviceRequest, false);
+ if (procedure != null) FHIRUtils.addToBundleEntry(bundle, procedure, false);
+ FHIRUtils.addToBundleEntry(bundle, patientDocuments, false);
+ return bundle;
+ }
+
+ public static FhirOPConsult fromOpenMrsOPConsult(OpenMrsOPConsult openMrsOPConsult, FHIRResourceMapper fhirResourceMapper) {
+ Patient patient = fhirResourceMapper.mapToPatient(openMrsOPConsult.getPatient());
+ Reference patientReference = FHIRUtils.getReferenceToResource(patient);
+ Encounter encounter = fhirResourceMapper.mapToEncounter(openMrsOPConsult.getEncounter());
+ Date visitDatetime = openMrsOPConsult.getEncounter().getVisit().getStartDatetime();
+ Integer encounterId = openMrsOPConsult.getEncounter().getId();
+ List medicationRequestsList = openMrsOPConsult.getDrugOrders().stream().
+ map(fhirResourceMapper::mapToMedicationRequest).collect(Collectors.toList());
+ List medications = openMrsOPConsult.getDrugOrders().stream().map(fhirResourceMapper::mapToMedication).
+ filter(medication -> !Objects.isNull(medication)).collect(Collectors.toList());
+ List practitioners = getPractitionersFrom(fhirResourceMapper, openMrsOPConsult.getEncounter().getEncounterProviders());
+ List fhirChiefComplaintConditionList = new ArrayList<>();
+ for(int i=0;i fhirMedicalHistoryList = new ArrayList<>();
+ for(int i=0;i fhirObservationList = openMrsOPConsult.getObservations().stream().
+ map(fhirResourceMapper::mapToObs).collect(Collectors.toList());
+ Procedure procedure = openMrsOPConsult.getProcedure() != null ?
+ fhirResourceMapper.mapToProcedure(openMrsOPConsult.getProcedure()) : null;
+ List patientDocuments = openMrsOPConsult.getPatientDocuments().stream().
+ map(fhirResourceMapper::mapToDocumentDocumentReference).collect(Collectors.toList());
+ List