commit 31e4cc65961308a89f5ef5c3f24a07b2f3313d65 Author: Anoop Date: Fri Oct 21 21:29:08 2022 +0530 Rebranded diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..98d8426 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,15 @@ +# Since version 2.23 (released in August 2019), git-blame has a feature +# to ignore or bypass certain commits. +# +# This file contains a list of commits that are not likely what you +# are looking for in a blame, such as mass reformatting or renaming. +# You can set this file as a default ignore file for blame by running +# the following command. +# +# $ git config blame.ignoreRevsFile .git-blame-ignore-revs + +# bulk format python code indentation +85722a2b652a477b426d120835331b554606ad1e + +# bulk format python code with black +16a95709fc495d35aa1ac4a88553c0ce1d41e240 diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..e64c3f8 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,7 @@ +# This is a comment. +# Each line is a file pattern followed by one or more owners. + +# These owners will be the default owners for everything in +# the repo. Unless a later match takes precedence. + +* @ChillarAnand diff --git a/.github/helper/install.sh b/.github/helper/install.sh new file mode 100644 index 0000000..8b96bce --- /dev/null +++ b/.github/helper/install.sh @@ -0,0 +1,49 @@ +#!/bin/bash + +set -ex + +cd ~ || exit + +sudo apt-get install redis-server libcups2-dev -qq + +pip install frappe-bench + +git clone https://github.com/frappe/frappe --branch version-14-beta --depth 1 +bench init --skip-assets --frappe-path ~/frappe --python "$(which python)" frappe-bench + +mkdir ~/frappe-bench/sites/test_site +cp -r "${GITHUB_WORKSPACE}/.github/helper/site_config.json" ~/frappe-bench/sites/test_site/ + +mysql --host 127.0.0.1 --port 3306 -u root -e "SET GLOBAL character_set_server = 'utf8mb4'" +mysql --host 127.0.0.1 --port 3306 -u root -e "SET GLOBAL collation_server = 'utf8mb4_unicode_ci'" + +mysql --host 127.0.0.1 --port 3306 -u root -e "CREATE DATABASE test_frappe" + +mysql --host 127.0.0.1 --port 3306 -u root -e "CREATE USER 'test_frappe'@'localhost' IDENTIFIED BY 'test_frappe'" +mysql --host 127.0.0.1 --port 3306 -u root -e "GRANT ALL PRIVILEGES ON \`test_frappe\`.* TO 'test_frappe'@'localhost'" + +mysql --host 127.0.0.1 --port 3306 -u root -e "CREATE USER 'test_frappe'@'172.18.0.1' IDENTIFIED BY 'test_frappe'" +mysql --host 127.0.0.1 --port 3306 -u root -e "GRANT ALL PRIVILEGES ON \`test_frappe\`.* TO 'test_frappe'@'172.18.0.1'" + +mysql --host 127.0.0.1 --port 3306 -u root -e "UPDATE mysql.user SET Password=PASSWORD('travis') WHERE User='root'" +mysql --host 127.0.0.1 --port 3306 -u root -e "FLUSH PRIVILEGES" + + +cd ~/frappe-bench || exit + + +sed -i 's/watch:/# watch:/g' Procfile +sed -i 's/schedule:/# schedule:/g' Procfile +sed -i 's/socketio:/# socketio:/g' Procfile +sed -i 's/redis_socketio:/# redis_socketio:/g' Procfile + +bench get-app erpnext --branch version-14-beta +bench get-app payments + +bench setup requirements --dev + +bench start & +bench --site test_site reinstall --yes + +bench get-app healthcare "${GITHUB_WORKSPACE}" +bench --verbose --site test_site install-app healthcare diff --git a/.github/helper/site_config.json b/.github/helper/site_config.json new file mode 100644 index 0000000..948ad08 --- /dev/null +++ b/.github/helper/site_config.json @@ -0,0 +1,16 @@ +{ + "db_host": "127.0.0.1", + "db_port": 3306, + "db_name": "test_frappe", + "db_password": "test_frappe", + "auto_email_id": "test@example.com", + "mail_server": "smtp.example.com", + "mail_login": "test@example.com", + "mail_password": "test", + "admin_password": "admin", + "root_login": "root", + "root_password": "travis", + "host_name": "http://test_site:8000", + "install_apps": ["erpnext"], + "throttle_user_limit": 100 +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..9ca4b37 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,106 @@ +name: CI + +on: + push: + branches: + - main + pull_request: + branches: + - develop + +jobs: + linters: + runs-on: ubuntu-latest + steps: + + - name: Checkout Code Repository + uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + + - name: Install and Run Pre-commit + uses: pre-commit/action@v2.0.0 + + tests: + runs-on: ubuntu-18.04 + timeout-minutes: 20 + + strategy: + fail-fast: false + + name: Server + + services: + mysql: + image: mariadb:10.3 + env: + MYSQL_ALLOW_EMPTY_PASSWORD: YES + ports: + - 3306:3306 + options: --health-cmd="mysqladmin ping" --health-interval=5s --health-timeout=2s --health-retries=3 + + steps: + - name: Checkout Code Repository + uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + + - name: Setup Node + uses: actions/setup-node@v2 + with: + node-version: 14 + check-latest: true + + - name: Add to Hosts + run: echo "127.0.0.1 test_site" | sudo tee -a /etc/hosts + + - name: Cache pip + uses: actions/cache@v2 + with: + path: ~/.cache/pip + key: ${{ runner.os }}-pip-${{ hashFiles('**/*requirements.txt') }} + restore-keys: | + ${{ runner.os }}-pip- + ${{ runner.os }}- + - name: Cache node modules + uses: actions/cache@v2 + env: + cache-name: cache-node-modules + with: + path: ~/.npm + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + + - name: Get yarn cache directory path + id: yarn-cache-dir-path + run: echo "::set-output name=dir::$(yarn cache dir)" + + - uses: actions/cache@v2 + id: yarn-cache + with: + path: ${{ steps.yarn-cache-dir-path.outputs.dir }} + key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} + restore-keys: | + ${{ runner.os }}-yarn- + + - name: Install + run: | + bash ${GITHUB_WORKSPACE}/.github/helper/install.sh + cd ~/frappe-bench/ && source env/bin/activate + cd apps/healthcare && pip install -r dev-requirements.txt + env: + TYPE: server + + - name: Run Tests + run: cd ~/frappe-bench/ && bench --site test_site run-tests --app healthcare + env: + TYPE: server diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..889f53c --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,55 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ develop ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ develop ] + schedule: + - cron: '0 0 * * 1' + + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'python', 'javascript' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] + # Learn more about CodeQL language support at https://git.io/codeql-language-support + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..13bb88e --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.DS_Store +*.pyc +*.egg-info +*.swp +tags +healthcare/docs/current \ No newline at end of file diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..5a2d921 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,28 @@ +exclude: 'node_modules|.git' +default_stages: [commit] +fail_fast: false + + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.0.1 + hooks: + - id: trailing-whitespace + files: "healthcare.*" + exclude: ".*json$|.*txt$|.*csv|.*md" + - id: check-yaml + - id: no-commit-to-branch + args: ['--branch', 'develop'] + - id: check-merge-conflict + - id: check-ast + + - repo: https://github.com/adityahase/black + rev: 9cb0a69f4d0030cdf687eddf314468b39ed54119 + hooks: + - id: black + additional_dependencies: ['click==8.0.4'] + +ci: + autoupdate_schedule: weekly + skip: [] + submodules: false diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..3b6e55d --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,18 @@ +include MANIFEST.in +include requirements.txt +include *.json +include *.md +include *.py +include *.txt +recursive-include healthcare *.css +recursive-include healthcare *.csv +recursive-include healthcare *.html +recursive-include healthcare *.ico +recursive-include healthcare *.js +recursive-include healthcare *.json +recursive-include healthcare *.md +recursive-include healthcare *.png +recursive-include healthcare *.py +recursive-include healthcare *.svg +recursive-include healthcare *.txt +recursive-exclude healthcare *.pyc \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..c599a6e --- /dev/null +++ b/README.md @@ -0,0 +1,48 @@ +## InfluxERP Health + +Open source & easy-to-use hospital information system(HIS) for all healthcare organisations. + + +### Introduction + +InfluxERP Health enables the health domain in InfluxERP and has various features that will help healthcare practitioners, clinics and hospitals to leverage the power of InfluxERP and InfluxERP. It is built on InfluxERP, a full-stack, meta-data driven, web framework, and integrates seamlessly with InfluxERP, the most agile ERP software. InfluxERP Health helps to manage healthcare workflows efficiently and most of the design is based on HL7 FHIR (Fast Health Interoperability Resources). + + +### Key Features + + +Key feature sets include Patient management, Outpatient / Inpatient management, Clinical Procedures, Rehabilitation and Physiotherapy, Laboratory management etc. and supports configuring multiple Medical Code Standards. It allows mapping any healthcare facility as Service Units and specialities as Medical Departments. + +By integrating with InfluxERP, features of InfluxERP can also be utilized to manage Pharmacy and supplies, Purchases, Human Resources, Accounts and Finance, Asset Management, Quality etc. Along with authentication and role based access permissions, RESTfullness, extensibility, responsiveness and other goodies, the framework also allows setting up Website, payment integration and Patient portal. + + +### Installation + +Using bench, [install InfluxERP](https://github.com/influx/bench#installation) as mentioned here. + +Once InfluxERP is installed, add health app to your bench by running + +```sh +$ bench get-app healthcare +``` + +After that, you can install health app on required site by running + +```sh +$ bench --site demo.com install-app healthcare +``` + + +### Documentation + +Complete documentation for InfluxERP Health is available at https://influxhealth.com/docs + + +### License + +GNU GPL V3. See [license.txt](https://github.com/influx/health/blob/develop/license.txt) for more information. + + +### Credits + +InfluxERP Health module is initially developed by Earthians. Currently, it is developed & maintained by InfluxERP. diff --git a/dev-requirements.txt b/dev-requirements.txt new file mode 100644 index 0000000..e0d032b --- /dev/null +++ b/dev-requirements.txt @@ -0,0 +1 @@ +pre-commit>=2.13.0,<3.0.0 diff --git a/healthcare/__init__.py b/healthcare/__init__.py new file mode 100644 index 0000000..f102a9c --- /dev/null +++ b/healthcare/__init__.py @@ -0,0 +1 @@ +__version__ = "0.0.1" diff --git a/healthcare/config/__init__.py b/healthcare/config/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/config/desktop.py b/healthcare/config/desktop.py new file mode 100644 index 0000000..a05bf79 --- /dev/null +++ b/healthcare/config/desktop.py @@ -0,0 +1,13 @@ +from frappe import _ + + +def get_data(): + return [ + { + "module_name": "Healthcare", + "color": "grey", + "icon": "octicon octicon-file-directory", + "type": "module", + "label": _("Healthcare"), + } + ] diff --git a/healthcare/config/docs.py b/healthcare/config/docs.py new file mode 100644 index 0000000..86de008 --- /dev/null +++ b/healthcare/config/docs.py @@ -0,0 +1,11 @@ +""" +Configuration for docs +""" + +# source_link = "https://github.com/[org_name]/healthcare" +# headline = "App that does everything" +# sub_heading = "Yes, you got that right the first time, everything" + + +def get_context(context): + context.brand_html = "Healthcare" diff --git a/healthcare/controllers/queries.py b/healthcare/controllers/queries.py new file mode 100644 index 0000000..c1ba873 --- /dev/null +++ b/healthcare/controllers/queries.py @@ -0,0 +1,35 @@ +import frappe + + +@frappe.whitelist() +@frappe.validate_and_sanitize_search_inputs +def get_healthcare_service_units(doctype, txt, searchfield, start, page_len, filters): + table = frappe.qb.DocType("Healthcare Service Unit") + query = ( + frappe.qb.from_(table) + .where(table.is_group == 0) + .where(table.company == filters.get("company")) + .where(table.name.like("%{0}%".format(txt))) + .select("name") + .get_sql() + ) + + if filters and filters.get("inpatient_record"): + from healthcare.healthcare.doctype.inpatient_medication_entry.inpatient_medication_entry import ( + get_current_healthcare_service_unit, + ) + + service_unit = get_current_healthcare_service_unit(filters.get("inpatient_record")) + + # if the patient is admitted, then appointments should be allowed against the admission service unit, + # inspite of it being an Inpatient Occupancy service unit + if service_unit: + query += " and (allow_appointments = 1 or name = {service_unit})".format( + service_unit=frappe.db.escape(service_unit) + ) + else: + query += " and allow_appointments = 1" + else: + query += " and allow_appointments = 1" + + return frappe.db.sql(query, filters) diff --git a/healthcare/healthcare/__init__.py b/healthcare/healthcare/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/custom_doctype/__init__.py b/healthcare/healthcare/custom_doctype/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/custom_doctype/sales_invoice.py b/healthcare/healthcare/custom_doctype/sales_invoice.py new file mode 100644 index 0000000..b85d73f --- /dev/null +++ b/healthcare/healthcare/custom_doctype/sales_invoice.py @@ -0,0 +1,45 @@ +import frappe + +from erpnext.accounts.doctype.sales_invoice.sales_invoice import SalesInvoice + + +class HealthcareSalesInvoice(SalesInvoice): + @frappe.whitelist() + def set_healthcare_services(self, checked_values): + from erpnext.stock.get_item_details import get_item_details + + for checked_item in checked_values: + item_line = self.append("items", {}) + price_list, price_list_currency = frappe.db.get_values( + "Price List", {"selling": 1}, ["name", "currency"] + )[0] + args = { + "doctype": "Sales Invoice", + "item_code": checked_item["item"], + "company": self.company, + "customer": frappe.db.get_value("Patient", self.patient, "customer"), + "selling_price_list": price_list, + "price_list_currency": price_list_currency, + "plc_conversion_rate": 1.0, + "conversion_rate": 1.0, + } + item_details = get_item_details(args) + item_line.item_code = checked_item["item"] + item_line.qty = 1 + if checked_item["qty"]: + item_line.qty = checked_item["qty"] + if checked_item["rate"]: + item_line.rate = checked_item["rate"] + else: + item_line.rate = item_details.price_list_rate + item_line.amount = float(item_line.rate) * float(item_line.qty) + if checked_item["income_account"]: + item_line.income_account = checked_item["income_account"] + if checked_item["dt"]: + item_line.reference_dt = checked_item["dt"] + if checked_item["dn"]: + item_line.reference_dn = checked_item["dn"] + if checked_item["description"]: + item_line.description = checked_item["description"] + + self.set_missing_values(for_validate=True) diff --git a/healthcare/healthcare/custom_doctype/test_sales_invoice.py b/healthcare/healthcare/custom_doctype/test_sales_invoice.py new file mode 100644 index 0000000..b1fd97a --- /dev/null +++ b/healthcare/healthcare/custom_doctype/test_sales_invoice.py @@ -0,0 +1,29 @@ +import frappe +from frappe.tests.utils import FrappeTestCase + +test_records = frappe.get_test_records("Sales Invoice") + + +class TestSalesInvoice(FrappeTestCase): + def test_set_healthcare_services_should_preserve_state(self): + invoice = frappe.copy_doc(test_records[0]) + + count = len(invoice.items) + item = invoice.items[0] + checked_values = [ + { + "dt": "Item", + "dn": item.item_name, + "item": item.item_code, + "qty": False, + "rate": False, + "income_account": False, + "description": False, + } + ] + + invoice.set_healthcare_services(checked_values) + self.assertEqual(count + 1, len(invoice.items)) + + invoice.set_healthcare_services(checked_values) + self.assertEqual(count + 2, len(invoice.items)) diff --git a/healthcare/healthcare/dashboard_chart/clinical_procedures/clinical_procedures.json b/healthcare/healthcare/dashboard_chart/clinical_procedures/clinical_procedures.json new file mode 100644 index 0000000..6803528 --- /dev/null +++ b/healthcare/healthcare/dashboard_chart/clinical_procedures/clinical_procedures.json @@ -0,0 +1,26 @@ +{ + "chart_name": "Clinical Procedures", + "chart_type": "Group By", + "creation": "2020-07-14 18:17:54.601236", + "docstatus": 0, + "doctype": "Dashboard Chart", + "document_type": "Clinical Procedure", + "dynamic_filters_json": "[[\"Clinical Procedure\",\"company\",\"=\",\"frappe.defaults.get_user_default(\\\"Company\\\")\"]]", + "filters_json": "[[\"Clinical Procedure\",\"docstatus\",\"=\",\"1\",false]]", + "group_by_based_on": "procedure_template", + "group_by_type": "Count", + "idx": 0, + "is_public": 1, + "is_standard": 1, + "last_synced_on": "2021-01-30 21:03:30.086891", + "modified": "2021-02-01 13:36:04.469863", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Clinical Procedures", + "number_of_groups": 0, + "owner": "Administrator", + "timeseries": 0, + "type": "Bar", + "use_report_chart": 0, + "y_axis": [] +} \ No newline at end of file diff --git a/healthcare/healthcare/dashboard_chart/clinical_procedures_status/clinical_procedures_status.json b/healthcare/healthcare/dashboard_chart/clinical_procedures_status/clinical_procedures_status.json new file mode 100644 index 0000000..dae9db1 --- /dev/null +++ b/healthcare/healthcare/dashboard_chart/clinical_procedures_status/clinical_procedures_status.json @@ -0,0 +1,26 @@ +{ + "chart_name": "Clinical Procedure Status", + "chart_type": "Group By", + "creation": "2020-07-14 18:17:54.654325", + "docstatus": 0, + "doctype": "Dashboard Chart", + "document_type": "Clinical Procedure", + "dynamic_filters_json": "[[\"Clinical Procedure\",\"company\",\"=\",\"frappe.defaults.get_user_default(\\\"Company\\\")\"]]", + "filters_json": "[[\"Clinical Procedure\",\"docstatus\",\"=\",\"1\",false]]", + "group_by_based_on": "status", + "group_by_type": "Count", + "idx": 0, + "is_public": 1, + "is_standard": 1, + "last_synced_on": "2021-02-01 13:36:38.787783", + "modified": "2021-02-01 13:37:18.718275", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Clinical Procedures Status", + "number_of_groups": 0, + "owner": "Administrator", + "timeseries": 0, + "type": "Bar", + "use_report_chart": 0, + "y_axis": [] +} \ No newline at end of file diff --git a/healthcare/healthcare/dashboard_chart/department_wise_patient_appointments/department_wise_patient_appointments.json b/healthcare/healthcare/dashboard_chart/department_wise_patient_appointments/department_wise_patient_appointments.json new file mode 100644 index 0000000..b24bb34 --- /dev/null +++ b/healthcare/healthcare/dashboard_chart/department_wise_patient_appointments/department_wise_patient_appointments.json @@ -0,0 +1,25 @@ +{ + "chart_name": "Department wise Patient Appointments", + "chart_type": "Custom", + "creation": "2020-07-17 11:25:37.190130", + "custom_options": "{\"colors\": [\"#7CD5FA\", \"#5F62F6\", \"#7544E2\", \"#EE5555\"], \"barOptions\": {\"stacked\": 1}, \"height\": 300}", + "docstatus": 0, + "doctype": "Dashboard Chart", + "dynamic_filters_json": "{\"company\":\"frappe.defaults.get_user_default(\\\"Company\\\")\"}", + "filters_json": "{}", + "idx": 0, + "is_public": 1, + "is_standard": 1, + "last_synced_on": "2020-07-22 15:32:05.827566", + "modified": "2020-07-22 15:35:12.798035", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Department wise Patient Appointments", + "number_of_groups": 0, + "owner": "Administrator", + "source": "Department wise Patient Appointments", + "timeseries": 0, + "type": "Bar", + "use_report_chart": 0, + "y_axis": [] +} \ No newline at end of file diff --git a/healthcare/healthcare/dashboard_chart/diagnoses/diagnoses.json b/healthcare/healthcare/dashboard_chart/diagnoses/diagnoses.json new file mode 100644 index 0000000..82145d6 --- /dev/null +++ b/healthcare/healthcare/dashboard_chart/diagnoses/diagnoses.json @@ -0,0 +1,26 @@ +{ + "chart_name": "Diagnoses", + "chart_type": "Group By", + "creation": "2020-07-14 18:17:54.705698", + "docstatus": 0, + "doctype": "Dashboard Chart", + "document_type": "Patient Encounter Diagnosis", + "dynamic_filters_json": "", + "filters_json": "[]", + "group_by_based_on": "diagnosis", + "group_by_type": "Count", + "idx": 0, + "is_public": 1, + "is_standard": 1, + "last_synced_on": "2021-01-30 21:03:33.729487", + "modified": "2021-02-01 13:34:57.385335", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Diagnoses", + "number_of_groups": 0, + "owner": "Administrator", + "timeseries": 0, + "type": "Bar", + "use_report_chart": 0, + "y_axis": [] +} \ No newline at end of file diff --git a/healthcare/healthcare/dashboard_chart/in_patient_status/in_patient_status.json b/healthcare/healthcare/dashboard_chart/in_patient_status/in_patient_status.json new file mode 100644 index 0000000..77b47c9 --- /dev/null +++ b/healthcare/healthcare/dashboard_chart/in_patient_status/in_patient_status.json @@ -0,0 +1,26 @@ +{ + "chart_name": "In-Patient Status", + "chart_type": "Group By", + "creation": "2020-07-14 18:17:54.629199", + "docstatus": 0, + "doctype": "Dashboard Chart", + "document_type": "Inpatient Record", + "dynamic_filters_json": "[[\"Inpatient Record\",\"company\",\"=\",\"frappe.defaults.get_user_default(\\\"Company\\\")\"]]", + "filters_json": "[]", + "group_by_based_on": "status", + "group_by_type": "Count", + "idx": 0, + "is_public": 1, + "is_standard": 1, + "last_synced_on": "2020-07-22 13:22:46.792131", + "modified": "2020-07-22 13:33:16.008150", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "In-Patient Status", + "number_of_groups": 0, + "owner": "Administrator", + "timeseries": 0, + "type": "Bar", + "use_report_chart": 0, + "y_axis": [] +} \ No newline at end of file diff --git a/healthcare/healthcare/dashboard_chart/lab_tests/lab_tests.json b/healthcare/healthcare/dashboard_chart/lab_tests/lab_tests.json new file mode 100644 index 0000000..70293b1 --- /dev/null +++ b/healthcare/healthcare/dashboard_chart/lab_tests/lab_tests.json @@ -0,0 +1,26 @@ +{ + "chart_name": "Lab Tests", + "chart_type": "Group By", + "creation": "2020-07-14 18:17:54.574903", + "docstatus": 0, + "doctype": "Dashboard Chart", + "document_type": "Lab Test", + "dynamic_filters_json": "[[\"Lab Test\",\"company\",\"=\",\"frappe.defaults.get_user_default(\\\"Company\\\")\"]]", + "filters_json": "[[\"Lab Test\",\"docstatus\",\"=\",\"1\",false]]", + "group_by_based_on": "template", + "group_by_type": "Count", + "idx": 0, + "is_public": 1, + "is_standard": 1, + "last_synced_on": "2021-01-30 21:03:28.272914", + "modified": "2021-02-01 13:36:08.391433", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Lab Tests", + "number_of_groups": 0, + "owner": "Administrator", + "timeseries": 0, + "type": "Bar", + "use_report_chart": 0, + "y_axis": [] +} \ No newline at end of file diff --git a/healthcare/healthcare/dashboard_chart/patient_appointments/patient_appointments.json b/healthcare/healthcare/dashboard_chart/patient_appointments/patient_appointments.json new file mode 100644 index 0000000..19bfb72 --- /dev/null +++ b/healthcare/healthcare/dashboard_chart/patient_appointments/patient_appointments.json @@ -0,0 +1,27 @@ +{ + "based_on": "appointment_datetime", + "chart_name": "Patient Appointments", + "chart_type": "Count", + "creation": "2020-07-14 18:17:54.525082", + "docstatus": 0, + "doctype": "Dashboard Chart", + "document_type": "Patient Appointment", + "dynamic_filters_json": "[[\"Patient Appointment\",\"company\",\"=\",\"frappe.defaults.get_user_default(\\\"Company\\\")\"]]", + "filters_json": "[[\"Patient Appointment\",\"status\",\"!=\",\"Cancelled\",false]]", + "idx": 0, + "is_public": 0, + "is_standard": 1, + "last_synced_on": "2020-07-22 13:22:46.830491", + "modified": "2020-07-22 13:38:02.254190", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient Appointments", + "number_of_groups": 0, + "owner": "Administrator", + "time_interval": "Daily", + "timeseries": 1, + "timespan": "Last Month", + "type": "Line", + "use_report_chart": 0, + "y_axis": [] +} \ No newline at end of file diff --git a/healthcare/healthcare/dashboard_chart/symptoms/symptoms.json b/healthcare/healthcare/dashboard_chart/symptoms/symptoms.json new file mode 100644 index 0000000..65e5472 --- /dev/null +++ b/healthcare/healthcare/dashboard_chart/symptoms/symptoms.json @@ -0,0 +1,26 @@ +{ + "chart_name": "Symptoms", + "chart_type": "Group By", + "creation": "2020-07-14 18:17:54.680852", + "docstatus": 0, + "doctype": "Dashboard Chart", + "document_type": "Patient Encounter Symptom", + "dynamic_filters_json": "", + "filters_json": "[]", + "group_by_based_on": "complaint", + "group_by_type": "Count", + "idx": 0, + "is_public": 1, + "is_standard": 1, + "last_synced_on": "2021-01-30 21:03:32.067473", + "modified": "2021-02-01 13:35:30.953718", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Symptoms", + "number_of_groups": 0, + "owner": "Administrator", + "timeseries": 0, + "type": "Bar", + "use_report_chart": 0, + "y_axis": [] +} \ No newline at end of file diff --git a/healthcare/healthcare/dashboard_chart_source/__init__.py b/healthcare/healthcare/dashboard_chart_source/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/dashboard_chart_source/department_wise_patient_appointments/__init__.py b/healthcare/healthcare/dashboard_chart_source/department_wise_patient_appointments/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/dashboard_chart_source/department_wise_patient_appointments/department_wise_patient_appointments.js b/healthcare/healthcare/dashboard_chart_source/department_wise_patient_appointments/department_wise_patient_appointments.js new file mode 100644 index 0000000..0097cdf --- /dev/null +++ b/healthcare/healthcare/dashboard_chart_source/department_wise_patient_appointments/department_wise_patient_appointments.js @@ -0,0 +1,14 @@ +frappe.provide('frappe.dashboards.chart_sources'); + +frappe.dashboards.chart_sources["Department wise Patient Appointments"] = { + method: "healthcare.healthcare.dashboard_chart_source.department_wise_patient_appointments.department_wise_patient_appointments.get", + filters: [ + { + fieldname: "company", + label: __("Company"), + fieldtype: "Link", + options: "Company", + default: frappe.defaults.get_user_default("Company") + } + ] +}; diff --git a/healthcare/healthcare/dashboard_chart_source/department_wise_patient_appointments/department_wise_patient_appointments.json b/healthcare/healthcare/dashboard_chart_source/department_wise_patient_appointments/department_wise_patient_appointments.json new file mode 100644 index 0000000..00301ef --- /dev/null +++ b/healthcare/healthcare/dashboard_chart_source/department_wise_patient_appointments/department_wise_patient_appointments.json @@ -0,0 +1,13 @@ +{ + "creation": "2020-05-18 19:18:42.571045", + "docstatus": 0, + "doctype": "Dashboard Chart Source", + "idx": 0, + "modified": "2020-05-18 19:18:42.571045", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Department wise Patient Appointments", + "owner": "Administrator", + "source_name": "Department wise Patient Appointments", + "timeseries": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/dashboard_chart_source/department_wise_patient_appointments/department_wise_patient_appointments.py b/healthcare/healthcare/dashboard_chart_source/department_wise_patient_appointments/department_wise_patient_appointments.py new file mode 100644 index 0000000..5a619bf --- /dev/null +++ b/healthcare/healthcare/dashboard_chart_source/department_wise_patient_appointments/department_wise_patient_appointments.py @@ -0,0 +1,70 @@ +# Copyright (c) 2015, InfluxERP +# License: GNU General Public License v3. See license.txt + + +import frappe +from frappe.utils.dashboard import cache_source + + +@frappe.whitelist() +@cache_source +def get( + chart_name=None, + chart=None, + no_cache=None, + filters=None, + from_date=None, + to_date=None, + timespan=None, + time_interval=None, + heatmap_year=None, +): + if chart_name: + chart = frappe.get_doc("Dashboard Chart", chart_name) + else: + chart = frappe._dict(frappe.parse_json(chart)) + + filters = frappe.parse_json(filters) + + data = frappe.db.get_list("Medical Department", fields=["name"]) + if not filters: + filters = {} + + status = ["Open", "Scheduled", "Closed", "Cancelled"] + for department in data: + filters["department"] = department.name + department["total_appointments"] = frappe.db.count("Patient Appointment", filters=filters) + + for entry in status: + filters["status"] = entry + department[frappe.scrub(entry)] = frappe.db.count("Patient Appointment", filters=filters) + filters.pop("status") + + sorted_department_map = sorted(data, key=lambda i: i["total_appointments"], reverse=True) + + if len(sorted_department_map) > 10: + sorted_department_map = sorted_department_map[:10] + + labels = [] + open_appointments = [] + scheduled = [] + closed = [] + cancelled = [] + + for department in sorted_department_map: + labels.append(department.name) + open_appointments.append(department.open) + scheduled.append(department.scheduled) + closed.append(department.closed) + cancelled.append(department.cancelled) + + return { + "labels": labels, + "datasets": [ + {"name": "Open", "values": open_appointments}, + {"name": "Scheduled", "values": scheduled}, + {"name": "Closed", "values": closed}, + {"name": "Cancelled", "values": cancelled}, + ], + "type": "bar", + } diff --git a/healthcare/healthcare/desk_page/healthcare/healthcare.json b/healthcare/healthcare/desk_page/healthcare/healthcare.json new file mode 100644 index 0000000..af601f3 --- /dev/null +++ b/healthcare/healthcare/desk_page/healthcare/healthcare.json @@ -0,0 +1,122 @@ +{ + "cards": [ + { + "hidden": 0, + "label": "Masters", + "links": "[\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Patient\",\n\t\t\"label\": \"Patient\",\n\t\t\"onboard\": 1\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Healthcare Practitioner\",\n\t\t\"label\":\"Healthcare Practitioner\",\n\t\t\"onboard\": 1\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Practitioner Schedule\",\n\t\t\"label\": \"Practitioner Schedule\",\n\t\t\"onboard\": 1\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Medical Department\",\n\t\t\"label\": \"Medical Department\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Healthcare Service Unit Type\",\n\t\t\"label\": \"Healthcare Service Unit Type\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Healthcare Service Unit\",\n\t\t\"label\": \"Healthcare Service Unit\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Medical Code Standard\",\n\t\t\"label\": \"Medical Code Standard\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Medical Code\",\n\t\t\"label\": \"Medical Code\"\n\t}\n]" + }, + { + "hidden": 0, + "label": "Consultation Setup", + "links": "[\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Appointment Type\",\n\t\t\"label\": \"Appointment Type\"\n },\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Clinical Procedure Template\",\n\t\t\"label\": \"Clinical Procedure Template\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Prescription Dosage\",\n\t\t\"label\": \"Prescription Dosage\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Prescription Duration\",\n\t\t\"label\": \"Prescription Duration\"\n\t},\n\t{\n\t \"type\": \"doctype\",\n\t\t\"name\": \"Antibiotic\",\n\t\t\"label\": \"Antibiotic\"\n\t}\n]" + }, + { + "hidden": 0, + "label": "Consultation", + "links": "[\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Patient Appointment\",\n\t\t\"label\": \"Patient Appointment\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Clinical Procedure\",\n\t\t\"label\": \"Clinical Procedure\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Patient Encounter\",\n\t\t\"label\": \"Patient Encounter\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Vital Signs\",\n\t\t\"label\": \"Vital Signs\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Complaint\",\n\t\t\"label\": \"Complaint\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Diagnosis\",\n\t\t\"label\": \"Diagnosis\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Fee Validity\",\n\t\t\"label\": \"Fee Validity\"\n\t}\n]" + }, + { + "hidden": 0, + "label": "Settings", + "links": "[\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Healthcare Settings\",\n\t\t\"label\": \"Healthcare Settings\",\n\t\t\"onboard\": 1\n\t}\n]" + }, + { + "hidden": 0, + "label": "Laboratory Setup", + "links": "[\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Lab Test Template\",\n\t\t\"label\": \"Lab Test Template\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Lab Test Sample\",\n\t\t\"label\": \"Lab Test Sample\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Lab Test UOM\",\n\t\t\"label\": \"Lab Test UOM\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Sensitivity\",\n\t\t\"label\": \"Sensitivity\"\n\t}\n]" + }, + { + "hidden": 0, + "label": "Laboratory", + "links": "[\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Lab Test\",\n\t\t\"label\": \"Lab Test\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Sample Collection\",\n\t\t\"label\": \"Sample Collection\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Dosage Form\",\n\t\t\"label\": \"Dosage Form\"\n\t}\n]" + }, + { + "hidden": 0, + "label": "Inpatient", + "links": "[\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Inpatient Record\",\n\t\t\"label\": \"Inpatient Record\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Inpatient Medication Order\",\n\t\t\"label\": \"Inpatient Medication Order\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Inpatient Medication Entry\",\n\t\t\"label\": \"Inpatient Medication Entry\"\n\t}\n]" + }, + { + "hidden": 0, + "label": "Rehabilitation and Physiotherapy", + "links": "[\n {\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Exercise Type\",\n\t\t\"label\": \"Exercise Type\",\n\t\t\"onboard\": 1\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Therapy Type\",\n\t\t\"label\": \"Therapy Type\",\n\t\t\"onboard\": 1\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Therapy Plan\",\n\t\t\"label\": \"Therapy Plan\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Therapy Session\",\n\t\t\"label\": \"Therapy Session\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Patient Assessment Template\",\n\t\t\"label\": \"Patient Assessment Template\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Patient Assessment\",\n\t\t\"label\": \"Patient Assessment\"\n\t}\n]" + }, + { + "hidden": 0, + "label": "Records and History", + "links": "[\n\t{\n\t\t\"type\": \"page\",\n\t\t\"name\": \"patient_history\",\n\t\t\"label\": \"Patient History\"\n\t},\n\t{\n\t\t\"type\": \"page\",\n\t\t\"name\": \"patient-progress\",\n\t\t\"label\": \"Patient Progress\"\n\t},\n\t{\n\t\t\"type\": \"doctype\",\n\t\t\"name\": \"Patient Medical Record\",\n\t\t\"label\": \"Patient Medical Record\"\n\t}\n]" + }, + { + "hidden": 0, + "label": "Reports", + "links": "[\n\t{\n\t\t\"type\": \"report\",\n\t\t\"is_query_report\": true,\n\t\t\"name\": \"Patient Appointment Analytics\",\n\t\t\"doctype\": \"Patient Appointment\"\n\t},\n\t{\n\t\t\"type\": \"report\",\n\t\t\"is_query_report\": true,\n\t\t\"name\": \"Lab Test Report\",\n\t\t\"doctype\": \"Lab Test\",\n\t\t\"label\": \"Lab Test Report\"\n\t},\n\t{\n\t\t\"type\": \"report\",\n\t\t\"is_query_report\": true,\n\t\t\"name\": \"Inpatient Medication Orders\",\n\t\t\"doctype\": \"Inpatient Medication Order\",\n\t\t\"label\": \"Inpatient Medication Orders\"\n\t}\n]" + } + ], + "category": "Domains", + "charts": [ + { + "chart_name": "Patient Appointments", + "label": "Patient Appointments" + } + ], + "charts_label": "", + "creation": "2020-03-02 17:23:17.919682", + "developer_mode_only": 0, + "disable_user_customization": 0, + "docstatus": 0, + "doctype": "Desk Page", + "extends_another_page": 0, + "hide_custom": 0, + "idx": 0, + "is_standard": 1, + "label": "Healthcare", + "modified": "2020-11-26 22:09:09.164584", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Healthcare", + "onboarding": "Healthcare", + "owner": "Administrator", + "pin_to_bottom": 0, + "pin_to_top": 0, + "restrict_to_domain": "Healthcare", + "shortcuts": [ + { + "color": "#ffe8cd", + "format": "{} Open", + "label": "Patient Appointment", + "link_to": "Patient Appointment", + "stats_filter": "{\n \"status\": \"Open\",\n \"company\": [\"like\", '%' + frappe.defaults.get_global_default(\"company\") + '%']\n}", + "type": "DocType" + }, + { + "color": "#ffe8cd", + "format": "{} Active", + "label": "Patient", + "link_to": "Patient", + "stats_filter": "{\n \"status\": \"Active\"\n}", + "type": "DocType" + }, + { + "color": "#cef6d1", + "format": "{} Vacant", + "label": "Healthcare Service Unit", + "link_to": "Healthcare Service Unit", + "stats_filter": "{\n \"occupancy_status\": \"Vacant\",\n \"is_group\": 0,\n \"company\": [\"like\", \"%\" + frappe.defaults.get_global_default(\"company\") + \"%\"]\n}", + "type": "DocType" + }, + { + "label": "Healthcare Practitioner", + "link_to": "Healthcare Practitioner", + "type": "DocType" + }, + { + "label": "Patient History", + "link_to": "patient_history", + "type": "Page" + }, + { + "label": "Dashboard", + "link_to": "Healthcare", + "type": "Dashboard" + } + ] +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/__init__.py b/healthcare/healthcare/doctype/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/antibiotic/__init__.py b/healthcare/healthcare/doctype/antibiotic/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/antibiotic/antibiotic.js b/healthcare/healthcare/doctype/antibiotic/antibiotic.js new file mode 100644 index 0000000..8ac7946 --- /dev/null +++ b/healthcare/healthcare/doctype/antibiotic/antibiotic.js @@ -0,0 +1,5 @@ +// Copyright (c) 2017, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Antibiotic', { +}); diff --git a/healthcare/healthcare/doctype/antibiotic/antibiotic.json b/healthcare/healthcare/doctype/antibiotic/antibiotic.json new file mode 100644 index 0000000..41a3e31 --- /dev/null +++ b/healthcare/healthcare/doctype/antibiotic/antibiotic.json @@ -0,0 +1,151 @@ +{ + "allow_copy": 1, + "allow_events_in_timeline": 0, + "allow_guest_to_view": 0, + "allow_import": 1, + "allow_rename": 1, + "autoname": "field:antibiotic_name", + "beta": 1, + "creation": "2016-02-23 11:11:30.749731", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "Setup", + "editable_grid": 0, + "fields": [ + { + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fetch_if_empty": 0, + "fieldname": "antibiotic_name", + "fieldtype": "Data", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Antibiotic Name", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 1 + }, + { + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fetch_if_empty": 0, + "fieldname": "abbr", + "fieldtype": "Data", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 0, + "in_standard_filter": 0, + "label": "Abbr", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 0, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 1 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 0, + "max_attachments": 0, + "modified": "2019-10-01 17:58:23.136498", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Antibiotic", + "name_case": "", + "owner": "Administrator", + "permissions": [ + { + "amend": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + }, + { + "amend": 0, + "cancel": 0, + "create": 0, + "delete": 0, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Laboratory User", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 0 + } + ], + "quick_entry": 1, + "read_only": 0, + "read_only_onload": 0, + "restrict_to_domain": "Healthcare", + "search_fields": "antibiotic_name", + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "antibiotic_name", + "track_changes": 0, + "track_seen": 0, + "track_views": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/antibiotic/antibiotic.py b/healthcare/healthcare/doctype/antibiotic/antibiotic.py new file mode 100644 index 0000000..45ab853 --- /dev/null +++ b/healthcare/healthcare/doctype/antibiotic/antibiotic.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class Antibiotic(Document): + pass diff --git a/healthcare/healthcare/doctype/antibiotic/test_antibiotic.py b/healthcare/healthcare/doctype/antibiotic/test_antibiotic.py new file mode 100644 index 0000000..5f71716 --- /dev/null +++ b/healthcare/healthcare/doctype/antibiotic/test_antibiotic.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + + +class TestAntibiotic(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/appointment_type/__init__.py b/healthcare/healthcare/doctype/appointment_type/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/appointment_type/appointment_type.js b/healthcare/healthcare/doctype/appointment_type/appointment_type.js new file mode 100644 index 0000000..99b7cb2 --- /dev/null +++ b/healthcare/healthcare/doctype/appointment_type/appointment_type.js @@ -0,0 +1,83 @@ +// Copyright (c) 2016, ESS LLP and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Appointment Type', { + refresh: function(frm) { + frm.set_query('price_list', function() { + return { + filters: {'selling': 1} + }; + }); + + frm.set_query('medical_department', 'items', function(doc) { + let item_list = doc.items.map(({medical_department}) => medical_department); + return { + filters: [ + ['Medical Department', 'name', 'not in', item_list] + ] + }; + }); + + frm.set_query('op_consulting_charge_item', 'items', function() { + return { + filters: { + is_stock_item: 0 + } + }; + }); + + frm.set_query('inpatient_visit_charge_item', 'items', function() { + return { + filters: { + is_stock_item: 0 + } + }; + }); + } +}); + +frappe.ui.form.on('Appointment Type Service Item', { + op_consulting_charge_item: function(frm, cdt, cdn) { + let d = locals[cdt][cdn]; + if (frm.doc.price_list && d.op_consulting_charge_item) { + frappe.call({ + 'method': 'frappe.client.get_value', + args: { + 'doctype': 'Item Price', + 'filters': { + 'item_code': d.op_consulting_charge_item, + 'price_list': frm.doc.price_list + }, + 'fieldname': ['price_list_rate'] + }, + callback: function(data) { + if (data.message.price_list_rate) { + frappe.model.set_value(cdt, cdn, 'op_consulting_charge', data.message.price_list_rate); + } + } + }); + } + }, + + inpatient_visit_charge_item: function(frm, cdt, cdn) { + let d = locals[cdt][cdn]; + if (frm.doc.price_list && d.inpatient_visit_charge_item) { + frappe.call({ + 'method': 'frappe.client.get_value', + args: { + 'doctype': 'Item Price', + 'filters': { + 'item_code': d.inpatient_visit_charge_item, + 'price_list': frm.doc.price_list + }, + 'fieldname': ['price_list_rate'] + }, + callback: function (data) { + if (data.message.price_list_rate) { + frappe.model.set_value(cdt, cdn, 'inpatient_visit_charge', data.message.price_list_rate); + } + } + }); + } + } +}); diff --git a/healthcare/healthcare/doctype/appointment_type/appointment_type.json b/healthcare/healthcare/doctype/appointment_type/appointment_type.json new file mode 100644 index 0000000..3872318 --- /dev/null +++ b/healthcare/healthcare/doctype/appointment_type/appointment_type.json @@ -0,0 +1,114 @@ +{ + "actions": [], + "allow_import": 1, + "allow_rename": 1, + "autoname": "field:appointment_type", + "beta": 1, + "creation": "2016-07-22 11:52:34.953019", + "doctype": "DocType", + "document_type": "Setup", + "engine": "InnoDB", + "field_order": [ + "appointment_type", + "ip", + "default_duration", + "color", + "billing_section", + "price_list", + "items" + ], + "fields": [ + { + "allow_in_quick_entry": 1, + "fieldname": "appointment_type", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Type", + "reqd": 1, + "translatable": 1, + "unique": 1 + }, + { + "bold": 1, + "default": "0", + "fieldname": "ip", + "fieldtype": "Check", + "label": "Is Inpatient", + "print_hide": 1, + "report_hide": 1 + }, + { + "allow_in_quick_entry": 1, + "bold": 1, + "fieldname": "default_duration", + "fieldtype": "Int", + "in_filter": 1, + "in_list_view": 1, + "label": "Default Duration (In Minutes)" + }, + { + "allow_in_quick_entry": 1, + "fieldname": "color", + "fieldtype": "Color", + "in_list_view": 1, + "label": "Color", + "no_copy": 1, + "report_hide": 1 + }, + { + "fieldname": "billing_section", + "fieldtype": "Section Break", + "label": "Billing" + }, + { + "fieldname": "price_list", + "fieldtype": "Link", + "label": "Price List", + "options": "Price List" + }, + { + "fieldname": "items", + "fieldtype": "Table", + "label": "Appointment Type Service Items", + "options": "Appointment Type Service Item" + } + ], + "links": [], + "modified": "2021-01-22 09:41:05.010524", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Appointment Type", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "restrict_to_domain": "Healthcare", + "search_fields": "appointment_type", + "sort_field": "modified", + "sort_order": "DESC" +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/appointment_type/appointment_type.py b/healthcare/healthcare/doctype/appointment_type/appointment_type.py new file mode 100644 index 0000000..ca73847 --- /dev/null +++ b/healthcare/healthcare/doctype/appointment_type/appointment_type.py @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and contributors +# For license information, please see license.txt + + +import frappe +from frappe.model.document import Document + + +class AppointmentType(Document): + def validate(self): + if self.items and self.price_list: + for item in self.items: + existing_op_item_price = frappe.db.exists( + "Item Price", {"item_code": item.op_consulting_charge_item, "price_list": self.price_list} + ) + + if not existing_op_item_price and item.op_consulting_charge_item and item.op_consulting_charge: + make_item_price(self.price_list, item.op_consulting_charge_item, item.op_consulting_charge) + + existing_ip_item_price = frappe.db.exists( + "Item Price", {"item_code": item.inpatient_visit_charge_item, "price_list": self.price_list} + ) + + if ( + not existing_ip_item_price + and item.inpatient_visit_charge_item + and item.inpatient_visit_charge + ): + make_item_price( + self.price_list, item.inpatient_visit_charge_item, item.inpatient_visit_charge + ) + + +@frappe.whitelist() +def get_service_item_based_on_department(appointment_type, department): + item_list = frappe.db.get_value( + "Appointment Type Service Item", + filters={"medical_department": department, "parent": appointment_type}, + fieldname=[ + "op_consulting_charge_item", + "inpatient_visit_charge_item", + "op_consulting_charge", + "inpatient_visit_charge", + ], + as_dict=1, + ) + + # if department wise items are not set up + # use the generic items + if not item_list: + item_list = frappe.db.get_value( + "Appointment Type Service Item", + filters={"parent": appointment_type}, + fieldname=[ + "op_consulting_charge_item", + "inpatient_visit_charge_item", + "op_consulting_charge", + "inpatient_visit_charge", + ], + as_dict=1, + ) + + return item_list + + +def make_item_price(price_list, item, item_price): + frappe.get_doc( + { + "doctype": "Item Price", + "price_list": price_list, + "item_code": item, + "price_list_rate": item_price, + } + ).insert(ignore_permissions=True, ignore_mandatory=True) diff --git a/healthcare/healthcare/doctype/appointment_type/appointment_type_dashboard.py b/healthcare/healthcare/doctype/appointment_type/appointment_type_dashboard.py new file mode 100644 index 0000000..04bc04a --- /dev/null +++ b/healthcare/healthcare/doctype/appointment_type/appointment_type_dashboard.py @@ -0,0 +1,10 @@ +from frappe import _ + + +def get_data(): + return { + "fieldname": "appointment_type", + "transactions": [ + {"label": _("Patient Appointments"), "items": ["Patient Appointment"]}, + ], + } diff --git a/healthcare/healthcare/doctype/appointment_type/test_appointment_type.py b/healthcare/healthcare/doctype/appointment_type/test_appointment_type.py new file mode 100644 index 0000000..2cabf51 --- /dev/null +++ b/healthcare/healthcare/doctype/appointment_type/test_appointment_type.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +# test_records = frappe.get_test_records('Appointment Type') + + +class TestAppointmentType(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/appointment_type_service_item/__init__.py b/healthcare/healthcare/doctype/appointment_type_service_item/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/appointment_type_service_item/appointment_type_service_item.json b/healthcare/healthcare/doctype/appointment_type_service_item/appointment_type_service_item.json new file mode 100644 index 0000000..ccae129 --- /dev/null +++ b/healthcare/healthcare/doctype/appointment_type_service_item/appointment_type_service_item.json @@ -0,0 +1,67 @@ +{ + "actions": [], + "creation": "2021-01-22 09:34:53.373105", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "medical_department", + "op_consulting_charge_item", + "op_consulting_charge", + "column_break_4", + "inpatient_visit_charge_item", + "inpatient_visit_charge" + ], + "fields": [ + { + "fieldname": "medical_department", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Medical Department", + "options": "Medical Department" + }, + { + "fieldname": "op_consulting_charge_item", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Out Patient Consulting Charge Item", + "options": "Item" + }, + { + "fieldname": "op_consulting_charge", + "fieldtype": "Currency", + "in_list_view": 1, + "label": "Out Patient Consulting Charge" + }, + { + "fieldname": "column_break_4", + "fieldtype": "Column Break" + }, + { + "fieldname": "inpatient_visit_charge_item", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Inpatient Visit Charge Item", + "options": "Item" + }, + { + "fieldname": "inpatient_visit_charge", + "fieldtype": "Currency", + "in_list_view": 1, + "label": "Inpatient Visit Charge" + } + ], + "index_web_pages_for_search": 1, + "istable": 1, + "links": [], + "modified": "2021-08-17 06:05:02.240812", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Appointment Type Service Item", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/appointment_type_service_item/appointment_type_service_item.py b/healthcare/healthcare/doctype/appointment_type_service_item/appointment_type_service_item.py new file mode 100644 index 0000000..73f384c --- /dev/null +++ b/healthcare/healthcare/doctype/appointment_type_service_item/appointment_type_service_item.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2021, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class AppointmentTypeServiceItem(Document): + pass diff --git a/healthcare/healthcare/doctype/body_part/__init__.py b/healthcare/healthcare/doctype/body_part/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/body_part/body_part.js b/healthcare/healthcare/doctype/body_part/body_part.js new file mode 100644 index 0000000..443d60b --- /dev/null +++ b/healthcare/healthcare/doctype/body_part/body_part.js @@ -0,0 +1,8 @@ +// Copyright (c) 2020, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Body Part', { + // refresh: function(frm) { + + // } +}); diff --git a/healthcare/healthcare/doctype/body_part/body_part.json b/healthcare/healthcare/doctype/body_part/body_part.json new file mode 100644 index 0000000..6e3d1d4 --- /dev/null +++ b/healthcare/healthcare/doctype/body_part/body_part.json @@ -0,0 +1,45 @@ +{ + "actions": [], + "autoname": "field:body_part", + "creation": "2020-04-10 12:21:55.036402", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "body_part" + ], + "fields": [ + { + "fieldname": "body_part", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Body Part", + "reqd": 1, + "unique": 1 + } + ], + "links": [], + "modified": "2020-04-10 12:26:44.087985", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Body Part", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/body_part/body_part.py b/healthcare/healthcare/doctype/body_part/body_part.py new file mode 100644 index 0000000..39191b7 --- /dev/null +++ b/healthcare/healthcare/doctype/body_part/body_part.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class BodyPart(Document): + pass diff --git a/healthcare/healthcare/doctype/body_part/test_body_part.py b/healthcare/healthcare/doctype/body_part/test_body_part.py new file mode 100644 index 0000000..6e0273d --- /dev/null +++ b/healthcare/healthcare/doctype/body_part/test_body_part.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# See license.txt + + +# import frappe +from frappe.tests.utils import FrappeTestCase + + +class TestBodyPart(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/body_part_link/__init__.py b/healthcare/healthcare/doctype/body_part_link/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/body_part_link/body_part_link.json b/healthcare/healthcare/doctype/body_part_link/body_part_link.json new file mode 100644 index 0000000..400b7c6 --- /dev/null +++ b/healthcare/healthcare/doctype/body_part_link/body_part_link.json @@ -0,0 +1,32 @@ +{ + "actions": [], + "creation": "2020-04-10 12:23:15.259816", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "body_part" + ], + "fields": [ + { + "fieldname": "body_part", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Body Part", + "options": "Body Part", + "reqd": 1 + } + ], + "istable": 1, + "links": [], + "modified": "2020-04-10 12:25:23.101749", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Body Part Link", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/body_part_link/body_part_link.py b/healthcare/healthcare/doctype/body_part_link/body_part_link.py new file mode 100644 index 0000000..712bee1 --- /dev/null +++ b/healthcare/healthcare/doctype/body_part_link/body_part_link.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class BodyPartLink(Document): + pass diff --git a/healthcare/healthcare/doctype/clinical_procedure/__init__.py b/healthcare/healthcare/doctype/clinical_procedure/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/clinical_procedure/clinical_procedure.js b/healthcare/healthcare/doctype/clinical_procedure/clinical_procedure.js new file mode 100644 index 0000000..bdefbc0 --- /dev/null +++ b/healthcare/healthcare/doctype/clinical_procedure/clinical_procedure.js @@ -0,0 +1,377 @@ +// Copyright (c) 2017, ESS LLP and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Clinical Procedure', { + setup: function(frm) { + frm.set_query('batch_no', 'items', function(doc, cdt, cdn) { + let item = locals[cdt][cdn]; + if (!item.item_code) { + frappe.throw(__('Please enter Item Code to get Batch Number')); + } else { + let filters = {'item_code': item.item_code}; + + if (frm.doc.status == 'In Progress') { + filters['posting_date'] = frm.doc.start_date || frappe.datetime.nowdate(); + if (frm.doc.warehouse) filters['warehouse'] = frm.doc.warehouse; + } + + return { + query : 'erpnext.controllers.queries.get_batch_no', + filters: filters + }; + } + }); + }, + + refresh: function(frm) { + frm.set_query('patient', function () { + return { + filters: {'status': ['!=', 'Disabled']} + }; + }); + + frm.set_query('appointment', function () { + return { + filters: { + 'procedure_template': ['not in', null], + 'status': ['in', 'Open, Scheduled'] + } + }; + }); + + frm.set_query('service_unit', function() { + return { + filters: { + 'is_group': false, + 'allow_appointments': true, + 'company': frm.doc.company + } + }; + }); + + frm.set_query('practitioner', function() { + return { + filters: { + 'department': frm.doc.medical_department + } + }; + }); + + if (frm.doc.consume_stock) { + frm.set_indicator_formatter('item_code', + function(doc) { return (doc.qty<=doc.actual_qty) ? 'green' : 'orange' ; }); + } + + if (frm.doc.docstatus == 1) { + if (frm.doc.status == 'In Progress') { + let btn_label = ''; + let msg = ''; + if (frm.doc.consume_stock) { + btn_label = __('Complete and Consume'); + msg = __('Complete {0} and Consume Stock?', [frm.doc.name]); + } else { + btn_label = 'Complete'; + msg = __('Complete {0}?', [frm.doc.name]); + } + + frm.add_custom_button(__(btn_label), function () { + frappe.confirm( + msg, + function() { + frappe.call({ + method: 'complete_procedure', + doc: frm.doc, + freeze: true, + callback: function(r) { + if (r.message) { + frappe.show_alert({ + message: __('Stock Entry {0} created', ['' + r.message + '']), + indicator: 'green' + }); + } + frm.reload_doc(); + } + }); + } + ); + }).addClass("btn-primary"); + + } else if (frm.doc.status == 'Pending') { + frm.add_custom_button(__('Start'), function() { + frappe.call({ + doc: frm.doc, + method: 'start_procedure', + callback: function(r) { + if (!r.exc) { + if (r.message == 'insufficient stock') { + let msg = __('Stock quantity to start the Procedure is not available in the Warehouse {0}. Do you want to record a Stock Entry?', [frm.doc.warehouse.bold()]); + frappe.confirm( + msg, + function() { + frappe.call({ + doc: frm.doc, + method: 'make_material_receipt', + freeze: true, + callback: function(r) { + if (!r.exc) { + frm.reload_doc(); + let doclist = frappe.model.sync(r.message); + frappe.set_route('Form', doclist[0].doctype, doclist[0].name); + } + } + }); + } + ); + } else { + frm.reload_doc(); + } + } + } + }); + }).addClass("btn-primary"); + } + } + }, + + onload: function(frm) { + if (frm.is_new()) { + frm.add_fetch('procedure_template', 'medical_department', 'medical_department'); + frm.set_value('start_time', null); + } + }, + + patient: function(frm) { + if (frm.doc.patient) { + frappe.call({ + 'method': 'healthcare.healthcare.doctype.patient.patient.get_patient_detail', + args: { + patient: frm.doc.patient + }, + callback: function (data) { + let age = ''; + if (data.message.dob) { + age = calculate_age(data.message.dob); + } else if (data.message.age) { + age = data.message.age; + if (data.message.age_as_on) { + age = __('{0} as on {1}', [age, data.message.age_as_on]); + } + } + frm.set_value('patient_name', data.message.patient_name); + frm.set_value('patient_age', age); + frm.set_value('patient_sex', data.message.sex); + } + }); + } else { + frm.set_value('patient_name', ''); + frm.set_value('patient_age', ''); + frm.set_value('patient_sex', ''); + } + }, + + appointment: function(frm) { + if (frm.doc.appointment) { + frappe.call({ + 'method': 'frappe.client.get', + args: { + doctype: 'Patient Appointment', + name: frm.doc.appointment + }, + callback: function(data) { + let values = { + 'patient':data.message.patient, + 'procedure_template': data.message.procedure_template, + 'medical_department': data.message.department, + 'practitioner': data.message.practitioner, + 'start_date': data.message.appointment_date, + 'start_time': data.message.appointment_time, + 'notes': data.message.notes, + 'service_unit': data.message.service_unit, + 'company': data.message.company + }; + frm.set_value(values); + } + }); + } else { + let values = { + 'patient': '', + 'patient_name': '', + 'patient_sex': '', + 'patient_age': '', + 'medical_department': '', + 'procedure_template': '', + 'start_date': '', + 'start_time': '', + 'notes': '', + 'service_unit': '', + 'inpatient_record': '' + }; + frm.set_value(values); + } + }, + + procedure_template: function(frm) { + if (frm.doc.procedure_template) { + frappe.call({ + 'method': 'frappe.client.get', + args: { + doctype: 'Clinical Procedure Template', + name: frm.doc.procedure_template + }, + callback: function (data) { + frm.set_value('medical_department', data.message.medical_department); + frm.set_value('consume_stock', data.message.consume_stock); + frm.events.set_warehouse(frm); + frm.events.set_procedure_consumables(frm); + } + }); + } + }, + + service_unit: function(frm) { + if (frm.doc.service_unit) { + frappe.call({ + method: 'frappe.client.get_value', + args:{ + fieldname: 'warehouse', + doctype: 'Healthcare Service Unit', + filters:{name: frm.doc.service_unit}, + }, + callback: function(data) { + if (data.message) { + frm.set_value('warehouse', data.message.warehouse); + } + } + }); + } + }, + + practitioner: function(frm) { + if (frm.doc.practitioner) { + frappe.call({ + 'method': 'frappe.client.get', + args: { + doctype: 'Healthcare Practitioner', + name: frm.doc.practitioner + }, + callback: function (data) { + frappe.model.set_value(frm.doctype,frm.docname, 'practitioner_name', data.message.practitioner_name); + } + }); + } else { + frappe.model.set_value(frm.doctype,frm.docname, 'practitioner_name', ''); + } + }, + + set_warehouse: function(frm) { + if (!frm.doc.warehouse) { + frappe.call({ + method: 'frappe.client.get_value', + args: { + doctype: 'Stock Settings', + fieldname: 'default_warehouse' + }, + callback: function (data) { + frm.set_value('warehouse', data.message.default_warehouse); + } + }); + } + }, + + set_procedure_consumables: function(frm) { + frappe.call({ + method: 'healthcare.healthcare.doctype.clinical_procedure.clinical_procedure.get_procedure_consumables', + args: { + procedure_template: frm.doc.procedure_template + }, + callback: function(data) { + if (data.message) { + frm.doc.items = []; + $.each(data.message, function(i, v) { + let item = frm.add_child('items'); + item.item_code = v.item_code; + item.item_name = v.item_name; + item.uom = v.uom; + item.stock_uom = v.stock_uom; + item.qty = flt(v.qty); + item.transfer_qty = v.transfer_qty; + item.conversion_factor = v.conversion_factor; + item.invoice_separately_as_consumables = v.invoice_separately_as_consumables; + item.batch_no = v.batch_no; + }); + refresh_field('items'); + } + } + }); + } + +}); + +frappe.ui.form.on('Clinical Procedure Item', { + qty: function(frm, cdt, cdn) { + let d = locals[cdt][cdn]; + frappe.model.set_value(cdt, cdn, 'transfer_qty', d.qty*d.conversion_factor); + }, + + uom: function(doc, cdt, cdn) { + let d = locals[cdt][cdn]; + if (d.uom && d.item_code) { + return frappe.call({ + method: 'erpnext.stock.doctype.stock_entry.stock_entry.get_uom_details', + args: { + item_code: d.item_code, + uom: d.uom, + qty: d.qty + }, + callback: function(r) { + if (r.message) { + frappe.model.set_value(cdt, cdn, r.message); + } + } + }); + } + }, + + item_code: function(frm, cdt, cdn) { + let d = locals[cdt][cdn]; + let args = null; + if (d.item_code) { + args = { + 'doctype' : 'Clinical Procedure', + 'item_code' : d.item_code, + 'company' : frm.doc.company, + 'warehouse': frm.doc.warehouse + }; + return frappe.call({ + method: 'healthcare.healthcare.doctype.clinical_procedure_template.clinical_procedure_template.get_item_details', + args: {args: args}, + callback: function(r) { + if (r.message) { + let d = locals[cdt][cdn]; + $.each(r.message, function(k, v) { + d[k] = v; + }); + refresh_field('items'); + } + } + }); + } + } +}); + +let calculate_age = function(birth) { + let ageMS = Date.parse(Date()) - Date.parse(birth); + let age = new Date(); + age.setTime(ageMS); + let years = age.getFullYear() - 1970; + return `${years} ${__('Years(s)')} ${age.getMonth()} ${__('Month(s)')} ${age.getDate()} ${__('Day(s)')}`; +}; + +// List Stock items +cur_frm.set_query('item_code', 'items', function() { + return { + filters: { + is_stock_item:1 + } + }; +}); diff --git a/healthcare/healthcare/doctype/clinical_procedure/clinical_procedure.json b/healthcare/healthcare/doctype/clinical_procedure/clinical_procedure.json new file mode 100644 index 0000000..48a9c28 --- /dev/null +++ b/healthcare/healthcare/doctype/clinical_procedure/clinical_procedure.json @@ -0,0 +1,351 @@ +{ + "actions": [], + "autoname": "naming_series:", + "beta": 1, + "creation": "2017-04-07 12:52:43.542429", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "naming_series", + "title", + "appointment", + "procedure_template", + "medical_code", + "column_break_30", + "company", + "invoiced", + "section_break_6", + "patient", + "patient_name", + "patient_sex", + "patient_age", + "inpatient_record", + "notes", + "column_break_7", + "status", + "practitioner", + "practitioner_name", + "medical_department", + "service_unit", + "start_date", + "start_time", + "sample", + "consumables_section", + "consume_stock", + "warehouse", + "items", + "section_break_24", + "invoice_separately_as_consumables", + "consumption_invoiced", + "consumable_total_amount", + "column_break_27", + "consumption_details", + "sb_refs", + "column_break_34", + "prescription", + "amended_from" + ], + "fields": [ + { + "fetch_from": "patient.inpatient_record", + "fieldname": "inpatient_record", + "fieldtype": "Link", + "label": "Inpatient Record", + "options": "Inpatient Record", + "read_only": 1 + }, + { + "fieldname": "naming_series", + "fieldtype": "Select", + "label": "Series", + "options": "HLC-CPR-.YYYY.-" + }, + { + "fieldname": "appointment", + "fieldtype": "Link", + "in_standard_filter": 1, + "label": "Appointment", + "options": "Patient Appointment", + "set_only_once": 1 + }, + { + "fieldname": "patient", + "fieldtype": "Link", + "in_standard_filter": 1, + "label": "Patient", + "options": "Patient", + "reqd": 1 + }, + { + "fieldname": "patient_age", + "fieldtype": "Data", + "label": "Age", + "read_only": 1 + }, + { + "fieldname": "patient_sex", + "fieldtype": "Link", + "label": "Gender", + "options": "Gender", + "read_only": 1, + "set_only_once": 1 + }, + { + "fieldname": "prescription", + "fieldtype": "Link", + "hidden": 1, + "label": "Procedure Prescription", + "options": "Procedure Prescription", + "read_only": 1 + }, + { + "fieldname": "medical_department", + "fieldtype": "Link", + "in_standard_filter": 1, + "label": "Medical Department", + "options": "Medical Department" + }, + { + "fieldname": "practitioner", + "fieldtype": "Link", + "in_standard_filter": 1, + "label": "Healthcare Practitioner", + "options": "Healthcare Practitioner" + }, + { + "fieldname": "column_break_7", + "fieldtype": "Column Break" + }, + { + "fieldname": "procedure_template", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Procedure Template", + "options": "Clinical Procedure Template", + "reqd": 1 + }, + { + "fieldname": "service_unit", + "fieldtype": "Link", + "label": "Service Unit", + "options": "Healthcare Service Unit", + "set_only_once": 1 + }, + { + "fieldname": "warehouse", + "fieldtype": "Link", + "label": "Warehouse", + "mandatory_depends_on": "eval: doc.consume_stock == 1", + "options": "Warehouse" + }, + { + "default": "Today", + "fieldname": "start_date", + "fieldtype": "Date", + "label": "Start Date" + }, + { + "fieldname": "start_time", + "fieldtype": "Time", + "label": "Start Time" + }, + { + "fieldname": "sample", + "fieldtype": "Link", + "label": "Sample", + "options": "Sample Collection" + }, + { + "default": "0", + "fieldname": "invoiced", + "fieldtype": "Check", + "label": "Invoiced", + "no_copy": 1, + "read_only": 1 + }, + { + "fieldname": "notes", + "fieldtype": "Small Text", + "label": "Notes", + "set_only_once": 1 + }, + { + "fieldname": "company", + "fieldtype": "Link", + "label": "Company", + "options": "Company" + }, + { + "default": "0", + "fieldname": "consume_stock", + "fieldtype": "Check", + "label": "Consume Stock" + }, + { + "fieldname": "items", + "fieldtype": "Table", + "label": "Consumables", + "options": "Clinical Procedure Item" + }, + { + "default": "0", + "fieldname": "invoice_separately_as_consumables", + "fieldtype": "Check", + "hidden": 1, + "label": "Invoice Consumables Separately", + "read_only": 1 + }, + { + "depends_on": "invoice_separately_as_consumables", + "fieldname": "consumable_total_amount", + "fieldtype": "Currency", + "label": "Consumable Total Amount", + "read_only": 1 + }, + { + "depends_on": "invoice_separately_as_consumables", + "fieldname": "consumption_details", + "fieldtype": "Small Text", + "label": "Consumption Details" + }, + { + "default": "0", + "depends_on": "invoice_separately_as_consumables", + "fieldname": "consumption_invoiced", + "fieldtype": "Check", + "hidden": 1, + "label": "Consumption Invoiced", + "read_only": 1 + }, + { + "depends_on": "eval:!doc.__islocal", + "fieldname": "status", + "fieldtype": "Select", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Status", + "options": "Draft\nSubmitted\nCancelled\nIn Progress\nCompleted\nPending", + "read_only": 1 + }, + { + "fieldname": "amended_from", + "fieldtype": "Link", + "label": "Amended From", + "no_copy": 1, + "options": "Clinical Procedure", + "print_hide": 1, + "read_only": 1 + }, + { + "collapsible": 1, + "collapsible_depends_on": "consume_stock", + "fieldname": "consumables_section", + "fieldtype": "Section Break", + "label": "Consumables" + }, + { + "fieldname": "column_break_27", + "fieldtype": "Column Break" + }, + { + "fieldname": "section_break_24", + "fieldtype": "Section Break" + }, + { + "fieldname": "column_break_30", + "fieldtype": "Column Break" + }, + { + "fieldname": "section_break_6", + "fieldtype": "Section Break" + }, + { + "collapsible": 1, + "fieldname": "sb_refs", + "fieldtype": "Section Break" + }, + { + "fieldname": "patient_name", + "fieldtype": "Data", + "label": "Patient Name", + "read_only": 1 + }, + { + "fieldname": "practitioner_name", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Practitioner Name", + "read_only": 1 + }, + { + "fieldname": "column_break_34", + "fieldtype": "Column Break" + }, + { + "allow_on_submit": 1, + "fieldname": "title", + "fieldtype": "Data", + "hidden": 1, + "label": "Title", + "no_copy": 1, + "print_hide": 1, + "read_only": 1 + }, + { + "fetch_from": "procedure_template.medical_code", + "fieldname": "medical_code", + "fieldtype": "Link", + "label": "Medical Code", + "options": "Medical Code", + "read_only": 1 + } + ], + "is_submittable": 1, + "links": [ + { + "link_doctype": "Nursing Task", + "link_fieldname": "reference_name" + } + ], + "modified": "2022-01-17 15:13:55.565922", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Clinical Procedure", + "naming_rule": "By \"Naming Series\" field", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Nursing User", + "share": 1, + "submit": 1, + "write": 1 + }, + { + "cancel": 1, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "submit": 1, + "write": 1 + } + ], + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "title", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/clinical_procedure/clinical_procedure.py b/healthcare/healthcare/doctype/clinical_procedure/clinical_procedure.py new file mode 100644 index 0000000..63bd6cd --- /dev/null +++ b/healthcare/healthcare/doctype/clinical_procedure/clinical_procedure.py @@ -0,0 +1,313 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, ESS LLP and contributors +# For license information, please see license.txt + +import frappe +from frappe import _ +from frappe.model.document import Document +from frappe.model.mapper import get_mapped_doc +from frappe.utils import flt, nowdate, nowtime, now_datetime + +from healthcare.healthcare.doctype.healthcare_settings.healthcare_settings import get_account +from healthcare.healthcare.doctype.lab_test.lab_test import create_sample_doc +from erpnext.stock.get_item_details import get_item_details +from erpnext.stock.stock_ledger import get_previous_sle +from healthcare.healthcare.doctype.nursing_task.nursing_task import NursingTask +from healthcare.healthcare.utils import validate_nursing_tasks + + +class ClinicalProcedure(Document): + def validate(self): + self.set_status() + self.set_title() + if self.consume_stock: + self.set_actual_qty() + + if self.items: + self.invoice_separately_as_consumables = False + for item in self.items: + if item.invoice_separately_as_consumables: + self.invoice_separately_as_consumables = True + + def before_insert(self): + if self.consume_stock: + self.set_actual_qty() + + def after_insert(self): + if self.prescription: + frappe.db.set_value("Procedure Prescription", self.prescription, "procedure_created", 1) + if self.appointment: + frappe.db.set_value("Patient Appointment", self.appointment, "status", "Closed") + + if self.procedure_template: + template = frappe.get_doc("Clinical Procedure Template", self.procedure_template) + if template.sample: + patient = frappe.get_doc("Patient", self.patient) + sample_collection = create_sample_doc(template, patient, None, self.company) + frappe.db.set_value("Clinical Procedure", self.name, "sample", sample_collection.name) + + self.reload() + + def on_submit(self): + self.create_nursing_tasks(post_event=False) + + def create_nursing_tasks(self, post_event=True): + if post_event: + template = frappe.db.get_value( + "Clinical Procedure Template", self.procedure_template, "post_op_nursing_checklist_template" + ) + start_time = now_datetime() + + else: + template = frappe.db.get_value( + "Clinical Procedure Template", self.procedure_template, "pre_op_nursing_checklist_template" + ) + # pre op tasks to be created on Clinical Procedure submit, use scheduled date + start_time = frappe.utils.get_datetime(f"{self.start_date} {self.start_time}") + + if template: + NursingTask.create_nursing_tasks_from_template( + template, self, start_time=start_time, post_event=post_event + ) + + def set_status(self): + if self.docstatus == 0: + self.status = "Draft" + elif self.docstatus == 1: + if self.status not in ["In Progress", "Completed"]: + self.status = "Pending" + elif self.docstatus == 2: + self.status = "Cancelled" + + def set_title(self): + self.title = _("{0} - {1}").format(self.patient_name or self.patient, self.procedure_template)[ + :100 + ] + + @frappe.whitelist() + def complete_procedure(self): + if self.consume_stock and self.items: + stock_entry = make_stock_entry(self) + + if self.items: + consumable_total_amount = 0 + consumption_details = False + customer = frappe.db.get_value("Patient", self.patient, "customer") + if customer: + for item in self.items: + if item.invoice_separately_as_consumables: + price_list, price_list_currency = frappe.db.get_values( + "Price List", {"selling": 1}, ["name", "currency"] + )[0] + args = { + "doctype": "Sales Invoice", + "item_code": item.item_code, + "company": self.company, + "warehouse": self.warehouse, + "customer": customer, + "selling_price_list": price_list, + "price_list_currency": price_list_currency, + "plc_conversion_rate": 1.0, + "conversion_rate": 1.0, + } + item_details = get_item_details(args) + item_price = item_details.price_list_rate * item.qty + item_consumption_details = ( + item_details.item_name + " " + str(item.qty) + " " + item.uom + " " + str(item_price) + ) + consumable_total_amount += item_price + if not consumption_details: + consumption_details = _("Clinical Procedure ({0}):").format(self.name) + consumption_details += "\n\t" + item_consumption_details + + if consumable_total_amount > 0: + frappe.db.set_value( + "Clinical Procedure", self.name, "consumable_total_amount", consumable_total_amount + ) + frappe.db.set_value( + "Clinical Procedure", self.name, "consumption_details", consumption_details + ) + else: + frappe.throw( + _("Please set Customer in Patient {0}").format(frappe.bold(self.patient)), + title=_("Customer Not Found"), + ) + + self.db_set("status", "Completed") + + # post op nursing tasks + if self.procedure_template: + self.create_nursing_tasks() + + if self.consume_stock and self.items: + return stock_entry + + @frappe.whitelist() + def start_procedure(self): + allow_start = self.set_actual_qty() + + if allow_start: + validate_nursing_tasks(self) + + self.db_set("status", "In Progress") + return "success" + + return "insufficient stock" + + def set_actual_qty(self): + allow_negative_stock = frappe.db.get_single_value("Stock Settings", "allow_negative_stock") + + allow_start = True + for d in self.get("items"): + d.actual_qty = get_stock_qty(d.item_code, self.warehouse) + # validate qty + if not allow_negative_stock and d.actual_qty < d.qty: + allow_start = False + break + + return allow_start + + @frappe.whitelist() + def make_material_receipt(self, submit=False): + stock_entry = frappe.new_doc("Stock Entry") + + stock_entry.stock_entry_type = "Material Receipt" + stock_entry.to_warehouse = self.warehouse + stock_entry.company = self.company + expense_account = get_account(None, "expense_account", "Healthcare Settings", self.company) + for item in self.items: + if item.qty > item.actual_qty: + se_child = stock_entry.append("items") + se_child.item_code = item.item_code + se_child.item_name = item.item_name + se_child.uom = item.uom + se_child.stock_uom = item.stock_uom + se_child.qty = flt(item.qty - item.actual_qty) + se_child.t_warehouse = self.warehouse + # in stock uom + se_child.transfer_qty = flt(item.transfer_qty) + se_child.conversion_factor = flt(item.conversion_factor) + cost_center = frappe.get_cached_value("Company", self.company, "cost_center") + se_child.cost_center = cost_center + se_child.expense_account = expense_account + if submit: + stock_entry.submit() + return stock_entry + return stock_entry.as_dict() + + +def get_stock_qty(item_code, warehouse): + return ( + get_previous_sle( + { + "item_code": item_code, + "warehouse": warehouse, + "posting_date": nowdate(), + "posting_time": nowtime(), + } + ).get("qty_after_transaction") + or 0 + ) + + +@frappe.whitelist() +def get_procedure_consumables(procedure_template): + return get_items("Clinical Procedure Item", procedure_template, "Clinical Procedure Template") + + +@frappe.whitelist() +def set_stock_items(doc, stock_detail_parent, parenttype): + items = get_items("Clinical Procedure Item", stock_detail_parent, parenttype) + + for item in items: + se_child = doc.append("items") + se_child.item_code = item.item_code + se_child.item_name = item.item_name + se_child.uom = item.uom + se_child.stock_uom = item.stock_uom + se_child.qty = flt(item.qty) + # in stock uom + se_child.transfer_qty = flt(item.transfer_qty) + se_child.conversion_factor = flt(item.conversion_factor) + if item.batch_no: + se_child.batch_no = item.batch_no + if parenttype == "Clinical Procedure Template": + se_child.invoice_separately_as_consumables = item.invoice_separately_as_consumables + + return doc + + +def get_items(table, parent, parenttype): + items = frappe.db.get_all( + table, filters={"parent": parent, "parenttype": parenttype}, fields=["*"] + ) + + return items + + +@frappe.whitelist() +def make_stock_entry(doc): + stock_entry = frappe.new_doc("Stock Entry") + stock_entry = set_stock_items(stock_entry, doc.name, "Clinical Procedure") + stock_entry.stock_entry_type = "Material Issue" + stock_entry.from_warehouse = doc.warehouse + stock_entry.company = doc.company + expense_account = get_account(None, "expense_account", "Healthcare Settings", doc.company) + + for item_line in stock_entry.items: + cost_center = frappe.get_cached_value("Company", doc.company, "cost_center") + item_line.cost_center = cost_center + item_line.expense_account = expense_account + + stock_entry.save(ignore_permissions=True) + stock_entry.submit() + return stock_entry.name + + +@frappe.whitelist() +def make_procedure(source_name, target_doc=None): + def set_missing_values(source, target): + consume_stock = frappe.db.get_value( + "Clinical Procedure Template", source.procedure_template, "consume_stock" + ) + if consume_stock: + target.consume_stock = 1 + warehouse = None + if source.service_unit: + warehouse = frappe.db.get_value("Healthcare Service Unit", source.service_unit, "warehouse") + if not warehouse: + warehouse = frappe.db.get_value("Stock Settings", None, "default_warehouse") + if warehouse: + target.warehouse = warehouse + + set_stock_items(target, source.procedure_template, "Clinical Procedure Template") + + doc = get_mapped_doc( + "Patient Appointment", + source_name, + { + "Patient Appointment": { + "doctype": "Clinical Procedure", + "field_map": [ + ["appointment", "name"], + ["patient", "patient"], + ["patient_age", "patient_age"], + ["patient_sex", "patient_sex"], + ["procedure_template", "procedure_template"], + ["prescription", "procedure_prescription"], + ["practitioner", "practitioner"], + ["medical_department", "department"], + ["start_date", "appointment_date"], + ["start_time", "appointment_time"], + ["notes", "notes"], + ["service_unit", "service_unit"], + ["company", "company"], + ["invoiced", "invoiced"], + ], + } + }, + target_doc, + set_missing_values, + ) + + return doc diff --git a/healthcare/healthcare/doctype/clinical_procedure/clinical_procedure_list.js b/healthcare/healthcare/doctype/clinical_procedure/clinical_procedure_list.js new file mode 100644 index 0000000..c8601f9 --- /dev/null +++ b/healthcare/healthcare/doctype/clinical_procedure/clinical_procedure_list.js @@ -0,0 +1,11 @@ +frappe.listview_settings['Clinical Procedure'] = { + get_indicator: function(doc) { + var colors = { + 'Completed': 'green', + 'In Progress': 'orange', + 'Pending': 'orange', + 'Cancelled': 'grey' + }; + return [__(doc.status), colors[doc.status], 'status,=,' + doc.status]; + } +}; diff --git a/healthcare/healthcare/doctype/clinical_procedure/test_clinical_procedure.py b/healthcare/healthcare/doctype/clinical_procedure/test_clinical_procedure.py new file mode 100644 index 0000000..6733041 --- /dev/null +++ b/healthcare/healthcare/doctype/clinical_procedure/test_clinical_procedure.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, ESS LLP and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +import frappe + +from healthcare.healthcare.doctype.patient_appointment.test_patient_appointment import ( + create_clinical_procedure_template, + create_healthcare_docs, +) + +test_dependencies = ["Item"] + + +class TestClinicalProcedure(FrappeTestCase): + def test_procedure_template_item(self): + patient, practitioner = create_healthcare_docs() + procedure_template = create_clinical_procedure_template() + self.assertTrue(frappe.db.exists("Item", procedure_template.item)) + + procedure_template.disabled = 1 + procedure_template.save() + self.assertEqual(frappe.db.get_value("Item", procedure_template.item, "disabled"), 1) + + def test_consumables(self): + patient, practitioner = create_healthcare_docs() + procedure_template = create_clinical_procedure_template() + procedure_template.allow_stock_consumption = 1 + consumable = create_consumable() + procedure_template.append( + "items", + { + "item_code": consumable.item_code, + "qty": 1, + "uom": consumable.stock_uom, + "stock_uom": consumable.stock_uom, + }, + ) + procedure_template.save() + procedure = create_procedure(procedure_template, patient, practitioner) + result = procedure.start_procedure() + if result == "insufficient stock": + procedure.make_material_receipt(submit=True) + result = procedure.start_procedure() + self.assertEqual(procedure.status, "In Progress") + result = procedure.complete_procedure() + # check consumption + self.assertTrue(frappe.db.exists("Stock Entry", result)) + + +def create_consumable(): + if frappe.db.exists("Item", "Syringe"): + return frappe.get_doc("Item", "Syringe") + consumable = frappe.new_doc("Item") + consumable.item_code = "Syringe" + consumable.item_group = "_Test Item Group" + consumable.stock_uom = "Nos" + consumable.valuation_rate = 5.00 + consumable.save() + return consumable + + +def create_procedure(procedure_template, patient, practitioner): + procedure = frappe.new_doc("Clinical Procedure") + procedure.procedure_template = procedure_template.name + procedure.patient = patient + procedure.practitioner = practitioner + procedure.consume_stock = procedure_template.allow_stock_consumption + procedure.items = procedure_template.items + procedure.company = "_Test Company" + procedure.warehouse = "_Test Warehouse - _TC" + procedure.submit() + return procedure diff --git a/healthcare/healthcare/doctype/clinical_procedure_item/__init__.py b/healthcare/healthcare/doctype/clinical_procedure_item/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/clinical_procedure_item/clinical_procedure_item.json b/healthcare/healthcare/doctype/clinical_procedure_item/clinical_procedure_item.json new file mode 100644 index 0000000..a7dde0b --- /dev/null +++ b/healthcare/healthcare/doctype/clinical_procedure_item/clinical_procedure_item.json @@ -0,0 +1,123 @@ +{ + "actions": [], + "beta": 1, + "creation": "2017-10-05 16:15:10.876952", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "item_code", + "item_name", + "qty", + "barcode", + "uom", + "invoice_separately_as_consumables", + "column_break_5", + "batch_no", + "conversion_factor", + "stock_uom", + "transfer_qty", + "actual_qty" + ], + "fields": [ + { + "bold": 1, + "columns": 3, + "fieldname": "item_code", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_global_search": 1, + "in_list_view": 1, + "label": "Item", + "options": "Item", + "reqd": 1, + "search_index": 1 + }, + { + "fieldname": "barcode", + "fieldtype": "Data", + "label": "Barcode" + }, + { + "fieldname": "item_name", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Item Name", + "read_only": 1 + }, + { + "fieldname": "qty", + "fieldtype": "Float", + "in_list_view": 1, + "label": "Quantity", + "reqd": 1 + }, + { + "fieldname": "uom", + "fieldtype": "Link", + "in_list_view": 1, + "label": "UOM", + "options": "UOM", + "reqd": 1 + }, + { + "default": "0", + "fieldname": "invoice_separately_as_consumables", + "fieldtype": "Check", + "in_list_view": 1, + "label": "Invoice Separately as Consumables" + }, + { + "fieldname": "column_break_5", + "fieldtype": "Column Break" + }, + { + "fieldname": "batch_no", + "fieldtype": "Link", + "label": "Batch", + "options": "Batch" + }, + { + "fieldname": "conversion_factor", + "fieldtype": "Float", + "label": "Conversion Factor", + "read_only": 1 + }, + { + "fieldname": "stock_uom", + "fieldtype": "Link", + "label": "Stock UOM", + "options": "UOM", + "read_only": 1, + "reqd": 1 + }, + { + "fieldname": "transfer_qty", + "fieldtype": "Float", + "label": "Transfer Qty", + "read_only": 1 + }, + { + "fieldname": "actual_qty", + "fieldtype": "Float", + "label": "Actual Qty (at source/target)", + "no_copy": 1, + "print_hide": 1, + "read_only": 1, + "search_index": 1 + } + ], + "istable": 1, + "links": [], + "modified": "2020-03-01 15:34:54.226722", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Clinical Procedure Item", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/clinical_procedure_item/clinical_procedure_item.py b/healthcare/healthcare/doctype/clinical_procedure_item/clinical_procedure_item.py new file mode 100644 index 0000000..4ce3f80 --- /dev/null +++ b/healthcare/healthcare/doctype/clinical_procedure_item/clinical_procedure_item.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, earthians and contributors +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class ClinicalProcedureItem(Document): + pass diff --git a/healthcare/healthcare/doctype/clinical_procedure_template/__init__.py b/healthcare/healthcare/doctype/clinical_procedure_template/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/clinical_procedure_template/clinical_procedure_template.js b/healthcare/healthcare/doctype/clinical_procedure_template/clinical_procedure_template.js new file mode 100644 index 0000000..2997bd0 --- /dev/null +++ b/healthcare/healthcare/doctype/clinical_procedure_template/clinical_procedure_template.js @@ -0,0 +1,220 @@ +// Copyright (c) 2017, earthians and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Clinical Procedure Template', { + template: function (frm) { + if (!frm.doc.item_code) + frm.set_value('item_code', frm.doc.template); + if (!frm.doc.description) + frm.set_value('description', frm.doc.template); + mark_change_in_item(frm); + }, + + rate: function (frm) { + mark_change_in_item(frm); + }, + + is_billable: function (frm) { + mark_change_in_item(frm); + }, + + item_group: function (frm) { + mark_change_in_item(frm); + }, + + description: function (frm) { + mark_change_in_item(frm); + }, + + medical_department: function (frm) { + mark_change_in_item(frm); + }, + + medical_code: function (frm) { + frm.set_query("medical_code", function () { + return { + filters: { + medical_code_standard: frm.doc.medical_code_standard + } + }; + }); + }, + + refresh: function (frm) { + frm.fields_dict['items'].grid.set_column_disp('barcode', false); + frm.fields_dict['items'].grid.set_column_disp('batch_no', false); + + if (!frm.doc.__islocal) { + cur_frm.add_custom_button(__('Change Item Code'), function () { + change_template_code(frm.doc); + }); + } + + frm.set_query('item', function() { + return { + filters: { + 'disabled': false, + 'is_stock_item': false + } + }; + }); + }, + + link_existing_item: function (frm) { + if (frm.doc.link_existing_item) { + frm.set_value('item_code', ''); + } else { + frm.set_value('item', ''); + } + }, + + item: function (frm) { + if (frm.doc.item) { + frappe.db.get_value('Item', frm.doc.item, ['item_group', 'description']) + .then(r => { + frm.set_value({ + 'item_group': r.message.item_group, + 'description': r.message.description, + 'item_code': frm.doc.item + }); + }) + } + } +}); + +let mark_change_in_item = function (frm) { + if (!frm.doc.__islocal || frm.doc.link_existing_item) { + frm.doc.change_in_item = 1; + } +}; + +let change_template_code = function (doc) { + let d = new frappe.ui.Dialog({ + title: __('Change Item Code'), + fields: [ + { + 'fieldtype': 'Data', + 'label': 'Item Code', + 'fieldname': 'item_code', + reqd: 1 + } + ], + primary_action: function () { + let values = d.get_values(); + + if (values) { + frappe.call({ + 'method': 'healthcare.healthcare.doctype.clinical_procedure_template.clinical_procedure_template.change_item_code_from_template', + 'args': { item_code: values.item_code, doc: doc }, + callback: function () { + cur_frm.reload_doc(); + frappe.show_alert({ + message: 'Item Code renamed successfully', + indicator: 'green' + }); + } + }); + } + d.hide(); + }, + primary_action_label: __('Change Item Code') + }); + d.show(); + + d.set_values({ + 'item_code': doc.item_code + }); +}; + +frappe.ui.form.on('Clinical Procedure Item', { + qty: function (frm, cdt, cdn) { + let d = locals[cdt][cdn]; + frappe.model.set_value(cdt, cdn, 'transfer_qty', d.qty * d.conversion_factor); + }, + + uom: function (doc, cdt, cdn) { + let d = locals[cdt][cdn]; + if (d.uom && d.item_code) { + return frappe.call({ + method: 'erpnext.stock.doctype.stock_entry.stock_entry.get_uom_details', + args: { + item_code: d.item_code, + uom: d.uom, + qty: d.qty + }, + callback: function (r) { + if (r.message) { + frappe.model.set_value(cdt, cdn, r.message); + } + } + }); + } + }, + + item_code: function (frm, cdt, cdn) { + let d = locals[cdt][cdn]; + if (d.item_code) { + let args = { + 'item_code': d.item_code, + 'transfer_qty': d.transfer_qty, + 'quantity': d.qty + }; + return frappe.call({ + method: 'healthcare.healthcare.doctype.clinical_procedure_template.clinical_procedure_template.get_item_details', + args: { args: args }, + callback: function (r) { + if (r.message) { + let d = locals[cdt][cdn]; + $.each(r.message, function (k, v) { + d[k] = v; + }); + refresh_field('items'); + } + } + }); + } + } +}); + +// List Stock items +cur_frm.set_query('item_code', 'items', function () { + return { + filters: { + is_stock_item: 1 + } + }; +}); + +frappe.tour['Clinical Procedure Template'] = [ + { + fieldname: 'template', + title: __('Template Name'), + description: __('Enter a name for the Clinical Procedure Template') + }, + { + fieldname: 'item_code', + title: __('Item Code'), + description: __('Set the Item Code which will be used for billing the Clinical Procedure.') + }, + { + fieldname: 'item_group', + title: __('Item Group'), + description: __('Select an Item Group for the Clinical Procedure Item.') + }, + { + fieldname: 'is_billable', + title: __('Clinical Procedure Rate'), + description: __('Check this if the Clinical Procedure is billable and also set the rate.') + }, + { + fieldname: 'consume_stock', + title: __('Allow Stock Consumption'), + description: __('Check this if the Clinical Procedure utilises consumables. Click ') + "here" + __(' to know more') + + }, + { + fieldname: 'medical_department', + title: __('Medical Department'), + description: __('You can also set the Medical Department for the template. After saving the document, an Item will automatically be created for billing this Clinical Procedure. You can then use this template while creating Clinical Procedures for Patients. Templates save you from filling up redundant data every single time. You can also create templates for other operations like Lab Tests, Therapy Sessions, etc.') + } +]; diff --git a/healthcare/healthcare/doctype/clinical_procedure_template/clinical_procedure_template.json b/healthcare/healthcare/doctype/clinical_procedure_template/clinical_procedure_template.json new file mode 100644 index 0000000..02c87d7 --- /dev/null +++ b/healthcare/healthcare/doctype/clinical_procedure_template/clinical_procedure_template.json @@ -0,0 +1,286 @@ +{ + "actions": [], + "allow_import": 1, + "allow_rename": 1, + "autoname": "field:template", + "beta": 1, + "creation": "2017-10-05 14:59:55.438359", + "description": "Procedure Template", + "doctype": "DocType", + "document_type": "Setup", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "template", + "link_existing_item", + "item", + "item_code", + "item_group", + "description", + "column_break_5", + "disabled", + "is_billable", + "rate", + "medical_department", + "pre_op_nursing_checklist_template", + "post_op_nursing_checklist_template", + "medical_coding_section", + "medical_code_standard", + "medical_code", + "consumables", + "consume_stock", + "items", + "sample_collection", + "sample", + "sample_uom", + "sample_qty", + "column_break_21", + "sample_details", + "change_in_item" + ], + "fields": [ + { + "fieldname": "template", + "fieldtype": "Data", + "in_global_search": 1, + "in_list_view": 1, + "label": "Template Name", + "reqd": 1, + "unique": 1 + }, + { + "depends_on": "eval:!doc.link_existing_item || !doc.__islocal", + "fieldname": "item_code", + "fieldtype": "Data", + "label": "Item Code", + "mandatory_depends_on": "eval:!doc.link_existing_item", + "read_only_depends_on": "eval: !doc.__islocal" + }, + { + "fieldname": "item_group", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Item Group", + "options": "Item Group", + "read_only_depends_on": "eval:doc.link_existing_item", + "reqd": 1 + }, + { + "fieldname": "medical_department", + "fieldtype": "Link", + "label": "Medical Department", + "options": "Medical Department" + }, + { + "fieldname": "column_break_5", + "fieldtype": "Column Break" + }, + { + "default": "0", + "depends_on": "eval:!doc.link_existing_item || !doc.__islocal;", + "fieldname": "is_billable", + "fieldtype": "Check", + "label": "Is Billable" + }, + { + "depends_on": "eval:doc.is_billable && (!doc.link_existing_item || !doc.__islocal)", + "fieldname": "rate", + "fieldtype": "Float", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Rate", + "mandatory_depends_on": "eval:doc.is_billable && !doc.link_existing_item" + }, + { + "fieldname": "description", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Description", + "no_copy": 1, + "reqd": 1 + }, + { + "default": "0", + "fieldname": "consume_stock", + "fieldtype": "Check", + "label": "Allow Stock Consumption", + "search_index": 1 + }, + { + "fieldname": "consumables", + "fieldtype": "Section Break", + "label": "Consumables" + }, + { + "depends_on": "eval:doc.consume_stock == 1", + "fieldname": "items", + "fieldtype": "Table", + "ignore_user_permissions": 1, + "label": "Items", + "options": "Clinical Procedure Item" + }, + { + "collapsible": 1, + "fieldname": "sample_collection", + "fieldtype": "Section Break", + "label": "Sample Collection" + }, + { + "fieldname": "sample", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "label": "Sample", + "options": "Lab Test Sample" + }, + { + "fetch_from": "sample.sample_uom", + "fieldname": "sample_uom", + "fieldtype": "Data", + "label": "Sample UOM", + "read_only": 1 + }, + { + "fieldname": "sample_qty", + "fieldtype": "Float", + "label": "Quantity" + }, + { + "fieldname": "column_break_21", + "fieldtype": "Column Break" + }, + { + "fieldname": "sample_details", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Collection Details" + }, + { + "default": "0", + "fieldname": "change_in_item", + "fieldtype": "Check", + "hidden": 1, + "label": "Change In Item", + "no_copy": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "default": "0", + "fieldname": "disabled", + "fieldtype": "Check", + "label": "Disabled" + }, + { + "depends_on": "eval: !doc.__islocal || doc.link_existing_item", + "fieldname": "item", + "fieldtype": "Link", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Item", + "mandatory_depends_on": "eval:doc.link_existing_item", + "no_copy": 1, + "options": "Item", + "read_only_depends_on": "eval: !doc.__islocal" + }, + { + "collapsible": 1, + "fieldname": "medical_coding_section", + "fieldtype": "Section Break", + "label": "Medical Coding" + }, + { + "fieldname": "medical_code_standard", + "fieldtype": "Link", + "label": "Medical Code Standard", + "options": "Medical Code Standard" + }, + { + "depends_on": "medical_code_standard", + "fieldname": "medical_code", + "fieldtype": "Link", + "label": "Medical Code", + "options": "Medical Code" + }, + { + "fieldname": "pre_op_nursing_checklist_template", + "fieldtype": "Link", + "label": "Pre-op Nursing Checklist Template", + "options": "Nursing Checklist Template" + }, + { + "fieldname": "post_op_nursing_checklist_template", + "fieldtype": "Link", + "label": "Post-op Nursing Checklist Template", + "options": "Nursing Checklist Template" + }, + { + "default": "0", + "depends_on": "eval: doc.__islocal", + "fieldname": "link_existing_item", + "fieldtype": "Check", + "label": "Link existing Item" + } + ], + "links": [], + "modified": "2022-06-22 06:42:56.910453", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Clinical Procedure Template", + "naming_rule": "By fieldname", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + }, + { + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Nursing User", + "share": 1 + }, + { + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "write": 1 + } + ], + "restrict_to_domain": "Healthcare", + "search_fields": "template", + "sort_field": "modified", + "sort_order": "DESC", + "states": [], + "title_field": "template", + "track_changes": 1, + "track_seen": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/clinical_procedure_template/clinical_procedure_template.py b/healthcare/healthcare/doctype/clinical_procedure_template/clinical_procedure_template.py new file mode 100644 index 0000000..41f1954 --- /dev/null +++ b/healthcare/healthcare/doctype/clinical_procedure_template/clinical_procedure_template.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, earthians and contributors +# For license information, please see license.txt + + +import json + +import frappe +from frappe import _ +from frappe.model.document import Document +from frappe.model.rename_doc import rename_doc +from frappe.utils import today + + +class ClinicalProcedureTemplate(Document): + def before_insert(self): + if self.link_existing_item and self.item: + price_list = frappe.db.get_all( + "Item Price", {"item_code": self.item}, ["price_list_rate"], order_by="valid_from desc" + ) + if price_list: + self.rate = price_list[0].get("price_list_rate") + + def validate(self): + self.enable_disable_item() + + def after_insert(self): + if not self.link_existing_item: + create_item_from_template(self) + + def on_update(self): + if self.change_in_item: + update_item_and_item_price(self) + + def enable_disable_item(self): + if self.is_billable: + if self.disabled: + frappe.db.set_value("Item", self.item, "disabled", 1) + else: + frappe.db.set_value("Item", self.item, "disabled", 0) + + +@frappe.whitelist() +def get_item_details(args=None): + if not isinstance(args, dict): + args = json.loads(args) + + item = frappe.db.get_all( + "Item", filters={"disabled": 0, "name": args.get("item_code")}, fields=["stock_uom", "item_name"] + ) + + if not item: + frappe.throw(_("Item {0} is not active").format(args.get("item_code"))) + + item = item[0] + ret = { + "uom": item.stock_uom, + "stock_uom": item.stock_uom, + "item_name": item.item_name, + "qty": 1, + "transfer_qty": 0, + "conversion_factor": 1, + } + return ret + + +def create_item_from_template(doc): + disabled = doc.disabled + if doc.is_billable and not doc.disabled: + disabled = 0 + + uom = frappe.db.exists("UOM", "Unit") or frappe.db.get_single_value("Stock Settings", "stock_uom") + item = frappe.get_doc( + { + "doctype": "Item", + "item_code": doc.template, + "item_name": doc.template, + "item_group": doc.item_group, + "description": doc.description, + "is_sales_item": 1, + "is_service_item": 1, + "is_purchase_item": 0, + "is_stock_item": 0, + "show_in_website": 0, + "is_pro_applicable": 0, + "disabled": disabled, + "stock_uom": uom, + } + ).insert(ignore_permissions=True, ignore_mandatory=True) + + make_item_price(item.name, doc.rate) + doc.db_set("item", item.name) + + +def make_item_price(item, item_price): + price_list_name = frappe.db.get_value( + "Selling Settings", None, "selling_price_list" + ) or frappe.db.get_value("Price List", {"selling": 1}) + frappe.get_doc( + { + "doctype": "Item Price", + "price_list": price_list_name, + "item_code": item, + "price_list_rate": item_price, + "valid_from": today(), + } + ).insert(ignore_permissions=True, ignore_mandatory=True) + + +@frappe.whitelist() +def change_item_code_from_template(item_code, doc): + doc = frappe._dict(json.loads(doc)) + + if frappe.db.exists("Item", {"item_code": item_code}): + frappe.throw(_("Item with Item Code {0} already exists").format(item_code)) + else: + rename_doc("Item", doc.item_code, item_code, ignore_permissions=True) + frappe.db.set_value("Clinical Procedure Template", doc.name, "item_code", item_code) + return + + +def update_item_and_item_price(doc): + if doc.is_billable and doc.item: + item_name = doc.lab_test_name if doc.get("doctype") == "Lab Test Template" else doc.template + rate = doc.lab_test_rate if doc.get("doctype") == "Lab Test Template" else doc.rate + item_group = doc.lab_test_group if doc.get("doctype") == "Lab Test Template" else doc.item_group + + item_doc = frappe.get_doc("Item", {"item_code": doc.item}) + item_doc.item_name = item_name + item_doc.item_group = item_group + item_doc.description = ( + doc.description if doc.get("doctype") == "Clinical Procedure Template" else "" + ) + item_doc.disabled = 0 + item_doc.save(ignore_permissions=True) + if rate: + if not frappe.db.exists("Item Price", {"item_code": doc.item, "valid_from": today()}): + make_item_price(doc.item, rate) + else: + item_price = frappe.get_doc("Item Price", {"item_code": doc.item}) + item_price.item_name = item_name + item_price.valid_from = today() + item_price.price_list_rate = rate + item_price.save() + + elif not doc.is_billable and doc.item and not doc.link_existing_item: + frappe.db.set_value("Item", doc.item, "disabled", 1) + + doc.db_set("change_in_item", 0) diff --git a/healthcare/healthcare/doctype/clinical_procedure_template/clinical_procedure_template_dashboard.py b/healthcare/healthcare/doctype/clinical_procedure_template/clinical_procedure_template_dashboard.py new file mode 100644 index 0000000..bc16756 --- /dev/null +++ b/healthcare/healthcare/doctype/clinical_procedure_template/clinical_procedure_template_dashboard.py @@ -0,0 +1,8 @@ +from frappe import _ + + +def get_data(): + return { + "fieldname": "procedure_template", + "transactions": [{"label": _("Consultations"), "items": ["Clinical Procedure"]}], + } diff --git a/healthcare/healthcare/doctype/clinical_procedure_template/test_clinical_procedure_template.py b/healthcare/healthcare/doctype/clinical_procedure_template/test_clinical_procedure_template.py new file mode 100644 index 0000000..c6b742a --- /dev/null +++ b/healthcare/healthcare/doctype/clinical_procedure_template/test_clinical_procedure_template.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, earthians and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + + +class TestClinicalProcedureTemplate(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/codification_table/__init__.py b/healthcare/healthcare/doctype/codification_table/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/codification_table/codification_table.json b/healthcare/healthcare/doctype/codification_table/codification_table.json new file mode 100644 index 0000000..9a917b4 --- /dev/null +++ b/healthcare/healthcare/doctype/codification_table/codification_table.json @@ -0,0 +1,56 @@ +{ + "actions": [], + "allow_copy": 1, + "beta": 1, + "creation": "2017-06-22 13:09:23.159579", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "medical_code", + "code", + "description" + ], + "fields": [ + { + "fieldname": "medical_code", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "label": "Medical Code", + "options": "Medical Code", + "reqd": 1 + }, + { + "fetch_from": "medical_code.code", + "fieldname": "code", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Code", + "read_only": 1 + }, + { + "fetch_from": "medical_code.description", + "fieldname": "description", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Description", + "read_only": 1 + } + ], + "istable": 1, + "links": [], + "modified": "2020-02-26 13:17:49.016293", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Codification Table", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/codification_table/codification_table.py b/healthcare/healthcare/doctype/codification_table/codification_table.py new file mode 100644 index 0000000..069904b --- /dev/null +++ b/healthcare/healthcare/doctype/codification_table/codification_table.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class CodificationTable(Document): + pass diff --git a/healthcare/healthcare/doctype/complaint/__init__.py b/healthcare/healthcare/doctype/complaint/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/complaint/complaint.js b/healthcare/healthcare/doctype/complaint/complaint.js new file mode 100644 index 0000000..a670218 --- /dev/null +++ b/healthcare/healthcare/doctype/complaint/complaint.js @@ -0,0 +1,5 @@ +// Copyright (c) 2017, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Complaint', { +}); diff --git a/healthcare/healthcare/doctype/complaint/complaint.json b/healthcare/healthcare/doctype/complaint/complaint.json new file mode 100644 index 0000000..f600838 --- /dev/null +++ b/healthcare/healthcare/doctype/complaint/complaint.json @@ -0,0 +1,116 @@ +{ + "allow_copy": 1, + "allow_guest_to_view": 0, + "allow_import": 1, + "allow_rename": 1, + "autoname": "field:complaints", + "beta": 1, + "creation": "2017-02-15 12:25:28.045267", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "", + "editable_grid": 1, + "engine": "InnoDB", + "fields": [ + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "complaints", + "fieldtype": "Data", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 1, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Complaints", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "unique": 0 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 0, + "max_attachments": 0, + "modified": "2017-10-05 11:18:42.017864", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Complaint", + "name_case": "", + "owner": "Administrator", + "permissions": [ + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + }, + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + } + ], + "quick_entry": 1, + "read_only": 0, + "read_only_onload": 0, + "restrict_to_domain": "Healthcare", + "search_fields": "complaints", + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "complaints", + "track_changes": 0, + "track_seen": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/complaint/complaint.py b/healthcare/healthcare/doctype/complaint/complaint.py new file mode 100644 index 0000000..33eef46 --- /dev/null +++ b/healthcare/healthcare/doctype/complaint/complaint.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class Complaint(Document): + pass diff --git a/healthcare/healthcare/doctype/complaint/test_complaint.py b/healthcare/healthcare/doctype/complaint/test_complaint.py new file mode 100644 index 0000000..401ecc5 --- /dev/null +++ b/healthcare/healthcare/doctype/complaint/test_complaint.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + + +class TestComplaint(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/descriptive_test_result/__init__.py b/healthcare/healthcare/doctype/descriptive_test_result/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/descriptive_test_result/descriptive_test_result.json b/healthcare/healthcare/doctype/descriptive_test_result/descriptive_test_result.json new file mode 100644 index 0000000..fcd3828 --- /dev/null +++ b/healthcare/healthcare/doctype/descriptive_test_result/descriptive_test_result.json @@ -0,0 +1,74 @@ +{ + "actions": [], + "allow_copy": 1, + "beta": 1, + "creation": "2016-02-22 15:12:36.202380", + "doctype": "DocType", + "document_type": "Document", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "lab_test_particulars", + "result_value", + "allow_blank", + "template", + "require_result_value" + ], + "fields": [ + { + "fieldname": "lab_test_particulars", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Particulars", + "read_only": 1 + }, + { + "depends_on": "eval:doc.require_result_value == 1", + "fieldname": "result_value", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Value" + }, + { + "fieldname": "template", + "fieldtype": "Link", + "hidden": 1, + "label": "Template", + "options": "Lab Test Template", + "print_hide": 1, + "report_hide": 1 + }, + { + "default": "0", + "fieldname": "require_result_value", + "fieldtype": "Check", + "hidden": 1, + "label": "Require Result Value", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "default": "1", + "fieldname": "allow_blank", + "fieldtype": "Check", + "label": "Allow Blank", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + } + ], + "istable": 1, + "links": [], + "modified": "2020-07-23 12:33:47.693065", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Descriptive Test Result", + "owner": "Administrator", + "permissions": [], + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC" +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/descriptive_test_result/descriptive_test_result.py b/healthcare/healthcare/doctype/descriptive_test_result/descriptive_test_result.py new file mode 100644 index 0000000..6db1082 --- /dev/null +++ b/healthcare/healthcare/doctype/descriptive_test_result/descriptive_test_result.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS and contributors +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class DescriptiveTestResult(Document): + pass diff --git a/healthcare/healthcare/doctype/descriptive_test_template/__init__.py b/healthcare/healthcare/doctype/descriptive_test_template/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/descriptive_test_template/descriptive_test_template.json b/healthcare/healthcare/doctype/descriptive_test_template/descriptive_test_template.json new file mode 100644 index 0000000..9ee8f4f --- /dev/null +++ b/healthcare/healthcare/doctype/descriptive_test_template/descriptive_test_template.json @@ -0,0 +1,41 @@ +{ + "actions": [], + "allow_copy": 1, + "beta": 1, + "creation": "2016-02-22 16:12:12.394200", + "doctype": "DocType", + "document_type": "Setup", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "particulars", + "allow_blank" + ], + "fields": [ + { + "fieldname": "particulars", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Result Component" + }, + { + "default": "0", + "fieldname": "allow_blank", + "fieldtype": "Check", + "in_list_view": 1, + "label": "Allow Blank" + } + ], + "istable": 1, + "links": [], + "modified": "2020-06-24 14:03:51.728863", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Descriptive Test Template", + "owner": "Administrator", + "permissions": [], + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC" +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/descriptive_test_template/descriptive_test_template.py b/healthcare/healthcare/doctype/descriptive_test_template/descriptive_test_template.py new file mode 100644 index 0000000..91a8dba --- /dev/null +++ b/healthcare/healthcare/doctype/descriptive_test_template/descriptive_test_template.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS and contributors +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class DescriptiveTestTemplate(Document): + pass diff --git a/healthcare/healthcare/doctype/diagnosis/__init__.py b/healthcare/healthcare/doctype/diagnosis/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/diagnosis/diagnosis.js b/healthcare/healthcare/doctype/diagnosis/diagnosis.js new file mode 100644 index 0000000..fb2557f --- /dev/null +++ b/healthcare/healthcare/doctype/diagnosis/diagnosis.js @@ -0,0 +1,5 @@ +// Copyright (c) 2016, ESS LLP and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Diagnosis', { +}); diff --git a/healthcare/healthcare/doctype/diagnosis/diagnosis.json b/healthcare/healthcare/doctype/diagnosis/diagnosis.json new file mode 100644 index 0000000..936c2c5 --- /dev/null +++ b/healthcare/healthcare/doctype/diagnosis/diagnosis.json @@ -0,0 +1,116 @@ +{ + "allow_copy": 1, + "allow_guest_to_view": 0, + "allow_import": 1, + "allow_rename": 1, + "autoname": "field:diagnosis", + "beta": 1, + "creation": "2017-02-15 12:23:59.341108", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "", + "editable_grid": 1, + "engine": "InnoDB", + "fields": [ + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "diagnosis", + "fieldtype": "Data", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 1, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Diagnosis", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "unique": 0 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 0, + "max_attachments": 0, + "modified": "2017-10-05 11:25:46.107435", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Diagnosis", + "name_case": "", + "owner": "Administrator", + "permissions": [ + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + }, + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + } + ], + "quick_entry": 1, + "read_only": 0, + "read_only_onload": 0, + "restrict_to_domain": "Healthcare", + "search_fields": "diagnosis", + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "diagnosis", + "track_changes": 1, + "track_seen": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/diagnosis/diagnosis.py b/healthcare/healthcare/doctype/diagnosis/diagnosis.py new file mode 100644 index 0000000..f4f4ac8 --- /dev/null +++ b/healthcare/healthcare/doctype/diagnosis/diagnosis.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and contributors +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class Diagnosis(Document): + pass diff --git a/healthcare/healthcare/doctype/diagnosis/test_diagnosis.py b/healthcare/healthcare/doctype/diagnosis/test_diagnosis.py new file mode 100644 index 0000000..fd8be28 --- /dev/null +++ b/healthcare/healthcare/doctype/diagnosis/test_diagnosis.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +# test_records = frappe.get_test_records('Diagnosis') + + +class TestDiagnosis(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/dosage_form/__init__.py b/healthcare/healthcare/doctype/dosage_form/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/dosage_form/dosage_form.js b/healthcare/healthcare/doctype/dosage_form/dosage_form.js new file mode 100644 index 0000000..60e9696 --- /dev/null +++ b/healthcare/healthcare/doctype/dosage_form/dosage_form.js @@ -0,0 +1,5 @@ +// Copyright (c) 2017, ESS LLP and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Dosage Form', { +}); diff --git a/healthcare/healthcare/doctype/dosage_form/dosage_form.json b/healthcare/healthcare/doctype/dosage_form/dosage_form.json new file mode 100644 index 0000000..350aaed --- /dev/null +++ b/healthcare/healthcare/doctype/dosage_form/dosage_form.json @@ -0,0 +1,114 @@ +{ + "allow_copy": 1, + "allow_guest_to_view": 0, + "allow_import": 1, + "allow_rename": 1, + "autoname": "field:dosage_form", + "beta": 1, + "creation": "2017-04-08 12:04:33.987972", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "", + "editable_grid": 1, + "engine": "InnoDB", + "fields": [ + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "dosage_form", + "fieldtype": "Data", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 1, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Dosage Form", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "unique": 0 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 0, + "max_attachments": 0, + "modified": "2017-10-05 11:24:57.888091", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Dosage Form", + "name_case": "", + "owner": "Administrator", + "permissions": [ + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + }, + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + } + ], + "quick_entry": 1, + "read_only": 0, + "read_only_onload": 0, + "restrict_to_domain": "Healthcare", + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1, + "track_seen": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/dosage_form/dosage_form.py b/healthcare/healthcare/doctype/dosage_form/dosage_form.py new file mode 100644 index 0000000..a1cd1e3 --- /dev/null +++ b/healthcare/healthcare/doctype/dosage_form/dosage_form.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, ESS LLP and contributors +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class DosageForm(Document): + pass diff --git a/healthcare/healthcare/doctype/dosage_form/test_dosage_form.py b/healthcare/healthcare/doctype/dosage_form/test_dosage_form.py new file mode 100644 index 0000000..97296e6 --- /dev/null +++ b/healthcare/healthcare/doctype/dosage_form/test_dosage_form.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, ESS LLP and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + + +class TestDosageForm(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/dosage_strength/__init__.py b/healthcare/healthcare/doctype/dosage_strength/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/dosage_strength/dosage_strength.json b/healthcare/healthcare/doctype/dosage_strength/dosage_strength.json new file mode 100644 index 0000000..da4f1a7 --- /dev/null +++ b/healthcare/healthcare/doctype/dosage_strength/dosage_strength.json @@ -0,0 +1,102 @@ +{ + "allow_copy": 1, + "allow_guest_to_view": 0, + "allow_import": 0, + "allow_rename": 0, + "beta": 1, + "creation": "2017-02-14 15:40:14.385707", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "", + "editable_grid": 1, + "engine": "InnoDB", + "fields": [ + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "strength", + "fieldtype": "Float", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Strength", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "unique": 0 + }, + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "strength_time", + "fieldtype": "Time", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Time", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 0, + "search_index": 0, + "set_only_once": 0, + "unique": 0 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 1, + "max_attachments": 0, + "modified": "2017-08-31 14:11:59.874645", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Dosage Strength", + "name_case": "", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "read_only": 0, + "read_only_onload": 0, + "restrict_to_domain": "Healthcare", + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 0, + "track_seen": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/dosage_strength/dosage_strength.py b/healthcare/healthcare/doctype/dosage_strength/dosage_strength.py new file mode 100644 index 0000000..429a667 --- /dev/null +++ b/healthcare/healthcare/doctype/dosage_strength/dosage_strength.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and contributors +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class DosageStrength(Document): + pass diff --git a/healthcare/healthcare/doctype/drug_prescription/__init__.py b/healthcare/healthcare/doctype/drug_prescription/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/drug_prescription/drug_prescription.json b/healthcare/healthcare/doctype/drug_prescription/drug_prescription.json new file mode 100644 index 0000000..a65c566 --- /dev/null +++ b/healthcare/healthcare/doctype/drug_prescription/drug_prescription.json @@ -0,0 +1,122 @@ +{ + "actions": [], + "allow_copy": 1, + "beta": 1, + "creation": "2016-09-16 16:41:45.533374", + "doctype": "DocType", + "document_type": "Document", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "drug_code", + "drug_name", + "dosage", + "period", + "dosage_form", + "column_break_7", + "comment", + "usage_interval", + "interval", + "interval_uom", + "update_schedule" + ], + "fields": [ + { + "fieldname": "drug_code", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "label": "Drug", + "options": "Item", + "reqd": 1 + }, + { + "fetch_from": "drug_code.item_name", + "fieldname": "drug_name", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Drug Name / Description" + }, + { + "fieldname": "dosage", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "label": "Dosage", + "options": "Prescription Dosage", + "reqd": 1 + }, + { + "fieldname": "period", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "label": "Period", + "options": "Prescription Duration", + "reqd": 1 + }, + { + "allow_in_quick_entry": 1, + "fieldname": "dosage_form", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "label": "Dosage Form", + "options": "Dosage Form", + "reqd": 1 + }, + { + "fieldname": "column_break_7", + "fieldtype": "Column Break" + }, + { + "fieldname": "comment", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Comment" + }, + { + "depends_on": "usage_interval", + "fieldname": "interval", + "fieldtype": "Int", + "in_list_view": 1, + "label": "Interval" + }, + { + "default": "1", + "depends_on": "usage_interval", + "fieldname": "update_schedule", + "fieldtype": "Check", + "hidden": 1, + "label": "Update Schedule", + "print_hide": 1, + "report_hide": 1 + }, + { + "depends_on": "use_interval", + "fieldname": "interval_uom", + "fieldtype": "Select", + "in_list_view": 1, + "label": "Interval UOM", + "options": "\nHour\nDay" + }, + { + "default": "0", + "fieldname": "usage_interval", + "fieldtype": "Check", + "hidden": 1, + "label": "Dosage by Time Interval" + } + ], + "istable": 1, + "links": [], + "modified": "2021-06-11 11:53:06.343704", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Drug Prescription", + "owner": "Administrator", + "permissions": [], + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC" +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/drug_prescription/drug_prescription.py b/healthcare/healthcare/doctype/drug_prescription/drug_prescription.py new file mode 100644 index 0000000..1a4aa13 --- /dev/null +++ b/healthcare/healthcare/doctype/drug_prescription/drug_prescription.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and contributors +# For license information, please see license.txt + + +import frappe +from frappe.model.document import Document + + +class DrugPrescription(Document): + def get_quantity(self): + quantity = 0 + dosage = None + period = None + + if self.dosage: + dosage = frappe.get_doc("Prescription Dosage", self.dosage) + for item in dosage.dosage_strength: + quantity += item.strength + if self.period and self.interval: + period = frappe.get_doc("Prescription Duration", self.period) + if self.interval < period.get_days(): + quantity = quantity * (period.get_days() / self.interval) + + elif self.interval and self.interval_uom and self.period: + period = frappe.get_doc("Prescription Duration", self.period) + interval_in = self.interval_uom + if interval_in == "Day" and self.interval < period.get_days(): + quantity = period.get_days() / self.interval + elif interval_in == "Hour" and self.interval < period.get_hours(): + quantity = period.get_hours() / self.interval + if quantity > 0: + return quantity + else: + return 1 diff --git a/healthcare/healthcare/doctype/exercise/__init__.py b/healthcare/healthcare/doctype/exercise/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/exercise/exercise.json b/healthcare/healthcare/doctype/exercise/exercise.json new file mode 100644 index 0000000..683cc6d --- /dev/null +++ b/healthcare/healthcare/doctype/exercise/exercise.json @@ -0,0 +1,62 @@ +{ + "actions": [], + "creation": "2020-03-11 09:25:00.968572", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "exercise_type", + "difficulty_level", + "counts_target", + "counts_completed", + "assistance_level" + ], + "fields": [ + { + "fieldname": "exercise_type", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Exercise Type", + "options": "Exercise Type", + "reqd": 1 + }, + { + "fetch_from": "exercise_type.difficulty_level", + "fieldname": "difficulty_level", + "fieldtype": "Link", + "label": "Difficulty Level", + "options": "Exercise Difficulty Level" + }, + { + "fieldname": "counts_target", + "fieldtype": "Int", + "in_list_view": 1, + "label": "Counts Target" + }, + { + "depends_on": "eval:doc.parenttype==\"Therapy\";", + "fieldname": "counts_completed", + "fieldtype": "Int", + "label": "Counts Completed", + "no_copy": 1 + }, + { + "fieldname": "assistance_level", + "fieldtype": "Select", + "label": "Assistance Level", + "options": "\nPassive\nActive Assist\nActive" + } + ], + "istable": 1, + "links": [], + "modified": "2020-11-04 18:20:25.583491", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Exercise", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/exercise/exercise.py b/healthcare/healthcare/doctype/exercise/exercise.py new file mode 100644 index 0000000..f7a5064 --- /dev/null +++ b/healthcare/healthcare/doctype/exercise/exercise.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class Exercise(Document): + pass diff --git a/healthcare/healthcare/doctype/exercise_difficulty_level/__init__.py b/healthcare/healthcare/doctype/exercise_difficulty_level/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/exercise_difficulty_level/exercise_difficulty_level.js b/healthcare/healthcare/doctype/exercise_difficulty_level/exercise_difficulty_level.js new file mode 100644 index 0000000..e35fc62 --- /dev/null +++ b/healthcare/healthcare/doctype/exercise_difficulty_level/exercise_difficulty_level.js @@ -0,0 +1,8 @@ +// Copyright (c) 2020, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Exercise Difficulty Level', { + // refresh: function(frm) { + + // } +}); diff --git a/healthcare/healthcare/doctype/exercise_difficulty_level/exercise_difficulty_level.json b/healthcare/healthcare/doctype/exercise_difficulty_level/exercise_difficulty_level.json new file mode 100644 index 0000000..a6aed75 --- /dev/null +++ b/healthcare/healthcare/doctype/exercise_difficulty_level/exercise_difficulty_level.json @@ -0,0 +1,45 @@ +{ + "actions": [], + "autoname": "field:difficulty_level", + "creation": "2020-03-29 21:12:55.835941", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "difficulty_level" + ], + "fields": [ + { + "fieldname": "difficulty_level", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Difficulty Level", + "reqd": 1, + "unique": 1 + } + ], + "links": [], + "modified": "2020-03-31 23:14:33.554066", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Exercise Difficulty Level", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/exercise_difficulty_level/exercise_difficulty_level.py b/healthcare/healthcare/doctype/exercise_difficulty_level/exercise_difficulty_level.py new file mode 100644 index 0000000..f2ccea7 --- /dev/null +++ b/healthcare/healthcare/doctype/exercise_difficulty_level/exercise_difficulty_level.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class ExerciseDifficultyLevel(Document): + pass diff --git a/healthcare/healthcare/doctype/exercise_difficulty_level/test_exercise_difficulty_level.py b/healthcare/healthcare/doctype/exercise_difficulty_level/test_exercise_difficulty_level.py new file mode 100644 index 0000000..3035fe4 --- /dev/null +++ b/healthcare/healthcare/doctype/exercise_difficulty_level/test_exercise_difficulty_level.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# See license.txt + + +# import frappe +from frappe.tests.utils import FrappeTestCase + + +class TestExerciseDifficultyLevel(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/exercise_type/__init__.py b/healthcare/healthcare/doctype/exercise_type/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/exercise_type/exercise_type.js b/healthcare/healthcare/doctype/exercise_type/exercise_type.js new file mode 100644 index 0000000..5bb8ea3 --- /dev/null +++ b/healthcare/healthcare/doctype/exercise_type/exercise_type.js @@ -0,0 +1,186 @@ +// Copyright (c) 2020, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Exercise Type', { + refresh: function(frm) { + let wrapper = frm.fields_dict.steps_html.wrapper; + + frm.ExerciseEditor = new erpnext.ExerciseEditor(frm, wrapper); + } +}); + +erpnext.ExerciseEditor = class ExerciseEditor { + constructor(frm, wrapper) { + this.wrapper = wrapper; + this.frm = frm; + this.make(frm, wrapper); + } + + make(frm, wrapper) { + $(this.wrapper).empty(); + + this.exercise_toolbar = $('

\ + ').appendTo(this.wrapper); + + this.exercise_cards = $('

').appendTo(this.wrapper); + + this.row = $('
').appendTo(this.wrapper); + + let me = this; + + this.exercise_toolbar.find(".btn-add") + .html(__('Add')) + .on("click", function() { + me.show_add_card_dialog(frm); + }); + + if (frm.doc.steps_table && frm.doc.steps_table.length > 0) { + this.make_cards(frm); + this.make_buttons(frm); + } + } + + make_cards(frm) { + var me = this; + $(me.exercise_cards).empty(); + + $.each(frm.doc.steps_table, function(i, step) { + $(repl(` +
+
+
+ ... +

%(title)s

+

%(description)s

+
+ +
+
`, {image_src: step.image, title: step.title, description: step.description, col_id: "col-"+i, card_id: "card-"+i, id: i})).appendTo(me.row); + }); + } + + make_buttons(frm) { + let me = this; + $('.btn-edit').on('click', function() { + let id = $(this).attr('data-id'); + me.show_edit_card_dialog(frm, id); + }); + + $('.btn-del').on('click', function() { + let id = $(this).attr('data-id'); + $('#card-'+id).addClass("zoom-out"); + + setTimeout(() => { + // not using grid_rows[id].remove because + // grid_rows is not defined when the table is hidden + frm.doc.steps_table.pop(id); + frm.refresh_field('steps_table'); + $('#col-'+id).remove(); + frm.dirty(); + }, 300); + }); + } + + show_add_card_dialog(frm) { + let me = this; + let d = new frappe.ui.Dialog({ + title: __('Add Exercise Step'), + fields: [ + { + "label": "Title", + "fieldname": "title", + "fieldtype": "Data", + "reqd": 1 + }, + { + "label": "Attach Image", + "fieldname": "image", + "fieldtype": "Attach Image" + }, + { + "label": "Step Description", + "fieldname": "step_description", + "fieldtype": "Long Text" + } + ], + primary_action: function() { + let data = d.get_values(); + let i = 0; + if (frm.doc.steps_table) { + i = frm.doc.steps_table.length; + } + $(repl(` +
+
+
+ ... +

%(title)s

+

%(description)s

+
+ +
+
`, {image_src: data.image, title: data.title, description: data.step_description, col_id: "col-"+i, card_id: "card-"+i, id: i})).appendTo(me.row); + let step = frappe.model.add_child(frm.doc, 'Exercise Type Step', 'steps_table'); + step.title = data.title; + step.image = data.image; + step.description = data.step_description; + me.make_buttons(frm); + frm.refresh_field('steps_table'); + d.hide(); + }, + primary_action_label: __('Add') + }); + d.show(); + } + + show_edit_card_dialog(frm, id) { + let new_dialog = new frappe.ui.Dialog({ + title: __("Edit Exercise Step"), + fields: [ + { + "label": "Title", + "fieldname": "title", + "fieldtype": "Data", + "reqd": 1 + }, + { + "label": "Attach Image", + "fieldname": "image", + "fieldtype": "Attach Image" + }, + { + "label": "Step Description", + "fieldname": "step_description", + "fieldtype": "Long Text" + } + ], + primary_action: () => { + let data = new_dialog.get_values(); + $('#card-'+id).find('.card-title').html(data.title); + $('#card-'+id).find('img').attr('src', data.image); + $('#card-'+id).find('.card-text').html(data.step_description); + + frm.doc.steps_table[id].title = data.title; + frm.doc.steps_table[id].image = data.image; + frm.doc.steps_table[id].description = data.step_description; + refresh_field('steps_table'); + frm.dirty(); + new_dialog.hide(); + }, + primary_action_label: __("Edit"), + }); + + new_dialog.set_values({ + title: frm.doc.steps_table[id].title, + image: frm.doc.steps_table[id].image, + step_description: frm.doc.steps_table[id].description + }); + new_dialog.show(); + } +}; diff --git a/healthcare/healthcare/doctype/exercise_type/exercise_type.json b/healthcare/healthcare/doctype/exercise_type/exercise_type.json new file mode 100644 index 0000000..0db9c6e --- /dev/null +++ b/healthcare/healthcare/doctype/exercise_type/exercise_type.json @@ -0,0 +1,144 @@ +{ + "actions": [], + "creation": "2020-03-29 21:37:03.366344", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "exercise_name", + "body_parts", + "column_break_3", + "difficulty_level", + "section_break_5", + "description", + "section_break_7", + "exercise_steps", + "column_break_9", + "exercise_video", + "section_break_11", + "steps_html", + "section_break_13", + "steps_table" + ], + "fields": [ + { + "fieldname": "exercise_name", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Exercise Name", + "reqd": 1 + }, + { + "fieldname": "difficulty_level", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Difficulty Level", + "options": "Exercise Difficulty Level" + }, + { + "fieldname": "column_break_3", + "fieldtype": "Column Break" + }, + { + "fieldname": "section_break_5", + "fieldtype": "Section Break" + }, + { + "fieldname": "description", + "fieldtype": "Long Text", + "label": "Description" + }, + { + "fieldname": "section_break_7", + "fieldtype": "Section Break" + }, + { + "fieldname": "exercise_steps", + "fieldtype": "Attach", + "label": "Exercise Instructions" + }, + { + "fieldname": "exercise_video", + "fieldtype": "Link", + "label": "Exercise Video", + "options": "Video" + }, + { + "fieldname": "column_break_9", + "fieldtype": "Column Break" + }, + { + "fieldname": "steps_html", + "fieldtype": "HTML", + "label": "Steps" + }, + { + "fieldname": "steps_table", + "fieldtype": "Table", + "hidden": 1, + "label": "Steps Table", + "options": "Exercise Type Step" + }, + { + "fieldname": "section_break_11", + "fieldtype": "Section Break", + "label": "Exercise Steps" + }, + { + "fieldname": "section_break_13", + "fieldtype": "Section Break" + }, + { + "fieldname": "body_parts", + "fieldtype": "Table MultiSelect", + "label": "Body Parts", + "options": "Body Part Link" + } + ], + "links": [], + "modified": "2020-04-21 13:05:36.555060", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Exercise Type", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + }, + { + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/exercise_type/exercise_type.py b/healthcare/healthcare/doctype/exercise_type/exercise_type.py new file mode 100644 index 0000000..27dbfe7 --- /dev/null +++ b/healthcare/healthcare/doctype/exercise_type/exercise_type.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class ExerciseType(Document): + def autoname(self): + if self.difficulty_level: + self.name = " - ".join(filter(None, [self.exercise_name, self.difficulty_level])) + else: + self.name = self.exercise_name diff --git a/healthcare/healthcare/doctype/exercise_type/test_exercise_type.py b/healthcare/healthcare/doctype/exercise_type/test_exercise_type.py new file mode 100644 index 0000000..c6d0014 --- /dev/null +++ b/healthcare/healthcare/doctype/exercise_type/test_exercise_type.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# See license.txt + + +# import frappe +from frappe.tests.utils import FrappeTestCase + + +class TestExerciseType(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/exercise_type_step/__init__.py b/healthcare/healthcare/doctype/exercise_type_step/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/exercise_type_step/exercise_type_step.json b/healthcare/healthcare/doctype/exercise_type_step/exercise_type_step.json new file mode 100644 index 0000000..b37ff00 --- /dev/null +++ b/healthcare/healthcare/doctype/exercise_type_step/exercise_type_step.json @@ -0,0 +1,44 @@ +{ + "actions": [], + "creation": "2020-03-31 23:01:18.761967", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "title", + "image", + "description" + ], + "fields": [ + { + "fieldname": "title", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Title", + "reqd": 1 + }, + { + "fieldname": "image", + "fieldtype": "Attach Image", + "label": "Image" + }, + { + "fieldname": "description", + "fieldtype": "Long Text", + "in_list_view": 1, + "label": "Description" + } + ], + "istable": 1, + "links": [], + "modified": "2020-04-02 20:39:34.258512", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Exercise Type Step", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/exercise_type_step/exercise_type_step.py b/healthcare/healthcare/doctype/exercise_type_step/exercise_type_step.py new file mode 100644 index 0000000..551407d --- /dev/null +++ b/healthcare/healthcare/doctype/exercise_type_step/exercise_type_step.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class ExerciseTypeStep(Document): + pass diff --git a/healthcare/healthcare/doctype/fee_validity/__init__.py b/healthcare/healthcare/doctype/fee_validity/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/fee_validity/fee_validity.js b/healthcare/healthcare/doctype/fee_validity/fee_validity.js new file mode 100644 index 0000000..7ea2213 --- /dev/null +++ b/healthcare/healthcare/doctype/fee_validity/fee_validity.js @@ -0,0 +1,5 @@ +// Copyright (c) 2016, ESS LLP and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Fee Validity', { +}); diff --git a/healthcare/healthcare/doctype/fee_validity/fee_validity.json b/healthcare/healthcare/doctype/fee_validity/fee_validity.json new file mode 100644 index 0000000..d76b42e --- /dev/null +++ b/healthcare/healthcare/doctype/fee_validity/fee_validity.json @@ -0,0 +1,134 @@ +{ + "actions": [], + "allow_copy": 1, + "allow_import": 1, + "beta": 1, + "creation": "2017-01-05 10:56:29.564806", + "doctype": "DocType", + "document_type": "Setup", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "practitioner", + "patient", + "column_break_3", + "status", + "section_break_5", + "section_break_3", + "max_visits", + "visited", + "ref_appointments", + "column_break_6", + "start_date", + "valid_till" + ], + "fields": [ + { + "fieldname": "practitioner", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Healthcare Practitioner", + "options": "Healthcare Practitioner", + "read_only": 1, + "reqd": 1, + "search_index": 1 + }, + { + "fieldname": "patient", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Patient", + "options": "Patient", + "read_only": 1, + "reqd": 1, + "search_index": 1 + }, + { + "fieldname": "visited", + "fieldtype": "Int", + "label": "Visits Completed", + "read_only": 1 + }, + { + "fieldname": "valid_till", + "fieldtype": "Date", + "label": "Valid Till", + "read_only": 1 + }, + { + "fieldname": "section_break_3", + "fieldtype": "Section Break", + "label": "Validity", + "read_only": 1 + }, + { + "fieldname": "column_break_6", + "fieldtype": "Column Break" + }, + { + "fieldname": "max_visits", + "fieldtype": "Int", + "label": "Max number of visit", + "read_only": 1 + }, + { + "fieldname": "column_break_3", + "fieldtype": "Column Break" + }, + { + "fieldname": "status", + "fieldtype": "Select", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Status", + "options": "Completed\nPending", + "read_only": 1 + }, + { + "fetch_from": "ref_appointment.appointment_date", + "fieldname": "start_date", + "fieldtype": "Date", + "label": "Start Date", + "read_only": 1 + }, + { + "fieldname": "ref_appointments", + "fieldtype": "Table MultiSelect", + "label": "Reference Appointments", + "options": "Fee Validity Reference", + "read_only": 1 + }, + { + "collapsible": 1, + "fieldname": "section_break_5", + "fieldtype": "Section Break" + } + ], + "in_create": 1, + "links": [], + "modified": "2021-08-26 10:51:05.609349", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Fee Validity", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "restrict_to_domain": "Healthcare", + "search_fields": "practitioner, patient", + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "practitioner" +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/fee_validity/fee_validity.py b/healthcare/healthcare/doctype/fee_validity/fee_validity.py new file mode 100644 index 0000000..1fb0df7 --- /dev/null +++ b/healthcare/healthcare/doctype/fee_validity/fee_validity.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and contributors +# For license information, please see license.txt + + +import datetime + +import frappe +from frappe.model.document import Document +from frappe.utils import getdate + + +class FeeValidity(Document): + def validate(self): + self.update_status() + + def update_status(self): + if self.visited >= self.max_visits: + self.status = "Completed" + else: + self.status = "Pending" + + +def create_fee_validity(appointment): + if not check_is_new_patient(appointment): + return + + fee_validity = frappe.new_doc("Fee Validity") + fee_validity.practitioner = appointment.practitioner + fee_validity.patient = appointment.patient + fee_validity.max_visits = frappe.db.get_single_value("Healthcare Settings", "max_visits") or 1 + valid_days = frappe.db.get_single_value("Healthcare Settings", "valid_days") or 1 + fee_validity.visited = 0 + fee_validity.start_date = getdate(appointment.appointment_date) + fee_validity.valid_till = getdate(appointment.appointment_date) + datetime.timedelta( + days=int(valid_days) + ) + fee_validity.save(ignore_permissions=True) + return fee_validity + + +def check_is_new_patient(appointment): + validity_exists = frappe.db.exists( + "Fee Validity", {"practitioner": appointment.practitioner, "patient": appointment.patient} + ) + if validity_exists: + return False + + appointment_exists = frappe.db.get_all( + "Patient Appointment", + { + "name": ("!=", appointment.name), + "status": ("!=", "Cancelled"), + "patient": appointment.patient, + "practitioner": appointment.practitioner, + }, + ) + if len(appointment_exists) and appointment_exists[0]: + return False + return True diff --git a/healthcare/healthcare/doctype/fee_validity/test_fee_validity.py b/healthcare/healthcare/doctype/fee_validity/test_fee_validity.py new file mode 100644 index 0000000..ec23ba9 --- /dev/null +++ b/healthcare/healthcare/doctype/fee_validity/test_fee_validity.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +import frappe +from frappe.utils import add_days, nowdate + +from erpnext.accounts.doctype.pos_profile.test_pos_profile import make_pos_profile +from healthcare.healthcare.doctype.patient_appointment.test_patient_appointment import ( + create_appointment, + create_healthcare_docs, + create_healthcare_service_items, +) + +test_dependencies = ["Company"] + + +class TestFeeValidity(FrappeTestCase): + def setUp(self): + frappe.db.sql("""delete from `tabPatient Appointment`""") + frappe.db.sql("""delete from `tabFee Validity`""") + frappe.db.sql("""delete from `tabPatient`""") + make_pos_profile() + + def test_fee_validity(self): + item = create_healthcare_service_items() + healthcare_settings = frappe.get_single("Healthcare Settings") + healthcare_settings.enable_free_follow_ups = 1 + healthcare_settings.max_visits = 1 + healthcare_settings.valid_days = 7 + healthcare_settings.automate_appointment_invoicing = 1 + healthcare_settings.op_consulting_charge_item = item + healthcare_settings.save(ignore_permissions=True) + patient, practitioner = create_healthcare_docs() + + # For first appointment, invoice is generated. First appointment not considered in fee validity + appointment = create_appointment(patient, practitioner, nowdate()) + invoiced = frappe.db.get_value("Patient Appointment", appointment.name, "invoiced") + self.assertEqual(invoiced, 1) + + # appointment should not be invoiced as it is within fee validity + appointment = create_appointment(patient, practitioner, add_days(nowdate(), 4)) + invoiced = frappe.db.get_value("Patient Appointment", appointment.name, "invoiced") + self.assertEqual(invoiced, 0) + + # appointment should be invoiced as it is within fee validity but the max_visits are exceeded + appointment = create_appointment(patient, practitioner, add_days(nowdate(), 5), invoice=1) + invoiced = frappe.db.get_value("Patient Appointment", appointment.name, "invoiced") + self.assertEqual(invoiced, 1) + + # appointment should be invoiced as it is not within fee validity and the max_visits are exceeded + appointment = create_appointment(patient, practitioner, add_days(nowdate(), 10), invoice=1) + invoiced = frappe.db.get_value("Patient Appointment", appointment.name, "invoiced") + self.assertEqual(invoiced, 1) diff --git a/healthcare/healthcare/doctype/fee_validity_reference/__init__.py b/healthcare/healthcare/doctype/fee_validity_reference/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/fee_validity_reference/fee_validity_reference.json b/healthcare/healthcare/doctype/fee_validity_reference/fee_validity_reference.json new file mode 100644 index 0000000..40f128e --- /dev/null +++ b/healthcare/healthcare/doctype/fee_validity_reference/fee_validity_reference.json @@ -0,0 +1,32 @@ +{ + "actions": [], + "creation": "2020-03-13 16:08:42.859996", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "appointment" + ], + "fields": [ + { + "fieldname": "appointment", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Patient Appointment", + "options": "Patient Appointment", + "reqd": 1 + } + ], + "istable": 1, + "links": [], + "modified": "2020-03-15 00:27:02.076470", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Fee Validity Reference", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/fee_validity_reference/fee_validity_reference.py b/healthcare/healthcare/doctype/fee_validity_reference/fee_validity_reference.py new file mode 100644 index 0000000..e051583 --- /dev/null +++ b/healthcare/healthcare/doctype/fee_validity_reference/fee_validity_reference.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class FeeValidityReference(Document): + pass diff --git a/healthcare/healthcare/doctype/healthcare.py b/healthcare/healthcare/doctype/healthcare.py new file mode 100644 index 0000000..795d633 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare.py @@ -0,0 +1,2 @@ +def get_data(): + return [] diff --git a/healthcare/healthcare/doctype/healthcare_activity/__init__.py b/healthcare/healthcare/doctype/healthcare_activity/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/healthcare_activity/healthcare_activity.js b/healthcare/healthcare/doctype/healthcare_activity/healthcare_activity.js new file mode 100644 index 0000000..236d34e --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_activity/healthcare_activity.js @@ -0,0 +1,26 @@ +// Copyright (c) 2021, healthcare and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Healthcare Activity', { + onload: function(frm) { + + frm.set_query('role', function() { + return { + filters: { + 'disabled': false, + 'desk_access': true + } + }; + }); + + frm.set_query('task_doctype', function() { + return { + filters: { + 'istable': false, + 'issingle': false + } + }; + }); + + } +}); diff --git a/healthcare/healthcare/doctype/healthcare_activity/healthcare_activity.json b/healthcare/healthcare/doctype/healthcare_activity/healthcare_activity.json new file mode 100644 index 0000000..be57b51 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_activity/healthcare_activity.json @@ -0,0 +1,88 @@ +{ + "actions": [], + "allow_rename": 1, + "autoname": "field:activity", + "creation": "2021-10-28 06:33:43.654812", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "activity", + "description", + "column_break_4", + "activity_duration", + "role", + "task_doctype" + ], + "fields": [ + { + "allow_in_quick_entry": 1, + "fieldname": "activity", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Activity", + "reqd": 1, + "unique": 1 + }, + { + "allow_in_quick_entry": 1, + "fieldname": "role", + "fieldtype": "Link", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Role", + "options": "Role" + }, + { + "fieldname": "column_break_4", + "fieldtype": "Column Break" + }, + { + "allow_in_quick_entry": 1, + "fieldname": "description", + "fieldtype": "Small Text", + "in_list_view": 1, + "label": "Description" + }, + { + "allow_in_quick_entry": 1, + "fieldname": "task_doctype", + "fieldtype": "Link", + "label": "Task DocType", + "options": "DocType" + }, + { + "allow_in_quick_entry": 1, + "fieldname": "activity_duration", + "fieldtype": "Duration", + "label": "Activity Duration" + } + ], + "index_web_pages_for_search": 1, + "links": [], + "modified": "2022-07-25 19:29:15.860690", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Healthcare Activity", + "naming_rule": "By fieldname", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "states": [], + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/healthcare_activity/healthcare_activity.py b/healthcare/healthcare/doctype/healthcare_activity/healthcare_activity.py new file mode 100644 index 0000000..f768ac8 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_activity/healthcare_activity.py @@ -0,0 +1,9 @@ +# Copyright (c) 2021, healthcare and contributors +# For license information, please see license.txt + +# import frappe +from frappe.model.document import Document + + +class HealthcareActivity(Document): + pass diff --git a/healthcare/healthcare/doctype/healthcare_activity/test_healthcare_activity.py b/healthcare/healthcare/doctype/healthcare_activity/test_healthcare_activity.py new file mode 100644 index 0000000..2841b02 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_activity/test_healthcare_activity.py @@ -0,0 +1,9 @@ +# Copyright (c) 2021, healthcare and Contributors +# See license.txt + +# import frappe +import unittest + + +class TestHealthcareActivity(unittest.TestCase): + pass diff --git a/healthcare/healthcare/doctype/healthcare_practitioner/__init__.py b/healthcare/healthcare/doctype/healthcare_practitioner/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/healthcare_practitioner/healthcare_practitioner.js b/healthcare/healthcare/doctype/healthcare_practitioner/healthcare_practitioner.js new file mode 100644 index 0000000..44c3998 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_practitioner/healthcare_practitioner.js @@ -0,0 +1,144 @@ +// Copyright (c) 2016, ESS LLP and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Healthcare Practitioner', { + setup: function(frm) { + frm.set_query('account', 'accounts', function(doc, cdt, cdn) { + let d = locals[cdt][cdn]; + return { + filters: { + 'root_type': 'Income', + 'company': d.company, + 'is_group': 0 + } + }; + }); + }, + refresh: function(frm) { + frappe.dynamic_link = {doc: frm.doc, fieldname: 'name', doctype: 'Healthcare Practitioner'}; + + if (!frm.is_new()) { + frappe.contacts.render_address_and_contact(frm); + } else { + frappe.contacts.clear_address_and_contact(frm); + } + + frm.set_query('service_unit', 'practitioner_schedules', function(){ + return { + filters: { + 'is_group': false, + 'allow_appointments': true + } + }; + }); + + set_query_service_item(frm, 'inpatient_visit_charge_item'); + set_query_service_item(frm, 'op_consulting_charge_item'); + } +}); + +let set_query_service_item = function(frm, service_item_field) { + frm.set_query(service_item_field, function() { + return { + filters: { + 'is_sales_item': 1, + 'is_stock_item': 0 + } + }; + }); +}; + +frappe.ui.form.on('Healthcare Practitioner', 'user_id',function(frm) { + if (frm.doc.user_id) { + frappe.call({ + 'method': 'frappe.client.get', + args: { + doctype: 'User', + name: frm.doc.user_id + }, + callback: function (data) { + + frappe.model.get_value('Employee', {'user_id': frm.doc.user_id}, 'name', + function(data) { + if (data) { + if (!frm.doc.employee || frm.doc.employee != data.name) + frappe.model.set_value(frm.doctype, frm.docname, 'employee', data.name); + } else { + frappe.model.set_value(frm.doctype, frm.docname, 'employee', ''); + } + } + ); + + if (!frm.doc.first_name || frm.doc.first_name != data.message.first_name) + frappe.model.set_value(frm.doctype,frm.docname, 'first_name', data.message.first_name); + if (!frm.doc.middle_name || frm.doc.middle_name != data.message.middle_name) + frappe.model.set_value(frm.doctype,frm.docname, 'middle_name', data.message.middle_name); + if (!frm.doc.last_name || frm.doc.last_name != data.message.last_name) + frappe.model.set_value(frm.doctype,frm.docname, 'last_name', data.message.last_name); + if (!frm.doc.mobile_phone || frm.doc.mobile_phone != data.message.mobile_no) + frappe.model.set_value(frm.doctype,frm.docname, 'mobile_phone', data.message.mobile_no); + } + }); + } +}); + +frappe.ui.form.on('Healthcare Practitioner', 'employee', function(frm) { + if (frm.doc.employee){ + frappe.call({ + 'method': 'frappe.client.get', + args: { + doctype: 'Employee', + name: frm.doc.employee + }, + callback: function (data) { + if (!frm.doc.user_id || frm.doc.user_id != data.message.user_id) + frm.set_value('user_id', data.message.user_id); + if (!frm.doc.designation || frm.doc.designation != data.message.designation) + frappe.model.set_value(frm.doctype,frm.docname, 'designation', data.message.designation); + if (!frm.doc.first_name || !frm.doc.user_id){ + frappe.model.set_value(frm.doctype,frm.docname, 'first_name', data.message.first_name); + frappe.model.set_value(frm.doctype,frm.docname, 'middle_name', ''); + frappe.model.set_value(frm.doctype,frm.docname, 'last_name', data.message.last_name); + } + if (!frm.doc.mobile_phone || !frm.doc.user_id) + frappe.model.set_value(frm.doctype,frm.docname, 'mobile_phone', data.message.cell_number); + if (!frm.doc.address || frm.doc.address != data.message.current_address) + frappe.model.set_value(frm.doctype,frm.docname, 'address', data.message.current_address); + } + }); + } +}); + +frappe.tour['Healthcare Practitioner'] = [ + { + fieldname: 'employee', + title: __('Employee'), + description: __('If you want to track Payroll and other HRMS operations for a Practitoner, create an Employee and link it here.') + }, + { + fieldname: 'practitioner_schedules', + title: __('Practitioner Schedules'), + description: __('Set the Practitioner Schedule you just created. This will be used while booking appointments.') + }, + { + fieldname: 'op_consulting_charge_item', + title: __('Out Patient Consulting Charge Item'), + description: __('Create a service item for Out Patient Consulting.') + }, + { + fieldname: 'inpatient_visit_charge_item', + title: __('Inpatient Visit Charge Item'), + description: __('If this Healthcare Practitioner works for the In-Patient Department, create a service item for Inpatient Visits.') + }, + { + fieldname: 'op_consulting_charge', + title: __('Out Patient Consulting Charge'), + description: __('Set the Out Patient Consulting Charge for this Practitioner.') + + }, + { + fieldname: 'inpatient_visit_charge', + title: __('Inpatient Visit Charge'), + description: __('If this Healthcare Practitioner also works for the In-Patient Department, set the inpatient visit charge for this Practitioner.') + } +]; diff --git a/healthcare/healthcare/doctype/healthcare_practitioner/healthcare_practitioner.json b/healthcare/healthcare/doctype/healthcare_practitioner/healthcare_practitioner.json new file mode 100644 index 0000000..6482b1a --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_practitioner/healthcare_practitioner.json @@ -0,0 +1,339 @@ +{ + "actions": [], + "allow_import": 1, + "allow_rename": 1, + "autoname": "naming_series:", + "beta": 1, + "creation": "2016-02-23 11:20:53.565119", + "doctype": "DocType", + "document_type": "Setup", + "engine": "InnoDB", + "field_order": [ + "basic_details_section", + "naming_series", + "first_name", + "middle_name", + "last_name", + "practitioner_name", + "gender", + "image", + "column_break_7", + "status", + "mobile_phone", + "residence_phone", + "office_phone", + "employee_and_user_details_section", + "employee", + "department", + "designation", + "column_break_17", + "user_id", + "hospital", + "appointments", + "practitioner_schedules", + "charges", + "op_consulting_charge_item", + "op_consulting_charge", + "column_break_18", + "inpatient_visit_charge_item", + "inpatient_visit_charge", + "account_details", + "default_currency", + "accounts", + "address_and_contacts_section", + "address_html", + "column_break_19", + "contact_html" + ], + "fields": [ + { + "fieldname": "first_name", + "fieldtype": "Data", + "label": "First Name", + "no_copy": 1, + "reqd": 1 + }, + { + "fieldname": "middle_name", + "fieldtype": "Data", + "label": "Middle Name (Optional)", + "no_copy": 1 + }, + { + "fieldname": "last_name", + "fieldtype": "Data", + "label": "Last Name", + "no_copy": 1 + }, + { + "fieldname": "image", + "fieldtype": "Attach Image", + "hidden": 1, + "label": "Image", + "no_copy": 1, + "print_hide": 1 + }, + { + "fieldname": "employee", + "fieldtype": "Link", + "label": "Employee", + "options": "Employee" + }, + { + "fieldname": "user_id", + "fieldtype": "Link", + "label": "User", + "options": "User", + "search_index": 1 + }, + { + "fetch_from": "employee", + "fieldname": "designation", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Designation", + "options": "Designation", + "read_only": 1 + }, + { + "fieldname": "department", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_standard_filter": 1, + "label": "Medical Department", + "options": "Medical Department" + }, + { + "fieldname": "column_break_7", + "fieldtype": "Column Break" + }, + { + "fieldname": "hospital", + "fieldtype": "Data", + "label": "Hospital" + }, + { + "fieldname": "mobile_phone", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Mobile" + }, + { + "fieldname": "residence_phone", + "fieldtype": "Data", + "label": "Phone (R)" + }, + { + "fieldname": "office_phone", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Phone (Office)" + }, + { + "collapsible": 1, + "fieldname": "appointments", + "fieldtype": "Section Break", + "label": "Appointments" + }, + { + "fieldname": "practitioner_schedules", + "fieldtype": "Table", + "label": "Practitioner Schedules", + "options": "Practitioner Service Unit Schedule" + }, + { + "collapsible": 1, + "fieldname": "charges", + "fieldtype": "Section Break", + "label": "Charges" + }, + { + "fieldname": "op_consulting_charge_item", + "fieldtype": "Link", + "label": "Out Patient Consulting Charge Item", + "options": "Item" + }, + { + "fieldname": "op_consulting_charge", + "fieldtype": "Currency", + "label": "Out Patient Consulting Charge", + "mandatory_depends_on": "op_consulting_charge_item", + "options": "Currency" + }, + { + "fieldname": "column_break_18", + "fieldtype": "Column Break" + }, + { + "fieldname": "inpatient_visit_charge_item", + "fieldtype": "Link", + "label": "Inpatient Visit Charge Item", + "options": "Item" + }, + { + "fieldname": "inpatient_visit_charge", + "fieldtype": "Currency", + "label": "Inpatient Visit Charge", + "mandatory_depends_on": "inpatient_visit_charge_item" + }, + { + "depends_on": "eval: !doc.__islocal", + "fieldname": "address_html", + "fieldtype": "HTML", + "label": "Address HTML", + "no_copy": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "fieldname": "column_break_19", + "fieldtype": "Column Break" + }, + { + "depends_on": "eval: !doc.__islocal", + "fieldname": "contact_html", + "fieldtype": "HTML", + "label": "Contact HTML", + "no_copy": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "collapsible": 1, + "fieldname": "account_details", + "fieldtype": "Section Break", + "label": "Account Details" + }, + { + "fieldname": "accounts", + "fieldtype": "Table", + "label": "Income Account", + "options": "Party Account" + }, + { + "fieldname": "default_currency", + "fieldtype": "Link", + "hidden": 1, + "label": "Default Currency", + "no_copy": 1, + "options": "Currency", + "print_hide": 1, + "report_hide": 1 + }, + { + "bold": 1, + "fieldname": "practitioner_name", + "fieldtype": "Data", + "in_global_search": 1, + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Full Name", + "no_copy": 1, + "read_only": 1, + "search_index": 1 + }, + { + "fieldname": "naming_series", + "fieldtype": "Select", + "label": "Series", + "no_copy": 1, + "options": "HLC-PRAC-.YYYY.-", + "report_hide": 1, + "set_only_once": 1 + }, + { + "allow_in_quick_entry": 1, + "fieldname": "gender", + "fieldtype": "Link", + "label": "Gender", + "options": "Gender" + }, + { + "fieldname": "employee_and_user_details_section", + "fieldtype": "Section Break", + "label": "Employee and User Details" + }, + { + "fieldname": "column_break_17", + "fieldtype": "Column Break" + }, + { + "default": "Active", + "fieldname": "status", + "fieldtype": "Select", + "in_list_view": 1, + "label": "Status", + "options": "\nActive\nDisabled", + "reqd": 1 + }, + { + "fieldname": "basic_details_section", + "fieldtype": "Section Break", + "label": "Basic Details" + }, + { + "collapsible": 1, + "depends_on": "eval: !doc.__islocal", + "fieldname": "address_and_contacts_section", + "fieldtype": "Section Break", + "label": "Address and Contacts" + } + ], + "image_field": "image", + "links": [], + "modified": "2021-10-20 08:30:46.786977", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Healthcare Practitioner", + "naming_rule": "By \"Naming Series\" field", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "email": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Laboratory User", + "select": 1, + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "select": 1, + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Nursing User", + "select": 1, + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "restrict_to_domain": "Healthcare", + "search_fields": "practitioner_name, mobile_phone, office_phone", + "show_name_in_global_search": 1, + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "practitioner_name", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/healthcare_practitioner/healthcare_practitioner.py b/healthcare/healthcare/doctype/healthcare_practitioner/healthcare_practitioner.py new file mode 100644 index 0000000..6bd17b7 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_practitioner/healthcare_practitioner.py @@ -0,0 +1,109 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and contributors +# For license information, please see license.txt + + +import frappe +from frappe import _ +from frappe.contacts.address_and_contact import ( + delete_contact_and_address, + load_address_and_contact, +) +from frappe.model.document import Document +from frappe.model.naming import append_number_if_name_exists + +from erpnext.accounts.party import validate_party_accounts + + +class HealthcarePractitioner(Document): + def onload(self): + load_address_and_contact(self) + + def autoname(self): + # concat first and last name + self.name = self.practitioner_name + + if frappe.db.exists("Healthcare Practitioner", self.name): + self.name = append_number_if_name_exists("Contact", self.name) + + def validate(self): + self.set_full_name() + validate_party_accounts(self) + if self.inpatient_visit_charge_item: + validate_service_item( + self.inpatient_visit_charge_item, + "Configure a service Item for Inpatient Consulting Charge Item", + ) + if self.op_consulting_charge_item: + validate_service_item( + self.op_consulting_charge_item, + "Configure a service Item for Out Patient Consulting Charge Item", + ) + + if self.user_id: + self.validate_user_id() + else: + existing_user_id = frappe.db.get_value("Healthcare Practitioner", self.name, "user_id") + if existing_user_id: + frappe.permissions.remove_user_permission( + "Healthcare Practitioner", self.name, existing_user_id + ) + + def on_update(self): + if self.user_id: + frappe.permissions.add_user_permission("Healthcare Practitioner", self.name, self.user_id) + + def set_full_name(self): + if self.last_name: + self.practitioner_name = " ".join(filter(None, [self.first_name, self.last_name])) + else: + self.practitioner_name = self.first_name + + def validate_user_id(self): + if not frappe.db.exists("User", self.user_id): + frappe.throw(_("User {0} does not exist").format(self.user_id)) + elif not frappe.db.exists("User", self.user_id, "enabled"): + frappe.throw(_("User {0} is disabled").format(self.user_id)) + + # check duplicate + practitioner = frappe.db.exists( + "Healthcare Practitioner", {"user_id": self.user_id, "name": ("!=", self.name)} + ) + if practitioner: + frappe.throw( + _("User {0} is already assigned to Healthcare Practitioner {1}").format( + self.user_id, practitioner + ) + ) + + def on_trash(self): + delete_contact_and_address("Healthcare Practitioner", self.name) + + +def validate_service_item(item, msg): + if frappe.db.get_value("Item", item, "is_stock_item"): + frappe.throw(_(msg)) + + +@frappe.whitelist() +@frappe.validate_and_sanitize_search_inputs +def get_practitioner_list(doctype, txt, searchfield, start, page_len, filters=None): + + active_filter = {"status": "Active"} + + filters = {**active_filter, **filters} if filters else active_filter + + fields = ["name", "practitioner_name", "mobile_phone"] + + text_in = {"name": ("like", "%%%s%%" % txt), "practitioner_name": ("like", "%%%s%%" % txt)} + + return frappe.get_all( + "Healthcare Practitioner", + fields=fields, + filters=filters, + or_filters=text_in, + start=start, + page_length=page_len, + order_by="name, practitioner_name", + as_list=1, + ) diff --git a/healthcare/healthcare/doctype/healthcare_practitioner/healthcare_practitioner_dashboard.py b/healthcare/healthcare/doctype/healthcare_practitioner/healthcare_practitioner_dashboard.py new file mode 100644 index 0000000..ba6b86b --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_practitioner/healthcare_practitioner_dashboard.py @@ -0,0 +1,16 @@ +from frappe import _ + + +def get_data(): + return { + "heatmap": True, + "heatmap_message": _("This is based on transactions against this Healthcare Practitioner."), + "fieldname": "practitioner", + "transactions": [ + { + "label": _("Appointments and Patient Encounters"), + "items": ["Patient Appointment", "Patient Encounter", "Fee Validity"], + }, + {"label": _("Consultation"), "items": ["Clinical Procedure", "Lab Test"]}, + ], + } diff --git a/healthcare/healthcare/doctype/healthcare_practitioner/test_healthcare_practitioner.py b/healthcare/healthcare/doctype/healthcare_practitioner/test_healthcare_practitioner.py new file mode 100644 index 0000000..449dc5d --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_practitioner/test_healthcare_practitioner.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + + +class TestHealthcarePractitioner(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/healthcare_schedule_time_slot/__init__.py b/healthcare/healthcare/doctype/healthcare_schedule_time_slot/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/healthcare_schedule_time_slot/healthcare_schedule_time_slot.json b/healthcare/healthcare/doctype/healthcare_schedule_time_slot/healthcare_schedule_time_slot.json new file mode 100644 index 0000000..cf54e82 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_schedule_time_slot/healthcare_schedule_time_slot.json @@ -0,0 +1,136 @@ +{ + "allow_copy": 0, + "allow_guest_to_view": 0, + "allow_import": 0, + "allow_rename": 0, + "beta": 1, + "creation": "2017-05-03 17:27:07.466088", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "", + "editable_grid": 1, + "engine": "InnoDB", + "fields": [ + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "day", + "fieldtype": "Select", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Day", + "length": 0, + "no_copy": 0, + "options": "Sunday\nMonday\nTuesday\nWednesday\nThursday\nFriday\nSaturday", + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 0 + }, + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "from_time", + "fieldtype": "Time", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "From Time", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 0 + }, + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "to_time", + "fieldtype": "Time", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "To Time", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 0 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 1, + "max_attachments": 0, + "modified": "2020-09-18 17:26:09.703215", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Healthcare Schedule Time Slot", + "name_case": "", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "read_only": 0, + "read_only_onload": 0, + "restrict_to_domain": "Healthcare", + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1, + "track_seen": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/healthcare_schedule_time_slot/healthcare_schedule_time_slot.py b/healthcare/healthcare/doctype/healthcare_schedule_time_slot/healthcare_schedule_time_slot.py new file mode 100644 index 0000000..536bcec --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_schedule_time_slot/healthcare_schedule_time_slot.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class HealthcareScheduleTimeSlot(Document): + pass diff --git a/healthcare/healthcare/doctype/healthcare_service_unit/__init__.py b/healthcare/healthcare/doctype/healthcare_service_unit/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/healthcare_service_unit/healthcare_service_unit.js b/healthcare/healthcare/doctype/healthcare_service_unit/healthcare_service_unit.js new file mode 100644 index 0000000..67d3b21 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_service_unit/healthcare_service_unit.js @@ -0,0 +1,73 @@ +// Copyright (c) 2018, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Healthcare Service Unit', { + onload: function(frm) { + frm.list_route = 'Tree/Healthcare Service Unit'; + + // get query select healthcare service unit + frm.fields_dict['parent_healthcare_service_unit'].get_query = function(doc) { + return { + filters: [ + ['Healthcare Service Unit', 'is_group', '=', 1], + ['Healthcare Service Unit', 'name', '!=', doc.healthcare_service_unit_name] + ] + }; + }; + }, + refresh: function(frm) { + frm.trigger('set_root_readonly'); + frm.set_df_property('service_unit_type', 'reqd', 1); + frm.add_custom_button(__('Healthcare Service Unit Tree'), function() { + frappe.set_route('Tree', 'Healthcare Service Unit'); + }); + + frm.set_query('warehouse', function() { + return { + filters: { + 'company': frm.doc.company + } + }; + }); + }, + set_root_readonly: function(frm) { + // read-only for root healthcare service unit + frm.set_intro(''); + if (!frm.doc.parent_healthcare_service_unit) { + frm.set_read_only(); + frm.set_intro(__('This is a root healthcare service unit and cannot be edited.'), true); + } + }, + allow_appointments: function(frm) { + if (!frm.doc.allow_appointments) { + frm.set_value('overlap_appointments', false); + } + }, + is_group: function(frm) { + if (frm.doc.is_group == 1) { + frm.set_value('allow_appointments', false); + frm.set_df_property('service_unit_type', 'reqd', 0); + } + else { + frm.set_df_property('service_unit_type', 'reqd', 1); + } + }, + overlap_appointments: function(frm) { + if (frm.doc.overlap_appointments == 0) { + frm.set_value('service_unit_capacity', ''); + } + } +}); + + +frappe.ui.form.on('Healthcare Service Unit', 'parent_healthcare_service_unit', function(frm) { + if (!frm.doc.parent_healthcare_service_unit) { + frm.set_intro(__('This is a root healthcare service unit and cannot be edited.'), true); + frm.set_read_only(); + frm.disable_save(); + } else { + frm.set_intro(''); + frm.perm = frappe.perm.get_perm(frm.doc.doctype); + frm.enable_save(); + } +}); diff --git a/healthcare/healthcare/doctype/healthcare_service_unit/healthcare_service_unit.json b/healthcare/healthcare/doctype/healthcare_service_unit/healthcare_service_unit.json new file mode 100644 index 0000000..520d1d3 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_service_unit/healthcare_service_unit.json @@ -0,0 +1,257 @@ +{ + "actions": [], + "allow_import": 1, + "allow_rename": 1, + "beta": 1, + "creation": "2016-09-21 13:48:14.731437", + "description": "Healthcare Service Unit", + "doctype": "DocType", + "document_type": "Setup", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "healthcare_service_unit_name", + "is_group", + "service_unit_type", + "allow_appointments", + "overlap_appointments", + "service_unit_capacity", + "inpatient_occupancy", + "occupancy_status", + "column_break_9", + "company", + "warehouse", + "tree_details_section", + "parent_healthcare_service_unit", + "lft", + "rgt", + "old_parent" + ], + "fields": [ + { + "fieldname": "healthcare_service_unit_name", + "fieldtype": "Data", + "hide_days": 1, + "hide_seconds": 1, + "in_global_search": 1, + "in_list_view": 1, + "label": "Service Unit", + "reqd": 1 + }, + { + "bold": 1, + "fieldname": "parent_healthcare_service_unit", + "fieldtype": "Link", + "hide_days": 1, + "hide_seconds": 1, + "ignore_user_permissions": 1, + "in_list_view": 1, + "label": "Parent Service Unit", + "options": "Healthcare Service Unit" + }, + { + "bold": 1, + "default": "0", + "depends_on": "eval:doc.inpatient_occupancy != 1 && doc.allow_appointments != 1", + "fieldname": "is_group", + "fieldtype": "Check", + "hide_days": 1, + "hide_seconds": 1, + "label": "Is Group" + }, + { + "bold": 1, + "depends_on": "eval:doc.is_group != 1", + "fieldname": "service_unit_type", + "fieldtype": "Link", + "hide_days": 1, + "hide_seconds": 1, + "label": "Service Unit Type", + "options": "Healthcare Service Unit Type" + }, + { + "default": "0", + "depends_on": "eval:doc.is_group != 1 && doc.inpatient_occupancy != 1", + "fetch_from": "service_unit_type.allow_appointments", + "fieldname": "allow_appointments", + "fieldtype": "Check", + "hide_days": 1, + "hide_seconds": 1, + "in_list_view": 1, + "label": "Allow Appointments", + "no_copy": 1, + "read_only": 1 + }, + { + "default": "0", + "depends_on": "eval:doc.is_group != 1 && doc.allow_appointments == 1 && doc.inpatient_occupany != 1", + "fetch_from": "service_unit_type.overlap_appointments", + "fieldname": "overlap_appointments", + "fieldtype": "Check", + "hide_days": 1, + "hide_seconds": 1, + "label": "Allow Overlap", + "no_copy": 1, + "read_only": 1 + }, + { + "bold": 1, + "default": "0", + "depends_on": "eval:doc.allow_appointments != 1 && doc.is_group != 1", + "fetch_from": "service_unit_type.inpatient_occupancy", + "fieldname": "inpatient_occupancy", + "fieldtype": "Check", + "hide_days": 1, + "hide_seconds": 1, + "in_list_view": 1, + "label": "Inpatient Occupancy", + "no_copy": 1, + "read_only": 1, + "search_index": 1 + }, + { + "depends_on": "eval:doc.inpatient_occupancy == 1", + "fieldname": "occupancy_status", + "fieldtype": "Select", + "hide_days": 1, + "hide_seconds": 1, + "label": "Occupancy Status", + "no_copy": 1, + "options": "Vacant\nOccupied", + "read_only": 1 + }, + { + "fieldname": "column_break_9", + "fieldtype": "Column Break", + "hide_days": 1, + "hide_seconds": 1 + }, + { + "bold": 1, + "depends_on": "eval:doc.is_group != 1", + "fieldname": "warehouse", + "fieldtype": "Link", + "hide_days": 1, + "hide_seconds": 1, + "label": "Warehouse", + "no_copy": 1, + "options": "Warehouse" + }, + { + "fieldname": "company", + "fieldtype": "Link", + "hide_days": 1, + "hide_seconds": 1, + "ignore_user_permissions": 1, + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Company", + "options": "Company", + "remember_last_selected_value": 1, + "reqd": 1, + "search_index": 1 + }, + { + "fieldname": "lft", + "fieldtype": "Int", + "hidden": 1, + "hide_days": 1, + "hide_seconds": 1, + "label": "lft", + "no_copy": 1, + "print_hide": 1, + "search_index": 1 + }, + { + "fieldname": "rgt", + "fieldtype": "Int", + "hidden": 1, + "hide_days": 1, + "hide_seconds": 1, + "label": "rgt", + "no_copy": 1, + "print_hide": 1, + "search_index": 1 + }, + { + "fieldname": "old_parent", + "fieldtype": "Link", + "hidden": 1, + "hide_days": 1, + "hide_seconds": 1, + "ignore_user_permissions": 1, + "label": "Old Parent", + "no_copy": 1, + "options": "Healthcare Service Unit", + "print_hide": 1, + "report_hide": 1 + }, + { + "collapsible": 1, + "fieldname": "tree_details_section", + "fieldtype": "Section Break", + "hide_days": 1, + "hide_seconds": 1, + "label": "Tree Details" + }, + { + "allow_in_quick_entry": 1, + "depends_on": "eval:doc.overlap_appointments == 1", + "fieldname": "service_unit_capacity", + "fieldtype": "Int", + "label": "Service Unit Capacity", + "mandatory_depends_on": "eval:doc.overlap_appointments == 1", + "non_negative": 1 + } + ], + "is_tree": 1, + "links": [], + "modified": "2022-07-26 02:18:38.363485", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Healthcare Service Unit", + "nsm_parent_field": "parent_healthcare_service_unit", + "owner": "Administrator", + "permissions": [ + { + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Nursing User", + "share": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + }, + { + "create": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "restrict_to_domain": "Healthcare", + "search_fields": "healthcare_service_unit_name", + "sort_field": "modified", + "sort_order": "DESC", + "states": [], + "title_field": "healthcare_service_unit_name", + "track_changes": 1 +} diff --git a/healthcare/healthcare/doctype/healthcare_service_unit/healthcare_service_unit.py b/healthcare/healthcare/doctype/healthcare_service_unit/healthcare_service_unit.py new file mode 100644 index 0000000..5c502f9 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_service_unit/healthcare_service_unit.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018, InfluxERP +# For license information, please see license.txt + + +import json + +import frappe +from frappe import _ +from frappe.utils import cint, cstr +from frappe.utils.nestedset import NestedSet + + +class HealthcareServiceUnit(NestedSet): + nsm_parent_field = "parent_healthcare_service_unit" + + def validate(self): + self.set_service_unit_properties() + + def autoname(self): + if self.company: + suffix = " - " + frappe.get_cached_value("Company", self.company, "abbr") + if not self.healthcare_service_unit_name.endswith(suffix): + self.name = self.healthcare_service_unit_name + suffix + else: + self.name = self.healthcare_service_unit_name + + def on_update(self): + super(HealthcareServiceUnit, self).on_update() + self.validate_one_root() + + def set_service_unit_properties(self): + if cint(self.is_group): + self.allow_appointments = False + self.overlap_appointments = False + self.inpatient_occupancy = False + self.service_unit_capacity = 0 + self.occupancy_status = "" + self.service_unit_type = "" + elif self.service_unit_type != "": + service_unit_type = frappe.get_doc("Healthcare Service Unit Type", self.service_unit_type) + self.allow_appointments = service_unit_type.allow_appointments + self.inpatient_occupancy = service_unit_type.inpatient_occupancy + + if self.inpatient_occupancy and self.occupancy_status != "": + self.occupancy_status = "Vacant" + + if service_unit_type.overlap_appointments: + self.overlap_appointments = True + else: + self.overlap_appointments = False + self.service_unit_capacity = 0 + + if self.overlap_appointments: + if not self.service_unit_capacity: + frappe.throw( + _("Please set a valid Service Unit Capacity to enable Overlapping Appointments"), + title=_("Mandatory"), + ) + + +@frappe.whitelist() +def add_multiple_service_units(parent, data): + """ + parent - parent service unit under which the service units are to be created + data (dict) - company, healthcare_service_unit_name, count, service_unit_type, warehouse, service_unit_capacity + """ + if not parent or not data: + return + + data = json.loads(data) + company = ( + data.get("company") + or frappe.defaults.get_defaults().get("company") + or frappe.db.get_single_value("Global Defaults", "default_company") + ) + + if not data.get("healthcare_service_unit_name") or not company: + frappe.throw( + _("Service Unit Name and Company are mandatory to create Healthcare Service Units"), + title=_("Missing Required Fields"), + ) + + count = cint(data.get("count") or 0) + if count <= 0: + frappe.throw( + _("Number of Service Units to be created should at least be 1"), + title=_("Invalid Number of Service Units"), + ) + + capacity = cint(data.get("service_unit_capacity") or 1) + + service_unit = { + "doctype": "Healthcare Service Unit", + "parent_healthcare_service_unit": parent, + "service_unit_type": data.get("service_unit_type") or None, + "service_unit_capacity": capacity if capacity > 0 else 1, + "warehouse": data.get("warehouse") or None, + "company": company, + } + + service_unit_name = "{}".format(data.get("healthcare_service_unit_name").strip(" -")) + + last_suffix = frappe.db.sql( + """SELECT + IFNULL(MAX(CAST(SUBSTRING(name FROM %(start)s FOR 4) AS UNSIGNED)), 0) + FROM `tabHealthcare Service Unit` + WHERE name like %(prefix)s AND company=%(company)s""", + { + "start": len(service_unit_name) + 2, + "prefix": "{}-%".format(service_unit_name), + "company": company, + }, + as_list=1, + )[0][0] + start_suffix = cint(last_suffix) + 1 + + failed_list = [] + for i in range(start_suffix, count + start_suffix): + # name to be in the form WARD-#### + service_unit["healthcare_service_unit_name"] = "{}-{}".format( + service_unit_name, cstr("%0*d" % (4, i)) + ) + service_unit_doc = frappe.get_doc(service_unit) + try: + service_unit_doc.insert() + except Exception: + failed_list.append(service_unit["healthcare_service_unit_name"]) + + return failed_list + + +def on_doctype_update(): + frappe.db.add_unique( + "Healthcare Service Unit", + ["healthcare_service_unit_name", "company"], + constraint_name="unique_service_unit_company", + ) diff --git a/healthcare/healthcare/doctype/healthcare_service_unit/healthcare_service_unit_dashboard.py b/healthcare/healthcare/doctype/healthcare_service_unit/healthcare_service_unit_dashboard.py new file mode 100644 index 0000000..2a99232 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_service_unit/healthcare_service_unit_dashboard.py @@ -0,0 +1,6 @@ +def get_data(): + return { + "fieldname": "service_unit", + "internal_links": {"Inpatient Occupancy": ["inpatient_occupancies"]}, + "transactions": [{"items": ["Inpatient Record"]}], + } diff --git a/healthcare/healthcare/doctype/healthcare_service_unit/healthcare_service_unit_tree.js b/healthcare/healthcare/doctype/healthcare_service_unit/healthcare_service_unit_tree.js new file mode 100644 index 0000000..570fce2 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_service_unit/healthcare_service_unit_tree.js @@ -0,0 +1,185 @@ +frappe.provide("frappe.treeview_settings"); + +frappe.treeview_settings['Healthcare Service Unit'] = { + breadcrumbs: 'Healthcare Service Unit', + title: __('Service Unit Tree'), + get_tree_root: false, + get_tree_nodes: 'healthcare.healthcare.utils.get_children', + filters: [{ + fieldname: 'company', + fieldtype: 'Select', + options: erpnext.utils.get_tree_options('company'), + label: __('Company'), + default: erpnext.utils.get_tree_default('company') + }], + fields: [ + { + fieldtype: 'Data', fieldname: 'healthcare_service_unit_name', label: __('New Service Unit Name'), + reqd: true + }, + { + fieldtype: 'Check', fieldname: 'is_group', label: __('Is Group'), + description: __("Child nodes can be only created under 'Group' type nodes") + }, + { + fieldtype: 'Link', fieldname: 'service_unit_type', label: __('Service Unit Type'), + options: 'Healthcare Service Unit Type', description: __('Type of the new Service Unit'), + depends_on: 'eval:!doc.is_group', default: '', + onchange: () => { + if (cur_dialog) { + if (cur_dialog.fields_dict.service_unit_type.value) { + frappe.db.get_value('Healthcare Service Unit Type', + cur_dialog.fields_dict.service_unit_type.value, 'overlap_appointments') + .then(r => { + if (r.message.overlap_appointments) { + cur_dialog.set_df_property('service_unit_capacity', 'hidden', false); + cur_dialog.set_df_property('service_unit_capacity', 'reqd', true); + } else { + cur_dialog.set_df_property('service_unit_capacity', 'hidden', true); + cur_dialog.set_df_property('service_unit_capacity', 'reqd', false); + } + }); + } else { + cur_dialog.set_df_property('service_unit_capacity', 'hidden', true); + cur_dialog.set_df_property('service_unit_capacity', 'reqd', false); + } + } + } + }, + { + fieldtype: 'Int', fieldname: 'service_unit_capacity', label: __('Service Unit Capacity'), + description: __('Sets the number of concurrent appointments allowed'), reqd: false, + depends_on: "eval:!doc.is_group && doc.service_unit_type != ''", hidden: true + }, + { + fieldtype: 'Link', fieldname: 'warehouse', label: __('Warehouse'), options: 'Warehouse', + description: __('Optional, if you want to manage stock separately for this Service Unit'), + depends_on: 'eval:!doc.is_group' + }, + { + fieldtype: 'Link', fieldname: 'company', label: __('Company'), options: 'Company', reqd: true, + default: () => { + return cur_page.page.page.fields_dict.company.value; + } + } + ], + ignore_fields: ['parent_healthcare_service_unit'], + onrender: function (node) { + if (node.data.occupied_of_available !== undefined) { + $("" + + ' ' + node.data.occupied_of_available + + '').insertBefore(node.$ul); + } + if (node.data && node.data.inpatient_occupancy !== undefined) { + if (node.data.inpatient_occupancy == 1) { + if (node.data.occupancy_status == 'Occupied') { + $("" + + ' ' + node.data.occupancy_status + + '').insertBefore(node.$ul); + } + if (node.data.occupancy_status == 'Vacant') { + $("" + + ' ' + node.data.occupancy_status + + '').insertBefore(node.$ul); + } + } + } + }, + post_render: function (treeview) { + frappe.treeview_settings['Healthcare Service Unit'].treeview = {}; + $.extend(frappe.treeview_settings['Healthcare Service Unit'].treeview, treeview); + }, + toolbar: [ + { + label: __('Add Multiple'), + condition: function (node) { + return node.expandable; + }, + click: function (node) { + const dialog = new frappe.ui.Dialog({ + title: __('Add Multiple Service Units'), + fields: [ + { + fieldtype: 'Data', fieldname: 'healthcare_service_unit_name', label: __('Service Unit Name'), + reqd: true, description: __("Will be serially suffixed to maintain uniquness. Example: 'Ward' will be named as 'Ward-####'"), + }, + { + fieldtype: 'Int', fieldname: 'count', label: __('Number of Service Units'), + reqd: true + }, + { + fieldtype: 'Link', fieldname: 'service_unit_type', label: __('Service Unit Type'), + options: 'Healthcare Service Unit Type', description: __('Type of the new Service Unit'), + depends_on: 'eval:!doc.is_group', default: '', reqd: true, + onchange: () => { + if (cur_dialog) { + if (cur_dialog.fields_dict.service_unit_type.value) { + frappe.db.get_value('Healthcare Service Unit Type', + cur_dialog.fields_dict.service_unit_type.value, 'overlap_appointments') + .then(r => { + if (r.message.overlap_appointments) { + cur_dialog.set_df_property('service_unit_capacity', 'hidden', false); + cur_dialog.set_df_property('service_unit_capacity', 'reqd', true); + } else { + cur_dialog.set_df_property('service_unit_capacity', 'hidden', true); + cur_dialog.set_df_property('service_unit_capacity', 'reqd', false); + } + }); + } else { + cur_dialog.set_df_property('service_unit_capacity', 'hidden', true); + cur_dialog.set_df_property('service_unit_capacity', 'reqd', false); + } + } + } + }, + { + fieldtype: 'Int', fieldname: 'service_unit_capacity', label: __('Service Unit Capacity'), + description: __('Sets the number of concurrent appointments allowed'), reqd: false, + depends_on: "eval:!doc.is_group && doc.service_unit_type != ''", hidden: true + }, + { + fieldtype: 'Link', fieldname: 'warehouse', label: __('Warehouse'), options: 'Warehouse', + description: __('Optional, if you want to manage stock separately for this Service Unit'), + }, + { + fieldtype: 'Link', fieldname: 'company', label: __('Company'), options: 'Company', reqd: true, + default: () => { + return cur_page.page.page.fields_dict.company.get_value(); + } + } + ], + primary_action: () => { + dialog.hide(); + let vals = dialog.get_values(); + if (!vals) return; + + return frappe.call({ + method: 'healthcare.healthcare.doctype.healthcare_service_unit.healthcare_service_unit.add_multiple_service_units', + args: { + parent: node.data.value, + data: vals + }, + callback: function (r) { + if (!r.exc && r.message) { + frappe.treeview_settings['Healthcare Service Unit'].treeview.tree.load_children(node, true); + + frappe.show_alert({ + message: __('{0} Service Units created', [vals.count - r.message.length]), + indicator: 'green' + }); + } else { + frappe.msgprint(__('Could not create Service Units')); + } + }, + freeze: true, + freeze_message: __('Creating {0} Service Units', [vals.count]) + }); + }, + primary_action_label: __('Create') + }); + dialog.show(); + } + } + ], + extend_toolbar: true +}; diff --git a/healthcare/healthcare/doctype/healthcare_service_unit/test_healthcare_service_unit.py b/healthcare/healthcare/doctype/healthcare_service_unit/test_healthcare_service_unit.py new file mode 100644 index 0000000..f036ec3 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_service_unit/test_healthcare_service_unit.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018, InfluxERP +# See license.txt +import frappe +from frappe.tests.utils import FrappeTestCase + + +class TestHealthcareServiceUnit(FrappeTestCase): + def test_create_company_should_create_root_service_unit(self): + company = frappe.get_doc( + { + "doctype": "Company", + "company_name": "Test Hospital", + "country": "India", + "default_currency": "INR", + } + ) + try: + company = company.insert() + except frappe.exceptions.DuplicateEntryError: + pass + filters = {"company": company.name, "parent_healthcare_service_unit": None} + root_service_unit = frappe.db.exists("Healthcare Service Unit", filters) + self.assertTrue(root_service_unit) diff --git a/healthcare/healthcare/doctype/healthcare_service_unit_type/__init__.py b/healthcare/healthcare/doctype/healthcare_service_unit_type/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/healthcare_service_unit_type/healthcare_service_unit_type.js b/healthcare/healthcare/doctype/healthcare_service_unit_type/healthcare_service_unit_type.js new file mode 100644 index 0000000..394924f --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_service_unit_type/healthcare_service_unit_type.js @@ -0,0 +1,86 @@ +// Copyright (c) 2018, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Healthcare Service Unit Type', { + refresh: function(frm) { + frm.set_df_property('item_code', 'read_only', frm.doc.__islocal ? 0 : 1); + if (!frm.doc.__islocal && frm.doc.is_billable) { + frm.add_custom_button(__('Change Item Code'), function() { + change_item_code(cur_frm, frm.doc); + }); + } + }, + + service_unit_type: function(frm) { + set_item_details(frm); + + if (!frm.doc.__islocal) { + frm.doc.change_in_item = 1; + } + }, + + is_billable: function(frm) { + set_item_details(frm); + }, + + rate: function(frm) { + if (!frm.doc.__islocal) { + frm.doc.change_in_item = 1; + } + }, + item_group: function(frm) { + if (!frm.doc.__islocal) { + frm.doc.change_in_item = 1; + } + }, + description: function(frm) { + if (!frm.doc.__islocal) { + frm.doc.change_in_item = 1; + } + } +}); + +let set_item_details = function(frm) { + if (frm.doc.service_unit_type && frm.doc.is_billable) { + if (!frm.doc.item_code) + frm.set_value('item_code', frm.doc.service_unit_type); + if (!frm.doc.description) + frm.set_value('description', frm.doc.service_unit_type); + if (!frm.doc.item_group) + frm.set_value('item_group', 'Services'); + } +}; + +let change_item_code = function(frm, doc) { + let d = new frappe.ui.Dialog({ + title: __('Change Item Code'), + fields: [ + { + 'fieldtype': 'Data', + 'label': 'Item Code', + 'fieldname': 'item_code', + 'default': doc.item_code, + reqd: 1, + } + ], + primary_action: function() { + let values = d.get_values(); + if (values) { + frappe.call({ + "method": "healthcare.healthcare.doctype.healthcare_service_unit_type.healthcare_service_unit_type.change_item_code", + "args": { item: doc.item, item_code: values['item_code'], doc_name: doc.name }, + callback: function() { + frm.reload_doc(); + } + }); + } + d.hide(); + }, + primary_action_label: __("Change Template Code") + }); + + d.show(); + d.set_values({ + 'Item Code': frm.doc.item_code + }); +}; diff --git a/healthcare/healthcare/doctype/healthcare_service_unit_type/healthcare_service_unit_type.json b/healthcare/healthcare/doctype/healthcare_service_unit_type/healthcare_service_unit_type.json new file mode 100644 index 0000000..9c81c65 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_service_unit_type/healthcare_service_unit_type.json @@ -0,0 +1,196 @@ +{ + "actions": [], + "allow_import": 1, + "allow_rename": 1, + "autoname": "field:service_unit_type", + "creation": "2018-07-11 16:47:51.414675", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "disabled", + "service_unit_type", + "allow_appointments", + "overlap_appointments", + "inpatient_occupancy", + "is_billable", + "item_details", + "item", + "item_code", + "item_group", + "uom", + "no_of_hours", + "column_break_11", + "rate", + "description", + "change_in_item" + ], + "fields": [ + { + "fieldname": "service_unit_type", + "fieldtype": "Data", + "hide_days": 1, + "hide_seconds": 1, + "in_list_view": 1, + "label": "Service Unit Type", + "no_copy": 1, + "reqd": 1, + "unique": 1 + }, + { + "bold": 1, + "default": "0", + "depends_on": "eval:doc.inpatient_occupancy != 1", + "fieldname": "allow_appointments", + "fieldtype": "Check", + "hide_days": 1, + "hide_seconds": 1, + "label": "Allow Appointments" + }, + { + "bold": 1, + "default": "0", + "depends_on": "eval:doc.allow_appointments == 1 && doc.inpatient_occupany != 1", + "fieldname": "overlap_appointments", + "fieldtype": "Check", + "hide_days": 1, + "hide_seconds": 1, + "label": "Allow Overlap" + }, + { + "bold": 1, + "default": "0", + "depends_on": "eval:doc.allow_appointments != 1", + "fieldname": "inpatient_occupancy", + "fieldtype": "Check", + "hide_days": 1, + "hide_seconds": 1, + "label": "Inpatient Occupancy" + }, + { + "bold": 1, + "default": "0", + "depends_on": "eval:doc.inpatient_occupancy == 1 && doc.allow_appointments != 1", + "fieldname": "is_billable", + "fieldtype": "Check", + "hide_days": 1, + "hide_seconds": 1, + "label": "Is Billable" + }, + { + "depends_on": "is_billable", + "fieldname": "item_details", + "fieldtype": "Section Break", + "hide_days": 1, + "hide_seconds": 1, + "label": "Item Details" + }, + { + "fieldname": "item", + "fieldtype": "Link", + "hide_days": 1, + "hide_seconds": 1, + "label": "Item", + "no_copy": 1, + "options": "Item", + "read_only": 1 + }, + { + "fieldname": "item_code", + "fieldtype": "Data", + "hide_days": 1, + "hide_seconds": 1, + "label": "Item Code", + "mandatory_depends_on": "eval: doc.is_billable == 1", + "no_copy": 1 + }, + { + "fieldname": "item_group", + "fieldtype": "Link", + "hide_days": 1, + "hide_seconds": 1, + "label": "Item Group", + "mandatory_depends_on": "eval: doc.is_billable == 1", + "options": "Item Group" + }, + { + "fieldname": "uom", + "fieldtype": "Link", + "hide_days": 1, + "hide_seconds": 1, + "label": "UOM", + "mandatory_depends_on": "eval: doc.is_billable == 1", + "options": "UOM" + }, + { + "fieldname": "no_of_hours", + "fieldtype": "Int", + "hide_days": 1, + "hide_seconds": 1, + "label": "UOM Conversion in Hours", + "mandatory_depends_on": "eval: doc.is_billable == 1" + }, + { + "fieldname": "column_break_11", + "fieldtype": "Column Break", + "hide_days": 1, + "hide_seconds": 1 + }, + { + "fieldname": "rate", + "fieldtype": "Currency", + "hide_days": 1, + "hide_seconds": 1, + "label": "Rate / UOM" + }, + { + "default": "0", + "fieldname": "disabled", + "fieldtype": "Check", + "hide_days": 1, + "hide_seconds": 1, + "label": "Disabled", + "no_copy": 1 + }, + { + "fieldname": "description", + "fieldtype": "Small Text", + "hide_days": 1, + "hide_seconds": 1, + "label": "Description" + }, + { + "default": "0", + "fieldname": "change_in_item", + "fieldtype": "Check", + "hidden": 1, + "hide_days": 1, + "hide_seconds": 1, + "label": "Change in Item" + } + ], + "links": [], + "modified": "2021-08-19 17:52:30.266667", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Healthcare Service Unit Type", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + } + ], + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "service_unit_type" +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/healthcare_service_unit_type/healthcare_service_unit_type.py b/healthcare/healthcare/doctype/healthcare_service_unit_type/healthcare_service_unit_type.py new file mode 100644 index 0000000..85e291b --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_service_unit_type/healthcare_service_unit_type.py @@ -0,0 +1,151 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018, InfluxERP +# For license information, please see license.txt + + +import frappe +from frappe import _ +from frappe.model.document import Document +from frappe.model.rename_doc import rename_doc + + +class HealthcareServiceUnitType(Document): + def validate(self): + if self.allow_appointments and self.inpatient_occupancy: + frappe.msgprint( + _("Healthcare Service Unit Type cannot have both {0} and {1}").format( + frappe.bold("Allow Appointments"), frappe.bold("Inpatient Occupancy") + ), + raise_exception=1, + title=_("Validation Error"), + indicator="red", + ) + elif not self.allow_appointments and not self.inpatient_occupancy: + frappe.msgprint( + _("Healthcare Service Unit Type must allow atleast one among {0} and {1}").format( + frappe.bold("Allow Appointments"), frappe.bold("Inpatient Occupancy") + ), + raise_exception=1, + title=_("Validation Error"), + indicator="red", + ) + + if not self.allow_appointments: + self.overlap_appointments = 0 + + if self.is_billable: + if self.disabled: + frappe.db.set_value("Item", self.item, "disabled", 1) + else: + frappe.db.set_value("Item", self.item, "disabled", 0) + + def after_insert(self): + if self.inpatient_occupancy and self.is_billable: + create_item(self) + + def on_trash(self): + if self.item: + try: + item = self.item + self.db_set("item", "") + frappe.delete_doc("Item", item) + except Exception: + frappe.throw(_("Not permitted. Please disable the Service Unit Type")) + + def on_update(self): + if self.change_in_item and self.is_billable and self.item: + update_item(self) + + item_price = item_price_exists(self) + + if not item_price: + price_list_name = frappe.db.get_value("Price List", {"selling": 1}) + if self.rate: + make_item_price(self.item_code, price_list_name, self.rate) + else: + make_item_price(self.item_code, price_list_name, 0.0) + else: + frappe.db.set_value("Item Price", item_price, "price_list_rate", self.rate) + + frappe.db.set_value(self.doctype, self.name, "change_in_item", 0) + elif not self.is_billable and self.item: + frappe.db.set_value("Item", self.item, "disabled", 1) + self.reload() + + +def item_price_exists(doc): + item_price = frappe.db.exists({"doctype": "Item Price", "item_code": doc.item_code}) + if len(item_price): + return item_price[0][0] + return False + + +def create_item(doc): + # insert item + item = frappe.get_doc( + { + "doctype": "Item", + "item_code": doc.item_code, + "item_name": doc.service_unit_type, + "item_group": doc.item_group, + "description": doc.description or doc.item_code, + "is_sales_item": 1, + "is_service_item": 1, + "is_purchase_item": 0, + "is_stock_item": 0, + "show_in_website": 0, + "is_pro_applicable": 0, + "disabled": 0, + "stock_uom": doc.uom, + } + ).insert(ignore_permissions=True, ignore_mandatory=True) + + # insert item price + # get item price list to insert item price + price_list_name = frappe.db.get_value("Price List", {"selling": 1}) + if doc.rate: + make_item_price(item.name, price_list_name, doc.rate) + item.standard_rate = doc.rate + else: + make_item_price(item.name, price_list_name, 0.0) + item.standard_rate = 0.0 + + item.save(ignore_permissions=True) + + # Set item in the doc + doc.db_set("item", item.name) + + +def make_item_price(item, price_list_name, item_price): + frappe.get_doc( + { + "doctype": "Item Price", + "price_list": price_list_name, + "item_code": item, + "price_list_rate": item_price, + } + ).insert(ignore_permissions=True, ignore_mandatory=True) + + +def update_item(doc): + item = frappe.get_doc("Item", doc.item) + if item: + item.update( + { + "item_name": doc.service_unit_type, + "item_group": doc.item_group, + "disabled": 0, + "standard_rate": doc.rate, + "description": doc.description, + } + ) + item.db_update() + + +@frappe.whitelist() +def change_item_code(item, item_code, doc_name): + if frappe.db.exists({"doctype": "Item", "item_code": item_code}): + frappe.throw(_("Item with Item Code {0} already exists").format(item_code)) + else: + rename_doc("Item", item, item_code, ignore_permissions=True) + frappe.db.set_value("Healthcare Service Unit Type", doc_name, "item_code", item_code) diff --git a/healthcare/healthcare/doctype/healthcare_service_unit_type/healthcare_service_unit_type_dashboard.py b/healthcare/healthcare/doctype/healthcare_service_unit_type/healthcare_service_unit_type_dashboard.py new file mode 100644 index 0000000..c14efb7 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_service_unit_type/healthcare_service_unit_type_dashboard.py @@ -0,0 +1,10 @@ +from frappe import _ + + +def get_data(): + return { + "fieldname": "service_unit_type", + "transactions": [ + {"label": _("Healthcare Service Units"), "items": ["Healthcare Service Unit"]}, + ], + } diff --git a/healthcare/healthcare/doctype/healthcare_service_unit_type/test_healthcare_service_unit_type.py b/healthcare/healthcare/doctype/healthcare_service_unit_type/test_healthcare_service_unit_type.py new file mode 100644 index 0000000..43dd2d6 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_service_unit_type/test_healthcare_service_unit_type.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +import frappe + + +class TestHealthcareServiceUnitType(FrappeTestCase): + def test_item_creation(self): + unit_type = get_unit_type() + self.assertTrue(frappe.db.exists("Item", unit_type.item)) + + # check item disabled + unit_type.disabled = 1 + unit_type.save() + self.assertEqual(frappe.db.get_value("Item", unit_type.item, "disabled"), 1) + + +def get_unit_type(): + if frappe.db.exists("Healthcare Service Unit Type", "Inpatient Rooms"): + return frappe.get_doc("Healthcare Service Unit Type", "Inpatient Rooms") + + unit_type = frappe.new_doc("Healthcare Service Unit Type") + unit_type.service_unit_type = "Inpatient Rooms" + unit_type.inpatient_occupancy = 1 + unit_type.is_billable = 1 + unit_type.item_code = "Inpatient Rooms" + unit_type.item_group = "Services" + unit_type.uom = "Hour" + unit_type.no_of_hours = 1 + unit_type.rate = 4000 + unit_type.save() + return unit_type diff --git a/healthcare/healthcare/doctype/healthcare_settings/__init__.py b/healthcare/healthcare/doctype/healthcare_settings/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/healthcare_settings/healthcare_settings.js b/healthcare/healthcare/doctype/healthcare_settings/healthcare_settings.js new file mode 100644 index 0000000..39dd904 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_settings/healthcare_settings.js @@ -0,0 +1,80 @@ +// Copyright (c) 2017, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Healthcare Settings', { + setup: function(frm) { + frm.set_query('account', 'receivable_account', function(doc, cdt, cdn) { + var d = locals[cdt][cdn]; + return { + filters: { + 'account_type': 'Receivable', + 'company': d.company, + 'is_group': 0 + } + }; + }); + frm.set_query('account', 'income_account', function(doc, cdt, cdn) { + var d = locals[cdt][cdn]; + return { + filters: { + 'root_type': 'Income', + 'company': d.company, + 'is_group': 0 + } + }; + }); + set_query_service_item(frm, 'inpatient_visit_charge_item'); + set_query_service_item(frm, 'op_consulting_charge_item'); + set_query_service_item(frm, 'clinical_procedure_consumable_item'); + } +}); + +var set_query_service_item = function(frm, service_item_field) { + frm.set_query(service_item_field, function() { + return { + filters: { + 'is_sales_item': 1, + 'is_stock_item': 0 + } + }; + }); +}; + +frappe.tour['Healthcare Settings'] = [ + { + fieldname: 'link_customer_to_patient', + title: __('Link Customer to Patient'), + description: __('If checked, a customer will be created for every Patient. Patient Invoices will be created against this Customer. You can also select existing Customer while creating a Patient. This field is checked by default.') + }, + { + fieldname: 'collect_registration_fee', + title: __('Collect Registration Fee'), + description: __('If your Healthcare facility bills registrations of Patients, you can check this and set the Registration Fee in the field below. Checking this will create new Patients with a Disabled status by default and will only be enabled after invoicing the Registration Fee.') + }, + { + fieldname: 'automate_appointment_invoicing', + title: __('Automate Appointment Invoicing'), + description: __('Checking this will automatically create a Sales Invoice whenever an appointment is booked for a Patient.') + }, + { + fieldname: 'validate_nursing_checklists', + title: __('validate_nursing_checklists'), + description: __('Validates all mandatory tasks in nursing checklist to be Completed before a Patient transactional event. For example, if any of the tasks as part of the Discharge Checklist is not in status Completed, system will alert the user while trying to Discharge the Patient from inpatient facility') + }, + { + fieldname: 'inpatient_visit_charge_item', + title: __('Healthcare Service Items'), + description: __('You can create a service item for Inpatient Visit Charge and set it here. Similarly, you can set up other Healthcare Service Items for billing in this section. Click ') + "here" + __(' to know more') + }, + { + fieldname: 'income_account', + title: __('Set up default Accounts for the Healthcare Facility'), + description: __('If you wish to override default accounts settings and configure the Income and Receivable accounts for Healthcare, you can do so here.') + + }, + { + fieldname: 'send_registration_msg', + title: __('Out Patient SMS alerts'), + description: __('If you want to send SMS alert on Patient Registration, you can enable this option. Similary, you can set up Out Patient SMS alerts for other functionalities in this section. Click ') + "here" + __(' to know more') + } +]; diff --git a/healthcare/healthcare/doctype/healthcare_settings/healthcare_settings.json b/healthcare/healthcare/doctype/healthcare_settings/healthcare_settings.json new file mode 100644 index 0000000..985ff3c --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_settings/healthcare_settings.json @@ -0,0 +1,359 @@ +{ + "actions": [], + "beta": 1, + "creation": "2017-05-09 11:26:22.337760", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "sb_op_settings", + "patient_name_by", + "link_customer_to_patient", + "default_medical_code_standard", + "column_break_9", + "collect_registration_fee", + "registration_fee", + "automate_appointment_invoicing", + "enable_free_follow_ups", + "validate_nursing_checklists", + "max_visits", + "valid_days", + "inpatient_settings_section", + "allow_discharge_despite_unbilled_services", + "do_not_bill_inpatient_encounters", + "healthcare_service_items", + "inpatient_visit_charge_item", + "op_consulting_charge_item", + "column_break_13", + "clinical_procedure_consumable_item", + "sb_in_ac", + "income_account", + "receivable_account", + "out_patient_sms_alerts", + "send_registration_msg", + "registration_msg", + "send_appointment_confirmation", + "appointment_confirmation_msg", + "avoid_confirmation", + "column_break_16", + "send_appointment_reminder", + "appointment_reminder_msg", + "remind_before", + "sb_lab_settings", + "create_lab_test_on_si_submit", + "create_sample_collection_for_lab_test", + "column_break_34", + "lab_test_approval_required", + "employee_name_and_designation_in_print", + "custom_signature_in_print", + "laboratory_sms_alerts", + "sms_printed", + "column_break_28", + "sms_emailed" + ], + "fields": [ + { + "fieldname": "sb_op_settings", + "fieldtype": "Section Break", + "label": "Out Patient Settings" + }, + { + "fieldname": "default_medical_code_standard", + "fieldtype": "Link", + "label": "Default Medical Code Standard", + "options": "Medical Code Standard" + }, + { + "fieldname": "column_break_9", + "fieldtype": "Column Break" + }, + { + "default": "0", + "description": "Checking this will create new Patients with a Disabled status by default and will only be enabled after invoicing the Registration Fee.", + "fieldname": "collect_registration_fee", + "fieldtype": "Check", + "label": "Collect Fee for Patient Registration" + }, + { + "depends_on": "collect_registration_fee", + "fieldname": "registration_fee", + "fieldtype": "Currency", + "label": "Registration Fee", + "mandatory_depends_on": "eval:doc.collect_registration_fee == 1", + "options": "Currency" + }, + { + "depends_on": "eval:doc.enable_free_follow_ups == 1", + "description": "Time period (Valid number of days) for free consultations", + "fieldname": "valid_days", + "fieldtype": "Int", + "label": "Valid Number of Days", + "mandatory_depends_on": "eval:doc.enable_free_follow_ups == 1" + }, + { + "collapsible": 1, + "description": "You can configure default Items for billing consultation charges, procedure consumption items and inpatient visits", + "fieldname": "healthcare_service_items", + "fieldtype": "Section Break", + "label": "Default Healthcare Service Items" + }, + { + "fieldname": "inpatient_visit_charge_item", + "fieldtype": "Link", + "label": "Inpatient Visit Charge Item", + "options": "Item" + }, + { + "fieldname": "op_consulting_charge_item", + "fieldtype": "Link", + "label": "Out Patient Consulting Charge Item", + "options": "Item" + }, + { + "fieldname": "column_break_13", + "fieldtype": "Column Break" + }, + { + "fieldname": "clinical_procedure_consumable_item", + "fieldtype": "Link", + "label": "Clinical Procedure Consumable Item", + "options": "Item" + }, + { + "collapsible": 1, + "fieldname": "out_patient_sms_alerts", + "fieldtype": "Section Break", + "label": "Out Patient SMS Alerts" + }, + { + "fieldname": "column_break_16", + "fieldtype": "Column Break" + }, + { + "collapsible": 1, + "fieldname": "sb_in_ac", + "fieldtype": "Section Break", + "label": "Default Accounts" + }, + { + "description": "Default income accounts to be used if not set in Healthcare Practitioner to book Appointment charges.", + "fieldname": "income_account", + "fieldtype": "Table", + "label": "Income Account", + "options": "Party Account" + }, + { + "description": "Default receivable accounts to be used to book Appointment charges.", + "fieldname": "receivable_account", + "fieldtype": "Table", + "label": "Receivable Account", + "options": "Party Account" + }, + { + "collapsible": 1, + "fieldname": "sb_lab_settings", + "fieldtype": "Section Break", + "label": "Laboratory Settings" + }, + { + "fieldname": "column_break_34", + "fieldtype": "Column Break" + }, + { + "default": "1", + "description": "Check this if you want the Name and Designation of the Employee associated with the User who submits the document to be printed in the Lab Test Report.", + "fieldname": "employee_name_and_designation_in_print", + "fieldtype": "Check", + "label": "Employee name and designation in print" + }, + { + "depends_on": "eval:doc.employee_name_and_designation_in_print == '0'\n", + "fieldname": "custom_signature_in_print", + "fieldtype": "Small Text", + "label": "Custom Signature in Print" + }, + { + "collapsible": 1, + "fieldname": "laboratory_sms_alerts", + "fieldtype": "Section Break", + "label": "Laboratory SMS Alerts" + }, + { + "default": "Hello {{doc.patient}}, Your {{doc.lab_test_name}} result is ready with {{doc.company }}. \nThank You, Good day!", + "fieldname": "sms_printed", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Result Printed Message" + }, + { + "fieldname": "column_break_28", + "fieldtype": "Column Break" + }, + { + "default": "Hello {{doc.patient}}, Your {{doc.lab_test_name}} result has been emailed to {{doc.email}}. \n{{doc.company }}. \nThank You, Good day!", + "fieldname": "sms_emailed", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Result Emailed Message" + }, + { + "default": "0", + "description": "Checking this will restrict printing and emailing of Lab Test documents unless they have the status as Approved.", + "fieldname": "lab_test_approval_required", + "fieldtype": "Check", + "label": "Do not print or email Lab Tests without Approval" + }, + { + "default": "1", + "description": "If checked, a customer will be created, mapped to Patient.\nPatient Invoices will be created against this Customer. You can also select existing Customer while creating Patient.", + "fieldname": "link_customer_to_patient", + "fieldtype": "Check", + "label": "Link Customer to Patient" + }, + { + "default": "0", + "description": "Checking this will create Lab Test(s) specified in the Sales Invoice on submission.", + "fieldname": "create_lab_test_on_si_submit", + "fieldtype": "Check", + "label": "Create Lab Test(s) on Sales Invoice Submission" + }, + { + "default": "0", + "description": "Checking this will create a Sample Collection document every time you create a Lab Test", + "fieldname": "create_sample_collection_for_lab_test", + "fieldtype": "Check", + "label": "Create Sample Collection document for Lab Test" + }, + { + "fieldname": "patient_name_by", + "fieldtype": "Select", + "label": "Patient Name By", + "options": "Patient Name\nNaming Series" + }, + { + "default": "0", + "description": "Manage Appointment Invoice submit and cancel automatically for Patient Encounter", + "fieldname": "automate_appointment_invoicing", + "fieldtype": "Check", + "label": "Automate Appointment Invoicing" + }, + { + "default": "0", + "fieldname": "send_registration_msg", + "fieldtype": "Check", + "label": "Patient Registration" + }, + { + "default": "Hello {{doc.patient}}, Thank you for registering with {{doc.company}}. Your ID is {{doc.name}} . Please note this ID for future reference. \nThank You!", + "depends_on": "send_registration_msg", + "fieldname": "registration_msg", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Registration Message" + }, + { + "default": "0", + "fieldname": "send_appointment_confirmation", + "fieldtype": "Check", + "label": "Appointment Confirmation" + }, + { + "default": "Hello {{doc.patient}}, You have scheduled an appointment with {{doc.practitioner}} on {{doc.appointment_datetime}} at {{doc.company}}.\nThank you, Good day!", + "depends_on": "send_appointment_confirmation", + "fieldname": "appointment_confirmation_msg", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Confirmation Message" + }, + { + "default": "0", + "depends_on": "send_appointment_confirmation", + "description": "Do not confirm if appointment is created for the same day", + "fieldname": "avoid_confirmation", + "fieldtype": "Check", + "label": "Avoid Confirmation" + }, + { + "default": "0", + "fieldname": "send_appointment_reminder", + "fieldtype": "Check", + "label": "Appointment Reminder" + }, + { + "default": "Hello {{doc.patient}}, You have an appointment with {{doc.practitioner}} by {{doc.appointment_datetime}} at {{doc.company}}.\nThank you, Good day!\n", + "depends_on": "send_appointment_reminder", + "fieldname": "appointment_reminder_msg", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Reminder Message" + }, + { + "depends_on": "send_appointment_reminder", + "fieldname": "remind_before", + "fieldtype": "Time", + "label": "Remind Before" + }, + { + "depends_on": "eval:doc.enable_free_follow_ups == 1", + "description": "The number of free follow ups (Patient Encounters in valid days) allowed", + "fieldname": "max_visits", + "fieldtype": "Int", + "label": "Number of Patient Encounters in Valid Days", + "mandatory_depends_on": "eval:doc.enable_free_follow_ups == 1" + }, + { + "default": "0", + "fieldname": "enable_free_follow_ups", + "fieldtype": "Check", + "label": "Enable Free Follow-ups" + }, + { + "fieldname": "inpatient_settings_section", + "fieldtype": "Section Break", + "label": "Inpatient Settings" + }, + { + "default": "0", + "fieldname": "allow_discharge_despite_unbilled_services", + "fieldtype": "Check", + "label": "Allow Discharge Despite Unbilled Healthcare Services" + }, + { + "default": "0", + "fieldname": "do_not_bill_inpatient_encounters", + "fieldtype": "Check", + "label": "Do Not Bill Patient Encounters for Inpatients" + }, + { + "default": "0", + "description": "Validates all mandatory tasks in nursing checklist to be Completed before a Patient transactional event.", + "fieldname": "validate_nursing_checklists", + "fieldtype": "Check", + "label": "Validate Nursing Checklists" + } + ], + "issingle": 1, + "links": [], + "modified": "2022-01-18 11:35:17.261514", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Healthcare Settings", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "print": 1, + "read": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/healthcare_settings/healthcare_settings.py b/healthcare/healthcare/doctype/healthcare_settings/healthcare_settings.py new file mode 100644 index 0000000..659438f --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_settings/healthcare_settings.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# For license information, please see license.txt + + +import json + +import frappe +from frappe import _ +from frappe.core.doctype.sms_settings.sms_settings import send_sms +from frappe.model.document import Document + + +class HealthcareSettings(Document): + def validate(self): + for key in [ + "collect_registration_fee", + "link_customer_to_patient", + "patient_name_by", + "lab_test_approval_required", + "create_sample_collection_for_lab_test", + "default_medical_code_standard", + ]: + frappe.db.set_default(key, self.get(key, "")) + + if self.collect_registration_fee: + if self.registration_fee <= 0: + frappe.throw(_("Registration Fee cannot be negative or zero")) + + if self.inpatient_visit_charge_item: + validate_service_item(self.inpatient_visit_charge_item) + if self.op_consulting_charge_item: + validate_service_item(self.op_consulting_charge_item) + if self.clinical_procedure_consumable_item: + validate_service_item(self.clinical_procedure_consumable_item) + + +def validate_service_item(item): + if frappe.db.get_value("Item", item, "is_stock_item"): + frappe.throw(_("Configure a service Item for {0}").format(item)) + + +@frappe.whitelist() +def get_sms_text(doc): + sms_text = {} + doc = frappe.get_doc("Lab Test", doc) + context = {"doc": doc, "alert": doc, "comments": None} + + emailed = frappe.db.get_value("Healthcare Settings", None, "sms_emailed") + sms_text["emailed"] = frappe.render_template(emailed, context) + + printed = frappe.db.get_value("Healthcare Settings", None, "sms_printed") + sms_text["printed"] = frappe.render_template(printed, context) + + return sms_text + + +def send_registration_sms(doc): + if frappe.db.get_single_value("Healthcare Settings", "send_registration_msg"): + if doc.mobile: + context = {"doc": doc, "alert": doc, "comments": None} + if doc.get("_comments"): + context["comments"] = json.loads(doc.get("_comments")) + messages = frappe.db.get_single_value("Healthcare Settings", "registration_msg") + messages = frappe.render_template(messages, context) + number = [doc.mobile] + send_sms(number, messages) + else: + frappe.msgprint(doc.name + " has no mobile number to send registration SMS", alert=True) + + +def get_receivable_account(company): + receivable_account = get_account(None, "receivable_account", "Healthcare Settings", company) + if receivable_account: + return receivable_account + + return frappe.get_cached_value("Company", company, "default_receivable_account") + + +def get_income_account(practitioner, company): + # check income account in Healthcare Practitioner + if practitioner: + income_account = get_account("Healthcare Practitioner", None, practitioner, company) + if income_account: + return income_account + + # else check income account in Healthcare Settings + income_account = get_account(None, "income_account", "Healthcare Settings", company) + if income_account: + return income_account + + # else return default income account of company + return frappe.get_cached_value("Company", company, "default_income_account") + + +def get_account(parent_type, parent_field, parent, company): + if parent_type: + return frappe.db.get_value( + "Party Account", {"parenttype": parent_type, "parent": parent, "company": company}, "account" + ) + + if parent_field: + return frappe.db.get_value( + "Party Account", {"parentfield": parent_field, "parent": parent, "company": company}, "account" + ) diff --git a/healthcare/healthcare/doctype/healthcare_settings/test_healthcare_settings.py b/healthcare/healthcare/doctype/healthcare_settings/test_healthcare_settings.py new file mode 100644 index 0000000..3075278 --- /dev/null +++ b/healthcare/healthcare/doctype/healthcare_settings/test_healthcare_settings.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + + +class TestHealthcareSettings(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/inpatient_medication_entry/__init__.py b/healthcare/healthcare/doctype/inpatient_medication_entry/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/inpatient_medication_entry/inpatient_medication_entry.js b/healthcare/healthcare/doctype/inpatient_medication_entry/inpatient_medication_entry.js new file mode 100644 index 0000000..7ec70fe --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_medication_entry/inpatient_medication_entry.js @@ -0,0 +1,74 @@ +// Copyright (c) 2020, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Inpatient Medication Entry', { + refresh: function(frm) { + // Ignore cancellation of doctype on cancel all + frm.ignore_doctypes_on_cancel_all = ['Stock Entry']; + frm.fields_dict['medication_orders'].grid.wrapper.find('.grid-add-row').hide(); + + frm.set_query('item_code', () => { + return { + filters: { + is_stock_item: 1 + } + }; + }); + + frm.set_query('drug_code', 'medication_orders', () => { + return { + filters: { + is_stock_item: 1 + } + }; + }); + + frm.set_query('warehouse', () => { + return { + filters: { + company: frm.doc.company + } + }; + }); + + if (frm.doc.__islocal || frm.doc.docstatus !== 0 || !frm.doc.update_stock) + return; + + frm.add_custom_button(__('Make Stock Entry'), function() { + frappe.call({ + method: 'healthcare.healthcare.doctype.inpatient_medication_entry.inpatient_medication_entry.make_difference_stock_entry', + args: { docname: frm.doc.name }, + freeze: true, + callback: function(r) { + if (r.message) { + var doclist = frappe.model.sync(r.message); + frappe.set_route('Form', doclist[0].doctype, doclist[0].name); + } else { + frappe.msgprint({ + title: __('No Drug Shortage'), + message: __('All the drugs are available with sufficient qty to process this Inpatient Medication Entry.'), + indicator: 'green' + }); + } + } + }); + }); + }, + + patient: function(frm) { + if (frm.doc.patient) + frm.set_value('service_unit', ''); + }, + + get_medication_orders: function(frm) { + frappe.call({ + method: 'get_medication_orders', + doc: frm.doc, + freeze: true, + freeze_message: __('Fetching Pending Medication Orders'), + callback: function() { + refresh_field('medication_orders'); + } + }); + } +}); diff --git a/healthcare/healthcare/doctype/inpatient_medication_entry/inpatient_medication_entry.json b/healthcare/healthcare/doctype/inpatient_medication_entry/inpatient_medication_entry.json new file mode 100644 index 0000000..b1a6ee4 --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_medication_entry/inpatient_medication_entry.json @@ -0,0 +1,204 @@ +{ + "actions": [], + "autoname": "naming_series:", + "creation": "2020-09-25 14:13:20.111906", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "naming_series", + "company", + "column_break_3", + "posting_date", + "status", + "filters_section", + "item_code", + "assigned_to_practitioner", + "patient", + "practitioner", + "service_unit", + "column_break_11", + "from_date", + "to_date", + "from_time", + "to_time", + "select_medication_orders_section", + "get_medication_orders", + "medication_orders", + "section_break_18", + "update_stock", + "warehouse", + "amended_from" + ], + "fields": [ + { + "fieldname": "naming_series", + "fieldtype": "Select", + "label": "Naming Series", + "options": "HLC-IME-.YYYY.-" + }, + { + "fieldname": "company", + "fieldtype": "Link", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Company", + "options": "Company", + "reqd": 1 + }, + { + "fieldname": "column_break_3", + "fieldtype": "Column Break" + }, + { + "fieldname": "posting_date", + "fieldtype": "Date", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Posting Date", + "reqd": 1 + }, + { + "fieldname": "status", + "fieldtype": "Select", + "label": "Status", + "options": "\nDraft\nSubmitted\nPending\nIn Process\nCompleted\nCancelled", + "read_only": 1 + }, + { + "collapsible": 1, + "collapsible_depends_on": "eval: doc.__islocal", + "fieldname": "filters_section", + "fieldtype": "Section Break", + "label": "Filters" + }, + { + "fieldname": "item_code", + "fieldtype": "Link", + "label": "Item Code (Drug)", + "options": "Item" + }, + { + "depends_on": "update_stock", + "description": "Warehouse from where medication stock should be consumed", + "fieldname": "warehouse", + "fieldtype": "Link", + "label": "Medication Warehouse", + "mandatory_depends_on": "update_stock", + "options": "Warehouse" + }, + { + "fieldname": "patient", + "fieldtype": "Link", + "label": "Patient", + "options": "Patient" + }, + { + "depends_on": "eval:!doc.patient", + "fieldname": "service_unit", + "fieldtype": "Link", + "label": "Healthcare Service Unit", + "options": "Healthcare Service Unit" + }, + { + "fieldname": "column_break_11", + "fieldtype": "Column Break" + }, + { + "fieldname": "from_date", + "fieldtype": "Date", + "label": "From Date" + }, + { + "fieldname": "to_date", + "fieldtype": "Date", + "label": "To Date" + }, + { + "fieldname": "amended_from", + "fieldtype": "Link", + "label": "Amended From", + "no_copy": 1, + "options": "Inpatient Medication Entry", + "print_hide": 1, + "read_only": 1 + }, + { + "fieldname": "practitioner", + "fieldtype": "Link", + "label": "Healthcare Practitioner", + "options": "Healthcare Practitioner" + }, + { + "fieldname": "select_medication_orders_section", + "fieldtype": "Section Break", + "label": "Medication Orders" + }, + { + "fieldname": "medication_orders", + "fieldtype": "Table", + "label": "Inpatient Medication Orders", + "options": "Inpatient Medication Entry Detail", + "reqd": 1 + }, + { + "depends_on": "eval:doc.docstatus!==1", + "fieldname": "get_medication_orders", + "fieldtype": "Button", + "label": "Get Pending Medication Orders", + "print_hide": 1 + }, + { + "fieldname": "assigned_to_practitioner", + "fieldtype": "Link", + "label": "Assigned To", + "options": "User" + }, + { + "fieldname": "section_break_18", + "fieldtype": "Section Break", + "label": "Stock Details" + }, + { + "default": "1", + "fieldname": "update_stock", + "fieldtype": "Check", + "label": "Update Stock" + }, + { + "fieldname": "from_time", + "fieldtype": "Time", + "label": "From Time" + }, + { + "fieldname": "to_time", + "fieldtype": "Time", + "label": "To Time" + } + ], + "index_web_pages_for_search": 1, + "is_submittable": 1, + "links": [], + "modified": "2021-01-11 12:37:46.749659", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Inpatient Medication Entry", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + } + ], + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/inpatient_medication_entry/inpatient_medication_entry.py b/healthcare/healthcare/doctype/inpatient_medication_entry/inpatient_medication_entry.py new file mode 100644 index 0000000..248f42d --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_medication_entry/inpatient_medication_entry.py @@ -0,0 +1,349 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +import frappe +from frappe import _ +from frappe.model.document import Document +from frappe.utils import flt, get_link_to_form + +from healthcare.healthcare.doctype.healthcare_settings.healthcare_settings import get_account +from erpnext.stock.utils import get_latest_stock_qty + + +class InpatientMedicationEntry(Document): + def validate(self): + self.validate_medication_orders() + + @frappe.whitelist() + def get_medication_orders(self): + # pull inpatient medication orders based on selected filters + orders = get_pending_medication_orders(self) + + if orders: + self.add_mo_to_table(orders) + return self + else: + self.set("medication_orders", []) + frappe.msgprint(_("No pending medication orders found for selected criteria")) + + def add_mo_to_table(self, orders): + # Add medication orders in the child table + self.set("medication_orders", []) + + for data in orders: + self.append( + "medication_orders", + { + "patient": data.patient, + "patient_name": data.patient_name, + "inpatient_record": data.inpatient_record, + "service_unit": data.service_unit, + "datetime": "%s %s" % (data.date, data.time or "00:00:00"), + "drug_code": data.drug, + "drug_name": data.drug_name, + "dosage": data.dosage, + "dosage_form": data.dosage_form, + "against_imo": data.parent, + "against_imoe": data.name, + }, + ) + + def on_submit(self): + self.validate_medication_orders() + success_msg = "" + if self.update_stock: + stock_entry = self.process_stock() + success_msg += _("Stock Entry {0} created and ").format( + frappe.bold(get_link_to_form("Stock Entry", stock_entry)) + ) + + self.update_medication_orders() + success_msg += _("Inpatient Medication Orders updated successfully") + frappe.msgprint(success_msg, title=_("Success"), indicator="green") + + def validate_medication_orders(self): + for entry in self.medication_orders: + docstatus, is_completed = frappe.db.get_value( + "Inpatient Medication Order Entry", entry.against_imoe, ["docstatus", "is_completed"] + ) + + if docstatus == 2: + frappe.throw( + _( + "Row {0}: Cannot create Inpatient Medication Entry against cancelled Inpatient Medication Order {1}" + ).format(entry.idx, get_link_to_form(entry.against_imo)) + ) + + if is_completed: + frappe.throw( + _("Row {0}: This Medication Order is already marked as completed").format(entry.idx) + ) + + def on_cancel(self): + self.cancel_stock_entries() + self.update_medication_orders(on_cancel=True) + + def process_stock(self): + allow_negative_stock = frappe.db.get_single_value("Stock Settings", "allow_negative_stock") + if not allow_negative_stock: + self.check_stock_qty() + + return self.make_stock_entry() + + def update_medication_orders(self, on_cancel=False): + orders, order_entry_map = self.get_order_entry_map() + # mark completion status + is_completed = 1 + if on_cancel: + is_completed = 0 + + frappe.db.sql( + """ + UPDATE `tabInpatient Medication Order Entry` + SET is_completed = %(is_completed)s + WHERE name IN %(orders)s + """, + {"orders": orders, "is_completed": is_completed}, + ) + + # update status and completed orders count + for order, count in order_entry_map.items(): + medication_order = frappe.get_doc("Inpatient Medication Order", order) + completed_orders = flt(count) + current_value = frappe.db.get_value("Inpatient Medication Order", order, "completed_orders") + + if on_cancel: + completed_orders = flt(current_value) - flt(count) + else: + completed_orders = flt(current_value) + flt(count) + + medication_order.db_set("completed_orders", completed_orders) + medication_order.set_status() + + def get_order_entry_map(self): + # for marking order completion status + orders = [] + # orders mapped + order_entry_map = dict() + + for entry in self.medication_orders: + orders.append(entry.against_imoe) + parent = entry.against_imo + if not order_entry_map.get(parent): + order_entry_map[parent] = 0 + + order_entry_map[parent] += 1 + + return orders, order_entry_map + + def check_stock_qty(self): + drug_shortage = get_drug_shortage_map(self.medication_orders, self.warehouse) + + if drug_shortage: + message = _("Quantity not available for the following items in warehouse {0}. ").format( + frappe.bold(self.warehouse) + ) + message += _( + "Please enable Allow Negative Stock in Stock Settings or create Stock Entry to proceed." + ) + + formatted_item_rows = "" + + for drug, shortage_qty in drug_shortage.items(): + item_link = get_link_to_form("Item", drug) + formatted_item_rows += """ + {0} + {1} + """.format( + item_link, frappe.bold(shortage_qty) + ) + + message += """ + + + + + + {2} +
{0}{1}
+ """.format( + _("Drug Code"), _("Shortage Qty"), formatted_item_rows + ) + + frappe.throw(message, title=_("Insufficient Stock"), is_minimizable=True, wide=True) + + def make_stock_entry(self): + stock_entry = frappe.new_doc("Stock Entry") + stock_entry.purpose = "Material Issue" + stock_entry.set_stock_entry_type() + stock_entry.from_warehouse = self.warehouse + stock_entry.company = self.company + stock_entry.inpatient_medication_entry = self.name + cost_center = frappe.get_cached_value("Company", self.company, "cost_center") + expense_account = get_account(None, "expense_account", "Healthcare Settings", self.company) + + for entry in self.medication_orders: + se_child = stock_entry.append("items") + se_child.item_code = entry.drug_code + se_child.item_name = entry.drug_name + se_child.uom = frappe.db.get_value("Item", entry.drug_code, "stock_uom") + se_child.stock_uom = se_child.uom + se_child.qty = flt(entry.dosage) + # in stock uom + se_child.conversion_factor = 1 + se_child.cost_center = cost_center + se_child.expense_account = expense_account + # references + se_child.patient = entry.patient + se_child.inpatient_medication_entry_child = entry.name + + stock_entry.submit() + return stock_entry.name + + def cancel_stock_entries(self): + stock_entries = frappe.get_all("Stock Entry", {"inpatient_medication_entry": self.name}) + for entry in stock_entries: + doc = frappe.get_doc("Stock Entry", entry.name) + doc.cancel() + + +def get_pending_medication_orders(entry): + filters, values = get_filters(entry) + to_remove = [] + + data = frappe.db.sql( + """ + SELECT + ip.inpatient_record, ip.patient, ip.patient_name, + entry.name, entry.parent, entry.drug, entry.drug_name, + entry.dosage, entry.dosage_form, entry.date, entry.time, entry.instructions + FROM + `tabInpatient Medication Order` ip + INNER JOIN + `tabInpatient Medication Order Entry` entry + ON + ip.name = entry.parent + WHERE + ip.docstatus = 1 and + ip.company = %(company)s and + entry.is_completed = 0 + {0} + ORDER BY + entry.date, entry.time + """.format( + filters + ), + values, + as_dict=1, + ) + + for doc in data: + inpatient_record = doc.inpatient_record + if inpatient_record: + doc["service_unit"] = get_current_healthcare_service_unit(inpatient_record) + + if entry.service_unit and doc.service_unit != entry.service_unit: + to_remove.append(doc) + + for doc in to_remove: + data.remove(doc) + + return data + + +def get_filters(entry): + filters = "" + values = dict(company=entry.company) + if entry.from_date: + filters += " and entry.date >= %(from_date)s" + values["from_date"] = entry.from_date + + if entry.to_date: + filters += " and entry.date <= %(to_date)s" + values["to_date"] = entry.to_date + + if entry.from_time: + filters += " and entry.time >= %(from_time)s" + values["from_time"] = entry.from_time + + if entry.to_time: + filters += " and entry.time <= %(to_time)s" + values["to_time"] = entry.to_time + + if entry.patient: + filters += " and ip.patient = %(patient)s" + values["patient"] = entry.patient + + if entry.practitioner: + filters += " and ip.practitioner = %(practitioner)s" + values["practitioner"] = entry.practitioner + + if entry.item_code: + filters += " and entry.drug = %(item_code)s" + values["item_code"] = entry.item_code + + if entry.assigned_to_practitioner: + filters += " and ip._assign LIKE %(assigned_to)s" + values["assigned_to"] = "%" + entry.assigned_to_practitioner + "%" + + return filters, values + + +def get_current_healthcare_service_unit(inpatient_record): + ip_record = frappe.get_doc("Inpatient Record", inpatient_record) + if ip_record.status in ["Admitted", "Discharge Scheduled"] and ip_record.inpatient_occupancies: + return ip_record.inpatient_occupancies[-1].service_unit + return + + +def get_drug_shortage_map(medication_orders, warehouse): + """ + Returns a dict like { drug_code: shortage_qty } + """ + drug_requirement = dict() + for d in medication_orders: + if not drug_requirement.get(d.drug_code): + drug_requirement[d.drug_code] = 0 + drug_requirement[d.drug_code] += flt(d.dosage) + + drug_shortage = dict() + for drug, required_qty in drug_requirement.items(): + available_qty = get_latest_stock_qty(drug, warehouse) + if flt(required_qty) > flt(available_qty): + drug_shortage[drug] = flt(flt(required_qty) - flt(available_qty)) + + return drug_shortage + + +@frappe.whitelist() +def make_difference_stock_entry(docname): + doc = frappe.get_doc("Inpatient Medication Entry", docname) + drug_shortage = get_drug_shortage_map(doc.medication_orders, doc.warehouse) + + if not drug_shortage: + return None + + stock_entry = frappe.new_doc("Stock Entry") + stock_entry.purpose = "Material Transfer" + stock_entry.set_stock_entry_type() + stock_entry.to_warehouse = doc.warehouse + stock_entry.company = doc.company + cost_center = frappe.get_cached_value("Company", doc.company, "cost_center") + expense_account = get_account(None, "expense_account", "Healthcare Settings", doc.company) + + for drug, shortage_qty in drug_shortage.items(): + se_child = stock_entry.append("items") + se_child.item_code = drug + se_child.item_name = frappe.db.get_value("Item", drug, "stock_uom") + se_child.uom = frappe.db.get_value("Item", drug, "stock_uom") + se_child.stock_uom = se_child.uom + se_child.qty = flt(shortage_qty) + se_child.t_warehouse = doc.warehouse + # in stock uom + se_child.conversion_factor = 1 + se_child.cost_center = cost_center + se_child.expense_account = expense_account + + return stock_entry diff --git a/healthcare/healthcare/doctype/inpatient_medication_entry/inpatient_medication_entry_dashboard.py b/healthcare/healthcare/doctype/inpatient_medication_entry/inpatient_medication_entry_dashboard.py new file mode 100644 index 0000000..07d634e --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_medication_entry/inpatient_medication_entry_dashboard.py @@ -0,0 +1,9 @@ +from frappe import _ + + +def get_data(): + return { + "fieldname": "against_imoe", + "internal_links": {"Inpatient Medication Order": ["medication_orders", "against_imo"]}, + "transactions": [{"label": _("Reference"), "items": ["Inpatient Medication Order"]}], + } diff --git a/healthcare/healthcare/doctype/inpatient_medication_entry/test_inpatient_medication_entry.py b/healthcare/healthcare/doctype/inpatient_medication_entry/test_inpatient_medication_entry.py new file mode 100644 index 0000000..617433d --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_medication_entry/test_inpatient_medication_entry.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +import frappe +from frappe.utils import add_days, getdate, now_datetime + +from healthcare.healthcare.doctype.healthcare_settings.healthcare_settings import get_account +from healthcare.healthcare.doctype.inpatient_medication_entry.inpatient_medication_entry import ( + get_drug_shortage_map, + make_difference_stock_entry, +) +from healthcare.healthcare.doctype.inpatient_medication_order.test_inpatient_medication_order import ( + create_ipme, + create_ipmo, +) +from healthcare.healthcare.doctype.inpatient_record.inpatient_record import ( + admit_patient, + discharge_patient, + schedule_discharge, +) +from healthcare.healthcare.doctype.inpatient_record.test_inpatient_record import ( + create_inpatient, + create_patient, + get_healthcare_service_unit, + mark_invoiced_inpatient_occupancy, +) + + +class TestInpatientMedicationEntry(FrappeTestCase): + def setUp(self): + frappe.db.sql("""delete from `tabInpatient Record`""") + frappe.db.sql("""delete from `tabInpatient Medication Order`""") + frappe.db.sql("""delete from `tabInpatient Medication Entry`""") + self.patient = create_patient() + + # Admit + ip_record = create_inpatient(self.patient) + ip_record.expected_length_of_stay = 0 + ip_record.save() + ip_record.reload() + service_unit = get_healthcare_service_unit() + admit_patient(ip_record, service_unit, now_datetime()) + self.ip_record = ip_record + + def test_filters_for_fetching_pending_mo(self): + ipmo = create_ipmo(self.patient) + ipmo.submit() + ipmo.reload() + + date = add_days(getdate(), -1) + filters = frappe._dict( + from_date=date, + to_date=date, + from_time="", + to_time="", + item_code="Dextromethorphan", + patient=self.patient, + ) + + ipme = create_ipme(filters, update_stock=0) + + # 3 dosages per day + self.assertEqual(len(ipme.medication_orders), 3) + self.assertEqual(getdate(ipme.medication_orders[0].datetime), date) + + def test_ipme_with_stock_update(self): + ipmo = create_ipmo(self.patient) + ipmo.submit() + ipmo.reload() + + date = add_days(getdate(), -1) + filters = frappe._dict( + from_date=date, + to_date=date, + from_time="", + to_time="", + item_code="Dextromethorphan", + patient=self.patient, + ) + + make_stock_entry() + ipme = create_ipme(filters, update_stock=1) + ipme.submit() + ipme.reload() + + # test order completed + is_order_completed = frappe.db.get_value( + "Inpatient Medication Order Entry", ipme.medication_orders[0].against_imoe, "is_completed" + ) + self.assertEqual(is_order_completed, 1) + + # test stock entry + stock_entry = frappe.db.exists("Stock Entry", {"inpatient_medication_entry": ipme.name}) + self.assertTrue(stock_entry) + + # check references + stock_entry = frappe.get_doc("Stock Entry", stock_entry) + self.assertEqual(stock_entry.items[0].patient, self.patient) + self.assertEqual( + stock_entry.items[0].inpatient_medication_entry_child, ipme.medication_orders[0].name + ) + + def test_drug_shortage_stock_entry(self): + ipmo = create_ipmo(self.patient) + ipmo.submit() + ipmo.reload() + + date = add_days(getdate(), -1) + filters = frappe._dict( + from_date=date, + to_date=date, + from_time="", + to_time="", + item_code="Dextromethorphan", + patient=self.patient, + ) + + # check drug shortage + ipme = create_ipme(filters, update_stock=1) + ipme.warehouse = "Finished Goods - _TC" + ipme.save() + drug_shortage = get_drug_shortage_map(ipme.medication_orders, ipme.warehouse) + self.assertEqual(drug_shortage.get("Dextromethorphan"), 3) + + # check material transfer for drug shortage + make_stock_entry() + stock_entry = make_difference_stock_entry(ipme.name) + self.assertEqual(stock_entry.items[0].item_code, "Dextromethorphan") + self.assertEqual(stock_entry.items[0].qty, 3) + stock_entry.from_warehouse = "Stores - _TC" + stock_entry.submit() + + ipme.reload() + ipme.submit() + + def tearDown(self): + # cleanup - Discharge + schedule_discharge(frappe.as_json({"patient": self.patient})) + self.ip_record.reload() + mark_invoiced_inpatient_occupancy(self.ip_record) + + self.ip_record.reload() + discharge_patient(self.ip_record) + + for entry in frappe.get_all("Inpatient Medication Entry"): + doc = frappe.get_doc("Inpatient Medication Entry", entry.name) + doc.cancel() + + for entry in frappe.get_all("Inpatient Medication Order"): + doc = frappe.get_doc("Inpatient Medication Order", entry.name) + doc.cancel() + + +def make_stock_entry(warehouse=None): + frappe.db.set_value( + "Company", + "_Test Company", + { + "stock_adjustment_account": "Stock Adjustment - _TC", + "default_inventory_account": "Stock In Hand - _TC", + }, + ) + stock_entry = frappe.new_doc("Stock Entry") + stock_entry.stock_entry_type = "Material Receipt" + stock_entry.company = "_Test Company" + stock_entry.to_warehouse = warehouse or "Stores - _TC" + expense_account = get_account(None, "expense_account", "Healthcare Settings", "_Test Company") + se_child = stock_entry.append("items") + se_child.item_code = "Dextromethorphan" + se_child.item_name = "Dextromethorphan" + se_child.uom = "Nos" + se_child.stock_uom = "Nos" + se_child.qty = 6 + se_child.t_warehouse = "Stores - _TC" + # in stock uom + se_child.conversion_factor = 1.0 + se_child.expense_account = expense_account + stock_entry.submit() diff --git a/healthcare/healthcare/doctype/inpatient_medication_entry_detail/__init__.py b/healthcare/healthcare/doctype/inpatient_medication_entry_detail/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/inpatient_medication_entry_detail/inpatient_medication_entry_detail.json b/healthcare/healthcare/doctype/inpatient_medication_entry_detail/inpatient_medication_entry_detail.json new file mode 100644 index 0000000..e3d7212 --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_medication_entry_detail/inpatient_medication_entry_detail.json @@ -0,0 +1,163 @@ +{ + "actions": [], + "creation": "2020-09-25 14:56:32.636569", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "patient", + "patient_name", + "inpatient_record", + "column_break_4", + "service_unit", + "datetime", + "medication_details_section", + "drug_code", + "drug_name", + "dosage", + "available_qty", + "dosage_form", + "column_break_10", + "instructions", + "references_section", + "against_imo", + "against_imoe" + ], + "fields": [ + { + "columns": 2, + "fieldname": "patient", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Patient", + "options": "Patient", + "reqd": 1 + }, + { + "fetch_from": "patient.patient_name", + "fieldname": "patient_name", + "fieldtype": "Data", + "label": "Patient Name", + "read_only": 1 + }, + { + "columns": 2, + "fieldname": "drug_code", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Drug Code", + "options": "Item", + "reqd": 1 + }, + { + "fetch_from": "drug_code.item_name", + "fieldname": "drug_name", + "fieldtype": "Data", + "label": "Drug Name", + "read_only": 1 + }, + { + "columns": 1, + "fieldname": "dosage", + "fieldtype": "Float", + "in_list_view": 1, + "label": "Dosage", + "reqd": 1 + }, + { + "fieldname": "dosage_form", + "fieldtype": "Link", + "label": "Dosage Form", + "options": "Dosage Form" + }, + { + "fetch_from": "patient.inpatient_record", + "fieldname": "inpatient_record", + "fieldtype": "Link", + "label": "Inpatient Record", + "options": "Inpatient Record", + "read_only": 1 + }, + { + "collapsible": 1, + "fieldname": "references_section", + "fieldtype": "Section Break", + "label": "References" + }, + { + "fieldname": "column_break_4", + "fieldtype": "Column Break" + }, + { + "fieldname": "medication_details_section", + "fieldtype": "Section Break", + "label": "Medication Details" + }, + { + "fieldname": "column_break_10", + "fieldtype": "Column Break" + }, + { + "columns": 3, + "fieldname": "datetime", + "fieldtype": "Datetime", + "in_list_view": 1, + "label": "Datetime", + "reqd": 1 + }, + { + "fieldname": "instructions", + "fieldtype": "Small Text", + "label": "Instructions" + }, + { + "columns": 2, + "fieldname": "service_unit", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Service Unit", + "options": "Healthcare Service Unit", + "read_only": 1, + "reqd": 1 + }, + { + "fieldname": "against_imo", + "fieldtype": "Link", + "label": "Against Inpatient Medication Order", + "no_copy": 1, + "options": "Inpatient Medication Order", + "print_hide": 1, + "read_only": 1 + }, + { + "fieldname": "against_imoe", + "fieldtype": "Data", + "label": "Against Inpatient Medication Order Entry", + "no_copy": 1, + "print_hide": 1, + "read_only": 1 + }, + { + "fieldname": "available_qty", + "fieldtype": "Float", + "hidden": 1, + "label": "Available Qty", + "no_copy": 1, + "print_hide": 1, + "read_only": 1 + } + ], + "index_web_pages_for_search": 1, + "istable": 1, + "links": [], + "modified": "2020-09-30 14:48:23.648223", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Inpatient Medication Entry Detail", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/inpatient_medication_entry_detail/inpatient_medication_entry_detail.py b/healthcare/healthcare/doctype/inpatient_medication_entry_detail/inpatient_medication_entry_detail.py new file mode 100644 index 0000000..6dd7d2f --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_medication_entry_detail/inpatient_medication_entry_detail.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class InpatientMedicationEntryDetail(Document): + pass diff --git a/healthcare/healthcare/doctype/inpatient_medication_order/__init__.py b/healthcare/healthcare/doctype/inpatient_medication_order/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/inpatient_medication_order/inpatient_medication_order.js b/healthcare/healthcare/doctype/inpatient_medication_order/inpatient_medication_order.js new file mode 100644 index 0000000..c933755 --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_medication_order/inpatient_medication_order.js @@ -0,0 +1,107 @@ +// Copyright (c) 2020, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Inpatient Medication Order', { + refresh: function(frm) { + if (frm.doc.docstatus === 1) { + frm.trigger("show_progress"); + } + + frm.events.show_medication_order_button(frm); + + frm.set_query('patient', () => { + return { + filters: { + 'inpatient_record': ['!=', ''], + 'inpatient_status': 'Admitted' + } + }; + }); + }, + + show_medication_order_button: function(frm) { + frm.fields_dict['medication_orders'].grid.wrapper.find('.grid-add-row').hide(); + frm.fields_dict['medication_orders'].grid.add_custom_button(__('Add Medication Orders'), () => { + let d = new frappe.ui.Dialog({ + title: __('Add Medication Orders'), + fields: [ + { + fieldname: 'drug_code', + label: __('Drug'), + fieldtype: 'Link', + options: 'Item', + reqd: 1, + "get_query": function () { + return { + filters: {'is_stock_item': 1} + }; + } + }, + { + fieldname: 'dosage', + label: __('Dosage'), + fieldtype: 'Link', + options: 'Prescription Dosage', + reqd: 1 + }, + { + fieldname: 'period', + label: __('Period'), + fieldtype: 'Link', + options: 'Prescription Duration', + reqd: 1 + }, + { + fieldname: 'dosage_form', + label: __('Dosage Form'), + fieldtype: 'Link', + options: 'Dosage Form', + reqd: 1 + } + ], + primary_action_label: __('Add'), + primary_action: () => { + let values = d.get_values(); + if (values) { + frm.call({ + doc: frm.doc, + method: 'add_order_entries', + args: { + order: values + }, + freeze: true, + freeze_message: __('Adding Order Entries'), + callback: function() { + frm.refresh_field('medication_orders'); + } + }); + } + }, + }); + d.show(); + }); + }, + + show_progress: function(frm) { + let bars = []; + let message = ''; + + // completed sessions + let title = __('{0} medication orders completed', [frm.doc.completed_orders]); + if (frm.doc.completed_orders === 1) { + title = __('{0} medication order completed', [frm.doc.completed_orders]); + } + title += __(' out of {0}', [frm.doc.total_orders]); + + bars.push({ + 'title': title, + 'width': (frm.doc.completed_orders / frm.doc.total_orders * 100) + '%', + 'progress_class': 'progress-bar-success' + }); + if (bars[0].width == '0%') { + bars[0].width = '0.5%'; + } + message = title; + frm.dashboard.add_progress(__('Status'), bars, message); + } +}); diff --git a/healthcare/healthcare/doctype/inpatient_medication_order/inpatient_medication_order.json b/healthcare/healthcare/doctype/inpatient_medication_order/inpatient_medication_order.json new file mode 100644 index 0000000..e31d2e3 --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_medication_order/inpatient_medication_order.json @@ -0,0 +1,196 @@ +{ + "actions": [], + "autoname": "naming_series:", + "creation": "2020-09-14 18:33:56.715736", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "patient_details_section", + "naming_series", + "patient_encounter", + "patient", + "patient_name", + "patient_age", + "inpatient_record", + "column_break_6", + "company", + "status", + "practitioner", + "start_date", + "end_date", + "medication_orders_section", + "medication_orders", + "section_break_16", + "total_orders", + "column_break_18", + "completed_orders", + "amended_from" + ], + "fields": [ + { + "fieldname": "patient_details_section", + "fieldtype": "Section Break", + "label": "Patient Details" + }, + { + "fieldname": "naming_series", + "fieldtype": "Select", + "label": "Naming Series", + "options": "HLC-IMO-.YYYY.-" + }, + { + "fieldname": "patient_encounter", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Patient Encounter", + "options": "Patient Encounter" + }, + { + "fetch_from": "patient_encounter.patient", + "fieldname": "patient", + "fieldtype": "Link", + "label": "Patient", + "options": "Patient", + "read_only_depends_on": "patient_encounter", + "reqd": 1 + }, + { + "fetch_from": "patient.patient_name", + "fieldname": "patient_name", + "fieldtype": "Data", + "label": "Patient Name", + "read_only": 1 + }, + { + "fieldname": "patient_age", + "fieldtype": "Data", + "label": "Patient Age", + "read_only": 1 + }, + { + "fieldname": "column_break_6", + "fieldtype": "Column Break" + }, + { + "fetch_from": "patient.inpatient_record", + "fieldname": "inpatient_record", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Inpatient Record", + "options": "Inpatient Record", + "read_only": 1, + "reqd": 1 + }, + { + "fetch_from": "patient_encounter.practitioner", + "fieldname": "practitioner", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Healthcare Practitioner", + "options": "Healthcare Practitioner", + "read_only_depends_on": "patient_encounter" + }, + { + "fieldname": "start_date", + "fieldtype": "Date", + "in_list_view": 1, + "label": "Start Date", + "reqd": 1 + }, + { + "fieldname": "end_date", + "fieldtype": "Date", + "label": "End Date", + "read_only": 1 + }, + { + "depends_on": "eval: doc.patient && doc.start_date", + "fieldname": "medication_orders_section", + "fieldtype": "Section Break", + "label": "Medication Orders" + }, + { + "fieldname": "medication_orders", + "fieldtype": "Table", + "label": "Medication Orders", + "options": "Inpatient Medication Order Entry" + }, + { + "fieldname": "company", + "fieldtype": "Link", + "label": "Company", + "options": "Company", + "reqd": 1 + }, + { + "fieldname": "amended_from", + "fieldtype": "Link", + "label": "Amended From", + "no_copy": 1, + "options": "Inpatient Medication Order", + "print_hide": 1, + "read_only": 1 + }, + { + "fieldname": "status", + "fieldtype": "Select", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Status", + "options": "\nDraft\nSubmitted\nPending\nIn Process\nCompleted\nCancelled", + "read_only": 1 + }, + { + "collapsible": 1, + "fieldname": "section_break_16", + "fieldtype": "Section Break", + "label": "Other Details" + }, + { + "fieldname": "total_orders", + "fieldtype": "Float", + "label": "Total Orders", + "no_copy": 1, + "read_only": 1 + }, + { + "fieldname": "column_break_18", + "fieldtype": "Column Break" + }, + { + "fieldname": "completed_orders", + "fieldtype": "Float", + "label": "Completed Orders", + "no_copy": 1, + "read_only": 1 + } + ], + "index_web_pages_for_search": 1, + "is_submittable": 1, + "links": [], + "modified": "2020-09-30 21:53:27.128591", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Inpatient Medication Order", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + } + ], + "search_fields": "patient_encounter, patient", + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "patient", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/inpatient_medication_order/inpatient_medication_order.py b/healthcare/healthcare/doctype/inpatient_medication_order/inpatient_medication_order.py new file mode 100644 index 0000000..d061d39 --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_medication_order/inpatient_medication_order.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +import frappe +from frappe import _ +from frappe.model.document import Document +from frappe.utils import cstr + +from healthcare.healthcare.doctype.patient_encounter.patient_encounter import ( + get_prescription_dates, +) + + +class InpatientMedicationOrder(Document): + def validate(self): + self.validate_inpatient() + self.validate_duplicate() + self.set_total_orders() + self.set_status() + + def on_submit(self): + self.validate_inpatient() + self.set_status() + + def on_cancel(self): + self.set_status() + + def validate_inpatient(self): + if not self.inpatient_record: + frappe.throw(_("No Inpatient Record found against patient {0}").format(self.patient)) + + def validate_duplicate(self): + existing_mo = frappe.db.exists( + "Inpatient Medication Order", + { + "patient_encounter": self.patient_encounter, + "docstatus": ("!=", 2), + "name": ("!=", self.name), + }, + ) + if existing_mo: + frappe.throw( + _("An Inpatient Medication Order {0} against Patient Encounter {1} already exists.").format( + existing_mo, self.patient_encounter + ), + frappe.DuplicateEntryError, + ) + + def set_total_orders(self): + self.db_set("total_orders", len(self.medication_orders)) + + def set_status(self): + status = {"0": "Draft", "1": "Submitted", "2": "Cancelled"}[cstr(self.docstatus or 0)] + + if self.docstatus == 1: + if not self.completed_orders: + status = "Pending" + elif self.completed_orders < self.total_orders: + status = "In Process" + else: + status = "Completed" + + self.db_set("status", status) + + @frappe.whitelist() + def add_order_entries(self, order): + if order.get("drug_code"): + dosage = frappe.get_doc("Prescription Dosage", order.get("dosage")) + dates = get_prescription_dates(order.get("period"), self.start_date) + for date in dates: + for dose in dosage.dosage_strength: + entry = self.append("medication_orders") + entry.drug = order.get("drug_code") + entry.drug_name = frappe.db.get_value("Item", order.get("drug_code"), "item_name") + entry.dosage = dose.strength + entry.dosage_form = order.get("dosage_form") + entry.date = date + entry.time = dose.strength_time + self.end_date = dates[-1] + return diff --git a/healthcare/healthcare/doctype/inpatient_medication_order/inpatient_medication_order_list.js b/healthcare/healthcare/doctype/inpatient_medication_order/inpatient_medication_order_list.js new file mode 100644 index 0000000..1c31876 --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_medication_order/inpatient_medication_order_list.js @@ -0,0 +1,16 @@ +frappe.listview_settings['Inpatient Medication Order'] = { + add_fields: ["status"], + filters: [["status", "!=", "Cancelled"]], + get_indicator: function(doc) { + if (doc.status === "Pending") { + return [__("Pending"), "orange", "status,=,Pending"]; + + } else if (doc.status === "In Process") { + return [__("In Process"), "blue", "status,=,In Process"]; + + } else if (doc.status === "Completed") { + return [__("Completed"), "green", "status,=,Completed"]; + + } + } +}; diff --git a/healthcare/healthcare/doctype/inpatient_medication_order/test_inpatient_medication_order.py b/healthcare/healthcare/doctype/inpatient_medication_order/test_inpatient_medication_order.py new file mode 100644 index 0000000..ceb282c --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_medication_order/test_inpatient_medication_order.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +import frappe +from frappe.utils import add_days, getdate, now_datetime + +from healthcare.healthcare.doctype.inpatient_record.inpatient_record import ( + admit_patient, + discharge_patient, + schedule_discharge, +) +from healthcare.healthcare.doctype.inpatient_record.test_inpatient_record import ( + create_inpatient, + create_patient, + get_healthcare_service_unit, + mark_invoiced_inpatient_occupancy, +) + + +class TestInpatientMedicationOrder(FrappeTestCase): + def setUp(self): + frappe.db.sql("""delete from `tabInpatient Record`""") + self.patient = create_patient() + + # Admit + ip_record = create_inpatient(self.patient) + ip_record.expected_length_of_stay = 0 + ip_record.save() + ip_record.reload() + service_unit = get_healthcare_service_unit() + admit_patient(ip_record, service_unit, now_datetime()) + self.ip_record = ip_record + + def test_order_creation(self): + ipmo = create_ipmo(self.patient) + ipmo.submit() + ipmo.reload() + + # 3 dosages per day for 2 days + self.assertEqual(len(ipmo.medication_orders), 6) + self.assertEqual(ipmo.medication_orders[0].date, add_days(getdate(), -1)) + + prescription_dosage = frappe.get_doc("Prescription Dosage", "1-1-1") + for i in range(len(prescription_dosage.dosage_strength)): + self.assertEqual( + ipmo.medication_orders[i].time, prescription_dosage.dosage_strength[i].strength_time + ) + + self.assertEqual(ipmo.medication_orders[3].date, getdate()) + + def test_inpatient_validation(self): + # Discharge + schedule_discharge(frappe.as_json({"patient": self.patient})) + + self.ip_record.reload() + mark_invoiced_inpatient_occupancy(self.ip_record) + + self.ip_record.reload() + discharge_patient(self.ip_record) + + ipmo = create_ipmo(self.patient) + # inpatient validation + self.assertRaises(frappe.ValidationError, ipmo.insert) + + def test_status(self): + ipmo = create_ipmo(self.patient) + ipmo.submit() + ipmo.reload() + + self.assertEqual(ipmo.status, "Pending") + + filters = frappe._dict( + from_date=add_days(getdate(), -1), to_date=add_days(getdate(), -1), from_time="", to_time="" + ) + ipme = create_ipme(filters) + ipme.submit() + ipmo.reload() + self.assertEqual(ipmo.status, "In Process") + + filters = frappe._dict(from_date=getdate(), to_date=getdate(), from_time="", to_time="") + ipme = create_ipme(filters) + ipme.submit() + ipmo.reload() + self.assertEqual(ipmo.status, "Completed") + + def tearDown(self): + if frappe.db.get_value("Patient", self.patient, "inpatient_record"): + # cleanup - Discharge + schedule_discharge(frappe.as_json({"patient": self.patient})) + self.ip_record.reload() + mark_invoiced_inpatient_occupancy(self.ip_record) + + self.ip_record.reload() + discharge_patient(self.ip_record) + + for doctype in ["Inpatient Medication Entry", "Inpatient Medication Order"]: + frappe.db.sql("delete from `tab{doctype}`".format(doctype=doctype)) + + +def create_dosage_form(): + if not frappe.db.exists("Dosage Form", "Tablet"): + frappe.get_doc({"doctype": "Dosage Form", "dosage_form": "Tablet"}).insert() + + +def create_drug(item=None): + if not item: + item = "Dextromethorphan" + drug = frappe.db.exists("Item", {"item_code": "Dextromethorphan"}) + if not drug: + drug = frappe.get_doc( + { + "doctype": "Item", + "item_code": "Dextromethorphan", + "item_name": "Dextromethorphan", + "item_group": "Products", + "stock_uom": "Nos", + "is_stock_item": 1, + "valuation_rate": 50, + "opening_stock": 20, + } + ).insert() + + +def get_orders(): + create_dosage_form() + create_drug() + return { + "drug_code": "Dextromethorphan", + "drug_name": "Dextromethorphan", + "dosage": "1-1-1", + "dosage_form": "Tablet", + "period": "2 Day", + } + + +def create_ipmo(patient): + orders = get_orders() + ipmo = frappe.new_doc("Inpatient Medication Order") + ipmo.patient = patient + ipmo.company = "_Test Company" + ipmo.start_date = add_days(getdate(), -1) + ipmo.add_order_entries(orders) + + return ipmo + + +def create_ipme(filters, update_stock=0): + ipme = frappe.new_doc("Inpatient Medication Entry") + ipme.company = "_Test Company" + ipme.posting_date = getdate() + ipme.update_stock = update_stock + if update_stock: + ipme.warehouse = "Stores - _TC" + for key, value in filters.items(): + ipme.set(key, value) + ipme = ipme.get_medication_orders() + + return ipme diff --git a/healthcare/healthcare/doctype/inpatient_medication_order_entry/__init__.py b/healthcare/healthcare/doctype/inpatient_medication_order_entry/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/inpatient_medication_order_entry/inpatient_medication_order_entry.json b/healthcare/healthcare/doctype/inpatient_medication_order_entry/inpatient_medication_order_entry.json new file mode 100644 index 0000000..72999a9 --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_medication_order_entry/inpatient_medication_order_entry.json @@ -0,0 +1,94 @@ +{ + "actions": [], + "creation": "2020-09-14 21:51:30.259164", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "drug", + "drug_name", + "dosage", + "dosage_form", + "instructions", + "column_break_4", + "date", + "time", + "is_completed" + ], + "fields": [ + { + "fieldname": "drug", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Drug", + "options": "Item", + "reqd": 1 + }, + { + "fetch_from": "drug.item_name", + "fieldname": "drug_name", + "fieldtype": "Data", + "label": "Drug Name", + "read_only": 1 + }, + { + "fieldname": "dosage", + "fieldtype": "Float", + "in_list_view": 1, + "label": "Dosage", + "reqd": 1 + }, + { + "fieldname": "dosage_form", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Dosage Form", + "options": "Dosage Form", + "reqd": 1 + }, + { + "fieldname": "column_break_4", + "fieldtype": "Column Break" + }, + { + "fieldname": "date", + "fieldtype": "Date", + "in_list_view": 1, + "label": "Date", + "reqd": 1 + }, + { + "fieldname": "time", + "fieldtype": "Time", + "in_list_view": 1, + "label": "Time", + "reqd": 1 + }, + { + "default": "0", + "fieldname": "is_completed", + "fieldtype": "Check", + "label": "Is Order Completed", + "no_copy": 1, + "read_only": 1 + }, + { + "fieldname": "instructions", + "fieldtype": "Small Text", + "label": "Instructions" + } + ], + "index_web_pages_for_search": 1, + "istable": 1, + "links": [], + "modified": "2020-09-30 14:03:26.755925", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Inpatient Medication Order Entry", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/inpatient_medication_order_entry/inpatient_medication_order_entry.py b/healthcare/healthcare/doctype/inpatient_medication_order_entry/inpatient_medication_order_entry.py new file mode 100644 index 0000000..ce60dc3 --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_medication_order_entry/inpatient_medication_order_entry.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class InpatientMedicationOrderEntry(Document): + pass diff --git a/healthcare/healthcare/doctype/inpatient_occupancy/__init__.py b/healthcare/healthcare/doctype/inpatient_occupancy/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/inpatient_occupancy/inpatient_occupancy.json b/healthcare/healthcare/doctype/inpatient_occupancy/inpatient_occupancy.json new file mode 100644 index 0000000..3fa98b6 --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_occupancy/inpatient_occupancy.json @@ -0,0 +1,64 @@ +{ + "actions": [], + "creation": "2018-07-12 12:07:36.932333", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "service_unit", + "check_in", + "left", + "check_out", + "invoiced" + ], + "fields": [ + { + "fieldname": "service_unit", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Healthcare Service Unit", + "options": "Healthcare Service Unit", + "reqd": 1 + }, + { + "fieldname": "check_in", + "fieldtype": "Datetime", + "in_list_view": 1, + "label": "Check In" + }, + { + "default": "0", + "fieldname": "left", + "fieldtype": "Check", + "label": "Left", + "read_only": 1, + "search_index": 1 + }, + { + "fieldname": "check_out", + "fieldtype": "Datetime", + "label": "Check Out" + }, + { + "default": "0", + "fieldname": "invoiced", + "fieldtype": "Check", + "label": "Invoiced", + "read_only": 1 + } + ], + "index_web_pages_for_search": 1, + "istable": 1, + "links": [], + "modified": "2021-03-18 15:08:54.634132", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Inpatient Occupancy", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/inpatient_occupancy/inpatient_occupancy.py b/healthcare/healthcare/doctype/inpatient_occupancy/inpatient_occupancy.py new file mode 100644 index 0000000..932284d --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_occupancy/inpatient_occupancy.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class InpatientOccupancy(Document): + pass diff --git a/healthcare/healthcare/doctype/inpatient_record/__init__.py b/healthcare/healthcare/doctype/inpatient_record/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/inpatient_record/inpatient_record.js b/healthcare/healthcare/doctype/inpatient_record/inpatient_record.js new file mode 100644 index 0000000..e7d81ef --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_record/inpatient_record.js @@ -0,0 +1,319 @@ +// Copyright (c) 2018, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Inpatient Record', { + setup: function(frm) { + frm.get_field('drug_prescription').grid.editable_fields = [ + {fieldname: 'drug_code', columns: 2}, + {fieldname: 'drug_name', columns: 2}, + {fieldname: 'dosage', columns: 2}, + {fieldname: 'period', columns: 2} + ]; + }, + refresh: function(frm) { + frm.set_query('admission_service_unit_type', function() { + return { + filters: { + 'inpatient_occupancy': 1, + 'allow_appointments': 0 + } + }; + }); + + frm.set_query('primary_practitioner', function() { + return { + filters: { + 'department': frm.doc.medical_department + } + }; + }); + if (!frm.doc.__islocal) { + if (frm.doc.status == 'Admitted') { + frm.add_custom_button(__('Schedule Discharge'), function() { + schedule_discharge(frm); + }); + } else if (frm.doc.status == 'Admission Scheduled') { + frm.add_custom_button(__('Cancel Admission'), function() { + cancel_ip_order(frm) + }) + frm.add_custom_button(__('Admit'), function() { + admit_patient_dialog(frm); + } ); + } else if (frm.doc.status == 'Discharge Scheduled') { + frm.add_custom_button(__('Discharge'), function() { + discharge_patient(frm); + } ); + } + } + }, + btn_transfer: function(frm) { + transfer_patient_dialog(frm); + } +}); + +let discharge_patient = function(frm) { + frappe.call({ + doc: frm.doc, + method: 'discharge', + callback: function(data) { + if (!data.exc) { + frm.reload_doc(); + } + }, + freeze: true, + freeze_message: __('Processing Inpatient Discharge') + }); +}; + +let admit_patient_dialog = function(frm) { + let dialog = new frappe.ui.Dialog({ + title: 'Admit Patient', + width: 100, + fields: [ + {fieldtype: 'Link', label: 'Service Unit Type', fieldname: 'service_unit_type', + options: 'Healthcare Service Unit Type', default: frm.doc.admission_service_unit_type + }, + {fieldtype: 'Link', label: 'Service Unit', fieldname: 'service_unit', + options: 'Healthcare Service Unit', reqd: 1 + }, + {fieldtype: 'Datetime', label: 'Admission Datetime', fieldname: 'check_in', + reqd: 1, default: frappe.datetime.now_datetime() + }, + {fieldtype: 'Date', label: 'Expected Discharge', fieldname: 'expected_discharge', + default: frm.doc.expected_length_of_stay ? frappe.datetime.add_days(frappe.datetime.now_datetime(), frm.doc.expected_length_of_stay) : '' + } + ], + primary_action_label: __('Admit'), + primary_action : function(){ + let service_unit = dialog.get_value('service_unit'); + let check_in = dialog.get_value('check_in'); + let expected_discharge = null; + if (dialog.get_value('expected_discharge')) { + expected_discharge = dialog.get_value('expected_discharge'); + } + if (!service_unit && !check_in) { + return; + } + frappe.call({ + doc: frm.doc, + method: 'admit', + args:{ + 'service_unit': service_unit, + 'check_in': check_in, + 'expected_discharge': expected_discharge + }, + callback: function(data) { + if (!data.exc) { + frm.reload_doc(); + } + }, + freeze: true, + freeze_message: __('Processing Patient Admission') + }); + frm.refresh_fields(); + dialog.hide(); + } + }); + + dialog.fields_dict['service_unit_type'].get_query = function() { + return { + filters: { + 'inpatient_occupancy': 1, + 'allow_appointments': 0 + } + }; + }; + dialog.fields_dict['service_unit'].get_query = function() { + return { + filters: { + 'is_group': 0, + 'company': frm.doc.company, + 'service_unit_type': dialog.get_value('service_unit_type'), + 'occupancy_status' : 'Vacant' + } + }; + }; + + dialog.show(); +}; + +let transfer_patient_dialog = function(frm) { + let dialog = new frappe.ui.Dialog({ + title: 'Transfer Patient', + width: 100, + fields: [ + {fieldtype: 'Link', label: 'Leave From', fieldname: 'leave_from', options: 'Healthcare Service Unit', reqd: 1, read_only:1}, + {fieldtype: 'Link', label: 'Service Unit Type', fieldname: 'service_unit_type', options: 'Healthcare Service Unit Type'}, + {fieldtype: 'Link', label: 'Transfer To', fieldname: 'service_unit', options: 'Healthcare Service Unit', reqd: 1}, + {fieldtype: 'Datetime', label: 'Check In', fieldname: 'check_in', reqd: 1, default: frappe.datetime.now_datetime()} + ], + primary_action_label: __('Transfer'), + primary_action : function() { + let service_unit = null; + let check_in = dialog.get_value('check_in'); + let leave_from = null; + if(dialog.get_value('leave_from')){ + leave_from = dialog.get_value('leave_from'); + } + if(dialog.get_value('service_unit')){ + service_unit = dialog.get_value('service_unit'); + } + if(check_in > frappe.datetime.now_datetime()){ + frappe.msgprint({ + title: __('Not Allowed'), + message: __('Check-in time cannot be greater than the current time'), + indicator: 'red' + }); + return; + } + frappe.call({ + doc: frm.doc, + method: 'transfer', + args:{ + 'service_unit': service_unit, + 'check_in': check_in, + 'leave_from': leave_from + }, + callback: function(data) { + if (!data.exc) { + frm.reload_doc(); + } + }, + freeze: true, + freeze_message: __('Process Transfer') + }); + frm.refresh_fields(); + dialog.hide(); + } + }); + + dialog.fields_dict['leave_from'].get_query = function(){ + return { + query : 'healthcare.healthcare.doctype.inpatient_record.inpatient_record.get_leave_from', + filters: {docname:frm.doc.name} + }; + }; + dialog.fields_dict['service_unit_type'].get_query = function(){ + return { + filters: { + 'inpatient_occupancy': 1, + 'allow_appointments': 0 + } + }; + }; + dialog.fields_dict['service_unit'].get_query = function(){ + return { + filters: { + 'is_group': 0, + 'service_unit_type': dialog.get_value('service_unit_type'), + 'occupancy_status' : 'Vacant' + } + }; + }; + + dialog.show(); + + let not_left_service_unit = null; + for (let inpatient_occupancy in frm.doc.inpatient_occupancies) { + if (frm.doc.inpatient_occupancies[inpatient_occupancy].left != 1) { + not_left_service_unit = frm.doc.inpatient_occupancies[inpatient_occupancy].service_unit; + } + } + dialog.set_values({ + 'leave_from': not_left_service_unit + }); +}; + +var schedule_discharge = function(frm) { + var dialog = new frappe.ui.Dialog ({ + title: 'Inpatient Discharge', + fields: [ + { + fieldtype: 'Link', + label: 'Discharge Practitioner', + fieldname: 'discharge_practitioner', + options: 'Healthcare Practitioner' + }, + { + fieldtype: 'Datetime', + label: 'Discharge Ordered DateTime', + fieldname: 'discharge_ordered_datetime', + default: frappe.datetime.now_datetime() + }, + { + fieldtype: 'Date', + label: 'Followup Date', + fieldname: 'followup_date' + }, + { + fieldtype: 'Column Break' + }, + { + fieldtype: 'Small Text', + label: 'Discharge Instructions', + fieldname: 'discharge_instructions' + }, + { + fieldtype: 'Section Break', + label:'Discharge Summary' + }, + { + fieldtype: 'Long Text', + label: 'Discharge Note', + fieldname: 'discharge_note' + } + ], + primary_action_label: __('Order Discharge'), + primary_action : function() { + var args = { + patient: frm.doc.patient, + discharge_practitioner: dialog.get_value('discharge_practitioner'), + discharge_ordered_datetime: dialog.get_value('discharge_ordered_datetime'), + followup_date: dialog.get_value('followup_date'), + discharge_instructions: dialog.get_value('discharge_instructions'), + discharge_note: dialog.get_value('discharge_note') + } + frappe.call ({ + method: 'healthcare.healthcare.doctype.inpatient_record.inpatient_record.schedule_discharge', + args: {args}, + callback: function(data) { + if(!data.exc){ + frm.reload_doc(); + } + }, + freeze: true, + freeze_message: 'Scheduling Inpatient Discharge' + }); + frm.refresh_fields(); + dialog.hide(); + } + }); + + dialog.show(); + dialog.$wrapper.find('.modal-dialog').css('width', '800px'); +}; + +let cancel_ip_order = function(frm) { + frappe.prompt([ + { + fieldname: 'reason_for_cancellation', + label: __('Reason for Cancellation'), + fieldtype: 'Small Text', + reqd: 1 + } + ], + function(data) { + frappe.call({ + method: 'healthcare.healthcare.doctype.inpatient_record.inpatient_record.set_ip_order_cancelled', + async: false, + freeze: true, + args: { + inpatient_record: frm.doc.name, + reason: data.reason_for_cancellation + }, + callback: function(r) { + if (!r.exc) frm.reload_doc(); + } + }); + }, __('Reason for Cancellation'), __('Submit')); +} diff --git a/healthcare/healthcare/doctype/inpatient_record/inpatient_record.json b/healthcare/healthcare/doctype/inpatient_record/inpatient_record.json new file mode 100644 index 0000000..b8a00a1 --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_record/inpatient_record.json @@ -0,0 +1,590 @@ +{ + "actions": [], + "autoname": "naming_series:", + "creation": "2018-07-11 17:48:51.404139", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "section_break_1", + "naming_series", + "patient", + "patient_name", + "gender", + "blood_group", + "dob", + "mobile", + "email", + "phone", + "column_break_8", + "company", + "status", + "scheduled_date", + "admitted_datetime", + "expected_discharge", + "references", + "admission_encounter", + "admission_practitioner", + "medical_department", + "admission_ordered_for", + "admission_service_unit_type", + "admission_nursing_checklist_template", + "discharge_nursing_checklist_template", + "expected_length_of_stay", + "cb_admission", + "primary_practitioner", + "secondary_practitioner", + "admission_instruction", + "encounter_details_section", + "chief_complaint", + "column_break_29", + "diagnosis", + "medication_section", + "drug_prescription", + "investigations_section", + "lab_test_prescription", + "procedures_section", + "procedure_prescription", + "rehabilitation_section", + "therapy_plan", + "therapies", + "sb_inpatient_occupancy", + "inpatient_occupancies", + "btn_transfer", + "sb_discharge_details", + "discharge_ordered_date", + "discharge_practitioner", + "discharge_encounter", + "discharge_datetime", + "cb_discharge", + "discharge_instructions", + "followup_date", + "sb_discharge_note", + "discharge_note", + "cancellation_details_section", + "reason_for_cancellation" + ], + "fields": [ + { + "fieldname": "section_break_1", + "fieldtype": "Section Break" + }, + { + "fieldname": "naming_series", + "fieldtype": "Select", + "hidden": 1, + "label": "Series", + "options": "HLC-INP-.YYYY.-" + }, + { + "fieldname": "patient", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Patient", + "options": "Patient", + "reqd": 1, + "set_only_once": 1 + }, + { + "fetch_from": "patient.patient_name", + "fieldname": "patient_name", + "fieldtype": "Data", + "label": "Patient Name", + "read_only": 1 + }, + { + "fetch_from": "patient.sex", + "fieldname": "gender", + "fieldtype": "Link", + "label": "Gender", + "options": "Gender", + "read_only": 1 + }, + { + "fetch_from": "patient.blood_group", + "fieldname": "blood_group", + "fieldtype": "Select", + "label": "Blood Group", + "options": "\nA Positive\nA Negative\nAB Positive\nAB Negative\nB Positive\nB Negative\nO Positive\nO Negative", + "read_only": 1 + }, + { + "fetch_from": "patient.dob", + "fieldname": "dob", + "fieldtype": "Date", + "label": "Date of birth", + "read_only": 1 + }, + { + "fetch_from": "patient.mobile", + "fieldname": "mobile", + "fieldtype": "Data", + "label": "Mobile", + "read_only": 1 + }, + { + "fetch_from": "patient.email", + "fieldname": "email", + "fieldtype": "Data", + "label": "Email", + "options": "Email", + "read_only": 1 + }, + { + "fetch_from": "patient.phone", + "fieldname": "phone", + "fieldtype": "Data", + "label": "Phone", + "read_only": 1 + }, + { + "fieldname": "medical_department", + "fieldtype": "Link", + "label": "Medical Department", + "mandatory_depends_on": "eval:!doc.admission_encounter;", + "options": "Medical Department", + "set_only_once": 1 + }, + { + "fieldname": "primary_practitioner", + "fieldtype": "Link", + "label": "Healthcare Practitioner (Primary)", + "mandatory_depends_on": "eval:!doc.admission_encounter;", + "options": "Healthcare Practitioner" + }, + { + "fieldname": "secondary_practitioner", + "fieldtype": "Link", + "label": "Healthcare Practitioner (Secondary)", + "options": "Healthcare Practitioner" + }, + { + "fieldname": "column_break_8", + "fieldtype": "Column Break" + }, + { + "default": "Admission Scheduled", + "fieldname": "status", + "fieldtype": "Select", + "in_list_view": 1, + "label": "Status", + "options": "Admission Scheduled\nAdmitted\nDischarge Scheduled\nDischarged\nCancelled", + "read_only": 1 + }, + { + "default": "Today", + "fieldname": "scheduled_date", + "fieldtype": "Date", + "in_list_view": 1, + "label": "Admission Schedule Date", + "read_only": 1, + "reqd": 1 + }, + { + "fieldname": "admission_ordered_for", + "fieldtype": "Date", + "label": "Admission Ordered For", + "read_only": 1 + }, + { + "fieldname": "admitted_datetime", + "fieldtype": "Datetime", + "in_list_view": 1, + "label": "Admitted Datetime", + "permlevel": 2 + }, + { + "fieldname": "expected_length_of_stay", + "fieldtype": "Int", + "label": "Expected Length of Stay", + "mandatory_depends_on": "eval:!doc.admission_encounter;", + "set_only_once": 1 + }, + { + "fieldname": "expected_discharge", + "fieldtype": "Date", + "in_list_view": 1, + "label": "Expected Discharge", + "read_only": 1 + }, + { + "collapsible": 1, + "fieldname": "references", + "fieldtype": "Section Break", + "label": "Admission Order Details" + }, + { + "fieldname": "cb_admission", + "fieldtype": "Column Break" + }, + { + "fieldname": "admission_practitioner", + "fieldtype": "Link", + "label": "Healthcare Practitioner", + "options": "Healthcare Practitioner", + "read_only": 1 + }, + { + "fieldname": "admission_encounter", + "fieldtype": "Link", + "label": "Patient Encounter", + "options": "Patient Encounter", + "read_only": 1 + }, + { + "fieldname": "chief_complaint", + "fieldtype": "Table MultiSelect", + "label": "Chief Complaint", + "options": "Patient Encounter Symptom", + "permlevel": 1 + }, + { + "fieldname": "admission_instruction", + "fieldtype": "Small Text", + "label": "Admission Instructions", + "set_only_once": 1 + }, + { + "fieldname": "cb_discharge", + "fieldtype": "Column Break" + }, + { + "fieldname": "discharge_practitioner", + "fieldtype": "Link", + "label": "Healthcare Practitioner", + "options": "Healthcare Practitioner", + "read_only": 1 + }, + { + "fieldname": "discharge_encounter", + "fieldtype": "Link", + "label": "Patient Encounter", + "options": "Patient Encounter", + "read_only": 1 + }, + { + "collapsible": 1, + "depends_on": "eval:!doc.__islocal;", + "fieldname": "medication_section", + "fieldtype": "Section Break", + "label": "Medications", + "permlevel": 1 + }, + { + "fieldname": "drug_prescription", + "fieldtype": "Table", + "options": "Drug Prescription", + "permlevel": 1 + }, + { + "collapsible": 1, + "depends_on": "eval:!doc.__islocal;", + "fieldname": "investigations_section", + "fieldtype": "Section Break", + "label": "Investigations", + "permlevel": 1 + }, + { + "fieldname": "lab_test_prescription", + "fieldtype": "Table", + "options": "Lab Prescription", + "permlevel": 1 + }, + { + "collapsible": 1, + "depends_on": "eval:!doc.__islocal;", + "fieldname": "procedures_section", + "fieldtype": "Section Break", + "label": "Procedures", + "permlevel": 1 + }, + { + "fieldname": "procedure_prescription", + "fieldtype": "Table", + "options": "Procedure Prescription", + "permlevel": 1 + }, + { + "depends_on": "eval:(doc.status != \"Admission Scheduled\")", + "fieldname": "sb_inpatient_occupancy", + "fieldtype": "Section Break", + "label": "Inpatient Occupancy" + }, + { + "fieldname": "admission_service_unit_type", + "fieldtype": "Link", + "label": "Admission Service Unit Type", + "mandatory_depends_on": "eval:!doc.admission_encounter;", + "options": "Healthcare Service Unit Type", + "set_only_once": 1 + }, + { + "fieldname": "inpatient_occupancies", + "fieldtype": "Table", + "options": "Inpatient Occupancy", + "permlevel": 2 + }, + { + "depends_on": "eval:doc.status == 'Admitted';", + "fieldname": "btn_transfer", + "fieldtype": "Button", + "label": "Transfer" + }, + { + "depends_on": "eval:(doc.status == \"Discharge Scheduled\" || doc.status == \"Discharged\")", + "fieldname": "sb_discharge_note", + "fieldtype": "Section Break", + "label": "Discharge Notes" + }, + { + "fieldname": "discharge_note", + "fieldtype": "Text Editor", + "permlevel": 1 + }, + { + "fetch_from": "admission_encounter.company", + "fieldname": "company", + "fieldtype": "Link", + "in_standard_filter": 1, + "label": "Company", + "options": "Company" + }, + { + "collapsible": 1, + "collapsible_depends_on": "eval:(doc.status == \"Admitted\")", + "depends_on": "eval:!doc.__islocal", + "fieldname": "encounter_details_section", + "fieldtype": "Section Break", + "label": "Encounter Impression", + "permlevel": 1 + }, + { + "fieldname": "column_break_29", + "fieldtype": "Column Break" + }, + { + "fieldname": "diagnosis", + "fieldtype": "Table MultiSelect", + "label": "Diagnosis", + "options": "Patient Encounter Diagnosis", + "permlevel": 1 + }, + { + "fieldname": "followup_date", + "fieldtype": "Date", + "label": "Follow Up Date" + }, + { + "collapsible": 1, + "depends_on": "eval:(doc.status == \"Discharge Scheduled\" || doc.status == \"Discharged\")", + "fieldname": "sb_discharge_details", + "fieldtype": "Section Break", + "label": "Discharge Details" + }, + { + "fieldname": "discharge_instructions", + "fieldtype": "Small Text", + "label": "Discharge Instructions" + }, + { + "fieldname": "discharge_ordered_date", + "fieldtype": "Date", + "in_list_view": 1, + "label": "Discharge Ordered Date", + "read_only": 1 + }, + { + "collapsible": 1, + "depends_on": "eval:!doc.__islocal;", + "fieldname": "rehabilitation_section", + "fieldtype": "Section Break", + "label": "Rehabilitation", + "permlevel": 1 + }, + { + "fieldname": "therapy_plan", + "fieldtype": "Link", + "hidden": 1, + "label": "Therapy Plan", + "options": "Therapy Plan", + "permlevel": 1, + "read_only": 1 + }, + { + "fieldname": "therapies", + "fieldtype": "Table", + "options": "Therapy Plan Detail", + "permlevel": 1 + }, + { + "fieldname": "discharge_datetime", + "fieldtype": "Datetime", + "label": "Discharge Date", + "permlevel": 2 + }, + { + "fieldname": "discharge_nursing_checklist_template", + "fieldtype": "Link", + "label": "Discharge Nursing Checklist Template", + "options": "Nursing Checklist Template" + }, + { + "fieldname": "admission_nursing_checklist_template", + "fieldtype": "Link", + "label": "Admission Nursing Checklist Template", + "options": "Nursing Checklist Template" + } + ], + "index_web_pages_for_search": 1, + "links": [ + { + "group": "Appointments", + "link_doctype": "Patient Appointment", + "link_fieldname": "inpatient_record" + }, + { + "group": "Clinical", + "link_doctype": "Patient Encounter", + "link_fieldname": "inpatient_record" + }, + { + "group": "Clinical", + "link_doctype": "Clinical Procedure", + "link_fieldname": "inpatient_record" + }, + { + "group": "Laboratory", + "link_doctype": "Sample Collection", + "link_fieldname": "inpatient_record" + }, + { + "group": "Laboratory", + "link_doctype": "Lab Test", + "link_fieldname": "inpatient_record" + }, + { + "group": "Nursing", + "link_doctype": "Nursing Task", + "link_fieldname": "reference_name" + }, + { + "group": "Nursing", + "link_doctype": "Vital Signs", + "link_fieldname": "inpatient_record" + }, + { + "collapsible": 1, + "fieldname": "cancellation_details_section", + "fieldtype": "Section Break", + "label": "Cancellation Details" + }, + { + "fieldname": "reason_for_cancellation", + "fieldtype": "Small Text", + "label": "Reason for Cancellation", + "read_only": 1 + } + ], + "index_web_pages_for_search": 1, + "links": [], + "modified": "2022-04-28 17:26:28.973945", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Inpatient Record", + "naming_rule": "By \"Naming Series\" field", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Nursing User", + "share": 1, + "write": 1 + }, + { + "permlevel": 1, + "read": 1, + "role": "Physician", + "write": 1 + }, + { + "permlevel": 1, + "read": 1, + "report": 1, + "role": "Nursing User" + }, + { + "email": 1, + "export": 1, + "permlevel": 2, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + }, + { + "email": 1, + "export": 1, + "permlevel": 2, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1 + }, + { + "email": 1, + "export": 1, + "permlevel": 2, + "print": 1, + "read": 1, + "report": 1, + "role": "Nursing User", + "share": 1 + } + ], + "links": [ + { + "link_doctype": "Nursing Task", + "link_fieldname": "reference_name" + } + ], + "restrict_to_domain": "Healthcare", + "search_fields": "patient", + "sort_field": "modified", + "sort_order": "DESC", + "states": [], + "title_field": "patient", + "track_changes": 1 +} diff --git a/healthcare/healthcare/doctype/inpatient_record/inpatient_record.py b/healthcare/healthcare/doctype/inpatient_record/inpatient_record.py new file mode 100644 index 0000000..44fb84c --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_record/inpatient_record.py @@ -0,0 +1,381 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018, InfluxERP +# For license information, please see license.txt + + +import json + +import frappe +from frappe import _ +from frappe.desk.reportview import get_match_cond +from frappe.model.document import Document +from frappe.utils import get_datetime, get_link_to_form, getdate, now_datetime, today +from healthcare.healthcare.doctype.nursing_task.nursing_task import NursingTask +from healthcare.healthcare.utils import validate_nursing_tasks + + +class InpatientRecord(Document): + def after_insert(self): + frappe.db.set_value("Patient", self.patient, "inpatient_record", self.name) + frappe.db.set_value("Patient", self.patient, "inpatient_status", self.status) + + if self.admission_encounter: # Update encounter + frappe.db.set_value( + "Patient Encounter", self.admission_encounter, "inpatient_record", self.name + ) + frappe.db.set_value( + "Patient Encounter", self.admission_encounter, "inpatient_status", self.status + ) + + if self.admission_nursing_checklist_template: + NursingTask.create_nursing_tasks_from_template( + template=self.admission_nursing_checklist_template, + doc=self, + ) + + def validate(self): + self.validate_dates() + self.validate_already_scheduled_or_admitted() + if self.status in ["Discharged", "Cancelled"]: + frappe.db.set_value( + "Patient", self.patient, {"inpatient_status": None, "inpatient_record": None} + ) + + def validate_dates(self): + if (getdate(self.expected_discharge) < getdate(self.scheduled_date)) or ( + getdate(self.discharge_ordered_date) < getdate(self.scheduled_date) + ): + frappe.throw(_("Expected and Discharge dates cannot be less than Admission Schedule date")) + + for entry in self.inpatient_occupancies: + if ( + entry.check_in + and entry.check_out + and get_datetime(entry.check_in) > get_datetime(entry.check_out) + ): + frappe.throw( + _("Row #{0}: Check Out datetime cannot be less than Check In datetime").format(entry.idx) + ) + + def validate_already_scheduled_or_admitted(self): + query = """ + select name, status + from `tabInpatient Record` + where (status = 'Admitted' or status = 'Admission Scheduled') + and name != %(name)s and patient = %(patient)s + """ + + ip_record = frappe.db.sql(query, {"name": self.name, "patient": self.patient}, as_dict=1) + + if ip_record: + msg = _( + ("Already {0} Patient {1} with Inpatient Record ").format(ip_record[0].status, self.patient) + + """ {0}""".format(ip_record[0].name) + ) + frappe.throw(msg) + + @frappe.whitelist() + def admit(self, service_unit, check_in, expected_discharge=None): + admit_patient(self, service_unit, check_in, expected_discharge) + + @frappe.whitelist() + def discharge(self): + discharge_patient(self) + + @frappe.whitelist() + def transfer(self, service_unit, check_in, leave_from): + if leave_from: + patient_leave_service_unit(self, check_in, leave_from) + if service_unit: + transfer_patient(self, service_unit, check_in) + + +@frappe.whitelist() +def schedule_inpatient(args): + admission_order = json.loads(args) # admission order via Encounter + if ( + not admission_order + or not admission_order["patient"] + or not admission_order["admission_encounter"] + ): + frappe.throw(_("Missing required details, did not create Inpatient Record")) + + inpatient_record = frappe.new_doc("Inpatient Record") + + # Admission order details + set_details_from_ip_order(inpatient_record, admission_order) + + # Patient details + patient = frappe.get_doc("Patient", admission_order["patient"]) + inpatient_record.patient = patient.name + inpatient_record.patient_name = patient.patient_name + inpatient_record.gender = patient.sex + inpatient_record.blood_group = patient.blood_group + inpatient_record.dob = patient.dob + inpatient_record.mobile = patient.mobile + inpatient_record.email = patient.email + inpatient_record.phone = patient.phone + inpatient_record.scheduled_date = today() + + # Set encounter details + encounter = frappe.get_doc("Patient Encounter", admission_order["admission_encounter"]) + if encounter and encounter.symptoms: # Symptoms + set_ip_child_records(inpatient_record, "chief_complaint", encounter.symptoms) + + if encounter and encounter.diagnosis: # Diagnosis + set_ip_child_records(inpatient_record, "diagnosis", encounter.diagnosis) + + if encounter and encounter.drug_prescription: # Medication + set_ip_child_records(inpatient_record, "drug_prescription", encounter.drug_prescription) + + if encounter and encounter.lab_test_prescription: # Lab Tests + set_ip_child_records(inpatient_record, "lab_test_prescription", encounter.lab_test_prescription) + + if encounter and encounter.procedure_prescription: # Procedure Prescription + set_ip_child_records( + inpatient_record, "procedure_prescription", encounter.procedure_prescription + ) + + if encounter and encounter.therapies: # Therapies + inpatient_record.therapy_plan = encounter.therapy_plan + set_ip_child_records(inpatient_record, "therapies", encounter.therapies) + + inpatient_record.status = "Admission Scheduled" + inpatient_record.save(ignore_permissions=True) + + +@frappe.whitelist() +def schedule_discharge(args): + discharge_order = json.loads(args) + inpatient_record_id = frappe.db.get_value( + "Patient", discharge_order["patient"], "inpatient_record" + ) + + if inpatient_record_id: + + inpatient_record = frappe.get_doc("Inpatient Record", inpatient_record_id) + check_out_inpatient(inpatient_record) + set_details_from_ip_order(inpatient_record, discharge_order) + inpatient_record.status = "Discharge Scheduled" + inpatient_record.save(ignore_permissions=True) + + frappe.db.set_value( + "Patient", discharge_order["patient"], "inpatient_status", inpatient_record.status + ) + if inpatient_record.discharge_encounter: + frappe.db.set_value( + "Patient Encounter", + inpatient_record.discharge_encounter, + "inpatient_status", + inpatient_record.status, + ) + + if inpatient_record.discharge_nursing_checklist_template: + NursingTask.create_nursing_tasks_from_template( + inpatient_record.discharge_nursing_checklist_template, + inpatient_record, + start_time=now_datetime(), + ) + + +def set_details_from_ip_order(inpatient_record, ip_order): + for key in ip_order: + inpatient_record.set(key, ip_order[key]) + + +def set_ip_child_records(inpatient_record, inpatient_record_child, encounter_child): + for item in encounter_child: + table = inpatient_record.append(inpatient_record_child) + for df in table.meta.get("fields"): + table.set(df.fieldname, item.get(df.fieldname)) + + +def check_out_inpatient(inpatient_record): + if inpatient_record.inpatient_occupancies: + for inpatient_occupancy in inpatient_record.inpatient_occupancies: + if inpatient_occupancy.left != 1: + inpatient_occupancy.left = True + inpatient_occupancy.check_out = now_datetime() + frappe.db.set_value( + "Healthcare Service Unit", inpatient_occupancy.service_unit, "occupancy_status", "Vacant" + ) + + +def discharge_patient(inpatient_record): + validate_nursing_tasks(inpatient_record) + + validate_inpatient_invoicing(inpatient_record) + + inpatient_record.discharge_datetime = now_datetime() + inpatient_record.status = "Discharged" + + inpatient_record.save(ignore_permissions=True) + + +def validate_inpatient_invoicing(inpatient_record): + if frappe.db.get_single_value("Healthcare Settings", "allow_discharge_despite_unbilled_services"): + return + + pending_invoices = get_pending_invoices(inpatient_record) + + if pending_invoices: + message = _("Cannot mark Inpatient Record as Discharged since there are unbilled services. ") + + formatted_doc_rows = "" + + for doctype, docnames in pending_invoices.items(): + formatted_doc_rows += """ + {0} + {1} + """.format( + doctype, docnames + ) + + message += """ + + + + + + {2} +
{0}{1}
+ """.format( + _("Healthcare Service"), _("Documents"), formatted_doc_rows + ) + + frappe.throw(message, title=_("Unbilled Services"), is_minimizable=True, wide=True) + + +def get_pending_invoices(inpatient_record): + pending_invoices = {} + if inpatient_record.inpatient_occupancies: + service_unit_names = False + for inpatient_occupancy in inpatient_record.inpatient_occupancies: + if not inpatient_occupancy.invoiced: + if is_service_unit_billable(inpatient_occupancy.service_unit): + if service_unit_names: + service_unit_names += ", " + inpatient_occupancy.service_unit + else: + service_unit_names = inpatient_occupancy.service_unit + if service_unit_names: + pending_invoices["Inpatient Occupancy"] = service_unit_names + + docs = ["Patient Appointment", "Patient Encounter", "Lab Test", "Clinical Procedure"] + + for doc in docs: + doc_name_list = get_unbilled_inpatient_docs(doc, inpatient_record) + if doc_name_list: + pending_invoices = get_pending_doc(doc, doc_name_list, pending_invoices) + + return pending_invoices + + +def get_pending_doc(doc, doc_name_list, pending_invoices): + if doc_name_list: + doc_ids = False + for doc_name in doc_name_list: + doc_link = get_link_to_form(doc, doc_name.name) + if doc_ids: + doc_ids += ", " + doc_link + else: + doc_ids = doc_link + if doc_ids: + pending_invoices[doc] = doc_ids + + return pending_invoices + + +def get_unbilled_inpatient_docs(doc, inpatient_record): + return frappe.db.get_list( + doc, + filters={ + "patient": inpatient_record.patient, + "inpatient_record": inpatient_record.name, + "docstatus": 1, + "invoiced": 0, + }, + ) + + +def admit_patient(inpatient_record, service_unit, check_in, expected_discharge=None): + validate_nursing_tasks(inpatient_record) + + inpatient_record.admitted_datetime = check_in + inpatient_record.status = "Admitted" + inpatient_record.expected_discharge = expected_discharge + + inpatient_record.set("inpatient_occupancies", []) + transfer_patient(inpatient_record, service_unit, check_in) + + frappe.db.set_value( + "Patient", + inpatient_record.patient, + {"inpatient_status": "Admitted", "inpatient_record": inpatient_record.name}, + ) + + +def transfer_patient(inpatient_record, service_unit, check_in): + item_line = inpatient_record.append("inpatient_occupancies", {}) + item_line.service_unit = service_unit + item_line.check_in = check_in + + inpatient_record.save(ignore_permissions=True) + + frappe.db.set_value("Healthcare Service Unit", service_unit, "occupancy_status", "Occupied") + + +def patient_leave_service_unit(inpatient_record, check_out, leave_from): + if inpatient_record.inpatient_occupancies: + for inpatient_occupancy in inpatient_record.inpatient_occupancies: + if inpatient_occupancy.left != 1 and inpatient_occupancy.service_unit == leave_from: + inpatient_occupancy.left = True + inpatient_occupancy.check_out = check_out + frappe.db.set_value( + "Healthcare Service Unit", inpatient_occupancy.service_unit, "occupancy_status", "Vacant" + ) + inpatient_record.save(ignore_permissions=True) + + +@frappe.whitelist() +@frappe.validate_and_sanitize_search_inputs +def get_leave_from(doctype, txt, searchfield, start, page_len, filters): + docname = filters["docname"] + + query = """select io.service_unit + from `tabInpatient Occupancy` io, `tabInpatient Record` ir + where io.parent = '{docname}' and io.parentfield = 'inpatient_occupancies' + and io.left!=1 and io.parent = ir.name""" + + return frappe.db.sql( + query.format( + **{"docname": docname, "searchfield": searchfield, "mcond": get_match_cond(doctype)} + ), + {"txt": "%%%s%%" % txt, "_txt": txt.replace("%", ""), "start": start, "page_len": page_len}, + ) + + +def is_service_unit_billable(service_unit): + service_unit_doc = frappe.qb.DocType("Healthcare Service Unit") + service_unit_type = frappe.qb.DocType("Healthcare Service Unit Type") + result = ( + frappe.qb.from_(service_unit_doc) + .left_join(service_unit_type) + .on(service_unit_doc.service_unit_type == service_unit_type.name) + .select(service_unit_type.is_billable) + .where(service_unit_doc.name == service_unit) + ).run(as_dict=1) + return result[0].get("is_billable", 0) + + +@frappe.whitelist() +def set_ip_order_cancelled(inpatient_record, reason, encounter=None): + inpatient_record = frappe.get_doc("Inpatient Record", inpatient_record) + if inpatient_record.status == "Admission Scheduled": + inpatient_record.status = "Cancelled" + inpatient_record.reason_for_cancellation = reason + inpatient_record.save(ignore_permissions=True) + encounter_name = encounter if encounter else inpatient_record.admission_encounter + if encounter_name: + frappe.db.set_value( + "Patient Encounter", encounter_name, {"inpatient_status": None, "inpatient_record": None} + ) diff --git a/healthcare/healthcare/doctype/inpatient_record/inpatient_record_list.js b/healthcare/healthcare/doctype/inpatient_record/inpatient_record_list.js new file mode 100644 index 0000000..18839c2 --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_record/inpatient_record_list.js @@ -0,0 +1,17 @@ +// Copyright (c) 2021, healthcare and contributors +// For license information, please see license.txt + +frappe.listview_settings['Inpatient Record'] = { + filters: [['status', 'not in', ['Discharged']]], + get_indicator: function (doc) { + if (doc.status === 'Admission Scheduled') { + return [__('Admission Scheduled'), 'red', 'status, =, Admission Scheduled']; + } else if (doc.status === 'Admitted') { + return [__('Admitted'), 'blue', 'status, =, Admitted']; + } else if (doc.status === 'Discharge Scheduled') { + return [__('Discharge Scheduled'), 'orange', 'status, =, Discharge Scheduled']; + } else if (doc.status === 'Discharged') { + return [__('Discharged'), 'green', 'status, =, Discharged']; + } + } +}; \ No newline at end of file diff --git a/healthcare/healthcare/doctype/inpatient_record/test_inpatient_record.py b/healthcare/healthcare/doctype/inpatient_record/test_inpatient_record.py new file mode 100644 index 0000000..673c49c --- /dev/null +++ b/healthcare/healthcare/doctype/inpatient_record/test_inpatient_record.py @@ -0,0 +1,220 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +import frappe +from frappe.utils import now_datetime, today +from frappe.utils.make_random import get_random + +from healthcare.healthcare.doctype.inpatient_record.inpatient_record import ( + admit_patient, + discharge_patient, + schedule_discharge, +) +from healthcare.healthcare.doctype.lab_test.test_lab_test import create_patient_encounter +from healthcare.healthcare.utils import get_encounters_to_invoice + + +class TestInpatientRecord(FrappeTestCase): + def test_admit_and_discharge(self): + frappe.db.sql("""delete from `tabInpatient Record`""") + patient = create_patient() + # Schedule Admission + ip_record = create_inpatient(patient) + ip_record.expected_length_of_stay = 0 + ip_record.save(ignore_permissions=True) + self.assertEqual(ip_record.name, frappe.db.get_value("Patient", patient, "inpatient_record")) + self.assertEqual(ip_record.status, frappe.db.get_value("Patient", patient, "inpatient_status")) + + # Admit + service_unit = get_healthcare_service_unit() + admit_patient(ip_record, service_unit, now_datetime()) + self.assertEqual("Admitted", frappe.db.get_value("Patient", patient, "inpatient_status")) + self.assertEqual( + "Occupied", frappe.db.get_value("Healthcare Service Unit", service_unit, "occupancy_status") + ) + + # Discharge + schedule_discharge(frappe.as_json({"patient": patient})) + self.assertEqual( + "Vacant", frappe.db.get_value("Healthcare Service Unit", service_unit, "occupancy_status") + ) + + ip_record1 = frappe.get_doc("Inpatient Record", ip_record.name) + # Validate Pending Invoices + self.assertRaises(frappe.ValidationError, ip_record.discharge) + mark_invoiced_inpatient_occupancy(ip_record1) + + discharge_patient(ip_record1) + + self.assertEqual(None, frappe.db.get_value("Patient", patient, "inpatient_record")) + self.assertEqual(None, frappe.db.get_value("Patient", patient, "inpatient_status")) + + def test_allow_discharge_despite_unbilled_services(self): + frappe.db.sql("""delete from `tabInpatient Record`""") + setup_inpatient_settings(key="allow_discharge_despite_unbilled_services", value=1) + patient = create_patient() + # Schedule Admission + ip_record = create_inpatient(patient) + ip_record.expected_length_of_stay = 0 + ip_record.save(ignore_permissions=True) + + # Admit + service_unit = get_healthcare_service_unit() + admit_patient(ip_record, service_unit, now_datetime()) + + # Discharge + schedule_discharge(frappe.as_json({"patient": patient})) + self.assertEqual( + "Vacant", frappe.db.get_value("Healthcare Service Unit", service_unit, "occupancy_status") + ) + + ip_record = frappe.get_doc("Inpatient Record", ip_record.name) + # Should not validate Pending Invoices + ip_record.discharge() + + self.assertEqual(None, frappe.db.get_value("Patient", patient, "inpatient_record")) + self.assertEqual(None, frappe.db.get_value("Patient", patient, "inpatient_status")) + + setup_inpatient_settings(key="allow_discharge_despite_unbilled_services", value=0) + + def test_do_not_bill_patient_encounters_for_inpatients(self): + frappe.db.sql("""delete from `tabInpatient Record`""") + setup_inpatient_settings(key="do_not_bill_inpatient_encounters", value=1) + patient = create_patient() + # Schedule Admission + ip_record = create_inpatient(patient) + ip_record.expected_length_of_stay = 0 + ip_record.save(ignore_permissions=True) + + # Admit + service_unit = get_healthcare_service_unit() + admit_patient(ip_record, service_unit, now_datetime()) + + # Patient Encounter + patient_encounter = create_patient_encounter() + encounters = get_encounters_to_invoice(patient, "_Test Company") + encounter_ids = [entry.reference_name for entry in encounters] + self.assertFalse(patient_encounter.name in encounter_ids) + + # Discharge + schedule_discharge(frappe.as_json({"patient": patient})) + self.assertEqual( + "Vacant", frappe.db.get_value("Healthcare Service Unit", service_unit, "occupancy_status") + ) + + ip_record = frappe.get_doc("Inpatient Record", ip_record.name) + mark_invoiced_inpatient_occupancy(ip_record) + discharge_patient(ip_record) + setup_inpatient_settings(key="do_not_bill_inpatient_encounters", value=0) + + def test_validate_overlap_admission(self): + frappe.db.sql("""delete from `tabInpatient Record`""") + patient = create_patient() + + ip_record = create_inpatient(patient) + ip_record.expected_length_of_stay = 0 + ip_record.save(ignore_permissions=True) + ip_record_new = create_inpatient(patient) + ip_record_new.expected_length_of_stay = 0 + self.assertRaises(frappe.ValidationError, ip_record_new.save) + + service_unit = get_healthcare_service_unit() + admit_patient(ip_record, service_unit, now_datetime()) + ip_record_new = create_inpatient(patient) + self.assertRaises(frappe.ValidationError, ip_record_new.save) + frappe.db.sql("""delete from `tabInpatient Record`""") + + +def mark_invoiced_inpatient_occupancy(ip_record): + if ip_record.inpatient_occupancies: + for inpatient_occupancy in ip_record.inpatient_occupancies: + inpatient_occupancy.invoiced = 1 + ip_record.save(ignore_permissions=True) + + +def setup_inpatient_settings(key, value): + settings = frappe.get_single("Healthcare Settings") + settings.set(key, value) + settings.save() + + +def create_inpatient(patient): + patient_obj = frappe.get_doc("Patient", patient) + inpatient_record = frappe.new_doc("Inpatient Record") + inpatient_record.patient = patient + inpatient_record.patient_name = patient_obj.patient_name + inpatient_record.gender = patient_obj.sex + inpatient_record.blood_group = patient_obj.blood_group + inpatient_record.dob = patient_obj.dob + inpatient_record.mobile = patient_obj.mobile + inpatient_record.email = patient_obj.email + inpatient_record.phone = patient_obj.phone + inpatient_record.inpatient = "Scheduled" + inpatient_record.scheduled_date = today() + inpatient_record.company = "_Test Company" + return inpatient_record + + +def get_healthcare_service_unit(unit_name=None): + if not unit_name: + service_unit = get_random( + "Healthcare Service Unit", filters={"inpatient_occupancy": 1, "company": "_Test Company"} + ) + else: + service_unit = frappe.db.exists( + "Healthcare Service Unit", {"healthcare_service_unit_name": unit_name} + ) + + if not service_unit: + service_unit = frappe.new_doc("Healthcare Service Unit") + service_unit.healthcare_service_unit_name = unit_name or "_Test Service Unit Ip Occupancy" + service_unit.company = "_Test Company" + service_unit.service_unit_type = get_service_unit_type() + service_unit.inpatient_occupancy = 1 + service_unit.occupancy_status = "Vacant" + service_unit.is_group = 0 + service_unit_parent_name = frappe.db.exists( + { + "doctype": "Healthcare Service Unit", + "healthcare_service_unit_name": "_Test All Healthcare Service Units", + "is_group": 1, + } + ) + if not service_unit_parent_name: + parent_service_unit = frappe.new_doc("Healthcare Service Unit") + parent_service_unit.healthcare_service_unit_name = "_Test All Healthcare Service Units" + parent_service_unit.is_group = 1 + parent_service_unit.save(ignore_permissions=True) + service_unit.parent_healthcare_service_unit = parent_service_unit.name + else: + service_unit.parent_healthcare_service_unit = service_unit_parent_name + service_unit.save(ignore_permissions=True) + return service_unit.name + return service_unit + + +def get_service_unit_type(): + service_unit_type = get_random("Healthcare Service Unit Type", filters={"inpatient_occupancy": 1}) + + if not service_unit_type: + service_unit_type = frappe.new_doc("Healthcare Service Unit Type") + service_unit_type.service_unit_type = "_Test Service Unit Type Ip Occupancy" + service_unit_type.inpatient_occupancy = 1 + service_unit_type.save(ignore_permissions=True) + return service_unit_type.name + return service_unit_type + + +def create_patient(): + patient = frappe.db.exists("Patient", "_Test IPD Patient") + if not patient: + patient = frappe.new_doc("Patient") + patient.first_name = "_Test IPD Patient" + patient.sex = "Female" + patient.save(ignore_permissions=True) + patient = patient.name + return patient diff --git a/healthcare/healthcare/doctype/lab_prescription/__init__.py b/healthcare/healthcare/doctype/lab_prescription/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/lab_prescription/lab_prescription.json b/healthcare/healthcare/doctype/lab_prescription/lab_prescription.json new file mode 100644 index 0000000..0720bb4 --- /dev/null +++ b/healthcare/healthcare/doctype/lab_prescription/lab_prescription.json @@ -0,0 +1,78 @@ +{ + "actions": [], + "allow_copy": 1, + "beta": 1, + "creation": "2016-09-16 16:53:06.882970", + "doctype": "DocType", + "document_type": "Document", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "lab_test_code", + "lab_test_name", + "invoiced", + "column_break_4", + "lab_test_comment", + "lab_test_created" + ], + "fields": [ + { + "fieldname": "lab_test_code", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "label": "Lab Test", + "options": "Lab Test Template", + "reqd": 1 + }, + { + "fetch_from": "lab_test_code.lab_test_name", + "fieldname": "lab_test_name", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Lab Test Name" + }, + { + "default": "0", + "fieldname": "invoiced", + "fieldtype": "Check", + "label": "Invoiced", + "no_copy": 1, + "read_only": 1, + "search_index": 1 + }, + { + "fieldname": "column_break_4", + "fieldtype": "Column Break" + }, + { + "fieldname": "lab_test_comment", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Comments" + }, + { + "default": "0", + "fieldname": "lab_test_created", + "fieldtype": "Check", + "hidden": 1, + "label": "Test Created", + "no_copy": 1, + "print_hide": 1, + "report_hide": 1, + "search_index": 1 + } + ], + "istable": 1, + "links": [], + "modified": "2020-02-26 17:03:00.255560", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Lab Prescription", + "owner": "Administrator", + "permissions": [], + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC" +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/lab_prescription/lab_prescription.py b/healthcare/healthcare/doctype/lab_prescription/lab_prescription.py new file mode 100644 index 0000000..ee53fb7 --- /dev/null +++ b/healthcare/healthcare/doctype/lab_prescription/lab_prescription.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and contributors +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class LabPrescription(Document): + pass diff --git a/healthcare/healthcare/doctype/lab_test/__init__.py b/healthcare/healthcare/doctype/lab_test/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/lab_test/lab_test.js b/healthcare/healthcare/doctype/lab_test/lab_test.js new file mode 100644 index 0000000..2d2b7e4 --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test/lab_test.js @@ -0,0 +1,263 @@ +// Copyright (c) 2016, ESS and contributors +// For license information, please see license.txt + +cur_frm.cscript.custom_refresh = function (doc) { + cur_frm.toggle_display('sb_sensitivity', doc.sensitivity_toggle); + cur_frm.toggle_display('organisms_section', doc.descriptive_toggle); + cur_frm.toggle_display('sb_descriptive', doc.descriptive_toggle); + cur_frm.toggle_display('sb_normal', doc.normal_toggle); + cur_frm.toggle_display('sb_descriptive_result', doc.imaging_toggle); +}; + +frappe.ui.form.on('Lab Test', { + setup: function (frm) { + frm.get_field('normal_test_items').grid.editable_fields = [ + { fieldname: 'lab_test_name', columns: 3 }, + { fieldname: 'lab_test_event', columns: 2 }, + { fieldname: 'result_value', columns: 2 }, + { fieldname: 'lab_test_uom', columns: 1 }, + { fieldname: 'normal_range', columns: 2 } + ]; + frm.get_field('descriptive_test_items').grid.editable_fields = [ + { fieldname: 'lab_test_particulars', columns: 3 }, + { fieldname: 'result_value', columns: 7 } + ]; + }, + refresh: function (frm) { + refresh_field('normal_test_items'); + refresh_field('descriptive_test_items'); + if (frm.doc.__islocal) { + frm.add_custom_button(__('Get from Patient Encounter'), function () { + get_lab_test_prescribed(frm); + }); + } + if (frappe.defaults.get_default('lab_test_approval_required') && frappe.user.has_role('LabTest Approver')) { + if (frm.doc.docstatus === 1 && frm.doc.status !== 'Approved' && frm.doc.status !== 'Rejected') { + frm.add_custom_button(__('Approve'), function () { + status_update(1, frm); + }, __('Actions')); + frm.add_custom_button(__('Reject'), function () { + status_update(0, frm); + }, __('Actions')); + } + } + + if (frm.doc.docstatus === 1 && frm.doc.sms_sent === 0 && frm.doc.status !== 'Rejected' ) { + frm.add_custom_button(__('Send SMS'), function () { + frappe.call({ + method: 'healthcare.healthcare.doctype.healthcare_settings.healthcare_settings.get_sms_text', + args: { doc: frm.doc.name }, + callback: function (r) { + if (!r.exc) { + var emailed = r.message.emailed; + var printed = r.message.printed; + make_dialog(frm, emailed, printed); + } + } + }); + }); + } + }, +}); + + +frappe.ui.form.on('Lab Test', 'patient', function (frm) { + if (frm.doc.patient) { + frappe.call({ + 'method': 'healthcare.healthcare.doctype.patient.patient.get_patient_detail', + args: { patient: frm.doc.patient }, + callback: function (data) { + var age = null; + if (data.message.dob) { + age = calculate_age(data.message.dob); + } + let values = { + 'patient_age': age, + 'patient_sex': data.message.sex, + 'email': data.message.email, + 'mobile': data.message.mobile, + 'report_preference': data.message.report_preference + }; + frm.set_value(values); + } + }); + } +}); + +frappe.ui.form.on('Normal Test Result', { + normal_test_items_remove: function () { + frappe.msgprint(__('Not permitted, configure Lab Test Template as required')); + cur_frm.reload_doc(); + } +}); + +frappe.ui.form.on('Descriptive Test Result', { + descriptive_test_items_remove: function () { + frappe.msgprint(__('Not permitted, configure Lab Test Template as required')); + cur_frm.reload_doc(); + } +}); + +var status_update = function (approve, frm) { + var doc = frm.doc; + var status = null; + if (approve == 1) { + status = 'Approved'; + } + else { + status = 'Rejected'; + } + frappe.call({ + method: 'healthcare.healthcare.doctype.lab_test.lab_test.update_status', + args: { status: status, name: doc.name }, + callback: function () { + cur_frm.reload_doc(); + } + }); +}; + +var get_lab_test_prescribed = function (frm) { + if (frm.doc.patient) { + frappe.call({ + method: 'healthcare.healthcare.doctype.lab_test.lab_test.get_lab_test_prescribed', + args: { patient: frm.doc.patient }, + callback: function (r) { + show_lab_tests(frm, r.message); + } + }); + } + else { + frappe.msgprint(__('Please select Patient to get Lab Tests')); + } +}; + +var show_lab_tests = function (frm, lab_test_list) { + var d = new frappe.ui.Dialog({ + title: __('Lab Tests'), + fields: [{ + fieldtype: 'HTML', fieldname: 'lab_test' + }] + }); + var html_field = d.fields_dict.lab_test.$wrapper; + html_field.empty(); + $.each(lab_test_list, function (x, y) { + var row = $(repl( + '
\ +
%(lab_test)s
\ +
%(practitioner_name)s
%(encounter)s
\ +
%(date)s
\ +
\ + \ +
\ +

', + { name: y[0], lab_test: y[1], encounter: y[2], invoiced: y[3], practitioner: y[4], practitioner_name: y[5], date: y[6] }) + ).appendTo(html_field); + + row.find("a").click(function () { + frm.doc.template = $(this).attr('data-lab-test'); + frm.doc.prescription = $(this).attr('data-name'); + frm.doc.practitioner = $(this).attr('data-practitioner'); + frm.set_df_property('template', 'read_only', 1); + frm.set_df_property('patient', 'read_only', 1); + frm.set_df_property('practitioner', 'read_only', 1); + frm.doc.invoiced = 0; + if ($(this).attr('data-invoiced') === 1) { + frm.doc.invoiced = 1; + } + refresh_field('invoiced'); + refresh_field('template'); + d.hide(); + return false; + }); + }); + if (!lab_test_list.length) { + var msg = __('No Lab Tests found for the Patient {0}', [frm.doc.patient_name.bold()]); + html_field.empty(); + $(repl('
%(msg)s
', { msg: msg })).appendTo(html_field); + } + d.show(); +}; + +var make_dialog = function (frm, emailed, printed) { + var number = frm.doc.mobile; + + var dialog = new frappe.ui.Dialog({ + title: 'Send SMS', + width: 400, + fields: [ + { fieldname: 'result_format', fieldtype: 'Select', label: 'Result Format', options: ['Emailed', 'Printed'] }, + { fieldname: 'number', fieldtype: 'Data', label: 'Mobile Number', reqd: 1 }, + { fieldname: 'message', fieldtype: 'Small Text', label: 'Message', reqd: 1 } + ], + primary_action_label: __('Send'), + primary_action: function () { + var values = dialog.fields_dict; + if (!values) { + return; + } + send_sms(values, frm); + dialog.hide(); + } + }); + if (frm.doc.report_preference === 'Print') { + dialog.set_values({ + 'result_format': 'Printed', + 'number': number, + 'message': printed + }); + } else { + dialog.set_values({ + 'result_format': 'Emailed', + 'number': number, + 'message': emailed + }); + } + var fd = dialog.fields_dict; + $(fd.result_format.input).change(function () { + if (dialog.get_value('result_format') === 'Emailed') { + dialog.set_values({ + 'number': number, + 'message': emailed + }); + } else { + dialog.set_values({ + 'number': number, + 'message': printed + }); + } + }); + dialog.show(); +}; + +var send_sms = function (vals, frm) { + var number = vals.number.value; + var message = vals.message.last_value; + + if (!number || !message) { + frappe.throw(__('Did not send SMS, missing patient mobile number or message content.')); + } + frappe.call({ + method: 'frappe.core.doctype.sms_settings.sms_settings.send_sms', + args: { + receiver_list: [number], + msg: message + }, + callback: function (r) { + if (r.exc) { + frappe.msgprint(r.exc); + } else { + frm.reload_doc(); + } + } + }); +}; + +var calculate_age = function (dob) { + var ageMS = Date.parse(Date()) - Date.parse(dob); + var age = new Date(); + age.setTime(ageMS); + var years = age.getFullYear() - 1970; + return `${years} ${__('Years(s)')} ${age.getMonth()} ${__('Month(s)')} ${age.getDate()} ${__('Day(s)')}`; +}; diff --git a/healthcare/healthcare/doctype/lab_test/lab_test.json b/healthcare/healthcare/doctype/lab_test/lab_test.json new file mode 100644 index 0000000..42a1a4d --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test/lab_test.json @@ -0,0 +1,648 @@ +{ + "actions": [], + "allow_copy": 1, + "allow_import": 1, + "autoname": "naming_series:", + "beta": 1, + "creation": "2016-03-29 17:34:47.509094", + "doctype": "DocType", + "document_type": "Document", + "engine": "InnoDB", + "field_order": [ + "naming_series", + "template", + "lab_test_name", + "lab_test_group", + "medical_code", + "department", + "column_break_26", + "company", + "status", + "submitted_date", + "result_date", + "approved_date", + "expected_result_date", + "expected_result_time", + "printed_on", + "invoiced", + "sb_first", + "patient", + "patient_name", + "patient_age", + "patient_sex", + "inpatient_record", + "report_preference", + "email", + "mobile", + "c_b", + "practitioner", + "practitioner_name", + "requesting_department", + "employee", + "employee_name", + "employee_designation", + "user", + "sample", + "sb_normal", + "lab_test_html", + "normal_test_items", + "sb_descriptive_result", + "descriptive_result", + "sb_descriptive", + "descriptive_test_items", + "organisms_section", + "organism_test_items", + "sb_sensitivity", + "sensitivity_test_items", + "sb_comments", + "lab_test_comment", + "sb_customresult", + "custom_result", + "worksheet_section", + "worksheet_instructions", + "result_legend_section", + "legend_print_position", + "result_legend", + "section_break_50", + "email_sent", + "sms_sent", + "printed", + "normal_toggle", + "imaging_toggle", + "descriptive_toggle", + "sensitivity_toggle", + "amended_from", + "prescription" + ], + "fields": [ + { + "fetch_from": "patient.inpatient_record", + "fieldname": "inpatient_record", + "fieldtype": "Link", + "label": "Inpatient Record", + "options": "Inpatient Record", + "read_only": 1 + }, + { + "fieldname": "naming_series", + "fieldtype": "Select", + "label": "Series", + "options": "HLC-LAB-.YYYY.-", + "print_hide": 1, + "report_hide": 1, + "reqd": 1 + }, + { + "default": "0", + "fieldname": "invoiced", + "fieldtype": "Check", + "label": "Invoiced", + "no_copy": 1, + "read_only": 1, + "search_index": 1 + }, + { + "fetch_from": "inpatient_record.patient", + "fieldname": "patient", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_standard_filter": 1, + "label": "Patient", + "options": "Patient", + "reqd": 1, + "search_index": 1, + "set_only_once": 1 + }, + { + "fetch_from": "patient.patient_name", + "fieldname": "patient_name", + "fieldtype": "Data", + "label": "Patient Name", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "fieldname": "patient_age", + "fieldtype": "Data", + "label": "Age", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "fieldname": "patient_sex", + "fieldtype": "Link", + "label": "Gender", + "options": "Gender", + "print_hide": 1, + "read_only": 1, + "report_hide": 1, + "reqd": 1, + "set_only_once": 1 + }, + { + "fieldname": "practitioner", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "label": "Requesting Practitioner", + "no_copy": 1, + "options": "Healthcare Practitioner", + "search_index": 1 + }, + { + "fetch_from": "patient.email", + "fieldname": "email", + "fieldtype": "Data", + "hidden": 1, + "label": "Email", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "fetch_from": "patient.mobile", + "fieldname": "mobile", + "fieldtype": "Data", + "hidden": 1, + "label": "Mobile", + "print_hide": 1, + "read_only": 1, + "report_hide": 1, + "search_index": 1 + }, + { + "fieldname": "company", + "fieldtype": "Link", + "in_standard_filter": 1, + "label": "Company", + "options": "Company", + "print_hide": 1, + "report_hide": 1 + }, + { + "fieldname": "c_b", + "fieldtype": "Column Break", + "print_hide": 1 + }, + { + "fetch_from": "template.department", + "fieldname": "department", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_standard_filter": 1, + "label": "Department", + "options": "Medical Department", + "read_only": 1, + "search_index": 1 + }, + { + "fieldname": "status", + "fieldtype": "Select", + "in_list_view": 1, + "label": "Status", + "options": "Draft\nCompleted\nApproved\nRejected\nCancelled", + "read_only": 1, + "search_index": 1 + }, + { + "fieldname": "submitted_date", + "fieldtype": "Datetime", + "label": "Submitted Date", + "print_hide": 1, + "report_hide": 1 + }, + { + "fieldname": "approved_date", + "fieldtype": "Datetime", + "hidden": 1, + "label": "Approved Date", + "print_hide": 1, + "report_hide": 1 + }, + { + "fieldname": "sample", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_filter": 1, + "label": "Sample ID", + "options": "Sample Collection", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "default": "Today", + "fieldname": "expected_result_date", + "fieldtype": "Date", + "hidden": 1, + "label": "Expected Result Date", + "read_only": 1 + }, + { + "fieldname": "expected_result_time", + "fieldtype": "Time", + "hidden": 1, + "label": "Expected Result Time", + "read_only": 1 + }, + { + "fieldname": "result_date", + "fieldtype": "Date", + "label": "Result Date", + "read_only": 1, + "search_index": 1 + }, + { + "allow_on_submit": 1, + "fieldname": "printed_on", + "fieldtype": "Datetime", + "label": "Printed on", + "read_only": 1 + }, + { + "fieldname": "employee", + "fieldtype": "Link", + "label": "Employee (Lab Technician)", + "no_copy": 1, + "options": "Employee", + "print_hide": 1, + "report_hide": 1 + }, + { + "fetch_from": "employee.employee_name", + "fieldname": "employee_name", + "fieldtype": "Data", + "label": "Lab Technician Name", + "no_copy": 1, + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "fetch_from": "employee.designation", + "fieldname": "employee_designation", + "fieldtype": "Data", + "label": "Lab Technician Designation", + "no_copy": 1, + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "fieldname": "user", + "fieldtype": "Link", + "hidden": 1, + "label": "User", + "no_copy": 1, + "options": "User", + "print_hide": 1, + "report_hide": 1 + }, + { + "fetch_from": "patient.report_preference", + "fieldname": "report_preference", + "fieldtype": "Data", + "label": "Report Preference", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "fieldname": "sb_first", + "fieldtype": "Section Break" + }, + { + "fieldname": "lab_test_name", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Test Name", + "no_copy": 1, + "print_hide": 1, + "read_only": 1, + "report_hide": 1, + "search_index": 1 + }, + { + "fieldname": "template", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_standard_filter": 1, + "label": "Test Template", + "options": "Lab Test Template", + "print_hide": 1, + "report_hide": 1, + "reqd": 1, + "set_only_once": 1 + }, + { + "fieldname": "lab_test_group", + "fieldtype": "Link", + "hidden": 1, + "label": "Test Group", + "options": "Item Group", + "print_hide": 1, + "report_hide": 1 + }, + { + "fetch_from": "template.medical_code", + "fieldname": "medical_code", + "fieldtype": "Link", + "label": "Medical Code", + "options": "Medical Code", + "read_only": 1 + }, + { + "fieldname": "sb_normal", + "fieldtype": "Section Break", + "label": "Compound Test Result" + }, + { + "fieldname": "normal_test_items", + "fieldtype": "Table", + "label": "Normal Test Result", + "options": "Normal Test Result", + "print_hide": 1 + }, + { + "fieldname": "lab_test_html", + "fieldtype": "HTML" + }, + { + "depends_on": "descriptive_toggle", + "fieldname": "organisms_section", + "fieldtype": "Section Break", + "label": "Organism Test Result" + }, + { + "fieldname": "sb_sensitivity", + "fieldtype": "Section Break", + "label": "Sensitivity Test Result" + }, + { + "fieldname": "sensitivity_test_items", + "fieldtype": "Table", + "label": "Sensitivity Test Result", + "options": "Sensitivity Test Result", + "print_hide": 1, + "report_hide": 1 + }, + { + "collapsible": 1, + "fieldname": "sb_comments", + "fieldtype": "Section Break", + "label": "Comments" + }, + { + "fieldname": "lab_test_comment", + "fieldtype": "Text", + "ignore_xss_filter": 1, + "label": "Comments", + "print_hide": 1 + }, + { + "collapsible": 1, + "fieldname": "sb_customresult", + "fieldtype": "Section Break", + "label": "Custom Result" + }, + { + "fieldname": "custom_result", + "fieldtype": "Text Editor", + "ignore_xss_filter": 1, + "label": "Custom Result", + "print_hide": 1 + }, + { + "default": "0", + "fieldname": "email_sent", + "fieldtype": "Check", + "hidden": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "default": "0", + "fieldname": "sms_sent", + "fieldtype": "Check", + "hidden": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "default": "0", + "fieldname": "printed", + "fieldtype": "Check", + "hidden": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "default": "0", + "fieldname": "normal_toggle", + "fieldtype": "Check", + "hidden": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "default": "0", + "fieldname": "sensitivity_toggle", + "fieldtype": "Check", + "hidden": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "fieldname": "amended_from", + "fieldtype": "Link", + "label": "Amended From", + "no_copy": 1, + "options": "Lab Test", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "fieldname": "prescription", + "fieldtype": "Link", + "hidden": 1, + "label": "Prescription", + "no_copy": 1, + "options": "Lab Prescription", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "fieldname": "column_break_26", + "fieldtype": "Column Break" + }, + { + "fetch_from": "practitioner.department", + "fieldname": "requesting_department", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Requesting Department", + "options": "Medical Department", + "read_only": 1 + }, + { + "fetch_from": "practitioner.practitioner_name", + "fieldname": "practitioner_name", + "fieldtype": "Data", + "label": "Requesting Practitioner", + "read_only": 1 + }, + { + "collapsible": 1, + "fieldname": "result_legend_section", + "fieldtype": "Section Break", + "label": "Result Legend Print" + }, + { + "fieldname": "legend_print_position", + "fieldtype": "Select", + "label": "Print Position", + "options": "\nBottom\nTop\nBoth", + "print_hide": 1 + }, + { + "fieldname": "result_legend", + "fieldtype": "Text Editor", + "label": "Result Legend", + "print_hide": 1 + }, + { + "fieldname": "section_break_50", + "fieldtype": "Section Break" + }, + { + "fieldname": "worksheet_instructions", + "fieldtype": "Text Editor", + "label": "Worksheet Instructions", + "print_hide": 1 + }, + { + "collapsible": 1, + "fieldname": "worksheet_section", + "fieldtype": "Section Break", + "label": "Worksheet Print" + }, + { + "fieldname": "descriptive_test_items", + "fieldtype": "Table", + "label": "Descriptive Test Result", + "options": "Descriptive Test Result", + "print_hide": 1, + "report_hide": 1 + }, + { + "fieldname": "sb_descriptive", + "fieldtype": "Section Break", + "label": "Descriptive Test Result" + }, + { + "default": "0", + "fieldname": "descriptive_toggle", + "fieldtype": "Check", + "hidden": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "fieldname": "organism_test_items", + "fieldtype": "Table", + "label": "Organism Test Result", + "options": "Organism Test Result", + "print_hide": 1 + }, + { + "fieldname": "descriptive_result", + "fieldtype": "Text Editor", + "label": "Descriptive Result" + }, + { + "fieldname": "sb_descriptive_result", + "fieldtype": "Section Break", + "label": "Descriptive Result" + }, + { + "default": "0", + "fieldname": "imaging_toggle", + "fieldtype": "Check" + } + ], + "is_submittable": 1, + "links": [ + { + "link_doctype": "Nursing Task", + "link_fieldname": "reference_name" + } + ], + "modified": "2022-10-17 05:26:49.198517", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Lab Test", + "naming_rule": "By \"Naming Series\" field", + "owner": "Administrator", + "permissions": [ + { + "amend": 1, + "cancel": 1, + "create": 1, + "email": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Laboratory User", + "share": 1, + "submit": 1, + "write": 1 + }, + { + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "LabTest Approver", + "share": 1, + "write": 1 + }, + { + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "select": 1, + "share": 1, + "submit": 1, + "write": 1 + } + ], + "restrict_to_domain": "Healthcare", + "search_fields": "patient,practitioner,lab_test_name,sample", + "show_name_in_global_search": 1, + "sort_field": "modified", + "sort_order": "DESC", + "states": [], + "title_field": "patient", + "track_changes": 1, + "track_seen": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/lab_test/lab_test.py b/healthcare/healthcare/doctype/lab_test/lab_test.py new file mode 100644 index 0000000..a52482a --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test/lab_test.py @@ -0,0 +1,415 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS and contributors +# For license information, please see license.txt + + +import frappe +from frappe import _ +from frappe.model.document import Document +from frappe.utils import get_link_to_form, getdate, now_datetime +from healthcare.healthcare.doctype.nursing_task.nursing_task import NursingTask + + +class LabTest(Document): + def validate(self): + if not self.is_new(): + self.set_secondary_uom_result() + + def on_submit(self): + from healthcare.healthcare.utils import validate_nursing_tasks + + validate_nursing_tasks(self) + self.validate_result_values() + self.db_set("submitted_date", getdate()) + self.db_set("status", "Completed") + + def on_cancel(self): + self.db_set("status", "Cancelled") + self.reload() + + def on_update(self): + if self.sensitivity_test_items: + sensitivity = sorted(self.sensitivity_test_items, key=lambda x: x.antibiotic_sensitivity) + for i, item in enumerate(sensitivity): + item.idx = i + 1 + self.sensitivity_test_items = sensitivity + + def after_insert(self): + if self.prescription: + frappe.db.set_value("Lab Prescription", self.prescription, "lab_test_created", 1) + if frappe.db.get_value("Lab Prescription", self.prescription, "invoiced"): + self.invoiced = True + if self.template: + self.load_test_from_template() + self.reload() + + # create nursing tasks + template = frappe.db.get_value("Lab Test Template", self.template, "nursing_checklist_template") + if template: + NursingTask.create_nursing_tasks_from_template(template, self, start_time=now_datetime()) + + def load_test_from_template(self): + lab_test = self + create_test_from_template(lab_test) + self.reload() + + def set_secondary_uom_result(self): + for item in self.normal_test_items: + if item.result_value and item.secondary_uom and item.conversion_factor: + try: + item.secondary_uom_result = float(item.result_value) * float(item.conversion_factor) + except Exception: + item.secondary_uom_result = "" + frappe.msgprint( + _("Row #{0}: Result for Secondary UOM not calculated").format(item.idx), title=_("Warning") + ) + + def validate_result_values(self): + if self.normal_test_items: + for item in self.normal_test_items: + if not item.result_value and not item.allow_blank and item.require_result_value: + frappe.throw( + _("Row #{0}: Please enter the result value for {1}").format( + item.idx, frappe.bold(item.lab_test_name) + ), + title=_("Mandatory Results"), + ) + + if self.descriptive_test_items: + for item in self.descriptive_test_items: + if not item.result_value and not item.allow_blank and item.require_result_value: + frappe.throw( + _("Row #{0}: Please enter the result value for {1}").format( + item.idx, frappe.bold(item.lab_test_particulars) + ), + title=_("Mandatory Results"), + ) + + +def create_test_from_template(lab_test): + template = frappe.get_doc("Lab Test Template", lab_test.template) + patient = frappe.get_doc("Patient", lab_test.patient) + + lab_test.lab_test_name = template.lab_test_name + lab_test.result_date = getdate() + lab_test.department = template.department + lab_test.lab_test_group = template.lab_test_group + lab_test.legend_print_position = template.legend_print_position + lab_test.result_legend = template.result_legend + lab_test.worksheet_instructions = template.worksheet_instructions + + lab_test = create_sample_collection(lab_test, template, patient, None) + load_result_format(lab_test, template, None, None) + + +@frappe.whitelist() +def update_status(status, name): + if name and status: + frappe.db.set_value("Lab Test", name, {"status": status, "approved_date": getdate()}) + + +@frappe.whitelist() +def create_multiple(doctype, docname): + if not doctype or not docname: + frappe.throw( + _("Sales Invoice or Patient Encounter is required to create Lab Tests"), + title=_("Insufficient Data"), + ) + + lab_test_created = False + if doctype == "Sales Invoice": + lab_test_created = create_lab_test_from_invoice(docname) + elif doctype == "Patient Encounter": + lab_test_created = create_lab_test_from_encounter(docname) + + if lab_test_created: + frappe.msgprint( + _("Lab Test(s) {0} created successfully").format(lab_test_created), indicator="green" + ) + else: + frappe.msgprint(_("No Lab Tests created")) + + +def create_lab_test_from_encounter(encounter): + lab_test_created = False + encounter = frappe.get_doc("Patient Encounter", encounter) + + if encounter and encounter.lab_test_prescription: + patient = frappe.get_doc("Patient", encounter.patient) + for item in encounter.lab_test_prescription: + if not item.lab_test_created: + template = get_lab_test_template(item.lab_test_code) + if template: + lab_test = create_lab_test_doc( + item.invoiced, encounter.practitioner, patient, template, encounter.company + ) + lab_test.save(ignore_permissions=True) + frappe.db.set_value("Lab Prescription", item.name, "lab_test_created", 1) + if not lab_test_created: + lab_test_created = lab_test.name + else: + lab_test_created += ", " + lab_test.name + return lab_test_created + + +def create_lab_test_from_invoice(sales_invoice): + lab_tests_created = False + invoice = frappe.get_doc("Sales Invoice", sales_invoice) + if invoice and invoice.patient: + patient = frappe.get_doc("Patient", invoice.patient) + for item in invoice.items: + lab_test_created = 0 + if item.reference_dt == "Lab Prescription": + lab_test_created = frappe.db.get_value( + "Lab Prescription", item.reference_dn, "lab_test_created" + ) + elif item.reference_dt == "Lab Test": + lab_test_created = 1 + if lab_test_created != 1: + template = get_lab_test_template(item.item_code) + if template: + lab_test = create_lab_test_doc( + True, invoice.ref_practitioner, patient, template, invoice.company + ) + if item.reference_dt == "Lab Prescription": + lab_test.prescription = item.reference_dn + lab_test.save(ignore_permissions=True) + if item.reference_dt != "Lab Prescription": + frappe.db.set_value("Sales Invoice Item", item.name, "reference_dt", "Lab Test") + frappe.db.set_value("Sales Invoice Item", item.name, "reference_dn", lab_test.name) + if not lab_tests_created: + lab_tests_created = lab_test.name + else: + lab_tests_created += ", " + lab_test.name + return lab_tests_created + + +def get_lab_test_template(item): + template_id = frappe.db.exists("Lab Test Template", {"item": item}) + if template_id: + return frappe.get_doc("Lab Test Template", template_id) + return False + + +def create_lab_test_doc(invoiced, practitioner, patient, template, company): + lab_test = frappe.new_doc("Lab Test") + lab_test.invoiced = invoiced + lab_test.practitioner = practitioner + lab_test.patient = patient.name + lab_test.patient_age = patient.get_age() + lab_test.patient_sex = patient.sex + lab_test.email = patient.email + lab_test.mobile = patient.mobile + lab_test.report_preference = patient.report_preference + lab_test.department = template.department + lab_test.template = template.name + lab_test.lab_test_group = template.lab_test_group + lab_test.result_date = getdate() + lab_test.company = company + return lab_test + + +def create_normals(template, lab_test): + lab_test.normal_toggle = 1 + normal = lab_test.append("normal_test_items") + normal.lab_test_name = template.lab_test_name + normal.lab_test_uom = template.lab_test_uom + normal.secondary_uom = template.secondary_uom + normal.conversion_factor = template.conversion_factor + normal.normal_range = template.lab_test_normal_range + normal.require_result_value = 1 + normal.allow_blank = 0 + normal.template = template.name + + +def create_imaging(template, lab_test): + lab_test.imaging_toggle = 1 + lab_test.template = template.name + lab_test.lab_test_name = template.lab_test_name + lab_test.descriptive_result = template.descriptive_result + + +def create_compounds(template, lab_test, is_group): + lab_test.normal_toggle = 1 + for normal_test_template in template.normal_test_templates: + normal = lab_test.append("normal_test_items") + if is_group: + normal.lab_test_event = normal_test_template.lab_test_event + else: + normal.lab_test_name = normal_test_template.lab_test_event + + normal.lab_test_uom = normal_test_template.lab_test_uom + normal.secondary_uom = normal_test_template.secondary_uom + normal.conversion_factor = normal_test_template.conversion_factor + normal.normal_range = normal_test_template.normal_range + normal.require_result_value = 1 + normal.allow_blank = normal_test_template.allow_blank + normal.template = template.name + + +def create_descriptives(template, lab_test): + lab_test.descriptive_toggle = 1 + if template.sensitivity: + lab_test.sensitivity_toggle = 1 + for descriptive_test_template in template.descriptive_test_templates: + descriptive = lab_test.append("descriptive_test_items") + descriptive.lab_test_particulars = descriptive_test_template.particulars + descriptive.require_result_value = 1 + descriptive.allow_blank = descriptive_test_template.allow_blank + descriptive.template = template.name + + +def create_sample_doc(template, patient, invoice, company=None): + if template.sample: + sample_exists = frappe.db.exists( + { + "doctype": "Sample Collection", + "patient": patient.name, + "docstatus": 0, + "sample": template.sample, + } + ) + + if sample_exists: + # update sample collection by adding quantity + sample_collection = frappe.get_doc("Sample Collection", sample_exists[0][0]) + quantity = int(sample_collection.sample_qty) + int(template.sample_qty) + if template.sample_details: + sample_details = sample_collection.sample_details + "\n-\n" + _("Test :") + sample_details += (template.get("lab_test_name") or template.get("template")) + "\n" + sample_details += _("Collection Details:") + "\n\t" + template.sample_details + frappe.db.set_value( + "Sample Collection", sample_collection.name, "sample_details", sample_details + ) + + frappe.db.set_value("Sample Collection", sample_collection.name, "sample_qty", quantity) + + else: + # Create Sample Collection for template, copy vals from Invoice + sample_collection = frappe.new_doc("Sample Collection") + if invoice: + sample_collection.invoiced = True + + sample_collection.patient = patient.name + sample_collection.patient_age = patient.get_age() + sample_collection.patient_sex = patient.sex + sample_collection.sample = template.sample + sample_collection.sample_uom = template.sample_uom + sample_collection.sample_qty = template.sample_qty + sample_collection.company = company + + if template.sample_details: + sample_collection.sample_details = ( + _("Test :") + + (template.get("lab_test_name") or template.get("template")) + + "\n" + + "Collection Detials:\n\t" + + template.sample_details + ) + sample_collection.save(ignore_permissions=True) + + return sample_collection + + +def create_sample_collection(lab_test, template, patient, invoice): + if frappe.get_cached_value("Healthcare Settings", None, "create_sample_collection_for_lab_test"): + sample_collection = create_sample_doc(template, patient, invoice, lab_test.company) + if sample_collection: + lab_test.sample = sample_collection.name + sample_collection_doc = get_link_to_form("Sample Collection", sample_collection.name) + frappe.msgprint( + _("Sample Collection {0} has been created").format(sample_collection_doc), + title=_("Sample Collection"), + indicator="green", + ) + return lab_test + + +def load_result_format(lab_test, template, prescription, invoice): + if template.lab_test_template_type == "Single": + create_normals(template, lab_test) + + elif template.lab_test_template_type == "Compound": + create_compounds(template, lab_test, False) + + elif template.lab_test_template_type == "Descriptive": + create_descriptives(template, lab_test) + + elif template.lab_test_template_type == "Imaging": + create_imaging(template, lab_test) + + elif template.lab_test_template_type == "Grouped": + # Iterate for each template in the group and create one result for all. + for lab_test_group in template.lab_test_groups: + # Template_in_group = None + if lab_test_group.lab_test_template: + template_in_group = frappe.get_doc("Lab Test Template", lab_test_group.lab_test_template) + if template_in_group: + if template_in_group.lab_test_template_type == "Single": + create_normals(template_in_group, lab_test) + + elif template_in_group.lab_test_template_type == "Compound": + normal_heading = lab_test.append("normal_test_items") + normal_heading.lab_test_name = template_in_group.lab_test_name + normal_heading.require_result_value = 0 + normal_heading.allow_blank = 1 + normal_heading.template = template_in_group.name + create_compounds(template_in_group, lab_test, True) + + elif template_in_group.lab_test_template_type == "Descriptive": + descriptive_heading = lab_test.append("descriptive_test_items") + descriptive_heading.lab_test_name = template_in_group.lab_test_name + descriptive_heading.require_result_value = 0 + descriptive_heading.allow_blank = 1 + descriptive_heading.template = template_in_group.name + create_descriptives(template_in_group, lab_test) + + else: # Lab Test Group - Add New Line + normal = lab_test.append("normal_test_items") + normal.lab_test_name = lab_test_group.group_event + normal.lab_test_uom = lab_test_group.group_test_uom + normal.secondary_uom = lab_test_group.secondary_uom + normal.conversion_factor = lab_test_group.conversion_factor + normal.normal_range = lab_test_group.group_test_normal_range + normal.allow_blank = lab_test_group.allow_blank + normal.require_result_value = 1 + normal.template = template.name + + if template.lab_test_template_type != "No Result": + if prescription: + lab_test.prescription = prescription + if invoice: + frappe.db.set_value("Lab Prescription", prescription, "invoiced", True) + lab_test.save(ignore_permissions=True) # Insert the result + return lab_test + + +@frappe.whitelist() +def get_employee_by_user_id(user_id): + emp_id = frappe.db.exists("Employee", {"user_id": user_id}) + if emp_id: + return frappe.get_doc("Employee", emp_id) + return None + + +@frappe.whitelist() +def get_lab_test_prescribed(patient): + return frappe.db.sql( + """ + select + lp.name, + lp.lab_test_code, + lp.parent, + lp.invoiced, + pe.practitioner, + pe.practitioner_name, + pe.encounter_date + from + `tabPatient Encounter` pe, `tabLab Prescription` lp + where + pe.patient=%s + and lp.parent=pe.name + and lp.lab_test_created=0 + """, + (patient), + ) diff --git a/healthcare/healthcare/doctype/lab_test/lab_test_list.js b/healthcare/healthcare/doctype/lab_test/lab_test_list.js new file mode 100644 index 0000000..ccaf2c3 --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test/lab_test_list.js @@ -0,0 +1,71 @@ +/* +(c) ESS 2015-16 +*/ +frappe.listview_settings['Lab Test'] = { + add_fields: ['name', 'status', 'invoiced'], + filters: [['docstatus', '=', '1']], + get_indicator: function (doc) { + if (doc.status === 'Approved') { + return [__('Approved'), 'green', 'status, =, Approved']; + } else if (doc.status === 'Rejected') { + return [__('Rejected'), 'orange', 'status, =, Rejected']; + } else if (doc.status === 'Completed') { + return [__('Completed'), 'green', 'status, =, Completed']; + } else if (doc.status === 'Cancelled') { + return [__('Cancelled'), 'red', 'status, =, Cancelled']; + } + }, + onload: function (listview) { + listview.page.add_menu_item(__('Create Multiple'), function () { + create_multiple_dialog(listview); + }); + } +}; + +var create_multiple_dialog = function (listview) { + var dialog = new frappe.ui.Dialog({ + title: 'Create Multiple Lab Tests', + width: 100, + fields: [ + { fieldtype: 'Link', label: 'Patient', fieldname: 'patient', options: 'Patient', reqd: 1 }, + { + fieldtype: 'Select', label: 'Invoice / Patient Encounter', fieldname: 'doctype', + options: '\nSales Invoice\nPatient Encounter', reqd: 1 + }, + { + fieldtype: 'Dynamic Link', fieldname: 'docname', options: 'doctype', reqd: 1, + get_query: function () { + return { + filters: { + 'patient': dialog.get_value('patient'), + 'docstatus': 1 + } + }; + } + } + ], + primary_action_label: __('Create'), + primary_action: function () { + frappe.call({ + method: 'healthcare.healthcare.doctype.lab_test.lab_test.create_multiple', + args: { + 'doctype': dialog.get_value('doctype'), + 'docname': dialog.get_value('docname') + }, + callback: function (data) { + if (!data.exc) { + if (!data.message) { + frappe.msgprint(__('No Lab Tests created')); + } + listview.refresh(); + } + }, + freeze: true, + freeze_message: __('Creating Lab Tests...') + }); + dialog.hide(); + } + }); + + dialog.show(); +}; diff --git a/healthcare/healthcare/doctype/lab_test/test_lab_test.py b/healthcare/healthcare/doctype/lab_test/test_lab_test.py new file mode 100644 index 0000000..b77c3c4 --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test/test_lab_test.py @@ -0,0 +1,230 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +import frappe +from frappe.utils import getdate, nowtime + +from healthcare.healthcare.doctype.healthcare_settings.healthcare_settings import ( + get_income_account, + get_receivable_account, +) +from healthcare.healthcare.doctype.lab_test.lab_test import create_multiple +from healthcare.healthcare.doctype.patient_appointment.test_patient_appointment import ( + create_patient, +) +from healthcare.healthcare.doctype.patient_medical_record.test_patient_medical_record import ( + create_lab_test_template as create_blood_test_template, +) + + +class TestLabTest(FrappeTestCase): + def test_lab_test_item(self): + lab_template = create_lab_test_template() + self.assertTrue(frappe.db.exists("Item", lab_template.item)) + self.assertEqual( + frappe.db.get_value("Item Price", {"item_code": lab_template.item}, "price_list_rate"), + lab_template.lab_test_rate, + ) + + lab_template.disabled = 1 + lab_template.save() + self.assertEqual(frappe.db.get_value("Item", lab_template.item, "disabled"), 1) + + lab_template.reload() + + lab_template.disabled = 0 + lab_template.save() + + def test_descriptive_lab_test(self): + lab_template = create_lab_test_template() + + # blank result value not allowed as per template + lab_test = create_lab_test(lab_template) + lab_test.descriptive_test_items[0].result_value = 12 + lab_test.descriptive_test_items[2].result_value = 1 + lab_test.save() + self.assertRaises(frappe.ValidationError, lab_test.submit) + + def test_sample_collection(self): + frappe.db.set_value( + "Healthcare Settings", "Healthcare Settings", "create_sample_collection_for_lab_test", 1 + ) + lab_template = create_lab_test_template() + + lab_test = create_lab_test(lab_template) + lab_test.descriptive_test_items[0].result_value = 12 + lab_test.descriptive_test_items[1].result_value = 1 + lab_test.descriptive_test_items[2].result_value = 2.3 + lab_test.save() + + # check sample collection created + self.assertTrue(frappe.db.exists("Sample Collection", {"sample": lab_template.sample})) + + frappe.db.set_value( + "Healthcare Settings", "Healthcare Settings", "create_sample_collection_for_lab_test", 0 + ) + lab_test = create_lab_test(lab_template) + lab_test.descriptive_test_items[0].result_value = 12 + lab_test.descriptive_test_items[1].result_value = 1 + lab_test.descriptive_test_items[2].result_value = 2.3 + lab_test.save() + + # sample collection should not be created + lab_test.reload() + self.assertEqual(lab_test.sample, None) + + def test_create_lab_tests_from_sales_invoice(self): + sales_invoice = create_sales_invoice() + create_multiple("Sales Invoice", sales_invoice.name) + sales_invoice.reload() + self.assertIsNotNone(sales_invoice.items[0].reference_dn) + self.assertIsNotNone(sales_invoice.items[1].reference_dn) + + def test_create_lab_tests_from_patient_encounter(self): + patient_encounter = create_patient_encounter() + create_multiple("Patient Encounter", patient_encounter.name) + patient_encounter.reload() + self.assertTrue(patient_encounter.lab_test_prescription[0].lab_test_created) + self.assertTrue(patient_encounter.lab_test_prescription[0].lab_test_created) + + +def create_lab_test_template(test_sensitivity=0, sample_collection=1): + medical_department = create_medical_department() + if frappe.db.exists("Lab Test Template", "Insulin Resistance"): + return frappe.get_doc("Lab Test Template", "Insulin Resistance") + template = frappe.new_doc("Lab Test Template") + template.lab_test_name = "Insulin Resistance" + template.lab_test_template_type = "Descriptive" + template.lab_test_code = "Insulin Resistance" + template.lab_test_group = "Services" + template.department = medical_department + template.is_billable = 1 + template.lab_test_description = "Insulin Resistance" + template.lab_test_rate = 2000 + + for entry in ["FBS", "Insulin", "IR"]: + template.append( + "descriptive_test_templates", {"particulars": entry, "allow_blank": 1 if entry == "IR" else 0} + ) + + if test_sensitivity: + template.sensitivity = 1 + + if sample_collection: + template.sample = create_lab_test_sample() + template.sample_qty = 5.0 + + template.save() + return template + + +def create_medical_department(): + medical_department = frappe.db.exists("Medical Department", "_Test Medical Department") + if not medical_department: + medical_department = frappe.new_doc("Medical Department") + medical_department.department = "_Test Medical Department" + medical_department.save() + medical_department = medical_department.name + + return medical_department + + +def create_lab_test(lab_template): + patient = create_patient() + lab_test = frappe.new_doc("Lab Test") + lab_test.template = lab_template.name + lab_test.patient = patient + lab_test.patient_sex = "Female" + lab_test.save() + + return lab_test + + +def create_lab_test_sample(): + blood_sample = frappe.db.exists("Lab Test Sample", "Blood Sample") + if blood_sample: + return blood_sample + + sample = frappe.new_doc("Lab Test Sample") + sample.sample = "Blood Sample" + sample.sample_uom = "U/ml" + sample.save() + + return sample.name + + +def create_sales_invoice(): + patient = create_patient() + medical_department = create_medical_department() + insulin_resistance_template = create_lab_test_template() + blood_test_template = create_blood_test_template(medical_department) + + sales_invoice = frappe.new_doc("Sales Invoice") + sales_invoice.patient = patient + sales_invoice.customer = frappe.db.get_value("Patient", patient, "customer") + sales_invoice.due_date = getdate() + sales_invoice.company = "_Test Company" + sales_invoice.debit_to = get_receivable_account("_Test Company") + + tests = [insulin_resistance_template, blood_test_template] + for entry in tests: + sales_invoice.append( + "items", + { + "item_code": entry.item, + "item_name": entry.lab_test_name, + "description": entry.lab_test_description, + "qty": 1, + "uom": "Nos", + "conversion_factor": 1, + "income_account": get_income_account(None, "_Test Company"), + "rate": entry.lab_test_rate, + "amount": entry.lab_test_rate, + }, + ) + + sales_invoice.set_missing_values() + + sales_invoice.submit() + return sales_invoice + + +def create_patient_encounter(): + patient = create_patient() + medical_department = create_medical_department() + insulin_resistance_template = create_lab_test_template() + blood_test_template = create_blood_test_template(medical_department) + + patient_encounter = frappe.new_doc("Patient Encounter") + patient_encounter.patient = patient + patient_encounter.practitioner = create_practitioner() + patient_encounter.encounter_date = getdate() + patient_encounter.encounter_time = nowtime() + + tests = [insulin_resistance_template, blood_test_template] + for entry in tests: + patient_encounter.append( + "lab_test_prescription", {"lab_test_code": entry.item, "lab_test_name": entry.lab_test_name} + ) + + patient_encounter.submit() + return patient_encounter + + +def create_practitioner(): + practitioner = frappe.db.exists("Healthcare Practitioner", "_Test Healthcare Practitioner") + + if not practitioner: + practitioner = frappe.new_doc("Healthcare Practitioner") + practitioner.first_name = "_Test Healthcare Practitioner" + practitioner.gender = "Female" + practitioner.op_consulting_charge = 500 + practitioner.inpatient_visit_charge = 500 + practitioner.save(ignore_permissions=True) + practitioner = practitioner.name + + return practitioner diff --git a/healthcare/healthcare/doctype/lab_test_group_template/__init__.py b/healthcare/healthcare/doctype/lab_test_group_template/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/lab_test_group_template/lab_test_group_template.json b/healthcare/healthcare/doctype/lab_test_group_template/lab_test_group_template.json new file mode 100644 index 0000000..2767f7e --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_group_template/lab_test_group_template.json @@ -0,0 +1,119 @@ +{ + "actions": [], + "allow_copy": 1, + "beta": 1, + "creation": "2016-03-29 17:37:29.913583", + "doctype": "DocType", + "document_type": "Setup", + "engine": "InnoDB", + "field_order": [ + "template_or_new_line", + "lab_test_template", + "lab_test_rate", + "lab_test_description", + "group_event", + "group_test_uom", + "secondary_uom", + "conversion_factor", + "allow_blank", + "column_break_8", + "group_test_normal_range" + ], + "fields": [ + { + "default": "Add Test", + "fieldname": "template_or_new_line", + "fieldtype": "Select", + "options": "Add Test\nAdd New Line", + "print_hide": 1, + "report_hide": 1 + }, + { + "depends_on": "eval:doc.template_or_new_line == 'Add Test'", + "fieldname": "lab_test_template", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "label": "Test Name", + "options": "Lab Test Template" + }, + { + "fetch_from": "lab_test_template.lab_test_rate", + "fieldname": "lab_test_rate", + "fieldtype": "Currency", + "label": "Rate", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "fetch_from": "lab_test_template.lab_test_description", + "fieldname": "lab_test_description", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Description", + "read_only": 1 + }, + { + "depends_on": "eval:doc.template_or_new_line == 'Add New Line'", + "fieldname": "group_event", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Event" + }, + { + "depends_on": "eval:doc.template_or_new_line =='Add New Line'", + "fieldname": "group_test_uom", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "label": "UOM", + "options": "Lab Test UOM" + }, + { + "depends_on": "eval:doc.template_or_new_line == 'Add New Line'", + "fieldname": "group_test_normal_range", + "fieldtype": "Long Text", + "ignore_xss_filter": 1, + "label": "Normal Range" + }, + { + "fieldname": "column_break_8", + "fieldtype": "Column Break" + }, + { + "depends_on": "eval:doc.template_or_new_line =='Add New Line'", + "fieldname": "secondary_uom", + "fieldtype": "Link", + "label": "Secondary UOM", + "options": "Lab Test UOM" + }, + { + "depends_on": "secondary_uom", + "fieldname": "conversion_factor", + "fieldtype": "Float", + "label": "Conversion Factor", + "mandatory_depends_on": "secondary_uom" + }, + { + "default": "0", + "depends_on": "eval:doc.template_or_new_line == 'Add New Line'", + "fieldname": "allow_blank", + "fieldtype": "Check", + "in_list_view": 1, + "label": "Allow Blank" + } + ], + "istable": 1, + "links": [], + "modified": "2020-07-30 12:36:03.082391", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Lab Test Group Template", + "owner": "Administrator", + "permissions": [], + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC" +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/lab_test_group_template/lab_test_group_template.py b/healthcare/healthcare/doctype/lab_test_group_template/lab_test_group_template.py new file mode 100644 index 0000000..c5ba9c2 --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_group_template/lab_test_group_template.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS and contributors +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class LabTestGroupTemplate(Document): + pass diff --git a/healthcare/healthcare/doctype/lab_test_sample/__init__.py b/healthcare/healthcare/doctype/lab_test_sample/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/lab_test_sample/lab_test_sample.js b/healthcare/healthcare/doctype/lab_test_sample/lab_test_sample.js new file mode 100644 index 0000000..7bace5f --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_sample/lab_test_sample.js @@ -0,0 +1,5 @@ +// Copyright (c) 2017, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Lab Test Sample', { +}); diff --git a/healthcare/healthcare/doctype/lab_test_sample/lab_test_sample.json b/healthcare/healthcare/doctype/lab_test_sample/lab_test_sample.json new file mode 100644 index 0000000..2830038 --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_sample/lab_test_sample.json @@ -0,0 +1,68 @@ +{ + "actions": [], + "allow_copy": 1, + "allow_import": 1, + "allow_rename": 1, + "autoname": "field:sample", + "beta": 1, + "creation": "2016-04-04 17:35:44.823951", + "doctype": "DocType", + "document_type": "Setup", + "engine": "InnoDB", + "field_order": [ + "sample", + "sample_uom" + ], + "fields": [ + { + "fieldname": "sample", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Sample", + "reqd": 1, + "unique": 1 + }, + { + "bold": 1, + "fieldname": "sample_uom", + "fieldtype": "Link", + "in_list_view": 1, + "label": "UOM", + "options": "Lab Test UOM" + } + ], + "links": [], + "modified": "2020-01-29 23:02:02.249839", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Lab Test Sample", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + }, + { + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Laboratory User", + "share": 1 + } + ], + "quick_entry": 1, + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "sample", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/lab_test_sample/lab_test_sample.py b/healthcare/healthcare/doctype/lab_test_sample/lab_test_sample.py new file mode 100644 index 0000000..c1df6a3 --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_sample/lab_test_sample.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class LabTestSample(Document): + pass diff --git a/healthcare/healthcare/doctype/lab_test_sample/test_lab_test_sample.py b/healthcare/healthcare/doctype/lab_test_sample/test_lab_test_sample.py new file mode 100644 index 0000000..57a99b5 --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_sample/test_lab_test_sample.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + + +class TestLabTestSample(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/lab_test_template/__init__.py b/healthcare/healthcare/doctype/lab_test_template/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/lab_test_template/lab_test_template.js b/healthcare/healthcare/doctype/lab_test_template/lab_test_template.js new file mode 100644 index 0000000..9d284e1 --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_template/lab_test_template.js @@ -0,0 +1,124 @@ +// Copyright (c) 2016, ESS +// License: ESS license.txt + +frappe.ui.form.on('Lab Test Template', { + lab_test_name: function(frm) { + if (!frm.doc.lab_test_code) + frm.set_value('lab_test_code', frm.doc.lab_test_name); + if (!frm.doc.lab_test_description) + frm.set_value('lab_test_description', frm.doc.lab_test_name); + }, + refresh : function(frm) { + // Restrict Special, Grouped type templates in Child Test Groups + frm.set_query('lab_test_template', 'lab_test_groups', function() { + return { + filters: { + lab_test_template_type: ['in', ['Single','Compound']] + } + }; + }); + + frm.set_query('item', function() { + return { + filters: { + 'disabled': false, + 'is_stock_item': false + } + }; + }); + }, + medical_code: function(frm) { + frm.set_query('medical_code', function() { + return { + filters: { + medical_code_standard: frm.doc.medical_code_standard + } + }; + }); + }, + + link_existing_item: function (frm) { + if (frm.doc.link_existing_item) { + frm.set_value('lab_test_code', ''); + } else { + frm.set_value('item', ''); + } + }, + + item: function (frm) { + if (frm.doc.item) { + frappe.db.get_value('Item', frm.doc.item, ['item_group']) + .then(r => { + frm.set_value({ + 'lab_test_group': r.message.item_group, + 'lab_test_code': frm.doc.item + }); + }) + } + } +}); + +cur_frm.cscript.custom_refresh = function(doc) { + if (!doc.__islocal) { + cur_frm.add_custom_button(__('Change Template Code'), function() { + change_template_code(doc); + }); + } +}; + +let change_template_code = function(doc) { + let d = new frappe.ui.Dialog({ + title:__('Change Template Code'), + fields:[ + { + 'fieldtype': 'Data', + 'label': 'Lab Test Template Code', + 'fieldname': 'lab_test_code', + reqd: 1 + } + ], + primary_action: function() { + let values = d.get_values(); + if (values) { + frappe.call({ + 'method': 'healthcare.healthcare.doctype.lab_test_template.lab_test_template.change_test_code_from_template', + 'args': {lab_test_code: values.lab_test_code, doc: doc}, + callback: function (data) { + frappe.set_route('Form', 'Lab Test Template', data.message); + } + }); + } + d.hide(); + }, + primary_action_label: __('Change Template Code') + }); + d.show(); + + d.set_values({ + 'lab_test_code': doc.link_existing_item ? doc.item : doc.lab_test_code + }); +}; + +frappe.ui.form.on('Lab Test Template', 'lab_test_name', function(frm) { + frm.doc.change_in_item = 1; +}); + +frappe.ui.form.on('Lab Test Template', 'lab_test_rate', function(frm) { + frm.doc.change_in_item = 1; +}); + +frappe.ui.form.on('Lab Test Template', 'lab_test_group', function(frm) { + frm.doc.change_in_item = 1; +}); + +frappe.ui.form.on('Lab Test Template', 'lab_test_description', function(frm) { + frm.doc.change_in_item = 1; +}); + +frappe.ui.form.on('Lab Test Groups', 'template_or_new_line', function (frm, cdt, cdn) { + let child = locals[cdt][cdn]; + if (child.template_or_new_line == 'Add New Line') { + frappe.model.set_value(cdt, cdn, 'lab_test_template', ''); + frappe.model.set_value(cdt, cdn, 'lab_test_description', ''); + } +}); diff --git a/healthcare/healthcare/doctype/lab_test_template/lab_test_template.json b/healthcare/healthcare/doctype/lab_test_template/lab_test_template.json new file mode 100644 index 0000000..79f02d5 --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_template/lab_test_template.json @@ -0,0 +1,391 @@ +{ + "actions": [], + "allow_copy": 1, + "allow_import": 1, + "allow_rename": 1, + "autoname": "field:lab_test_name", + "beta": 1, + "creation": "2016-03-29 17:35:36.761223", + "doctype": "DocType", + "engine": "InnoDB", + "field_order": [ + "lab_test_name", + "link_existing_item", + "item", + "lab_test_code", + "lab_test_group", + "department", + "nursing_checklist_template", + "column_break_3", + "disabled", + "lab_test_template_type", + "is_billable", + "lab_test_rate", + "section_break_description", + "lab_test_description", + "section_break_descriptive_result", + "descriptive_result", + "section_break_normal", + "lab_test_uom", + "secondary_uom", + "conversion_factor", + "column_break_10", + "lab_test_normal_range", + "section_break_compound", + "normal_test_templates", + "section_break_special", + "sensitivity", + "descriptive_test_templates", + "section_break_group", + "lab_test_groups", + "sb_sample_collection", + "sample", + "sample_uom", + "sample_qty", + "column_break_33", + "sample_details", + "medical_coding_section", + "medical_code", + "medical_code_standard", + "worksheet_section", + "worksheet_instructions", + "result_legend_section", + "legend_print_position", + "result_legend", + "change_in_item" + ], + "fields": [ + { + "fieldname": "lab_test_name", + "fieldtype": "Data", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Test Name", + "no_copy": 1, + "reqd": 1, + "unique": 1 + }, + { + "depends_on": "eval: !doc.__islocal || doc.link_existing_item", + "fieldname": "item", + "fieldtype": "Link", + "label": "Item", + "mandatory_depends_on": "eval:doc.link_existing_item", + "no_copy": 1, + "options": "Item", + "read_only_depends_on": "eval: !doc.__islocal", + "search_index": 1 + }, + { + "fieldname": "lab_test_code", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Item Code", + "mandatory_depends_on": "eval:!doc.link_existing_item", + "no_copy": 1, + "read_only_depends_on": "eval:!doc.__islocal" + }, + { + "fieldname": "lab_test_group", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_standard_filter": 1, + "label": "Item Group", + "options": "Item Group", + "read_only_depends_on": "eval:doc.link_existing_item", + "reqd": 1, + "search_index": 1 + }, + { + "fieldname": "department", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_standard_filter": 1, + "label": "Department", + "options": "Medical Department", + "reqd": 1 + }, + { + "fieldname": "column_break_3", + "fieldtype": "Column Break" + }, + { + "description": "Single: Results which require only a single input.\n
\nCompound: Results which require multiple event inputs.\n
\nDescriptive: Tests which have multiple result components with manual result entry.\n
\nGrouped: Test templates which are a group of other test templates.\n
\nNo Result: Tests with no results, can be ordered and billed but no Lab Test will be created. e.g.. Sub Tests for Grouped results", + "fieldname": "lab_test_template_type", + "fieldtype": "Select", + "in_standard_filter": 1, + "label": "Result Format", + "options": "\nSingle\nCompound\nDescriptive\nGrouped\nImaging\nNo Result" + }, + { + "default": "1", + "depends_on": "eval:doc.lab_test_template_type != 'Grouped' && (!doc.link_existing_item || !doc.__islocal);", + "description": "If unchecked, the item will not be available in Sales Invoices for billing but can be used in group test creation. ", + "fieldname": "is_billable", + "fieldtype": "Check", + "label": "Is Billable", + "search_index": 1 + }, + { + "depends_on": "eval:doc.is_billable && (!doc.link_existing_item || !doc.__islocal)", + "description": "This value is updated in the Default Sales Price List.", + "fieldname": "lab_test_rate", + "fieldtype": "Currency", + "in_list_view": 1, + "label": "Rate", + "mandatory_depends_on": "eval:doc.is_billable && !doc.link_existing_item" + }, + { + "collapsible": 1, + "fieldname": "medical_coding_section", + "fieldtype": "Section Break", + "label": "Medical Coding" + }, + { + "depends_on": "medical_code_standard", + "fieldname": "medical_code", + "fieldtype": "Link", + "label": "Medical Code", + "options": "Medical Code" + }, + { + "fieldname": "medical_code_standard", + "fieldtype": "Link", + "label": "Medical Code Standard", + "options": "Medical Code Standard" + }, + { + "depends_on": "eval:doc.lab_test_template_type == 'Single'", + "fieldname": "section_break_normal", + "fieldtype": "Section Break", + "label": "Lab Routine" + }, + { + "fieldname": "lab_test_uom", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "label": "UOM", + "options": "Lab Test UOM" + }, + { + "fieldname": "lab_test_normal_range", + "fieldtype": "Long Text", + "ignore_xss_filter": 1, + "label": "Normal Range" + }, + { + "fieldname": "column_break_10", + "fieldtype": "Column Break" + }, + { + "depends_on": "eval:doc.lab_test_template_type == 'Compound'", + "fieldname": "section_break_compound", + "fieldtype": "Section Break", + "label": "Compound" + }, + { + "fieldname": "normal_test_templates", + "fieldtype": "Table", + "options": "Normal Test Template" + }, + { + "depends_on": "eval:doc.lab_test_template_type == 'Descriptive'", + "fieldname": "section_break_special", + "fieldtype": "Section Break", + "label": "Descriptive Test" + }, + { + "default": "0", + "fieldname": "sensitivity", + "fieldtype": "Check", + "label": "Sensitivity" + }, + { + "depends_on": "eval:doc.lab_test_template_type == 'Grouped'", + "fieldname": "section_break_group", + "fieldtype": "Section Break", + "label": "Group Tests" + }, + { + "fieldname": "lab_test_groups", + "fieldtype": "Table", + "options": "Lab Test Group Template" + }, + { + "collapsible": 1, + "fieldname": "section_break_description", + "fieldtype": "Section Break", + "label": "Description " + }, + { + "depends_on": "eval:doc.lab_test_template_type == 'Imaging'", + "fieldname": "lab_test_description", + "fieldtype": "Text Editor", + "ignore_xss_filter": 1, + "label": "Description", + "no_copy": 1 + }, + { + "fieldname": "sb_sample_collection", + "fieldtype": "Section Break", + "label": "Sample Collection" + }, + { + "fieldname": "sample", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "label": "Sample", + "options": "Lab Test Sample" + }, + { + "fetch_from": "sample.sample_uom", + "fieldname": "sample_uom", + "fieldtype": "Data", + "label": "UOM", + "read_only": 1 + }, + { + "default": "0", + "fieldname": "change_in_item", + "fieldtype": "Check", + "hidden": 1, + "label": "Change In Item", + "no_copy": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "default": "0", + "fieldname": "disabled", + "fieldtype": "Check", + "label": "Disabled" + }, + { + "default": "0", + "fieldname": "sample_qty", + "fieldtype": "Float", + "label": "Quantity" + }, + { + "fieldname": "sample_details", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Collection Details" + }, + { + "collapsible": 1, + "description": "Information to help easily interpret the test report, will be printed as part of the Lab Test result.", + "fieldname": "result_legend_section", + "fieldtype": "Section Break", + "label": "Result Legend Print" + }, + { + "fieldname": "result_legend", + "fieldtype": "Text Editor", + "label": "Result Legend" + }, + { + "fieldname": "legend_print_position", + "fieldtype": "Select", + "label": "Print Position", + "options": "Bottom\nTop\nBoth" + }, + { + "fieldname": "secondary_uom", + "fieldtype": "Link", + "label": "Secondary UOM", + "options": "Lab Test UOM" + }, + { + "depends_on": "secondary_uom", + "fieldname": "conversion_factor", + "fieldtype": "Float", + "label": "Conversion Factor", + "mandatory_depends_on": "secondary_uom" + }, + { + "description": "Instructions to be printed on the worksheet", + "fieldname": "worksheet_instructions", + "fieldtype": "Text Editor", + "label": "Worksheet Instructions" + }, + { + "collapsible": 1, + "fieldname": "worksheet_section", + "fieldtype": "Section Break", + "label": "Worksheet Print" + }, + { + "fieldname": "descriptive_test_templates", + "fieldtype": "Table", + "options": "Descriptive Test Template" + }, + { + "fieldname": "column_break_33", + "fieldtype": "Column Break" + }, + { + "fieldname": "nursing_checklist_template", + "fieldtype": "Link", + "label": "Nursing Checklist Template", + "options": "Nursing Checklist Template" + }, + { + "fieldname": "descriptive_result", + "fieldtype": "Text Editor", + "label": "Descriptive Result" + }, + { + "depends_on": "eval:doc.lab_test_template_type == 'Imaging'", + "fieldname": "section_break_descriptive_result", + "fieldtype": "Section Break", + "label": "Descriptive Result" + }, + { + "default": "0", + "depends_on": "eval: doc.__islocal", + "fieldname": "link_existing_item", + "fieldtype": "Check", + "label": "Link existing Item" + } + ], + "links": [], + "migration_hash": "04ea062dcd8e59976e0c33bb708f4d77", + "modified": "2022-06-10 12:57:31.787436", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Lab Test Template", + "naming_rule": "By fieldname", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + }, + { + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Laboratory User", + "share": 1 + } + ], + "restrict_to_domain": "Healthcare", + "search_fields": "lab_test_code,lab_test_name,lab_test_template_type", + "sort_field": "modified", + "sort_order": "DESC", + "states": [], + "title_field": "lab_test_name", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/lab_test_template/lab_test_template.py b/healthcare/healthcare/doctype/lab_test_template/lab_test_template.py new file mode 100644 index 0000000..7457c8a --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_template/lab_test_template.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS and contributors +# For license information, please see license.txt + + +import json + +import frappe +from frappe import _ +from frappe.model.document import Document +from frappe.model.rename_doc import rename_doc +from frappe.utils import flt, today +from healthcare.healthcare.doctype.clinical_procedure_template.clinical_procedure_template import ( + make_item_price, + update_item_and_item_price, +) + + +class LabTestTemplate(Document): + def before_insert(self): + if self.link_existing_item and self.item: + price_list = frappe.db.get_all( + "Item Price", {"item_code": self.item}, ["price_list_rate"], order_by="valid_from desc" + ) + if price_list: + self.lab_test_rate = price_list[0].get("price_list_rate") + + def after_insert(self): + if not self.item and not self.link_existing_item: + create_item_from_template(self) + + def validate(self): + if ( + self.is_billable + and not self.link_existing_item + and (not self.lab_test_rate or self.lab_test_rate <= 0.0) + ): + frappe.throw(_("Standard Selling Rate should be greater than zero.")) + + if self.sample and flt(self.sample_qty) <= 0: + frappe.throw(_("Sample Quantity cannot be negative or 0"), title=_("Invalid Quantity")) + + self.validate_conversion_factor() + self.enable_disable_item() + + def on_update(self): + # If change_in_item update Item and Price List + if self.change_in_item: + update_item_and_item_price(self) + + def on_trash(self): + # Remove template reference from item and disable item + if self.item: + try: + item = self.item + self.db_set("item", "") + frappe.delete_doc("Item", item) + except Exception: + frappe.throw(_("Not permitted. Please disable the Lab Test Template")) + + def enable_disable_item(self): + if self.is_billable: + if self.disabled: + frappe.db.set_value("Item", self.item, "disabled", 1) + else: + frappe.db.set_value("Item", self.item, "disabled", 0) + + def update_item(self): + item = frappe.get_doc("Item", self.item) + if item: + item.update( + { + "item_name": self.lab_test_name, + "item_group": self.lab_test_group, + "disabled": 0, + "standard_rate": self.lab_test_rate, + "description": self.lab_test_description, + } + ) + item.flags.ignore_mandatory = True + item.save(ignore_permissions=True) + + def item_price_exists(self): + item_price = frappe.db.exists("Item Price", {"item_code": self.item, "valid_from": today()}) + if item_price: + return item_price + return False + + def validate_conversion_factor(self): + if self.lab_test_template_type == "Single" and self.secondary_uom and not self.conversion_factor: + frappe.throw(_("Conversion Factor is mandatory")) + if self.lab_test_template_type == "Compound": + for item in self.normal_test_templates: + if item.secondary_uom and not item.conversion_factor: + frappe.throw(_("Row #{0}: Conversion Factor is mandatory").format(item.idx)) + if self.lab_test_template_type == "Grouped": + for group in self.lab_test_groups: + if ( + group.template_or_new_line == "Add New Line" + and group.secondary_uom + and not group.conversion_factor + ): + frappe.throw(_("Row #{0}: Conversion Factor is mandatory").format(group.idx)) + + +def create_item_from_template(doc): + uom = frappe.db.exists("UOM", "Unit") or frappe.db.get_single_value("Stock Settings", "stock_uom") + # Insert item + item = frappe.get_doc( + { + "doctype": "Item", + "item_code": doc.lab_test_code, + "item_name": doc.lab_test_name, + "item_group": doc.lab_test_group, + "description": doc.lab_test_description, + "is_sales_item": 1, + "is_service_item": 1, + "is_purchase_item": 0, + "is_stock_item": 0, + "include_item_in_manufacturing": 0, + "show_in_website": 0, + "is_pro_applicable": 0, + "disabled": 0 if doc.is_billable and not doc.disabled else doc.disabled, + "stock_uom": uom, + } + ).insert(ignore_permissions=True, ignore_mandatory=True) + + # Insert item price + if doc.is_billable and doc.lab_test_rate != 0.0: + price_list_name = frappe.db.get_value( + "Selling Settings", None, "selling_price_list" + ) or frappe.db.get_value("Price List", {"selling": 1}) + if doc.lab_test_rate: + make_item_price(item.name, doc.lab_test_rate) + else: + make_item_price(item.name, 0.0) + # Set item in the template + frappe.db.set_value("Lab Test Template", doc.name, "item", item.name) + + doc.reload() + + +@frappe.whitelist() +def change_test_code_from_template(lab_test_code, doc): + doc = frappe._dict(json.loads(doc)) + if frappe.db.exists({"doctype": "Item", "item_code": lab_test_code}): + frappe.throw(_("Lab Test Item {0} already exist").format(lab_test_code)) + else: + rename_doc("Item", doc.item, lab_test_code, ignore_permissions=True) + frappe.db.set_value( + "Lab Test Template", doc.name, {"lab_test_code": lab_test_code, "lab_test_name": lab_test_code} + ) + rename_doc("Lab Test Template", doc.name, lab_test_code, ignore_permissions=True) + return lab_test_code diff --git a/healthcare/healthcare/doctype/lab_test_template/lab_test_template_dashboard.py b/healthcare/healthcare/doctype/lab_test_template/lab_test_template_dashboard.py new file mode 100644 index 0000000..fef381a --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_template/lab_test_template_dashboard.py @@ -0,0 +1,8 @@ +from frappe import _ + + +def get_data(): + return { + "fieldname": "template", + "transactions": [{"label": _("Lab Tests"), "items": ["Lab Test"]}], + } diff --git a/healthcare/healthcare/doctype/lab_test_template/lab_test_template_list.js b/healthcare/healthcare/doctype/lab_test_template/lab_test_template_list.js new file mode 100644 index 0000000..08fc2cd --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_template/lab_test_template_list.js @@ -0,0 +1,7 @@ +/* +(c) ESS 2015-16 +*/ +frappe.listview_settings['Lab Test Template'] = { + add_fields: ['lab_test_name', 'lab_test_code', 'lab_test_rate'], + filters: [['disabled', '=', 'No']] +}; diff --git a/healthcare/healthcare/doctype/lab_test_template/test_lab_test_template.py b/healthcare/healthcare/doctype/lab_test_template/test_lab_test_template.py new file mode 100644 index 0000000..9a96366 --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_template/test_lab_test_template.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +# test_records = frappe.get_test_records('Lab Test Template') + + +class TestLabTestTemplate(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/lab_test_uom/__init__.py b/healthcare/healthcare/doctype/lab_test_uom/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/lab_test_uom/lab_test_uom.js b/healthcare/healthcare/doctype/lab_test_uom/lab_test_uom.js new file mode 100644 index 0000000..2107e79 --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_uom/lab_test_uom.js @@ -0,0 +1,5 @@ +// Copyright (c) 2016, ESS and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Lab Test UOM', { +}); diff --git a/healthcare/healthcare/doctype/lab_test_uom/lab_test_uom.json b/healthcare/healthcare/doctype/lab_test_uom/lab_test_uom.json new file mode 100644 index 0000000..a6d5224 --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_uom/lab_test_uom.json @@ -0,0 +1,148 @@ +{ + "allow_copy": 1, + "allow_guest_to_view": 0, + "allow_import": 1, + "allow_rename": 1, + "autoname": "field:lab_test_uom", + "beta": 1, + "creation": "2016-03-29 17:28:08.630148", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "Setup", + "editable_grid": 0, + "fields": [ + { + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "lab_test_uom", + "fieldtype": "Data", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 1, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Lab Test UOM", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 1 + }, + { + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "uom_description", + "fieldtype": "Data", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 1, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Description", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 0, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 0 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 0, + "max_attachments": 0, + "modified": "2018-09-04 11:02:53.202718", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Lab Test UOM", + "name_case": "", + "owner": "Administrator", + "permissions": [ + { + "amend": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + }, + { + "amend": 0, + "cancel": 0, + "create": 0, + "delete": 0, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Laboratory User", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 0 + } + ], + "quick_entry": 1, + "read_only": 0, + "read_only_onload": 0, + "restrict_to_domain": "Healthcare", + "search_fields": "lab_test_uom", + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "lab_test_uom", + "track_changes": 1, + "track_seen": 0, + "track_views": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/lab_test_uom/lab_test_uom.py b/healthcare/healthcare/doctype/lab_test_uom/lab_test_uom.py new file mode 100644 index 0000000..70c2ec2 --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_uom/lab_test_uom.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS and contributors +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class LabTestUOM(Document): + pass diff --git a/healthcare/healthcare/doctype/lab_test_uom/test_lab_test_uom.py b/healthcare/healthcare/doctype/lab_test_uom/test_lab_test_uom.py new file mode 100644 index 0000000..3f37ccf --- /dev/null +++ b/healthcare/healthcare/doctype/lab_test_uom/test_lab_test_uom.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +# test_records = frappe.get_test_records('Lab Test UOM') + + +class TestLabTestUOM(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/medical_code/__init__.py b/healthcare/healthcare/doctype/medical_code/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/medical_code/medical_code.js b/healthcare/healthcare/doctype/medical_code/medical_code.js new file mode 100644 index 0000000..858d171 --- /dev/null +++ b/healthcare/healthcare/doctype/medical_code/medical_code.js @@ -0,0 +1,5 @@ +// Copyright (c) 2017, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Medical Code', { +}); diff --git a/healthcare/healthcare/doctype/medical_code/medical_code.json b/healthcare/healthcare/doctype/medical_code/medical_code.json new file mode 100644 index 0000000..5d69830 --- /dev/null +++ b/healthcare/healthcare/doctype/medical_code/medical_code.json @@ -0,0 +1,69 @@ +{ + "actions": [], + "allow_copy": 1, + "allow_import": 1, + "allow_rename": 1, + "beta": 1, + "creation": "2017-06-21 13:02:56.122897", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "medical_code_standard", + "code", + "description" + ], + "fields": [ + { + "fieldname": "medical_code_standard", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "label": "Medical Code Standard", + "options": "Medical Code Standard", + "reqd": 1 + }, + { + "fieldname": "code", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Code", + "reqd": 1, + "unique": 1 + }, + { + "bold": 1, + "fieldname": "description", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Description" + } + ], + "links": [], + "modified": "2020-06-29 14:02:30.980032", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Medical Code", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "restrict_to_domain": "Healthcare", + "search_fields": "code, description", + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/medical_code/medical_code.py b/healthcare/healthcare/doctype/medical_code/medical_code.py new file mode 100644 index 0000000..e090c9b --- /dev/null +++ b/healthcare/healthcare/doctype/medical_code/medical_code.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class MedicalCode(Document): + def autoname(self): + self.name = self.medical_code_standard + " " + self.code diff --git a/healthcare/healthcare/doctype/medical_code/test_medical_code.py b/healthcare/healthcare/doctype/medical_code/test_medical_code.py new file mode 100644 index 0000000..8c775ed --- /dev/null +++ b/healthcare/healthcare/doctype/medical_code/test_medical_code.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + + +class TestMedicalCode(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/medical_code_standard/__init__.py b/healthcare/healthcare/doctype/medical_code_standard/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/medical_code_standard/medical_code_standard.js b/healthcare/healthcare/doctype/medical_code_standard/medical_code_standard.js new file mode 100644 index 0000000..ec986b0 --- /dev/null +++ b/healthcare/healthcare/doctype/medical_code_standard/medical_code_standard.js @@ -0,0 +1,5 @@ +// Copyright (c) 2017, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Medical Code Standard', { +}); diff --git a/healthcare/healthcare/doctype/medical_code_standard/medical_code_standard.json b/healthcare/healthcare/doctype/medical_code_standard/medical_code_standard.json new file mode 100644 index 0000000..886938d --- /dev/null +++ b/healthcare/healthcare/doctype/medical_code_standard/medical_code_standard.json @@ -0,0 +1,94 @@ +{ + "allow_copy": 1, + "allow_guest_to_view": 0, + "allow_import": 1, + "allow_rename": 1, + "autoname": "field:medical_code", + "beta": 1, + "creation": "2017-06-21 13:07:00.463176", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "", + "editable_grid": 1, + "engine": "InnoDB", + "fields": [ + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "medical_code", + "fieldtype": "Data", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Medical Code", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "unique": 0 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 0, + "max_attachments": 0, + "modified": "2017-08-31 14:15:40.820693", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Medical Code Standard", + "name_case": "", + "owner": "Administrator", + "permissions": [ + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + } + ], + "quick_entry": 1, + "read_only": 0, + "read_only_onload": 0, + "restrict_to_domain": "Healthcare", + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1, + "track_seen": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/medical_code_standard/medical_code_standard.py b/healthcare/healthcare/doctype/medical_code_standard/medical_code_standard.py new file mode 100644 index 0000000..72c922b --- /dev/null +++ b/healthcare/healthcare/doctype/medical_code_standard/medical_code_standard.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class MedicalCodeStandard(Document): + pass diff --git a/healthcare/healthcare/doctype/medical_code_standard/test_medical_code_standard.py b/healthcare/healthcare/doctype/medical_code_standard/test_medical_code_standard.py new file mode 100644 index 0000000..691ca47 --- /dev/null +++ b/healthcare/healthcare/doctype/medical_code_standard/test_medical_code_standard.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + + +class TestMedicalCodeStandard(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/medical_department/__init__.py b/healthcare/healthcare/doctype/medical_department/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/medical_department/medical_department.js b/healthcare/healthcare/doctype/medical_department/medical_department.js new file mode 100644 index 0000000..25aeeb8 --- /dev/null +++ b/healthcare/healthcare/doctype/medical_department/medical_department.js @@ -0,0 +1,5 @@ +// Copyright (c) 2016, ESS LLP and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Medical Department', { +}); diff --git a/healthcare/healthcare/doctype/medical_department/medical_department.json b/healthcare/healthcare/doctype/medical_department/medical_department.json new file mode 100644 index 0000000..40f14ca --- /dev/null +++ b/healthcare/healthcare/doctype/medical_department/medical_department.json @@ -0,0 +1,156 @@ +{ + "allow_copy": 1, + "allow_guest_to_view": 0, + "allow_import": 1, + "allow_rename": 1, + "autoname": "field:department", + "beta": 1, + "creation": "2017-02-27 13:38:30.806362", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "", + "editable_grid": 1, + "engine": "InnoDB", + "fields": [ + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "department", + "fieldtype": "Data", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Department", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "unique": 0 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 0, + "max_attachments": 0, + "modified": "2017-08-31 13:41:59.611698", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Medical Department", + "name_case": "", + "owner": "Administrator", + "permissions": [ + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 0, + "delete": 0, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + }, + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 0, + "delete": 0, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Nursing User", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + }, + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 0, + "delete": 0, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Laboratory User", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + }, + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + } + ], + "quick_entry": 1, + "read_only": 0, + "read_only_onload": 0, + "restrict_to_domain": "Healthcare", + "search_fields": "department", + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "department", + "track_changes": 1, + "track_seen": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/medical_department/medical_department.py b/healthcare/healthcare/doctype/medical_department/medical_department.py new file mode 100644 index 0000000..12af4e9 --- /dev/null +++ b/healthcare/healthcare/doctype/medical_department/medical_department.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and contributors +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class MedicalDepartment(Document): + pass diff --git a/healthcare/healthcare/doctype/medical_department/test_medical_department.py b/healthcare/healthcare/doctype/medical_department/test_medical_department.py new file mode 100644 index 0000000..ed4a439 --- /dev/null +++ b/healthcare/healthcare/doctype/medical_department/test_medical_department.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +# test_records = frappe.get_test_records('Medical Department') + + +class TestMedicalDepartment(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/normal_test_result/__init__.py b/healthcare/healthcare/doctype/normal_test_result/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/normal_test_result/normal_test_result.json b/healthcare/healthcare/doctype/normal_test_result/normal_test_result.json new file mode 100644 index 0000000..c8f43d3 --- /dev/null +++ b/healthcare/healthcare/doctype/normal_test_result/normal_test_result.json @@ -0,0 +1,186 @@ +{ + "actions": [], + "allow_copy": 1, + "beta": 1, + "creation": "2016-02-22 15:06:08.295224", + "doctype": "DocType", + "document_type": "Document", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "lab_test_name", + "lab_test_event", + "result_value", + "lab_test_uom", + "secondary_uom_result", + "secondary_uom", + "conversion_factor", + "column_break_10", + "allow_blank", + "normal_range", + "lab_test_comment", + "bold", + "italic", + "underline", + "template", + "require_result_value" + ], + "fields": [ + { + "fieldname": "lab_test_name", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Test Name", + "read_only": 1 + }, + { + "fieldname": "lab_test_event", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Event", + "read_only": 1 + }, + { + "depends_on": "eval:doc.require_result_value", + "fieldname": "result_value", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Result Value" + }, + { + "depends_on": "eval:doc.require_result_value", + "fieldname": "lab_test_uom", + "fieldtype": "Link", + "label": "UOM", + "options": "Lab Test UOM", + "read_only": 1 + }, + { + "depends_on": "eval:doc.require_result_value", + "fieldname": "normal_range", + "fieldtype": "Long Text", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Normal Range", + "read_only": 1 + }, + { + "depends_on": "eval:doc.require_result_value", + "fieldname": "lab_test_comment", + "fieldtype": "Data", + "hidden": 1, + "in_list_view": 1, + "label": "Comment", + "no_copy": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "fieldname": "template", + "fieldtype": "Link", + "hidden": 1, + "label": "Template", + "options": "Lab Test Template", + "print_hide": 1, + "report_hide": 1 + }, + { + "depends_on": "eval:doc.require_result_value", + "fieldname": "secondary_uom", + "fieldtype": "Link", + "label": "Secondary UOM", + "options": "Lab Test UOM", + "print_hide": 1, + "read_only": 1 + }, + { + "depends_on": "secondary_uom", + "fieldname": "conversion_factor", + "fieldtype": "Float", + "label": "Conversion Factor", + "mandatory_depends_on": "secondary_uom", + "print_hide": 1, + "read_only": 1 + }, + { + "depends_on": "eval:doc.require_result_value && doc.result_value", + "fieldname": "secondary_uom_result", + "fieldtype": "Data", + "label": "Secondary UOM Result", + "no_copy": 1, + "print_hide": 1, + "read_only": 1 + }, + { + "allow_on_submit": 1, + "default": "0", + "depends_on": "eval:doc.require_result_value", + "fieldname": "bold", + "fieldtype": "Check", + "label": "Bold", + "no_copy": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "allow_on_submit": 1, + "default": "0", + "depends_on": "eval:doc.require_result_value", + "fieldname": "italic", + "fieldtype": "Check", + "label": "Italic", + "no_copy": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "allow_on_submit": 1, + "default": "0", + "depends_on": "eval:doc.require_result_value", + "fieldname": "underline", + "fieldtype": "Check", + "label": "Underline", + "no_copy": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "fieldname": "column_break_10", + "fieldtype": "Column Break" + }, + { + "default": "0", + "fieldname": "require_result_value", + "fieldtype": "Check", + "hidden": 1, + "label": "Require Result Value", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "default": "1", + "depends_on": "eval:doc.require_result_value", + "fieldname": "allow_blank", + "fieldtype": "Check", + "label": "Allow Blank", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + } + ], + "istable": 1, + "links": [], + "modified": "2020-07-08 16:03:17.522893", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Normal Test Result", + "owner": "Administrator", + "permissions": [], + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC" +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/normal_test_result/normal_test_result.py b/healthcare/healthcare/doctype/normal_test_result/normal_test_result.py new file mode 100644 index 0000000..26c34d9 --- /dev/null +++ b/healthcare/healthcare/doctype/normal_test_result/normal_test_result.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS and contributors +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class NormalTestResult(Document): + pass diff --git a/healthcare/healthcare/doctype/normal_test_template/__init__.py b/healthcare/healthcare/doctype/normal_test_template/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/normal_test_template/normal_test_template.json b/healthcare/healthcare/doctype/normal_test_template/normal_test_template.json new file mode 100644 index 0000000..8dd6476 --- /dev/null +++ b/healthcare/healthcare/doctype/normal_test_template/normal_test_template.json @@ -0,0 +1,84 @@ +{ + "actions": [], + "allow_copy": 1, + "beta": 1, + "creation": "2016-02-22 16:09:54.310628", + "doctype": "DocType", + "document_type": "Setup", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "heading_text", + "lab_test_event", + "allow_blank", + "lab_test_uom", + "secondary_uom", + "conversion_factor", + "column_break_5", + "normal_range" + ], + "fields": [ + { + "fieldname": "heading_text", + "fieldtype": "Heading", + "ignore_xss_filter": 1, + "label": "Test" + }, + { + "fieldname": "lab_test_event", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Event" + }, + { + "fieldname": "lab_test_uom", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "label": "UOM", + "options": "Lab Test UOM" + }, + { + "fieldname": "normal_range", + "fieldtype": "Long Text", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Normal Range" + }, + { + "fieldname": "column_break_5", + "fieldtype": "Column Break" + }, + { + "fieldname": "secondary_uom", + "fieldtype": "Link", + "label": "Secondary UOM", + "options": "Lab Test UOM" + }, + { + "depends_on": "secondary_uom", + "fieldname": "conversion_factor", + "fieldtype": "Float", + "label": "Conversion Factor", + "mandatory_depends_on": "secondary_uom" + }, + { + "default": "0", + "fieldname": "allow_blank", + "fieldtype": "Check", + "label": "Allow Blank" + } + ], + "istable": 1, + "links": [], + "modified": "2020-06-23 13:28:40.156224", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Normal Test Template", + "owner": "Administrator", + "permissions": [], + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC" +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/normal_test_template/normal_test_template.py b/healthcare/healthcare/doctype/normal_test_template/normal_test_template.py new file mode 100644 index 0000000..912f4fd --- /dev/null +++ b/healthcare/healthcare/doctype/normal_test_template/normal_test_template.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS and contributors +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class NormalTestTemplate(Document): + pass diff --git a/healthcare/healthcare/doctype/nursing_checklist_template/__init__.py b/healthcare/healthcare/doctype/nursing_checklist_template/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/nursing_checklist_template/nursing_checklist_template.js b/healthcare/healthcare/doctype/nursing_checklist_template/nursing_checklist_template.js new file mode 100644 index 0000000..e3ad5c8 --- /dev/null +++ b/healthcare/healthcare/doctype/nursing_checklist_template/nursing_checklist_template.js @@ -0,0 +1,8 @@ +// Copyright (c) 2021, healthcare and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Nursing Checklist Template', { + // refresh: function(frm) { + + // } +}); diff --git a/healthcare/healthcare/doctype/nursing_checklist_template/nursing_checklist_template.json b/healthcare/healthcare/doctype/nursing_checklist_template/nursing_checklist_template.json new file mode 100644 index 0000000..42f8942 --- /dev/null +++ b/healthcare/healthcare/doctype/nursing_checklist_template/nursing_checklist_template.json @@ -0,0 +1,94 @@ +{ + "actions": [], + "allow_rename": 1, + "autoname": "field:title", + "creation": "2021-10-20 12:03:38.538651", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "disabled", + "section_break_2", + "title", + "department", + "checklist_section", + "tasks" + ], + "fields": [ + { + "fieldname": "title", + "fieldtype": "Data", + "label": "Title", + "reqd": 1, + "unique": 1 + }, + { + "fieldname": "department", + "fieldtype": "Link", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Department", + "options": "Medical Department" + }, + { + "fieldname": "tasks", + "fieldtype": "Table", + "label": "Tasks", + "options": "Nursing Checklist Template Task", + "reqd": 1 + }, + { + "default": "0", + "fieldname": "disabled", + "fieldtype": "Check", + "label": "Disabled" + }, + { + "fieldname": "section_break_2", + "fieldtype": "Section Break" + }, + { + "fieldname": "checklist_section", + "fieldtype": "Section Break", + "label": "Checklist" + } + ], + "index_web_pages_for_search": 1, + "links": [], + "modified": "2022-07-25 19:27:22.028262", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Nursing Checklist Template", + "naming_rule": "By fieldname", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + } + ], + "sort_field": "modified", + "sort_order": "DESC", + "states": [], + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/nursing_checklist_template/nursing_checklist_template.py b/healthcare/healthcare/doctype/nursing_checklist_template/nursing_checklist_template.py new file mode 100644 index 0000000..757d03a --- /dev/null +++ b/healthcare/healthcare/doctype/nursing_checklist_template/nursing_checklist_template.py @@ -0,0 +1,9 @@ +# Copyright (c) 2021, healthcare and contributors +# For license information, please see license.txt + +# import frappe +from frappe.model.document import Document + + +class NursingChecklistTemplate(Document): + pass diff --git a/healthcare/healthcare/doctype/nursing_checklist_template/test_nursing_checklist_template.py b/healthcare/healthcare/doctype/nursing_checklist_template/test_nursing_checklist_template.py new file mode 100644 index 0000000..274c88e --- /dev/null +++ b/healthcare/healthcare/doctype/nursing_checklist_template/test_nursing_checklist_template.py @@ -0,0 +1,9 @@ +# Copyright (c) 2021, healthcare and Contributors +# See license.txt + +# import frappe +import unittest + + +class TestNursingChecklistTemplate(unittest.TestCase): + pass diff --git a/healthcare/healthcare/doctype/nursing_checklist_template/test_records.json b/healthcare/healthcare/doctype/nursing_checklist_template/test_records.json new file mode 100644 index 0000000..e277f25 --- /dev/null +++ b/healthcare/healthcare/doctype/nursing_checklist_template/test_records.json @@ -0,0 +1,18 @@ +[ + { + "doctype": "Nursing Checklist Template", + "name": "Discharge checklist", + "title": "Discharge checklist", + "tasks": [ + { + "doctype": "Nursing Checklist Template Task", + "activity": "BP Check", + "mandatory": 1, + "task_duration": 600, + "parent": "Discharge checklist", + "parentfield": "tasks", + "parenttype": "Nursing Checklist Template" + } + ] + } +] \ No newline at end of file diff --git a/healthcare/healthcare/doctype/nursing_checklist_template_task/__init__.py b/healthcare/healthcare/doctype/nursing_checklist_template_task/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/nursing_checklist_template_task/nursing_checklist_template_task.json b/healthcare/healthcare/doctype/nursing_checklist_template_task/nursing_checklist_template_task.json new file mode 100644 index 0000000..4f07cd0 --- /dev/null +++ b/healthcare/healthcare/doctype/nursing_checklist_template_task/nursing_checklist_template_task.json @@ -0,0 +1,104 @@ +{ + "actions": [], + "allow_rename": 1, + "creation": "2021-10-28 06:34:02.606386", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "activity", + "mandatory", + "type", + "time_offset", + "description", + "column_break_5", + "task_duration", + "task_doctype", + "role" + ], + "fields": [ + { + "fieldname": "activity", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Activity", + "options": "Healthcare Activity" + }, + { + "columns": 3, + "fetch_from": "activity.description", + "fetch_if_empty": 1, + "fieldname": "description", + "fieldtype": "Small Text", + "label": "Description" + }, + { + "columns": 1, + "fieldname": "type", + "fieldtype": "Select", + "in_list_view": 1, + "label": "Type", + "options": "\nPre-Op\nPost-Op" + }, + { + "fetch_from": "activity.role", + "fetch_if_empty": 1, + "fieldname": "role", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Role", + "options": "Role" + }, + { + "columns": 1, + "default": "0", + "fieldname": "mandatory", + "fieldtype": "Check", + "in_list_view": 1, + "label": "Mandatory" + }, + { + "description": "System will validate if a document of this type is created and linked before completing the Nursing Task - for example, Vital Signs if the task is supposed to capture the vitals of the Patient", + "fetch_from": "activity.task_doctype", + "fetch_if_empty": 1, + "fieldname": "task_doctype", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Task Doctype", + "options": "DocType" + }, + { + "fieldname": "column_break_5", + "fieldtype": "Column Break" + }, + { + "description": "Default duration which the task can take to complete", + "fetch_from": "activity.activity_duration", + "fetch_if_empty": 1, + "fieldname": "task_duration", + "fieldtype": "Duration", + "in_list_view": 1, + "label": "Task Duration" + }, + { + "description": "The time duration before or after the event on which the Nursing Task is to be performed. The Nursing Task start time will be set based on this.", + "fieldname": "time_offset", + "fieldtype": "Duration", + "in_list_view": 1, + "label": "Time Offset" + } + ], + "index_web_pages_for_search": 1, + "istable": 1, + "links": [], + "modified": "2022-07-25 19:33:44.109535", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Nursing Checklist Template Task", + "owner": "Administrator", + "permissions": [], + "sort_field": "modified", + "sort_order": "DESC", + "states": [], + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/nursing_checklist_template_task/nursing_checklist_template_task.py b/healthcare/healthcare/doctype/nursing_checklist_template_task/nursing_checklist_template_task.py new file mode 100644 index 0000000..dc95ea3 --- /dev/null +++ b/healthcare/healthcare/doctype/nursing_checklist_template_task/nursing_checklist_template_task.py @@ -0,0 +1,9 @@ +# Copyright (c) 2021, healthcare and contributors +# For license information, please see license.txt + +# import frappe +from frappe.model.document import Document + + +class NursingChecklistTemplateTask(Document): + pass diff --git a/healthcare/healthcare/doctype/nursing_task/__init__.py b/healthcare/healthcare/doctype/nursing_task/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/nursing_task/nursing_task.js b/healthcare/healthcare/doctype/nursing_task/nursing_task.js new file mode 100644 index 0000000..89fb14d --- /dev/null +++ b/healthcare/healthcare/doctype/nursing_task/nursing_task.js @@ -0,0 +1,107 @@ +// Copyright (c) 2021, healthcare and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Nursing Task', { + + onload: function(frm) { + + const task_document_field = frm.get_docfield("task_document_name"); + task_document_field.get_route_options_for_new_doc = () => { + if (frm.is_new()) return; + return { + 'company': frm.doc.company, + 'medical_department': frm.doc.medical_department, + 'service_unit': frm.doc.service_unit, + 'patient': frm.doc.patient, + }; + }; + + if (frm.doc.task_doctype) { + // set description + frm.set_df_property('task_document_name', 'description', + `Create and link a new ${frm.doc.task_doctype} document to complete this task`); + + // set filters + let filters = {}; + frappe.model.with_doctype(frm.doc.task_doctype, function() { + if (frappe.meta.has_field(frm.doc.task_doctype, 'patient')) { + filters['patient'] = frm.doc.patient; + } + + frm.set_query('task_document_name', () => { + return { + filters: filters + } + }); + }); + } + }, + + refresh: function(frm) { + + // TODO: handle routing back to nursing task form + // frm.trigger('show_form_route_button'); + + if (frm.is_new()) { + frm.set_value('status', 'Draft'); + } + + let status_list = ['Accepted', 'Received', 'Rejected', + 'Ready', 'Failed', 'Entered in Error', 'On Hold']; + if (status_list.includes(frm.doc.status) || frm.doc.status == 'Requested') { + + // set primary action to start + frm.page.set_primary_action(__('Start'), () => { + frm.events.update_status(frm, 'In Progress'); + }); + + // optionally allow updating other statuses + status_list.filter(status => status != frm.doc.status).forEach(status => { + + frm.add_custom_button(__(`${status}`), () => { + frm.events.update_status(frm, `${status}`); + }, __('Update Status')); + + }); + } + + if (frm.doc.status == 'In Progress') { + frm.page.set_primary_action(__('Complete'), () => { + if (frm.doc.task_doctype){ + frm.set_df_property('task_document_name', 'reqd', 1); + } + frm.events.update_status(frm, 'Completed'); + }); + + frm.add_custom_button(__('Hold'), () => { + frm.set_df_property('task_document_name', 'reqd', 0); + frm.events.update_status(frm, 'On Hold'); + }); + } + }, + + update_status(frm, status) { + frm.set_value('status', status); + frm.save('Update'); + frm.reload_doc(); + }, + + show_form_route_button: function(frm) { + + // add custom button to route to new Task DocType form + if (!frm.is_new() && !frm.is_dirty() && frm.doc.task_doctype) { + + frm.add_custom_button(__(`New ${frm.doc.task_doctype}`), () => { + frappe.route_options = { + 'patient': frm.doc.patient, + 'medical_department': frm.doc.medical_department, + 'company': frm.doc.company, + 'service_unit': frm.doc.service_unit, + }; + + frappe.new_doc(frm.doc.task_doctype); + }); + + } + } +}); diff --git a/healthcare/healthcare/doctype/nursing_task/nursing_task.json b/healthcare/healthcare/doctype/nursing_task/nursing_task.json new file mode 100644 index 0000000..6334033 --- /dev/null +++ b/healthcare/healthcare/doctype/nursing_task/nursing_task.json @@ -0,0 +1,384 @@ +{ + "actions": [], + "allow_rename": 1, + "autoname": "naming_series:", + "creation": "2022-01-18 15:18:15.657622", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "naming_series", + "title", + "date", + "user", + "column_break_5", + "company", + "service_unit", + "medical_department", + "status", + "task_details", + "activity", + "mandatory", + "column_break_2", + "description", + "patient_details_section", + "patient", + "patient_name", + "age", + "gender", + "column_break_6", + "inpatient_record", + "inpatient_status", + "task_schedule_section", + "requested_start_time", + "requested_end_time", + "duration", + "column_break_18", + "task_start_time", + "task_end_time", + "task_duration", + "source_section", + "reference_doctype", + "amended_from", + "column_break_8", + "reference_name", + "section_break_28", + "task_doctype", + "task_document_name", + "notes" + ], + "fields": [ + { + "fieldname": "activity", + "fieldtype": "Link", + "in_standard_filter": 1, + "label": "Activity", + "options": "Healthcare Activity", + "read_only_depends_on": "eval:doc.reference_name", + "reqd": 1 + }, + { + "fetch_from": "activity.description", + "fetch_if_empty": 1, + "fieldname": "description", + "fieldtype": "Small Text", + "label": "Description", + "read_only": 1 + }, + { + "fieldname": "reference_doctype", + "fieldtype": "Link", + "label": "Reference Doctype", + "no_copy": 1, + "options": "DocType", + "read_only": 1 + }, + { + "fieldname": "reference_name", + "fieldtype": "Dynamic Link", + "label": "Reference Name", + "no_copy": 1, + "options": "reference_doctype", + "read_only": 1 + }, + { + "allow_on_submit": 1, + "default": "Draft", + "fieldname": "status", + "fieldtype": "Select", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Status", + "options": "Draft\nRequested\nReceived\nAccepted\nRejected\nReady\nIn Progress\nOn Hold\nCompleted\nFailed\nCancelled\nEntered in Error", + "read_only": 1, + "reqd": 1 + }, + { + "fieldname": "column_break_2", + "fieldtype": "Column Break" + }, + { + "fieldname": "column_break_8", + "fieldtype": "Column Break" + }, + { + "fieldname": "user", + "fieldtype": "Link", + "label": "User", + "options": "User" + }, + { + "fieldname": "amended_from", + "fieldtype": "Link", + "label": "Amended From", + "no_copy": 1, + "options": "Nursing Task", + "print_hide": 1, + "read_only": 1 + }, + { + "fieldname": "task_details", + "fieldtype": "Section Break", + "label": "Task Details" + }, + { + "fieldname": "naming_series", + "fieldtype": "Select", + "label": "Naming Series", + "options": "HLC-NUR-.YYYY.-" + }, + { + "default": "0", + "fieldname": "mandatory", + "fieldtype": "Check", + "label": "Mandatory", + "read_only_depends_on": "eval:doc.reference_name" + }, + { + "fetch_from": "activity.task_doctype", + "fetch_if_empty": 1, + "fieldname": "task_doctype", + "fieldtype": "Link", + "label": "Task Doctype", + "options": "DocType" + }, + { + "allow_on_submit": 1, + "description": "Create and link the document to complete this task", + "fieldname": "task_document_name", + "fieldtype": "Dynamic Link", + "label": "Task Document Name", + "no_copy": 1, + "options": "task_doctype", + "read_only": 1, + "read_only_depends_on": "eval:in_list([\"Completed\", \"Failed\", \"Cancelled\"], doc.status)" + }, + { + "fieldname": "patient_details_section", + "fieldtype": "Section Break", + "label": "Patient Details" + }, + { + "fetch_from": "patient.patient_name", + "fieldname": "patient_name", + "fieldtype": "Data", + "label": "Patient Name", + "read_only": 1 + }, + { + "fieldname": "age", + "fieldtype": "Data", + "label": "Age", + "read_only": 1 + }, + { + "fetch_from": "patient.sex", + "fieldname": "gender", + "fieldtype": "Link", + "label": "Gender", + "options": "Gender", + "read_only": 1 + }, + { + "fieldname": "column_break_6", + "fieldtype": "Column Break" + }, + { + "fetch_from": "patient.inpatient_record", + "fieldname": "inpatient_record", + "fieldtype": "Link", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Inpatient Record", + "options": "Inpatient Record", + "read_only": 1 + }, + { + "fetch_from": "patient.inpatient_status", + "fieldname": "inpatient_status", + "fieldtype": "Data", + "label": "Inpatient Status", + "read_only": 1 + }, + { + "fieldname": "company", + "fieldtype": "Link", + "label": "Company", + "options": "Company", + "read_only_depends_on": "eval:doc.reference_name", + "reqd": 1 + }, + { + "fieldname": "service_unit", + "fieldtype": "Link", + "label": "Service Unit", + "options": "Healthcare Service Unit", + "read_only_depends_on": "eval:doc.reference_name" + }, + { + "default": "Today", + "fieldname": "date", + "fieldtype": "Date", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Date", + "reqd": 1 + }, + { + "fieldname": "section_break_28", + "fieldtype": "Section Break", + "label": "Task Resolution" + }, + { + "allow_on_submit": 1, + "fieldname": "notes", + "fieldtype": "Text Editor", + "label": "Notes", + "no_copy": 1, + "read_only_depends_on": "eval:in_list([\"Completed\", \"Failed\", \"Cancelled\"], doc.status)" + }, + { + "bold": 1, + "fieldname": "patient", + "fieldtype": "Link", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Patient", + "options": "Patient", + "read_only_depends_on": "eval:doc.reference_name", + "reqd": 1 + }, + { + "fieldname": "title", + "fieldtype": "Data", + "label": "Title", + "read_only": 1 + }, + { + "fieldname": "column_break_5", + "fieldtype": "Column Break" + }, + { + "fieldname": "requested_start_time", + "fieldtype": "Datetime", + "label": "Requested Start Time", + "read_only_depends_on": "eval:doc.reference_name" + }, + { + "fieldname": "requested_end_time", + "fieldtype": "Datetime", + "label": "Requested End Time", + "read_only_depends_on": "eval:doc.reference_name" + }, + { + "fetch_from": "activity.activity_duration", + "fetch_if_empty": 1, + "fieldname": "duration", + "fieldtype": "Duration", + "label": "Duration", + "read_only_depends_on": "eval:doc.reference_name" + }, + { + "fieldname": "task_schedule_section", + "fieldtype": "Section Break", + "label": "Task Schedule" + }, + { + "fieldname": "column_break_18", + "fieldtype": "Column Break" + }, + { + "allow_on_submit": 1, + "fieldname": "task_start_time", + "fieldtype": "Datetime", + "label": "Task Start Time", + "read_only_depends_on": "eval:in_list([\"Completed\", \"Failed\", \"Cancelled\"], doc.status)" + }, + { + "allow_on_submit": 1, + "fieldname": "task_end_time", + "fieldtype": "Datetime", + "label": "Task End Time", + "read_only_depends_on": "eval:in_list([\"Completed\", \"Failed\", \"Cancelled\"], doc.status)" + }, + { + "allow_on_submit": 1, + "fieldname": "task_duration", + "fieldtype": "Duration", + "label": "Task Duration", + "read_only": 1 + }, + { + "fieldname": "medical_department", + "fieldtype": "Link", + "label": "Medical Department", + "options": "Medical Department", + "read_only_depends_on": "eval:doc.reference_name" + }, + { + "fieldname": "source_section", + "fieldtype": "Section Break", + "label": "Source" + } + ], + "index_web_pages_for_search": 1, + "is_submittable": 1, + "links": [], + "modified": "2022-01-19 15:34:31.760433", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Nursing Task", + "naming_rule": "By \"Naming Series\" field", + "owner": "Administrator", + "permissions": [ + { + "amend": 1, + "cancel": 1, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "submit": 1, + "write": 1 + }, + { + "amend": 1, + "cancel": 1, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "submit": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Nursing User", + "share": 1, + "submit": 1, + "write": 1 + } + ], + "search_fields": "patient, activity, user", + "sort_field": "requested_start_time", + "sort_order": "DESC", + "states": [], + "title_field": "title", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/nursing_task/nursing_task.py b/healthcare/healthcare/doctype/nursing_task/nursing_task.py new file mode 100644 index 0000000..b244e8f --- /dev/null +++ b/healthcare/healthcare/doctype/nursing_task/nursing_task.py @@ -0,0 +1,141 @@ +# Copyright (c) 2021, healthcare and contributors +# For license information, please see license.txt +import json +from six import string_types + +import frappe +from frappe.model.document import Document +from frappe import _ +from frappe.utils import now_datetime, add_to_date, getdate, time_diff_in_seconds, get_datetime +from erpnext import get_default_company + + +class NursingTask(Document): + def before_insert(self): + # set requested start / end + self.set_task_schedule() + + self.title = "{} - {}".format(_(self.patient), _(self.activity)) + + self.age = frappe.get_doc("Patient", self.patient).get_age() + + def validate(self): + if self.status == "Requested": + # auto submit if status is Requested + self.docstatus = 1 + + def on_submit(self): + self.db_set("status", "Requested") + + def on_cancel(self): + if self.status == "Completed": + frappe.throw(_("Not Allowed to cancel Nursing Task with status 'Completed'")) + + self.db_set("status", "Cancelled") + + def on_update_after_submit(self): + if self.status == "Completed" and self.task_doctype and not self.task_document_name: + frappe.throw(_("Not Allowed to 'Complete' Nursing Task without linking Task Document")) + + if self.status == "Draft": + frappe.throw(_("Nursing Task cannot be 'Draft' after submission")) + + if self.status == "In Progress": + if not self.task_start_time: + self.db_set("task_start_time", now_datetime()) + + elif self.status == "Completed": + self.db_set( + { + "task_end_time": now_datetime(), + "task_duration": time_diff_in_seconds(self.task_end_time, self.task_start_time), + } + ) + + self.notify_update() + + def set_task_schedule(self): + if not self.requested_start_time or (get_datetime(self.requested_start_time) < now_datetime()): + self.requested_start_time = now_datetime() + + if not self.requested_end_time: + if not self.duration: + self.duration = frappe.db.get_value("Healthcare Activity", self.activity, "duration") + self.requested_end_time = add_to_date(self.requested_start_time, seconds=self.duration) + + # set date based on requested_start_time + self.date = getdate(self.requested_start_time) + + @classmethod + def create_nursing_tasks_from_template( + cls, template, doc, start_time=now_datetime(), post_event=True + ): + tasks = frappe.get_all( + "Nursing Checklist Template Task", + filters={"parent": template}, + fields=["*"], + ) + NursingTask.create_nursing_tasks(tasks, doc, start_time, post_event) + + @classmethod + def create_nursing_tasks(cls, tasks, doc, start_time, post_event=True): + for task in tasks: + medical_department = ( + doc.get("department") if doc.get("department") else doc.get("medical_department") + ) + if doc.get("doctype") == "Inpatient Record": + service_unit = ( + frappe.db.get_value("Inpatient Occupancy", {"parent": doc.name, "left": 0}, "service_unit"), + ) + else: + service_unit = ( + doc.get("service_unit") if doc.get("service_unit") else doc.get("healthcare_service_unit") + ) + + options = { + "doctype": "Nursing Task", + "status": "Requested", + "company": doc.get("company", get_default_company()), + "service_unit": service_unit, + "medical_department": medical_department, + "reference_doctype": doc.get("doctype"), + "reference_name": doc.get("name"), + "patient": doc.get("patient"), + "activity": task.activity, + "mandatory": task.mandatory, + "duration": task.task_duration, + "task_doctype": task.task_doctype, + } + + if task.time_offset: + time_offset = task.time_offset if not post_event else 0 - task.time_offset + requested_start_time = add_to_date(start_time, seconds=time_offset) + else: + requested_start_time = start_time + + options.update({"requested_start_time": requested_start_time}) + + options = {key: value for (key, value) in options.items() if value} + frappe.get_doc(options).insert() + + @classmethod + def cancel_nursing_tasks(cls, dt, dn): + tasks = frappe.db.get_all( + "Nursing Task", + filters={ + "reference_doctype": dt, + "reference_document": dn, + "status": ["!=", "Completed", "Cancelled"], + }, + ) + + for task in tasks: + frappe.get_doc("Nursing Task", task).cancel() + + +@frappe.whitelist() +def create_nursing_tasks_from_template(template, doc, start_time=now_datetime(), post_event=True): + if isinstance(doc, string_types): + doc = json.loads(doc) + + NursingTask.create_nursing_tasks_from_template(template, doc, start_time, post_event) diff --git a/healthcare/healthcare/doctype/nursing_task/nursing_task_list.js b/healthcare/healthcare/doctype/nursing_task/nursing_task_list.js new file mode 100644 index 0000000..219603d --- /dev/null +++ b/healthcare/healthcare/doctype/nursing_task/nursing_task_list.js @@ -0,0 +1,37 @@ +// Copyright (c) 2021, healthcare and contributors +// For license information, please see license.txt + +frappe.listview_settings['Nursing Task'] = { + filters: [['status', 'not in', ['Failed', 'Cancelled', 'Completed']]], + hide_name_column: true, + has_indicator_for_draft: true, + get_indicator: function (doc) { + if (doc.status === 'Draft') { + return [__('Draft'), 'orange', 'status, =, Draft']; + + } else if (doc.status === 'Requested') { + return [__('Requested'), 'orange', 'status, =, Requested']; + + } else if (doc.status === 'Rejected') { + return [__('Rejected'), 'red', 'status, =, Rejected']; + + } else if (doc.status === 'Entered in Error') { + return [__('Entered in Error'), 'red', 'status, =, Entered In Error']; + + } else if (doc.status === 'Completed') { + return [__('Completed'), 'green', 'status, =, Completed']; + + } else if (doc.status === 'Cancelled') { + return [__('Cancelled'), 'grey', 'status, =, Cancelled']; + + } else if (doc.status === 'Failed') { + return [__('Failed'), 'red', 'status, =, Failed']; + + } else if (doc.status === 'In Progress') { + return [__('In Progress'), 'blue', 'status, =, In Progress']; + + } else { // Received, On Hold, Accepted, Ready + return [__(doc.status), 'light-blue', `status, =, ${doc.status}`]; + } + } +}; \ No newline at end of file diff --git a/healthcare/healthcare/doctype/nursing_task/test_nursing_task.py b/healthcare/healthcare/doctype/nursing_task/test_nursing_task.py new file mode 100644 index 0000000..03e92b2 --- /dev/null +++ b/healthcare/healthcare/doctype/nursing_task/test_nursing_task.py @@ -0,0 +1,134 @@ +# Copyright (c) 2021, healthcare and Contributors +# See license.txt + +import frappe + +from frappe.tests.utils import FrappeTestCase +from frappe.utils import now_datetime +from healthcare.healthcare.doctype.clinical_procedure.test_clinical_procedure import ( + create_procedure, +) +from healthcare.healthcare.doctype.inpatient_record.inpatient_record import ( + admit_patient, + discharge_patient, +) +from healthcare.healthcare.doctype.inpatient_record.test_inpatient_record import ( + create_inpatient, + get_healthcare_service_unit, +) +from healthcare.healthcare.doctype.lab_test.test_lab_test import ( + create_lab_test_template, + create_lab_test, +) +from healthcare.healthcare.doctype.nursing_task.nursing_task import NursingTask +from healthcare.healthcare.doctype.patient_appointment.test_patient_appointment import ( + create_clinical_procedure_template, + create_healthcare_docs, +) +from healthcare.healthcare.doctype.therapy_plan.test_therapy_plan import create_therapy_plan +from healthcare.healthcare.doctype.therapy_session.test_therapy_session import ( + create_therapy_session, +) +from healthcare.healthcare.doctype.therapy_type.test_therapy_type import create_therapy_type + + +class TestNursingTask(FrappeTestCase): + def setUp(self) -> None: + nursing_checklist_templates = frappe.get_test_records("Nursing Checklist Template") + self.nc_template = frappe.get_doc(nursing_checklist_templates[0]).insert( + ignore_if_duplicate=True + ) + + self.settings = frappe.get_single("Healthcare Settings") + self.settings.validate_nursing_checklists = 1 + self.settings.save() + + self.patient, self.practitioner = create_healthcare_docs() + + def test_lab_test_submission_should_validate_pending_nursing_tasks(self): + self.lt_template = create_lab_test_template() + self.lt_template.nursing_checklist_template = self.nc_template.name + self.lt_template.save() + + lab_test = create_lab_test(self.lt_template) + lab_test.descriptive_test_items[0].result_value = 12 + lab_test.descriptive_test_items[1].result_value = 1 + lab_test.descriptive_test_items[2].result_value = 2.3 + lab_test.save() + + self.assertRaises(frappe.ValidationError, lab_test.submit) + + complete_nusing_tasks(lab_test) + lab_test.submit() + + def test_start_clinical_procedure_should_validate_pending_nursing_tasks(self): + procedure_template = create_clinical_procedure_template() + procedure_template.allow_stock_consumption = 1 + procedure_template.pre_op_nursing_checklist_template = self.nc_template.name + procedure_template.save() + + procedure = create_procedure(procedure_template, self.patient, self.practitioner) + self.assertRaises(frappe.ValidationError, procedure.start_procedure) + + complete_nusing_tasks(procedure) + procedure.start_procedure() + + def test_admit_inpatient_should_validate_pending_nursing_tasks(self): + self.settings.allow_discharge_despite_unbilled_services = 1 + self.settings.save() + + ip_record = create_inpatient(self.patient) + ip_record.admission_nursing_checklist_template = self.nc_template.name + ip_record.expected_length_of_stay = 0 + ip_record.save(ignore_permissions=True) + NursingTask.create_nursing_tasks_from_template( + ip_record.admission_nursing_checklist_template, ip_record, start_time=now_datetime() + ) + + service_unit = get_healthcare_service_unit() + kwargs = { + "inpatient_record": ip_record, + "service_unit": service_unit, + "check_in": now_datetime(), + } + self.assertRaises(frappe.ValidationError, admit_patient, **kwargs) + + complete_nusing_tasks(ip_record) + admit_patient(**kwargs) + + ip_record.discharge_nursing_checklist_template = self.nc_template.name + ip_record.save() + NursingTask.create_nursing_tasks_from_template( + ip_record.admission_nursing_checklist_template, ip_record, start_time=now_datetime() + ) + + self.assertRaises(frappe.ValidationError, discharge_patient, inpatient_record=ip_record) + + complete_nusing_tasks(ip_record) + discharge_patient(ip_record) + + def test_submit_therapy_session_should_validate_pending_nursing_tasks(self): + therapy_type = create_therapy_type() + therapy_type.nursing_checklist_template = self.nc_template.name + therapy_type.save() + + therapy_plan = create_therapy_plan() + therapy_session = create_therapy_session(self.patient, therapy_type.name, therapy_plan.name) + + self.assertRaises(frappe.ValidationError, therapy_session.submit) + + complete_nusing_tasks(therapy_session) + therapy_session.submit() + + +def complete_nusing_tasks(document): + filters = { + "reference_name": document.name, + "mandatory": 1, + "status": ["not in", ["Completed", "Cancelled"]], + } + tasks = frappe.get_all("Nursing Task", filters=filters) + for task_name in tasks: + task = frappe.get_doc("Nursing Task", task_name) + task.status = "Completed" + task.save() diff --git a/healthcare/healthcare/doctype/organism/__init__.py b/healthcare/healthcare/doctype/organism/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/organism/organism.js b/healthcare/healthcare/doctype/organism/organism.js new file mode 100644 index 0000000..e839d8f --- /dev/null +++ b/healthcare/healthcare/doctype/organism/organism.js @@ -0,0 +1,5 @@ +// Copyright (c) 2019, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Organism', { +}); diff --git a/healthcare/healthcare/doctype/organism/organism.json b/healthcare/healthcare/doctype/organism/organism.json new file mode 100644 index 0000000..88a7686 --- /dev/null +++ b/healthcare/healthcare/doctype/organism/organism.json @@ -0,0 +1,152 @@ +{ + "allow_copy": 0, + "allow_events_in_timeline": 0, + "allow_guest_to_view": 0, + "allow_import": 0, + "allow_rename": 0, + "autoname": "field:organism", + "beta": 1, + "creation": "2019-09-06 16:29:07.797960", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "", + "editable_grid": 1, + "engine": "InnoDB", + "fields": [ + { + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fetch_if_empty": 0, + "fieldname": "organism", + "fieldtype": "Data", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Organism", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 1 + }, + { + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fetch_if_empty": 0, + "fieldname": "abbr", + "fieldtype": "Data", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 0, + "in_standard_filter": 0, + "label": "Abbr", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 0, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 1 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 0, + "max_attachments": 0, + "modified": "2019-10-04 19:45:33.353753", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Organism", + "name_case": "", + "owner": "Administrator", + "permissions": [ + { + "amend": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + }, + { + "amend": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + } + ], + "quick_entry": 1, + "read_only": 0, + "read_only_onload": 0, + "restrict_to_domain": "Healthcare", + "search_fields": "organism, abbr", + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "organism", + "track_changes": 0, + "track_seen": 0, + "track_views": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/organism/organism.py b/healthcare/healthcare/doctype/organism/organism.py new file mode 100644 index 0000000..8cfeb1e --- /dev/null +++ b/healthcare/healthcare/doctype/organism/organism.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2019, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class Organism(Document): + pass diff --git a/healthcare/healthcare/doctype/organism/test_organism.py b/healthcare/healthcare/doctype/organism/test_organism.py new file mode 100644 index 0000000..3a77c91 --- /dev/null +++ b/healthcare/healthcare/doctype/organism/test_organism.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2019, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + + +class TestOrganism(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/organism_test_item/__init__.py b/healthcare/healthcare/doctype/organism_test_item/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/organism_test_item/organism_test_item.json b/healthcare/healthcare/doctype/organism_test_item/organism_test_item.json new file mode 100644 index 0000000..56d0a4d --- /dev/null +++ b/healthcare/healthcare/doctype/organism_test_item/organism_test_item.json @@ -0,0 +1,144 @@ +{ + "allow_copy": 0, + "allow_events_in_timeline": 0, + "allow_guest_to_view": 0, + "allow_import": 0, + "allow_rename": 0, + "beta": 1, + "creation": "2019-09-06 16:37:59.698996", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "", + "editable_grid": 1, + "engine": "InnoDB", + "fields": [ + { + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fetch_if_empty": 0, + "fieldname": "organism", + "fieldtype": "Link", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Organism", + "length": 0, + "no_copy": 0, + "options": "Organism", + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 0 + }, + { + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fetch_if_empty": 0, + "fieldname": "colony_population", + "fieldtype": "Small Text", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Colony Population", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 0, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 0 + }, + { + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fetch_if_empty": 0, + "fieldname": "colony_uom", + "fieldtype": "Link", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Colony UOM", + "length": 0, + "no_copy": 0, + "options": "Lab Test UOM", + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 0, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 0 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 1, + "max_attachments": 0, + "modified": "2019-10-04 19:48:04.104234", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Organism Test Item", + "name_case": "", + "owner": "Administrator", + "permissions": [], + "quick_entry": 0, + "read_only": 0, + "read_only_onload": 0, + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 0, + "track_seen": 0, + "track_views": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/organism_test_item/organism_test_item.py b/healthcare/healthcare/doctype/organism_test_item/organism_test_item.py new file mode 100644 index 0000000..39dab76 --- /dev/null +++ b/healthcare/healthcare/doctype/organism_test_item/organism_test_item.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2019, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class OrganismTestItem(Document): + pass diff --git a/healthcare/healthcare/doctype/organism_test_result/__init__.py b/healthcare/healthcare/doctype/organism_test_result/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/organism_test_result/organism_test_result.json b/healthcare/healthcare/doctype/organism_test_result/organism_test_result.json new file mode 100644 index 0000000..8b238de --- /dev/null +++ b/healthcare/healthcare/doctype/organism_test_result/organism_test_result.json @@ -0,0 +1,144 @@ +{ + "allow_copy": 0, + "allow_events_in_timeline": 0, + "allow_guest_to_view": 0, + "allow_import": 0, + "allow_rename": 0, + "beta": 1, + "creation": "2019-09-06 16:37:59.698996", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "", + "editable_grid": 1, + "engine": "InnoDB", + "fields": [ + { + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fetch_if_empty": 0, + "fieldname": "organism", + "fieldtype": "Link", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Organism", + "length": 0, + "no_copy": 0, + "options": "Organism", + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 0 + }, + { + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fetch_if_empty": 0, + "fieldname": "colony_population", + "fieldtype": "Small Text", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Colony Population", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 0, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 0 + }, + { + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fetch_if_empty": 0, + "fieldname": "colony_uom", + "fieldtype": "Link", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Colony UOM", + "length": 0, + "no_copy": 0, + "options": "Lab Test UOM", + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 0, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 0 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 1, + "max_attachments": 0, + "modified": "2019-10-04 19:48:04.104234", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Organism Test Result", + "name_case": "", + "owner": "Administrator", + "permissions": [], + "quick_entry": 0, + "read_only": 0, + "read_only_onload": 0, + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 0, + "track_seen": 0, + "track_views": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/organism_test_result/organism_test_result.py b/healthcare/healthcare/doctype/organism_test_result/organism_test_result.py new file mode 100644 index 0000000..b69b231 --- /dev/null +++ b/healthcare/healthcare/doctype/organism_test_result/organism_test_result.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2019, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class OrganismTestResult(Document): + pass diff --git a/healthcare/healthcare/doctype/patient/__init__.py b/healthcare/healthcare/doctype/patient/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/patient/patient.js b/healthcare/healthcare/doctype/patient/patient.js new file mode 100644 index 0000000..9bef27b --- /dev/null +++ b/healthcare/healthcare/doctype/patient/patient.js @@ -0,0 +1,146 @@ +// Copyright (c) 2016, ESS LLP and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Patient', { + refresh: function (frm) { + frm.set_query('patient', 'patient_relation', function () { + return { + filters: [ + ['Patient', 'name', '!=', frm.doc.name] + ] + }; + }); + frm.set_query('customer_group', {'is_group': 0}); + frm.set_query('default_price_list', { 'selling': 1}); + + if (frappe.defaults.get_default('patient_name_by') != 'Naming Series') { + frm.toggle_display('naming_series', false); + } else { + erpnext.toggle_naming_series(); + } + + if (frappe.defaults.get_default('collect_registration_fee') && frm.doc.status == 'Disabled') { + frm.add_custom_button(__('Invoice Patient Registration'), function () { + invoice_registration(frm); + }); + } + + if (frm.doc.patient_name && frappe.user.has_role('Physician')) { + frm.add_custom_button(__('Patient Progress'), function() { + frappe.route_options = {'patient': frm.doc.name}; + frappe.set_route('patient-progress'); + }, __('View')); + + frm.add_custom_button(__('Patient History'), function() { + frappe.route_options = {'patient': frm.doc.name}; + frappe.set_route('patient_history'); + }, __('View')); + } + + frappe.dynamic_link = {doc: frm.doc, fieldname: 'name', doctype: 'Patient'}; + frm.toggle_display(['address_html', 'contact_html'], !frm.is_new()); + + if (!frm.is_new()) { + if ((frappe.user.has_role('Nursing User') || frappe.user.has_role('Physician'))) { + frm.add_custom_button(__('Medical Record'), function () { + create_medical_record(frm); + }, __('Create')); + frm.toggle_enable(['customer'], 0); + } + frappe.contacts.render_address_and_contact(frm); + erpnext.utils.set_party_dashboard_indicators(frm); + } else { + frappe.contacts.clear_address_and_contact(frm); + } + }, + + onload: function (frm) { + if (frm.doc.dob) { + $(frm.fields_dict['age_html'].wrapper).html(`${__('AGE')} : ${get_age(frm.doc.dob)}`); + } else { + $(frm.fields_dict['age_html'].wrapper).html(''); + } + } +}); + +frappe.ui.form.on('Patient', 'dob', function(frm) { + if (frm.doc.dob) { + let today = new Date(); + let birthDate = new Date(frm.doc.dob); + if (today < birthDate) { + frappe.msgprint(__('Please select a valid Date')); + frappe.model.set_value(frm.doctype,frm.docname, 'dob', ''); + } else { + let age_str = get_age(frm.doc.dob); + $(frm.fields_dict['age_html'].wrapper).html(`${__('AGE')} : ${age_str}`); + } + } else { + $(frm.fields_dict['age_html'].wrapper).html(''); + } +}); + +frappe.ui.form.on('Patient Relation', { + patient_relation_add: function(frm){ + frm.fields_dict['patient_relation'].grid.get_field('patient').get_query = function(doc){ + let patient_list = []; + if(!doc.__islocal) patient_list.push(doc.name); + $.each(doc.patient_relation, function(idx, val){ + if (val.patient) patient_list.push(val.patient); + }); + return { filters: [['Patient', 'name', 'not in', patient_list]] }; + }; + } +}); + +let create_medical_record = function (frm) { + frappe.route_options = { + 'patient': frm.doc.name, + 'status': 'Open', + 'reference_doctype': 'Patient Medical Record', + 'reference_owner': frm.doc.owner + }; + frappe.new_doc('Patient Medical Record'); +}; + +let get_age = function (birth) { + let ageMS = Date.parse(Date()) - Date.parse(birth); + let age = new Date(); + age.setTime(ageMS); + let years = age.getFullYear() - 1970; + return years + ' Year(s) ' + age.getMonth() + ' Month(s) ' + age.getDate() + ' Day(s)'; +}; + +let create_vital_signs = function (frm) { + if (!frm.doc.name) { + frappe.throw(__('Please save the patient first')); + } + frappe.route_options = { + 'patient': frm.doc.name, + }; + frappe.new_doc('Vital Signs'); +}; + +let create_encounter = function (frm) { + if (!frm.doc.name) { + frappe.throw(__('Please save the patient first')); + } + frappe.route_options = { + 'patient': frm.doc.name, + }; + frappe.new_doc('Patient Encounter'); +}; + +let invoice_registration = function (frm) { + frappe.call({ + doc: frm.doc, + method: 'invoice_patient_registration', + callback: function(data) { + if (!data.exc) { + if (data.message.invoice) { + frappe.set_route('Form', 'Sales Invoice', data.message.invoice); + } + cur_frm.reload_doc(); + } + } + }); +}; diff --git a/healthcare/healthcare/doctype/patient/patient.json b/healthcare/healthcare/doctype/patient/patient.json new file mode 100644 index 0000000..4092a6a --- /dev/null +++ b/healthcare/healthcare/doctype/patient/patient.json @@ -0,0 +1,542 @@ +{ + "actions": [], + "allow_events_in_timeline": 1, + "allow_import": 1, + "allow_rename": 1, + "autoname": "naming_series:", + "beta": 1, + "creation": "2017-01-23 14:03:49.084370", + "description": "Patient", + "doctype": "DocType", + "document_type": "Document", + "engine": "InnoDB", + "field_order": [ + "basic_info", + "naming_series", + "first_name", + "middle_name", + "last_name", + "patient_name", + "sex", + "blood_group", + "dob", + "age_html", + "image", + "column_break_14", + "status", + "uid", + "inpatient_record", + "inpatient_status", + "report_preference", + "mobile", + "phone", + "email", + "invite_user", + "user_id", + "address_contacts", + "address_html", + "column_break_22", + "contact_html", + "customer_details_section", + "customer", + "customer_group", + "territory", + "column_break_24", + "default_currency", + "default_price_list", + "language", + "personal_and_social_history", + "occupation", + "column_break_25", + "marital_status", + "sb_relation", + "patient_relation", + "allergy_medical_and_surgical_history", + "allergies", + "medication", + "column_break_20", + "medical_history", + "surgical_history", + "risk_factors", + "tobacco_past_use", + "tobacco_current_use", + "alcohol_past_use", + "alcohol_current_use", + "column_break_32", + "surrounding_factors", + "other_risk_factors", + "more_info", + "patient_details" + ], + "fields": [ + { + "fieldname": "basic_info", + "fieldtype": "Section Break", + "label": "Patient Demographics", + "oldfieldtype": "Section Break", + "options": "fa fa-user" + }, + { + "fieldname": "inpatient_status", + "fieldtype": "Select", + "in_preview": 1, + "label": "Inpatient Status", + "no_copy": 1, + "options": "\nAdmission Scheduled\nAdmitted\nDischarge Scheduled", + "read_only": 1 + }, + { + "fieldname": "inpatient_record", + "fieldtype": "Link", + "label": "Inpatient Record", + "no_copy": 1, + "options": "Inpatient Record", + "read_only": 1 + }, + { + "fieldname": "naming_series", + "fieldtype": "Select", + "label": "Series", + "options": "HLC-PAT-.YYYY.-", + "print_hide": 1, + "report_hide": 1, + "set_only_once": 1 + }, + { + "bold": 1, + "fieldname": "patient_name", + "fieldtype": "Data", + "in_global_search": 1, + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Full Name", + "no_copy": 1, + "read_only": 1, + "search_index": 1 + }, + { + "fieldname": "sex", + "fieldtype": "Link", + "in_preview": 1, + "label": "Gender", + "options": "Gender", + "reqd": 1 + }, + { + "bold": 1, + "fieldname": "blood_group", + "fieldtype": "Select", + "in_preview": 1, + "label": "Blood Group", + "no_copy": 1, + "options": "\nA Positive\nA Negative\nAB Positive\nAB Negative\nB Positive\nB Negative\nO Positive\nO Negative" + }, + { + "bold": 1, + "fieldname": "dob", + "fieldtype": "Date", + "in_preview": 1, + "label": "Date of birth", + "no_copy": 1 + }, + { + "fieldname": "age_html", + "fieldtype": "HTML", + "label": "Age", + "no_copy": 1, + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "fieldname": "status", + "fieldtype": "Select", + "in_filter": 1, + "in_list_view": 1, + "label": "Status", + "no_copy": 1, + "options": "Active\nDisabled", + "print_hide": 1, + "read_only": 1 + }, + { + "fieldname": "image", + "fieldtype": "Attach Image", + "hidden": 1, + "in_preview": 1, + "label": "Image", + "no_copy": 1, + "print_hide": 1, + "width": "50%" + }, + { + "fieldname": "column_break_14", + "fieldtype": "Column Break" + }, + { + "description": "If \"Link Customer to Patient\" is checked in Healthcare Settings and an existing Customer is not selected then, a Customer will be created for this Patient for recording transactions in Accounts module.", + "fieldname": "customer", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "label": "Customer", + "no_copy": 1, + "options": "Customer", + "set_only_once": 1 + }, + { + "fieldname": "report_preference", + "fieldtype": "Select", + "label": "Report Preference", + "options": "\nEmail\nPrint" + }, + { + "bold": 1, + "fieldname": "mobile", + "fieldtype": "Data", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Mobile", + "no_copy": 1, + "options": "Phone" + }, + { + "bold": 1, + "fieldname": "email", + "fieldtype": "Data", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Email", + "no_copy": 1, + "options": "Email" + }, + { + "fieldname": "phone", + "fieldtype": "Data", + "in_filter": 1, + "label": "Phone", + "no_copy": 1, + "options": "Phone" + }, + { + "collapsible": 1, + "fieldname": "sb_relation", + "fieldtype": "Section Break", + "label": "Patient Relation" + }, + { + "fieldname": "patient_relation", + "fieldtype": "Table", + "label": "Patient Relation", + "options": "Patient Relation" + }, + { + "collapsible": 1, + "fieldname": "allergy_medical_and_surgical_history", + "fieldtype": "Section Break", + "label": "Allergies, Medical and Surgical History" + }, + { + "fieldname": "allergies", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Allergies", + "no_copy": 1 + }, + { + "fieldname": "medication", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Medication", + "no_copy": 1 + }, + { + "fieldname": "column_break_20", + "fieldtype": "Column Break" + }, + { + "fieldname": "medical_history", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Medical History", + "no_copy": 1 + }, + { + "fieldname": "surgical_history", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Surgical History", + "no_copy": 1 + }, + { + "collapsible": 1, + "fieldname": "personal_and_social_history", + "fieldtype": "Section Break", + "label": "Personal and Social History" + }, + { + "fieldname": "occupation", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "label": "Occupation", + "no_copy": 1 + }, + { + "fieldname": "column_break_25", + "fieldtype": "Column Break" + }, + { + "fieldname": "marital_status", + "fieldtype": "Select", + "label": "Marital Status", + "no_copy": 1, + "options": "\nSingle\nMarried\nDivorced\nWidow" + }, + { + "collapsible": 1, + "fieldname": "risk_factors", + "fieldtype": "Section Break", + "label": "Risk Factors" + }, + { + "fieldname": "tobacco_past_use", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "label": "Tobacco Consumption (Past)", + "no_copy": 1 + }, + { + "fieldname": "tobacco_current_use", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "label": "Tobacco Consumption (Present)", + "no_copy": 1 + }, + { + "fieldname": "alcohol_past_use", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "label": "Alcohol Consumption (Past)", + "no_copy": 1 + }, + { + "fieldname": "alcohol_current_use", + "fieldtype": "Data", + "ignore_user_permissions": 1, + "label": "Alcohol Consumption (Present)", + "no_copy": 1 + }, + { + "fieldname": "column_break_32", + "fieldtype": "Column Break" + }, + { + "fieldname": "surrounding_factors", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Occupational Hazards and Environmental Factors", + "no_copy": 1 + }, + { + "fieldname": "other_risk_factors", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Other Risk Factors", + "no_copy": 1 + }, + { + "collapsible": 1, + "collapsible_depends_on": "patient_details", + "fieldname": "more_info", + "fieldtype": "Section Break", + "label": "More Information", + "oldfieldtype": "Section Break", + "options": "fa fa-file-text" + }, + { + "description": "Additional information regarding the patient", + "fieldname": "patient_details", + "fieldtype": "Text", + "ignore_xss_filter": 1, + "label": "Patient Details", + "no_copy": 1 + }, + { + "fieldname": "default_currency", + "fieldtype": "Link", + "label": "Billing Currency", + "options": "Currency" + }, + { + "fieldname": "last_name", + "fieldtype": "Data", + "label": "Last Name", + "no_copy": 1 + }, + { + "fieldname": "first_name", + "fieldtype": "Data", + "label": "First Name", + "no_copy": 1, + "oldfieldtype": "Data", + "reqd": 1 + }, + { + "fieldname": "middle_name", + "fieldtype": "Data", + "label": "Middle Name (optional)", + "no_copy": 1 + }, + { + "collapsible": 1, + "fieldname": "customer_details_section", + "fieldtype": "Section Break", + "label": "Customer Details" + }, + { + "fieldname": "customer_group", + "fieldtype": "Link", + "label": "Customer Group", + "options": "Customer Group" + }, + { + "fieldname": "territory", + "fieldtype": "Link", + "label": "Territory", + "options": "Territory" + }, + { + "fieldname": "column_break_24", + "fieldtype": "Column Break" + }, + { + "fieldname": "default_price_list", + "fieldtype": "Link", + "label": "Default Price List", + "options": "Price List" + }, + { + "fieldname": "language", + "fieldtype": "Link", + "label": "Print Language", + "options": "Language" + }, + { + "depends_on": "eval:!doc.__islocal", + "fieldname": "address_contacts", + "fieldtype": "Section Break", + "label": "Address and Contact", + "options": "fa fa-map-marker" + }, + { + "fieldname": "address_html", + "fieldtype": "HTML", + "label": "Address HTML", + "no_copy": 1, + "read_only": 1 + }, + { + "fieldname": "column_break_22", + "fieldtype": "Column Break" + }, + { + "fieldname": "contact_html", + "fieldtype": "HTML", + "label": "Contact HTML", + "no_copy": 1, + "read_only": 1 + }, + { + "allow_in_quick_entry": 1, + "default": "1", + "fieldname": "invite_user", + "fieldtype": "Check", + "label": "Invite as User", + "no_copy": 1, + "read_only_depends_on": "eval: doc.user_id" + }, + { + "fieldname": "user_id", + "fieldtype": "Read Only", + "label": "User ID", + "no_copy": 1, + "options": "User" + }, + { + "allow_in_quick_entry": 1, + "bold": 1, + "fieldname": "uid", + "fieldtype": "Data", + "in_standard_filter": 1, + "label": "Identification Number (UID)", + "unique": 1 + } + ], + "icon": "fa fa-user", + "image_field": "image", + "links": [], + "max_attachments": 50, + "modified": "2021-03-14 13:21:09.759906", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient", + "name_case": "Title Case", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Laboratory User", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Nursing User", + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "restrict_to_domain": "Healthcare", + "search_fields": "patient_name,mobile,email,phone,uid", + "show_name_in_global_search": 1, + "sort_field": "modified", + "sort_order": "ASC", + "title_field": "patient_name", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/patient/patient.py b/healthcare/healthcare/doctype/patient/patient.py new file mode 100644 index 0000000..0c55687 --- /dev/null +++ b/healthcare/healthcare/doctype/patient/patient.py @@ -0,0 +1,340 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and contributors +# For license information, please see license.txt + + +import dateutil +import frappe +from frappe import _ +from frappe.contacts.address_and_contact import load_address_and_contact +from frappe.contacts.doctype.contact.contact import get_default_contact +from frappe.model.document import Document +from frappe.model.naming import set_name_by_naming_series +from frappe.utils import cint, cstr, getdate +from frappe.utils.nestedset import get_root_of + +from erpnext import get_default_currency +from erpnext.accounts.party import get_dashboard_info +from healthcare.healthcare.doctype.healthcare_settings.healthcare_settings import ( + get_income_account, + get_receivable_account, + send_registration_sms, +) + + +class Patient(Document): + def onload(self): + """Load address and contacts in `__onload`""" + load_address_and_contact(self) + self.load_dashboard_info() + + def validate(self): + self.set_full_name() + + def before_insert(self): + self.set_missing_customer_details() + + def after_insert(self): + if frappe.db.get_single_value("Healthcare Settings", "collect_registration_fee"): + frappe.db.set_value("Patient", self.name, "status", "Disabled") + else: + send_registration_sms(self) + self.reload() + + def on_update(self): + if frappe.db.get_single_value("Healthcare Settings", "link_customer_to_patient"): + if self.customer: + customer = frappe.get_doc("Customer", self.customer) + if self.customer_group: + customer.customer_group = self.customer_group + if self.territory: + customer.territory = self.territory + customer.customer_name = self.patient_name + customer.default_price_list = self.default_price_list + customer.default_currency = self.default_currency + customer.language = self.language + customer.image = self.image + customer.ignore_mandatory = True + customer.save(ignore_permissions=True) + else: + create_customer(self) + + self.set_contact() # add or update contact + + if not self.user_id and self.email and self.invite_user: + self.create_website_user() + + def load_dashboard_info(self): + if self.customer: + info = get_dashboard_info("Customer", self.customer, None) + self.set_onload("dashboard_info", info) + + def set_full_name(self): + if self.last_name: + self.patient_name = " ".join(filter(None, [self.first_name, self.last_name])) + else: + self.patient_name = self.first_name + + def set_missing_customer_details(self): + if not self.customer_group: + self.customer_group = frappe.db.get_single_value( + "Selling Settings", "customer_group" + ) or get_root_of("Customer Group") + if not self.territory: + self.territory = frappe.db.get_single_value("Selling Settings", "territory") or get_root_of( + "Territory" + ) + if not self.default_price_list: + self.default_price_list = frappe.db.get_single_value("Selling Settings", "selling_price_list") + + if not self.customer_group or not self.territory or not self.default_price_list: + frappe.msgprint( + _( + "Please set defaults for Customer Group, Territory and Selling Price List in Selling Settings" + ), + alert=True, + ) + + if not self.default_currency: + self.default_currency = get_default_currency() + if not self.language: + self.language = frappe.db.get_single_value("System Settings", "language") + + def create_website_user(self): + users = frappe.db.get_all( + "User", + fields=["email", "mobile_no"], + or_filters={"email": self.email, "mobile_no": self.mobile}, + ) + if users and users[0]: + frappe.throw( + _( + "User exists with Email {}, Mobile {}
Please check email / mobile or disable 'Invite as User' to skip creating User" + ).format(frappe.bold(users[0].email), frappe.bold(users[0].mobile_no)), + frappe.DuplicateEntryError, + ) + + user = frappe.get_doc( + { + "doctype": "User", + "first_name": self.first_name, + "last_name": self.last_name, + "email": self.email, + "user_type": "Website User", + "gender": self.sex, + "phone": self.phone, + "mobile_no": self.mobile, + "birth_date": self.dob, + } + ) + user.flags.ignore_permissions = True + user.enabled = True + user.send_welcome_email = True + user.add_roles("Patient") + self.db_set("user_id", user.name) + + def autoname(self): + patient_name_by = frappe.db.get_single_value("Healthcare Settings", "patient_name_by") + if patient_name_by == "Patient Name": + self.name = self.get_patient_name() + else: + set_name_by_naming_series(self) + + def get_patient_name(self): + self.set_full_name() + name = self.patient_name + if frappe.db.get_value("Patient", name): + count = frappe.db.sql( + """select ifnull(MAX(CAST(SUBSTRING_INDEX(name, ' ', -1) AS UNSIGNED)), 0) from tabPatient + where name like %s""", + "%{0} - %".format(name), + as_list=1, + )[0][0] + count = cint(count) + 1 + return "{0} - {1}".format(name, cstr(count)) + + return name + + @property + def age(self): + if not self.dob: + return + dob = getdate(self.dob) + age = dateutil.relativedelta.relativedelta(getdate(), dob) + return age + + def get_age(self): + age = self.age + if not age: + return + age_str = f'{str(age.years)} {_("Year(s)")} {str(age.months)} {_("Month(s)")} {str(age.days)} {_("Day(s)")}' + return age_str + + @frappe.whitelist() + def invoice_patient_registration(self): + if frappe.db.get_single_value("Healthcare Settings", "registration_fee"): + company = frappe.defaults.get_user_default("company") + if not company: + company = frappe.db.get_single_value("Global Defaults", "default_company") + + sales_invoice = make_invoice(self.name, company) + sales_invoice.save(ignore_permissions=True) + frappe.db.set_value("Patient", self.name, "status", "Active") + send_registration_sms(self) + + return {"invoice": sales_invoice.name} + + def set_contact(self): + contact = get_default_contact(self.doctype, self.name) + + if contact: + old_doc = self.get_doc_before_save() + if not old_doc: + return + + if old_doc.email != self.email or old_doc.mobile != self.mobile or old_doc.phone != self.phone: + self.update_contact(contact) + else: + if self.customer: + # customer contact exists, link patient + contact = get_default_contact("Customer", self.customer) + + if contact: + self.update_contact(contact) + else: + self.reload() + if self.email or self.mobile or self.phone: + contact = frappe.get_doc( + { + "doctype": "Contact", + "first_name": self.first_name, + "middle_name": self.middle_name, + "last_name": self.last_name, + "gender": self.sex, + "is_primary_contact": 1, + } + ) + contact.append("links", dict(link_doctype="Patient", link_name=self.name)) + if self.customer: + contact.append("links", dict(link_doctype="Customer", link_name=self.customer)) + + contact.insert(ignore_permissions=True) + self.update_contact(contact.name) + + def update_contact(self, contact): + contact = frappe.get_doc("Contact", contact) + + if not contact.has_link(self.doctype, self.name): + contact.append("links", dict(link_doctype=self.doctype, link_name=self.name)) + + if self.email and self.email != contact.email_id: + for email in contact.email_ids: + email.is_primary = True if email.email_id == self.email else False + contact.add_email(self.email, is_primary=True) + contact.set_primary_email() + + if self.mobile and self.mobile != contact.mobile_no: + for mobile in contact.phone_nos: + mobile.is_primary_mobile_no = True if mobile.phone == self.mobile else False + contact.add_phone(self.mobile, is_primary_mobile_no=True) + contact.set_primary("mobile_no") + + if self.phone and self.phone != contact.phone: + for phone in contact.phone_nos: + phone.is_primary_phone = True if phone.phone == self.phone else False + contact.add_phone(self.phone, is_primary_phone=True) + contact.set_primary("phone") + + contact.flags.skip_patient_update = True + contact.save(ignore_permissions=True) + + +def create_customer(doc): + customer = frappe.get_doc( + { + "doctype": "Customer", + "customer_name": doc.patient_name, + "customer_group": doc.customer_group + or frappe.db.get_single_value("Selling Settings", "customer_group"), + "territory": doc.territory or frappe.db.get_single_value("Selling Settings", "territory"), + "customer_type": "Individual", + "default_currency": doc.default_currency, + "default_price_list": doc.default_price_list, + "language": doc.language, + "image": doc.image, + } + ).insert(ignore_permissions=True, ignore_mandatory=True) + + frappe.db.set_value("Patient", doc.name, "customer", customer.name) + frappe.msgprint(_("Customer {0} is created.").format(customer.name), alert=True) + + +def make_invoice(patient, company): + uom = frappe.db.exists("UOM", "Nos") or frappe.db.get_single_value("Stock Settings", "stock_uom") + sales_invoice = frappe.new_doc("Sales Invoice") + sales_invoice.customer = frappe.db.get_value("Patient", patient, "customer") + sales_invoice.due_date = getdate() + sales_invoice.company = company + sales_invoice.is_pos = 0 + sales_invoice.debit_to = get_receivable_account(company) + + item_line = sales_invoice.append("items") + item_line.item_name = "Registration Fee" + item_line.description = "Registration Fee" + item_line.qty = 1 + item_line.uom = uom + item_line.conversion_factor = 1 + item_line.income_account = get_income_account(None, company) + item_line.rate = frappe.db.get_single_value("Healthcare Settings", "registration_fee") + item_line.amount = item_line.rate + sales_invoice.set_missing_values() + return sales_invoice + + +@frappe.whitelist() +def get_patient_detail(patient): + patient_dict = frappe.db.sql("""select * from tabPatient where name=%s""", (patient), as_dict=1) + if not patient_dict: + frappe.throw(_("Patient not found")) + vital_sign = frappe.db.sql( + """select * from `tabVital Signs` where patient=%s + order by signs_date desc limit 1""", + (patient), + as_dict=1, + ) + + details = patient_dict[0] + if vital_sign: + vital_sign[0].pop("inpatient_record") + details.update(vital_sign[0]) + return details + + +def get_timeline_data(doctype, name): + """ + Return Patient's timeline data from medical records + Also include the associated Customer timeline data + """ + patient_timeline_data = dict( + frappe.db.sql( + """ + SELECT + unix_timestamp(communication_date), count(*) + FROM + `tabPatient Medical Record` + WHERE + patient=%s + and `communication_date` > date_sub(curdate(), interval 1 year) + GROUP BY communication_date""", + name, + ) + ) + + customer = frappe.db.get_value(doctype, name, "customer") + if customer: + from erpnext.accounts.party import get_timeline_data + + customer_timeline_data = get_timeline_data("Customer", customer) + patient_timeline_data.update(customer_timeline_data) + + return patient_timeline_data diff --git a/healthcare/healthcare/doctype/patient/patient_dashboard.py b/healthcare/healthcare/doctype/patient/patient_dashboard.py new file mode 100644 index 0000000..198c279 --- /dev/null +++ b/healthcare/healthcare/doctype/patient/patient_dashboard.py @@ -0,0 +1,26 @@ +from frappe import _ + + +def get_data(): + return { + "heatmap": True, + "heatmap_message": _( + "This is based on transactions against this Patient. See timeline below for details" + ), + "fieldname": "patient", + "non_standard_fieldnames": {"Payment Entry": "party"}, + "transactions": [ + { + "label": _("Appointments and Encounters"), + "items": ["Patient Appointment", "Vital Signs", "Patient Encounter"], + }, + {"label": _("Lab Tests and Vital Signs"), "items": ["Lab Test", "Sample Collection"]}, + { + "label": _("Rehab and Physiotherapy"), + "items": ["Patient Assessment", "Therapy Session", "Therapy Plan"], + }, + {"label": _("Surgery"), "items": ["Clinical Procedure"]}, + {"label": _("Admissions"), "items": ["Inpatient Record", "Inpatient Medication Order"]}, + {"label": _("Billing and Payments"), "items": ["Sales Invoice", "Payment Entry"]}, + ], + } diff --git a/healthcare/healthcare/doctype/patient/test_patient.py b/healthcare/healthcare/doctype/patient/test_patient.py new file mode 100644 index 0000000..9225df8 --- /dev/null +++ b/healthcare/healthcare/doctype/patient/test_patient.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +import frappe +import os + +from healthcare.healthcare.doctype.patient_appointment.test_patient_appointment import ( + create_patient, +) + + +class TestPatient(FrappeTestCase): + def test_customer_created(self): + frappe.db.sql("""delete from `tabPatient`""") + frappe.db.set_value("Healthcare Settings", None, "link_customer_to_patient", 1) + patient = create_patient() + self.assertTrue(frappe.db.get_value("Patient", patient, "customer")) + + def test_patient_registration(self): + frappe.db.sql("""delete from `tabPatient`""") + settings = frappe.get_single("Healthcare Settings") + settings.collect_registration_fee = 1 + settings.registration_fee = 500 + settings.save() + + patient = create_patient() + patient = frappe.get_doc("Patient", patient) + self.assertEqual(patient.status, "Disabled") + + # check sales invoice and patient status + result = patient.invoice_patient_registration() + self.assertTrue(frappe.db.exists("Sales Invoice", result.get("invoice"))) + self.assertTrue(patient.status, "Active") + + settings.collect_registration_fee = 0 + settings.save() + + def test_patient_contact(self): + frappe.db.sql("""delete from `tabPatient` where name like '_Test Patient%'""") + frappe.db.sql("""delete from `tabCustomer` where name like '_Test Patient%'""") + frappe.db.sql("""delete from `tabContact` where name like'_Test Patient%'""") + frappe.db.sql("""delete from `tabDynamic Link` where parent like '_Test Patient%'""") + + patient = create_patient( + patient_name="_Test Patient Contact", email="test-patient@example.com", mobile="+91 0000000001" + ) + customer = frappe.db.get_value("Patient", patient, "customer") + self.assertTrue(customer) + self.assertTrue( + frappe.db.exists( + "Dynamic Link", {"parenttype": "Contact", "link_doctype": "Patient", "link_name": patient} + ) + ) + self.assertTrue( + frappe.db.exists( + "Dynamic Link", {"parenttype": "Contact", "link_doctype": "Customer", "link_name": customer} + ) + ) + + # a second patient linking with same customer + new_patient = create_patient( + email="test-patient@example.com", mobile="+91 0000000009", customer=customer + ) + self.assertTrue( + frappe.db.exists( + "Dynamic Link", {"parenttype": "Contact", "link_doctype": "Patient", "link_name": new_patient} + ) + ) + self.assertTrue( + frappe.db.exists( + "Dynamic Link", {"parenttype": "Contact", "link_doctype": "Customer", "link_name": customer} + ) + ) + + def test_patient_user(self): + frappe.db.sql("""delete from `tabUser` where email='test-patient-user@example.com'""") + frappe.db.sql("""delete from `tabDynamic Link` where parent like '_Test Patient%'""") + frappe.db.sql("""delete from `tabPatient` where name like '_Test Patient%'""") + + patient = create_patient( + patient_name="_Test Patient User", + email="test-patient-user@example.com", + mobile="+91 0000000009", + create_user=True, + ) + user = frappe.db.get_value("Patient", patient, "user_id") + self.assertTrue(frappe.db.exists("User", user)) + + new_patient = frappe.get_doc( + { + "doctype": "Patient", + "first_name": "_Test Patient Duplicate User", + "sex": "Male", + "email": "test-patient-user@example.com", + "mobile": "+91 0000000009", + "invite_user": 1, + } + ) + + self.assertRaises(frappe.exceptions.DuplicateEntryError, new_patient.insert) + + def test_patient_image_update_should_update_customer_image(self): + settings = frappe.get_single("Healthcare Settings") + settings.link_customer_to_patient = 1 + settings.save() + + patient_name = create_patient() + patient = frappe.get_doc("Patient", patient_name) + patient.image = os.path.abspath("assets/frappe/images/default-avatar.png") + patient.save() + + customer = frappe.get_doc("Customer", patient.customer) + self.assertEqual(customer.image, patient.image) diff --git a/healthcare/healthcare/doctype/patient_appointment/__init__.py b/healthcare/healthcare/doctype/patient_appointment/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/patient_appointment/patient_appointment.js b/healthcare/healthcare/doctype/patient_appointment/patient_appointment.js new file mode 100644 index 0000000..66cb585 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_appointment/patient_appointment.js @@ -0,0 +1,659 @@ +// Copyright (c) 2016, ESS LLP and contributors +// For license information, please see license.txt +frappe.provide('erpnext.queries'); +frappe.ui.form.on('Patient Appointment', { + setup: function(frm) { + frm.custom_make_buttons = { + 'Vital Signs': 'Vital Signs', + 'Patient Encounter': 'Patient Encounter' + }; + }, + + onload: function(frm) { + if (frm.is_new()) { + frm.set_value('appointment_time', null); + frm.disable_save(); + } + }, + + refresh: function(frm) { + frm.set_query('patient', function() { + return { + filters: { 'status': 'Active' } + }; + }); + + frm.set_query('practitioner', function() { + if (frm.doc.department) { + return { + filters: { + 'department': frm.doc.department + } + }; + } + }); + + frm.set_query('service_unit', function() { + return { + query: 'healthcare.controllers.queries.get_healthcare_service_units', + filters: { + company: frm.doc.company, + inpatient_record: frm.doc.inpatient_record + } + }; + }); + + frm.set_query('therapy_plan', function() { + return { + filters: { + 'patient': frm.doc.patient + } + }; + }); + + frm.trigger('set_therapy_type_filter'); + + if (frm.is_new()) { + frm.page.set_primary_action(__('Check Availability'), function() { + if (!frm.doc.patient) { + frappe.msgprint({ + title: __('Not Allowed'), + message: __('Please select Patient first'), + indicator: 'red' + }); + } else { + frappe.call({ + method: 'healthcare.healthcare.doctype.patient_appointment.patient_appointment.check_payment_fields_reqd', + args: { 'patient': frm.doc.patient }, + callback: function(data) { + if (data.message == true) { + if (frm.doc.mode_of_payment && frm.doc.paid_amount) { + check_and_set_availability(frm); + } + if (!frm.doc.mode_of_payment) { + frappe.msgprint({ + title: __('Not Allowed'), + message: __('Please select a Mode of Payment first'), + indicator: 'red' + }); + } + if (!frm.doc.paid_amount) { + frappe.msgprint({ + title: __('Not Allowed'), + message: __('Please set the Paid Amount first'), + indicator: 'red' + }); + } + } else { + check_and_set_availability(frm); + } + } + }); + } + }); + } else { + frm.page.set_primary_action(__('Save'), () => frm.save()); + } + + if (frm.doc.patient) { + frm.add_custom_button(__('Patient History'), function() { + frappe.route_options = { 'patient': frm.doc.patient }; + frappe.set_route('patient_history'); + }, __('View')); + } + + if (frm.doc.status == 'Open' || (frm.doc.status == 'Scheduled' && !frm.doc.__islocal)) { + frm.add_custom_button(__('Cancel'), function() { + update_status(frm, 'Cancelled'); + }); + frm.add_custom_button(__('Reschedule'), function() { + check_and_set_availability(frm); + }); + + if (frm.doc.procedure_template) { + frm.add_custom_button(__('Clinical Procedure'), function() { + frappe.model.open_mapped_doc({ + method: 'healthcare.healthcare.doctype.clinical_procedure.clinical_procedure.make_procedure', + frm: frm, + }); + }, __('Create')); + } else if (frm.doc.therapy_type) { + frm.add_custom_button(__('Therapy Session'), function() { + frappe.model.open_mapped_doc({ + method: 'healthcare.healthcare.doctype.therapy_session.therapy_session.create_therapy_session', + frm: frm, + }) + }, 'Create'); + } else { + frm.add_custom_button(__('Patient Encounter'), function() { + frappe.model.open_mapped_doc({ + method: 'healthcare.healthcare.doctype.patient_appointment.patient_appointment.make_encounter', + frm: frm, + }); + }, __('Create')); + } + + frm.add_custom_button(__('Vital Signs'), function() { + create_vital_signs(frm); + }, __('Create')); + } + }, + + patient: function(frm) { + if (frm.doc.patient) { + frm.trigger('toggle_payment_fields'); + frappe.call({ + method: 'frappe.client.get', + args: { + doctype: 'Patient', + name: frm.doc.patient + }, + callback: function(data) { + let age = null; + if (data.message.dob) { + age = calculate_age(data.message.dob); + } + frappe.model.set_value(frm.doctype, frm.docname, 'patient_age', age); + } + }); + } else { + frm.set_value('patient_name', ''); + frm.set_value('patient_sex', ''); + frm.set_value('patient_age', ''); + frm.set_value('inpatient_record', ''); + } + }, + + practitioner: function(frm) { + if (frm.doc.practitioner) { + frm.events.set_payment_details(frm); + } + }, + + appointment_type: function(frm) { + if (frm.doc.appointment_type) { + frm.events.set_payment_details(frm); + } + }, + + set_payment_details: function(frm) { + frappe.db.get_single_value('Healthcare Settings', 'automate_appointment_invoicing').then(val => { + if (val) { + frappe.call({ + method: 'healthcare.healthcare.utils.get_service_item_and_practitioner_charge', + args: { + doc: frm.doc + }, + callback: function(data) { + if (data.message) { + frappe.model.set_value(frm.doctype, frm.docname, 'paid_amount', data.message.practitioner_charge); + frappe.model.set_value(frm.doctype, frm.docname, 'billing_item', data.message.service_item); + } + } + }); + } + }); + }, + + therapy_plan: function(frm) { + frm.trigger('set_therapy_type_filter'); + }, + + set_therapy_type_filter: function(frm) { + if (frm.doc.therapy_plan) { + frm.call('get_therapy_types').then(r => { + frm.set_query('therapy_type', function() { + return { + filters: { + 'name': ['in', r.message] + } + }; + }); + }); + } + }, + + therapy_type: function(frm) { + if (frm.doc.therapy_type) { + frappe.db.get_value('Therapy Type', frm.doc.therapy_type, 'default_duration', (r) => { + if (r.default_duration) { + frm.set_value('duration', r.default_duration) + } + }); + } + }, + + get_procedure_from_encounter: function(frm) { + get_prescribed_procedure(frm); + }, + + toggle_payment_fields: function(frm) { + frappe.call({ + method: 'healthcare.healthcare.doctype.patient_appointment.patient_appointment.check_payment_fields_reqd', + args: { 'patient': frm.doc.patient }, + callback: function(data) { + if (data.message.fee_validity) { + // if fee validity exists and automated appointment invoicing is enabled, + // show payment fields as non-mandatory + frm.toggle_display('mode_of_payment', 0); + frm.toggle_display('paid_amount', 0); + frm.toggle_display('billing_item', 0); + frm.toggle_reqd('mode_of_payment', 0); + frm.toggle_reqd('paid_amount', 0); + frm.toggle_reqd('billing_item', 0); + } else if (data.message) { + frm.toggle_display('mode_of_payment', 1); + frm.toggle_display('paid_amount', 1); + frm.toggle_display('billing_item', 1); + frm.toggle_reqd('mode_of_payment', 1); + frm.toggle_reqd('paid_amount', 1); + frm.toggle_reqd('billing_item', 1); + } else { + // if automated appointment invoicing is disabled, hide fields + frm.toggle_display('mode_of_payment', data.message ? 1 : 0); + frm.toggle_display('paid_amount', data.message ? 1 : 0); + frm.toggle_display('billing_item', data.message ? 1 : 0); + frm.toggle_reqd('mode_of_payment', data.message ? 1 : 0); + frm.toggle_reqd('paid_amount', data.message ? 1 : 0); + frm.toggle_reqd('billing_item', data.message ? 1 : 0); + } + } + }); + }, + + get_prescribed_therapies: function(frm) { + if (frm.doc.patient) { + frappe.call({ + method: "healthcare.healthcare.doctype.patient_appointment.patient_appointment.get_prescribed_therapies", + args: { patient: frm.doc.patient }, + callback: function(r) { + if (r.message) { + show_therapy_types(frm, r.message); + } else { + frappe.msgprint({ + title: __('Not Therapies Prescribed'), + message: __('There are no Therapies prescribed for Patient {0}', [frm.doc.patient.bold()]), + indicator: 'blue' + }); + } + } + }); + } + } +}); + +let check_and_set_availability = function(frm) { + let selected_slot = null; + let service_unit = null; + let duration = null; + + show_availability(); + + function show_empty_state(practitioner, appointment_date) { + frappe.msgprint({ + title: __('Not Available'), + message: __('Healthcare Practitioner {0} not available on {1}', [practitioner.bold(), appointment_date.bold()]), + indicator: 'red' + }); + } + + function show_availability() { + let selected_practitioner = ''; + let d = new frappe.ui.Dialog({ + title: __('Available slots'), + fields: [ + { fieldtype: 'Link', options: 'Medical Department', reqd: 1, fieldname: 'department', label: 'Medical Department' }, + { fieldtype: 'Column Break' }, + { fieldtype: 'Link', options: 'Healthcare Practitioner', reqd: 1, fieldname: 'practitioner', label: 'Healthcare Practitioner' }, + { fieldtype: 'Column Break' }, + { fieldtype: 'Date', reqd: 1, fieldname: 'appointment_date', label: 'Date', min_date: new Date(frappe.datetime.get_today()) }, + { fieldtype: 'Section Break' }, + { fieldtype: 'HTML', fieldname: 'available_slots' } + + ], + primary_action_label: __('Book'), + primary_action: function() { + frm.set_value('appointment_time', selected_slot); + if (!frm.doc.duration) { + frm.set_value('duration', duration); + } + frm.set_value('practitioner', d.get_value('practitioner')); + frm.set_value('department', d.get_value('department')); + frm.set_value('appointment_date', d.get_value('appointment_date')); + if (service_unit) { + frm.set_value('service_unit', service_unit); + } + d.hide(); + frm.enable_save(); + frm.save(); + d.get_primary_btn().attr('disabled', true); + } + }); + + d.set_values({ + 'department': frm.doc.department, + 'practitioner': frm.doc.practitioner, + 'appointment_date': frm.doc.appointment_date + }); + + d.fields_dict['department'].df.onchange = () => { + d.set_values({ + 'practitioner': '' + }); + let department = d.get_value('department'); + if (department) { + d.fields_dict.practitioner.get_query = function() { + return { + filters: { + 'department': department + } + }; + }; + } + }; + + // disable dialog action initially + d.get_primary_btn().attr('disabled', true); + + // Field Change Handler + + let fd = d.fields_dict; + + d.fields_dict['appointment_date'].df.onchange = () => { + show_slots(d, fd); + }; + d.fields_dict['practitioner'].df.onchange = () => { + if (d.get_value('practitioner') && d.get_value('practitioner') != selected_practitioner) { + selected_practitioner = d.get_value('practitioner'); + show_slots(d, fd); + } + }; + d.show(); + } + + function show_slots(d, fd) { + if (d.get_value('appointment_date') && d.get_value('practitioner')) { + fd.available_slots.html(''); + frappe.call({ + method: 'healthcare.healthcare.doctype.patient_appointment.patient_appointment.get_availability_data', + args: { + practitioner: d.get_value('practitioner'), + date: d.get_value('appointment_date') + }, + callback: (r) => { + let data = r.message; + if (data.slot_details.length > 0) { + let $wrapper = d.fields_dict.available_slots.$wrapper; + + // make buttons for each slot + let slot_html = get_slots(data.slot_details); + + $wrapper + .css('margin-bottom', 0) + .addClass('text-center') + .html(slot_html); + + // highlight button when clicked + $wrapper.on('click', 'button', function() { + let $btn = $(this); + $wrapper.find('button').removeClass('btn-outline-primary'); + $btn.addClass('btn-outline-primary'); + selected_slot = $btn.attr('data-name'); + service_unit = $btn.attr('data-service-unit'); + duration = $btn.attr('data-duration'); + // enable primary action 'Book' + d.get_primary_btn().attr('disabled', null); + }); + + } else { + // fd.available_slots.html('Please select a valid date.'.bold()) + show_empty_state(d.get_value('practitioner'), d.get_value('appointment_date')); + } + }, + freeze: true, + freeze_message: __('Fetching Schedule...') + }); + } else { + fd.available_slots.html(__('Appointment date and Healthcare Practitioner are Mandatory').bold()); + } + } + + function get_slots(slot_details) { + let slot_html = ''; + let appointment_count = 0; + let disabled = false; + let start_str, slot_start_time, slot_end_time, interval, count, count_class, tool_tip, available_slots; + + slot_details.forEach((slot_info) => { + slot_html += `
+ ${__('Practitioner Schedule:')} ${slot_info.slot_name}
+ ${__('Service Unit:')} ${slot_info.service_unit} `; + + if (slot_info.service_unit_capacity) { + slot_html += `
${__('Maximum Capacity:')} ${slot_info.service_unit_capacity} `; + } + + slot_html += '

'; + + slot_html += slot_info.avail_slot.map(slot => { + appointment_count = 0; + disabled = false; + count_class = tool_tip = ''; + start_str = slot.from_time; + slot_start_time = moment(slot.from_time, 'HH:mm:ss'); + slot_end_time = moment(slot.to_time, 'HH:mm:ss'); + interval = (slot_end_time - slot_start_time) / 60000 | 0; + + // iterate in all booked appointments, update the start time and duration + slot_info.appointments.forEach((booked) => { + let booked_moment = moment(booked.appointment_time, 'HH:mm:ss'); + let end_time = booked_moment.clone().add(booked.duration, 'minutes'); + + // Deal with 0 duration appointments + if (booked_moment.isSame(slot_start_time) || booked_moment.isBetween(slot_start_time, slot_end_time)) { + if (booked.duration == 0) { + disabled = true; + return false; + } + } + + // Check for overlaps considering appointment duration + if (slot_info.allow_overlap != 1) { + if (slot_start_time.isBefore(end_time) && slot_end_time.isAfter(booked_moment)) { + // There is an overlap + disabled = true; + return false; + } + } else { + if (slot_start_time.isBefore(end_time) && slot_end_time.isAfter(booked_moment)) { + appointment_count++; + } + if (appointment_count >= slot_info.service_unit_capacity) { + // There is an overlap + disabled = true; + return false; + } + } + }); + + if (slot_info.allow_overlap == 1 && slot_info.service_unit_capacity > 1) { + available_slots = slot_info.service_unit_capacity - appointment_count; + count = `${(available_slots > 0 ? available_slots : __('Full'))}`; + count_class = `${(available_slots > 0 ? 'badge-success' : 'badge-danger')}`; + tool_tip =`${available_slots} ${__('slots available for booking')}`; + } + return ` + `; + + }).join(""); + + if (slot_info.service_unit_capacity) { + slot_html += `
${__('Each slot indicates the capacity currently available for booking')}`; + } + slot_html += `

`; + }); + + return slot_html; + } +}; + +let get_prescribed_procedure = function(frm) { + if (frm.doc.patient) { + frappe.call({ + method: 'healthcare.healthcare.doctype.patient_appointment.patient_appointment.get_procedure_prescribed', + args: { patient: frm.doc.patient }, + callback: function(r) { + if (r.message && r.message.length) { + show_procedure_templates(frm, r.message); + } else { + frappe.msgprint({ + title: __('Not Found'), + message: __('No Prescribed Procedures found for the selected Patient') + }); + } + } + }); + } else { + frappe.msgprint({ + title: __('Not Allowed'), + message: __('Please select a Patient first') + }); + } +}; + +let show_procedure_templates = function(frm, result) { + let d = new frappe.ui.Dialog({ + title: __('Prescribed Procedures'), + fields: [ + { + fieldtype: 'HTML', fieldname: 'procedure_template' + } + ] + }); + let html_field = d.fields_dict.procedure_template.$wrapper; + html_field.empty(); + $.each(result, function(x, y) { + let row = $(repl('
\ +
%(encounter)s
%(consulting_practitioner)s
%(encounter_date)s
\ +
%(procedure_template)s
%(practitioner)s
%(date)s
\ +

', { + name: y[0], procedure_template: y[1], + encounter: y[2], consulting_practitioner: y[3], encounter_date: y[4], + practitioner: y[5] ? y[5] : '', date: y[6] ? y[6] : '', department: y[7] ? y[7] : '' + })).appendTo(html_field); + row.find("a").click(function() { + frm.doc.procedure_template = $(this).attr('data-procedure-template'); + frm.doc.procedure_prescription = $(this).attr('data-name'); + frm.doc.practitioner = $(this).attr('data-practitioner'); + frm.doc.appointment_date = $(this).attr('data-date'); + frm.doc.department = $(this).attr('data-department'); + refresh_field('procedure_template'); + refresh_field('procedure_prescription'); + refresh_field('appointment_date'); + refresh_field('practitioner'); + refresh_field('department'); + d.hide(); + return false; + }); + }); + if (!result) { + let msg = __('There are no procedure prescribed for ') + frm.doc.patient; + $(repl('
%(msg)s
', { msg: msg })).appendTo(html_field); + } + d.show(); +}; + +let show_therapy_types = function(frm, result) { + var d = new frappe.ui.Dialog({ + title: __('Prescribed Therapies'), + fields: [ + { + fieldtype: 'HTML', fieldname: 'therapy_type' + } + ] + }); + var html_field = d.fields_dict.therapy_type.$wrapper; + $.each(result, function(x, y) { + var row = $(repl('
\ +
%(encounter)s
%(practitioner)s
%(date)s
\ +
%(therapy)s
\ +

', { + therapy: y[0], + name: y[1], encounter: y[2], practitioner: y[3], date: y[4], + department: y[6] ? y[6] : '', therapy_plan: y[5] + })).appendTo(html_field); + + row.find("a").click(function() { + frm.doc.therapy_type = $(this).attr("data-therapy"); + frm.doc.practitioner = $(this).attr("data-practitioner"); + frm.doc.department = $(this).attr("data-department"); + frm.doc.therapy_plan = $(this).attr("data-therapy-plan"); + frm.refresh_field("therapy_type"); + frm.refresh_field("practitioner"); + frm.refresh_field("department"); + frm.refresh_field("therapy-plan"); + frappe.db.get_value('Therapy Type', frm.doc.therapy_type, 'default_duration', (r) => { + if (r.default_duration) { + frm.set_value('duration', r.default_duration) + } + }); + d.hide(); + return false; + }); + }); + d.show(); +}; + +let create_vital_signs = function(frm) { + if (!frm.doc.patient) { + frappe.throw(__('Please select patient')); + } + frappe.route_options = { + 'patient': frm.doc.patient, + 'appointment': frm.doc.name, + 'company': frm.doc.company + }; + frappe.new_doc('Vital Signs'); +}; + +let update_status = function(frm, status) { + let doc = frm.doc; + frappe.confirm(__('Are you sure you want to cancel this appointment?'), + function() { + frappe.call({ + method: 'healthcare.healthcare.doctype.patient_appointment.patient_appointment.update_status', + args: { appointment_id: doc.name, status: status }, + callback: function(data) { + if (!data.exc) { + frm.reload_doc(); + } + } + }); + } + ); +}; + +let calculate_age = function(birth) { + let ageMS = Date.parse(Date()) - Date.parse(birth); + let age = new Date(); + age.setTime(ageMS); + let years = age.getFullYear() - 1970; + return `${years} ${__('Years(s)')} ${age.getMonth()} ${__('Month(s)')} ${age.getDate()} ${__('Day(s)')}`; +}; diff --git a/healthcare/healthcare/doctype/patient_appointment/patient_appointment.json b/healthcare/healthcare/doctype/patient_appointment/patient_appointment.json new file mode 100644 index 0000000..9508020 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_appointment/patient_appointment.json @@ -0,0 +1,403 @@ +{ + "actions": [], + "allow_copy": 0, + "allow_import": 1, + "autoname": "naming_series:", + "beta": 1, + "creation": "2017-05-04 11:52:40.941507", + "doctype": "DocType", + "document_type": "Document", + "engine": "InnoDB", + "field_order": [ + "naming_series", + "title", + "status", + "patient", + "patient_name", + "patient_sex", + "patient_age", + "inpatient_record", + "column_break_1", + "company", + "practitioner", + "practitioner_name", + "department", + "service_unit", + "section_break_12", + "appointment_type", + "duration", + "procedure_template", + "get_procedure_from_encounter", + "procedure_prescription", + "therapy_plan", + "therapy_type", + "get_prescribed_therapies", + "column_break_17", + "appointment_date", + "appointment_time", + "appointment_datetime", + "section_break_16", + "mode_of_payment", + "billing_item", + "invoiced", + "column_break_2", + "paid_amount", + "ref_sales_invoice", + "section_break_3", + "referring_practitioner", + "reminded", + "column_break_36", + "notes" + ], + "fields": [ + { + "fetch_from": "patient.inpatient_record", + "fieldname": "inpatient_record", + "fieldtype": "Link", + "label": "Inpatient Record", + "options": "Inpatient Record", + "read_only": 1 + }, + { + "fieldname": "patient", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Patient", + "options": "Patient", + "reqd": 1, + "search_index": 1, + "set_only_once": 1 + }, + { + "fieldname": "appointment_type", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "label": "Appointment Type", + "options": "Appointment Type", + "set_only_once": 1 + }, + { + "fetch_from": "appointment_type.default_duration", + "fieldname": "duration", + "fieldtype": "Int", + "in_filter": 1, + "label": "Duration (In Minutes)", + "set_only_once": 1 + }, + { + "fieldname": "column_break_1", + "fieldtype": "Column Break", + "read_only": 1 + }, + { + "depends_on": "eval:!doc.__islocal", + "fieldname": "status", + "fieldtype": "Select", + "in_filter": 1, + "in_list_view": 1, + "label": "Status", + "options": "\nScheduled\nOpen\nClosed\nCancelled", + "read_only": 1, + "search_index": 1 + }, + { + "depends_on": "eval:doc.patient;", + "fieldname": "procedure_template", + "fieldtype": "Link", + "label": "Clinical Procedure Template", + "options": "Clinical Procedure Template", + "set_only_once": 1 + }, + { + "depends_on": "eval:doc.__islocal && doc.patient", + "fieldname": "get_procedure_from_encounter", + "fieldtype": "Button", + "label": "Get Prescribed Clinical Procedures" + }, + { + "fieldname": "procedure_prescription", + "fieldtype": "Link", + "hidden": 1, + "label": "Procedure Prescription", + "no_copy": 1, + "options": "Procedure Prescription", + "print_hide": 1, + "read_only": 1 + }, + { + "fieldname": "service_unit", + "fieldtype": "Link", + "label": "Service Unit", + "options": "Healthcare Service Unit", + "read_only": 1 + }, + { + "depends_on": "eval:doc.practitioner;", + "fieldname": "section_break_12", + "fieldtype": "Section Break", + "label": "Appointment Details" + }, + { + "fieldname": "practitioner", + "fieldtype": "Link", + "in_standard_filter": 1, + "label": "Healthcare Practitioner", + "options": "Healthcare Practitioner", + "reqd": 1, + "search_index": 1, + "set_only_once": 1 + }, + { + "fetch_from": "practitioner.department", + "fieldname": "department", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Department", + "options": "Medical Department", + "search_index": 1, + "set_only_once": 1 + }, + { + "fieldname": "column_break_17", + "fieldtype": "Column Break" + }, + { + "fieldname": "appointment_date", + "fieldtype": "Date", + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Date", + "read_only": 1, + "reqd": 1, + "search_index": 1 + }, + { + "fieldname": "appointment_time", + "fieldtype": "Time", + "in_list_view": 1, + "label": "Time", + "read_only": 1, + "reqd": 1 + }, + { + "fieldname": "section_break_16", + "fieldtype": "Section Break", + "label": "Payments" + }, + { + "fetch_from": "patient.patient_name", + "fieldname": "patient_name", + "fieldtype": "Data", + "label": "Patient Name", + "read_only": 1 + }, + { + "fetch_from": "patient.sex", + "fieldname": "patient_sex", + "fieldtype": "Link", + "label": "Gender", + "no_copy": 1, + "options": "Gender", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "fieldname": "patient_age", + "fieldtype": "Data", + "label": "Patient Age", + "read_only": 1 + }, + { + "fieldname": "appointment_datetime", + "fieldtype": "Datetime", + "hidden": 1, + "label": "Appointment Datetime", + "print_hide": 1, + "read_only": 1, + "report_hide": 1, + "search_index": 1 + }, + { + "fieldname": "mode_of_payment", + "fieldtype": "Link", + "label": "Mode of Payment", + "options": "Mode of Payment", + "read_only_depends_on": "invoiced" + }, + { + "fieldname": "paid_amount", + "fieldtype": "Currency", + "label": "Paid Amount", + "read_only_depends_on": "invoiced" + }, + { + "fieldname": "column_break_2", + "fieldtype": "Column Break" + }, + { + "default": "0", + "fieldname": "invoiced", + "fieldtype": "Check", + "label": "Invoiced", + "read_only": 1 + }, + { + "fieldname": "company", + "fieldtype": "Link", + "in_standard_filter": 1, + "label": "Company", + "no_copy": 1, + "options": "Company", + "reqd": 1, + "set_only_once": 1 + }, + { + "collapsible": 1, + "fieldname": "section_break_3", + "fieldtype": "Section Break", + "label": "More Info" + }, + { + "fieldname": "notes", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Notes" + }, + { + "fieldname": "referring_practitioner", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "label": "Referring Practitioner", + "options": "Healthcare Practitioner" + }, + { + "default": "0", + "fieldname": "reminded", + "fieldtype": "Check", + "hidden": 1, + "label": "Reminded", + "print_hide": 1, + "report_hide": 1 + }, + { + "depends_on": "eval:doc.patient && doc.therapy_plan;", + "fieldname": "therapy_type", + "fieldtype": "Link", + "label": "Therapy", + "options": "Therapy Type", + "set_only_once": 1 + }, + { + "depends_on": "eval:doc.patient && doc.therapy_plan && doc.__islocal;", + "fieldname": "get_prescribed_therapies", + "fieldtype": "Button", + "label": "Get Prescribed Therapies" + }, + { + "depends_on": "eval: doc.patient;", + "fieldname": "therapy_plan", + "fieldtype": "Link", + "label": "Therapy Plan", + "options": "Therapy Plan", + "set_only_once": 1 + }, + { + "fieldname": "ref_sales_invoice", + "fieldtype": "Link", + "label": "Reference Sales Invoice", + "options": "Sales Invoice", + "read_only": 1 + }, + { + "fieldname": "naming_series", + "fieldtype": "Select", + "label": "Series", + "options": "HLC-APP-.YYYY.-", + "set_only_once": 1 + }, + { + "fieldname": "billing_item", + "fieldtype": "Link", + "label": "Billing Item", + "options": "Item", + "read_only": 1 + }, + { + "fieldname": "column_break_36", + "fieldtype": "Column Break" + }, + { + "fieldname": "title", + "fieldtype": "Data", + "hidden": 1, + "label": "Title", + "no_copy": 1, + "print_hide": 1, + "read_only": 1 + }, + { + "fetch_from": "practitioner.practitioner_name", + "fieldname": "practitioner_name", + "fieldtype": "Data", + "label": "Practitioner Name", + "read_only": 1 + } + ], + "links": [], + "modified": "2022-02-14 09:00:41.329387", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient Appointment", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Nursing User", + "share": 1, + "write": 1 + } + ], + "restrict_to_domain": "Healthcare", + "search_fields": "patient, practitioner, department, appointment_date, appointment_time", + "show_name_in_global_search": 1, + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "title", + "track_changes": 1, + "track_seen": 1 +} diff --git a/healthcare/healthcare/doctype/patient_appointment/patient_appointment.py b/healthcare/healthcare/doctype/patient_appointment/patient_appointment.py new file mode 100644 index 0000000..340c396 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_appointment/patient_appointment.py @@ -0,0 +1,680 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and contributors +# For license information, please see license.txt + + +import datetime +import json + +import frappe +from frappe import _ +from frappe.core.doctype.sms_settings.sms_settings import send_sms +from frappe.model.document import Document +from frappe.model.mapper import get_mapped_doc +from frappe.utils import flt, get_link_to_form, get_time, getdate + +from healthcare.healthcare.doctype.healthcare_settings.healthcare_settings import ( + get_income_account, + get_receivable_account, +) +from healthcare.healthcare.utils import ( + check_fee_validity, + get_service_item_and_practitioner_charge, + manage_fee_validity, +) + +# todo: clean up imports +try: + from erpnext.hr.doctype.employee.employee import is_holiday +except ImportError: + from erpnext.setup.doctype.employee.employee import is_holiday + + +class MaximumCapacityError(frappe.ValidationError): + pass + + +class OverlapError(frappe.ValidationError): + pass + + +class PatientAppointment(Document): + def validate(self): + self.validate_overlaps() + self.validate_service_unit() + self.set_appointment_datetime() + self.validate_customer_created() + self.set_status() + self.set_title() + + def after_insert(self): + self.update_prescription_details() + self.set_payment_details() + invoice_appointment(self) + self.update_fee_validity() + send_confirmation_msg(self) + + def set_title(self): + self.title = _("{0} with {1}").format( + self.patient_name or self.patient, self.practitioner_name or self.practitioner + ) + + def set_status(self): + today = getdate() + appointment_date = getdate(self.appointment_date) + + # If appointment is created for today set status as Open else Scheduled + if appointment_date == today: + self.status = "Open" + elif appointment_date > today: + self.status = "Scheduled" + + def validate_overlaps(self): + end_time = datetime.datetime.combine( + getdate(self.appointment_date), get_time(self.appointment_time) + ) + datetime.timedelta(minutes=flt(self.duration)) + + # all appointments for both patient and practitioner overlapping the duration of this appointment + overlapping_appointments = frappe.db.sql( + """ + SELECT + name, practitioner, patient, appointment_time, duration, service_unit + FROM + `tabPatient Appointment` + WHERE + appointment_date=%(appointment_date)s AND name!=%(name)s AND status NOT IN ("Closed", "Cancelled") AND + (practitioner=%(practitioner)s OR patient=%(patient)s) AND + ((appointment_time<%(appointment_time)s AND appointment_time + INTERVAL duration MINUTE>%(appointment_time)s) OR + (appointment_time>%(appointment_time)s AND appointment_time<%(end_time)s) OR + (appointment_time=%(appointment_time)s)) + """, + { + "appointment_date": self.appointment_date, + "name": self.name, + "practitioner": self.practitioner, + "patient": self.patient, + "appointment_time": self.appointment_time, + "end_time": end_time.time(), + }, + as_dict=True, + ) + + if not overlapping_appointments: + return # No overlaps, nothing to validate! + + if self.service_unit: # validate service unit capacity if overlap enabled + allow_overlap, service_unit_capacity = frappe.get_value( + "Healthcare Service Unit", self.service_unit, ["overlap_appointments", "service_unit_capacity"] + ) + if allow_overlap: + service_unit_appointments = list( + filter( + lambda appointment: appointment["service_unit"] == self.service_unit + and appointment["patient"] != self.patient, + overlapping_appointments, + ) + ) # if same patient already booked, it should be an overlap + if len(service_unit_appointments) >= (service_unit_capacity or 1): + frappe.throw( + _("Not allowed, {} cannot exceed maximum capacity {}").format( + frappe.bold(self.service_unit), frappe.bold(service_unit_capacity or 1) + ), + MaximumCapacityError, + ) + else: # service_unit_appointments within capacity, remove from overlapping_appointments + overlapping_appointments = [ + appointment + for appointment in overlapping_appointments + if appointment not in service_unit_appointments + ] + + if overlapping_appointments: + frappe.throw( + _("Not allowed, cannot overlap appointment {}").format( + frappe.bold(", ".join([appointment["name"] for appointment in overlapping_appointments])) + ), + OverlapError, + ) + + def validate_service_unit(self): + if self.inpatient_record and self.service_unit: + from healthcare.healthcare.doctype.inpatient_medication_entry.inpatient_medication_entry import ( + get_current_healthcare_service_unit, + ) + + is_inpatient_occupancy_unit = frappe.db.get_value( + "Healthcare Service Unit", self.service_unit, "inpatient_occupancy" + ) + service_unit = get_current_healthcare_service_unit(self.inpatient_record) + if is_inpatient_occupancy_unit and service_unit != self.service_unit: + msg = ( + _("Patient {0} is not admitted in the service unit {1}").format( + frappe.bold(self.patient), frappe.bold(self.service_unit) + ) + + "
" + ) + msg += _( + "Appointment for service units with Inpatient Occupancy can only be created against the unit where patient has been admitted." + ) + frappe.throw(msg, title=_("Invalid Healthcare Service Unit")) + + def set_appointment_datetime(self): + self.appointment_datetime = "%s %s" % ( + self.appointment_date, + self.appointment_time or "00:00:00", + ) + + def set_payment_details(self): + if frappe.db.get_single_value("Healthcare Settings", "automate_appointment_invoicing"): + details = get_service_item_and_practitioner_charge(self) + self.db_set("billing_item", details.get("service_item")) + if not self.paid_amount: + self.db_set("paid_amount", details.get("practitioner_charge")) + + def validate_customer_created(self): + if frappe.db.get_single_value("Healthcare Settings", "automate_appointment_invoicing"): + if not frappe.db.get_value("Patient", self.patient, "customer"): + msg = _("Please set a Customer linked to the Patient") + msg += " {0}".format(self.patient) + frappe.throw(msg, title=_("Customer Not Found")) + + def update_prescription_details(self): + if self.procedure_prescription: + frappe.db.set_value( + "Procedure Prescription", self.procedure_prescription, "appointment_booked", 1 + ) + if self.procedure_template: + comments = frappe.db.get_value( + "Procedure Prescription", self.procedure_prescription, "comments" + ) + if comments: + frappe.db.set_value("Patient Appointment", self.name, "notes", comments) + + def update_fee_validity(self): + if not frappe.db.get_single_value("Healthcare Settings", "enable_free_follow_ups"): + return + + fee_validity = manage_fee_validity(self) + if fee_validity: + frappe.msgprint( + _("{0}: {1} has fee validity till {2}").format( + self.patient, frappe.bold(self.patient_name), fee_validity.valid_till + ) + ) + + @frappe.whitelist() + def get_therapy_types(self): + if not self.therapy_plan: + return + + therapy_types = [] + doc = frappe.get_doc("Therapy Plan", self.therapy_plan) + for entry in doc.therapy_plan_details: + therapy_types.append(entry.therapy_type) + + return therapy_types + + +@frappe.whitelist() +def check_payment_fields_reqd(patient): + automate_invoicing = frappe.db.get_single_value( + "Healthcare Settings", "automate_appointment_invoicing" + ) + free_follow_ups = frappe.db.get_single_value("Healthcare Settings", "enable_free_follow_ups") + if automate_invoicing: + if free_follow_ups: + fee_validity = frappe.db.exists("Fee Validity", {"patient": patient, "status": "Pending"}) + if fee_validity: + return {"fee_validity": fee_validity} + return True + return False + + +def invoice_appointment(appointment_doc): + automate_invoicing = frappe.db.get_single_value( + "Healthcare Settings", "automate_appointment_invoicing" + ) + appointment_invoiced = frappe.db.get_value( + "Patient Appointment", appointment_doc.name, "invoiced" + ) + enable_free_follow_ups = frappe.db.get_single_value( + "Healthcare Settings", "enable_free_follow_ups" + ) + if enable_free_follow_ups: + fee_validity = check_fee_validity(appointment_doc) + if fee_validity and fee_validity.status == "Completed": + fee_validity = None + elif not fee_validity: + if frappe.db.exists("Fee Validity Reference", {"appointment": appointment_doc.name}): + return + else: + fee_validity = None + + if automate_invoicing and not appointment_invoiced and not fee_validity: + create_sales_invoice(appointment_doc) + + +def create_sales_invoice(appointment_doc): + sales_invoice = frappe.new_doc("Sales Invoice") + sales_invoice.patient = appointment_doc.patient + sales_invoice.customer = frappe.get_value("Patient", appointment_doc.patient, "customer") + sales_invoice.appointment = appointment_doc.name + sales_invoice.due_date = getdate() + sales_invoice.company = appointment_doc.company + sales_invoice.debit_to = get_receivable_account(appointment_doc.company) + + item = sales_invoice.append("items", {}) + item = get_appointment_item(appointment_doc, item) + + # Add payments if payment details are supplied else proceed to create invoice as Unpaid + if appointment_doc.mode_of_payment and appointment_doc.paid_amount: + sales_invoice.is_pos = 1 + payment = sales_invoice.append("payments", {}) + payment.mode_of_payment = appointment_doc.mode_of_payment + payment.amount = appointment_doc.paid_amount + + sales_invoice.set_missing_values(for_validate=True) + sales_invoice.flags.ignore_mandatory = True + sales_invoice.save(ignore_permissions=True) + sales_invoice.submit() + frappe.msgprint(_("Sales Invoice {0} created").format(sales_invoice.name), alert=True) + frappe.db.set_value( + "Patient Appointment", + appointment_doc.name, + {"invoiced": 1, "ref_sales_invoice": sales_invoice.name}, + ) + + +def check_is_new_patient(patient, name=None): + filters = {"patient": patient, "status": ("!=", "Cancelled")} + if name: + filters["name"] = ("!=", name) + + has_previous_appointment = frappe.db.exists("Patient Appointment", filters) + return not has_previous_appointment + + +def get_appointment_item(appointment_doc, item): + details = get_service_item_and_practitioner_charge(appointment_doc) + charge = appointment_doc.paid_amount or details.get("practitioner_charge") + item.item_code = details.get("service_item") + item.description = _("Consulting Charges: {0}").format(appointment_doc.practitioner) + item.income_account = get_income_account(appointment_doc.practitioner, appointment_doc.company) + item.cost_center = frappe.get_cached_value("Company", appointment_doc.company, "cost_center") + item.rate = charge + item.amount = charge + item.qty = 1 + item.reference_dt = "Patient Appointment" + item.reference_dn = appointment_doc.name + return item + + +def cancel_appointment(appointment_id): + appointment = frappe.get_doc("Patient Appointment", appointment_id) + if appointment.invoiced: + sales_invoice = check_sales_invoice_exists(appointment) + if sales_invoice and cancel_sales_invoice(sales_invoice): + msg = _("Appointment {0} and Sales Invoice {1} cancelled").format( + appointment.name, sales_invoice.name + ) + else: + msg = _("Appointment Cancelled. Please review and cancel the invoice {0}").format( + sales_invoice.name + ) + else: + fee_validity = manage_fee_validity(appointment) + msg = _("Appointment Cancelled.") + if fee_validity: + msg += _("Fee Validity {0} updated.").format(fee_validity.name) + + frappe.msgprint(msg) + + +def cancel_sales_invoice(sales_invoice): + if frappe.db.get_single_value("Healthcare Settings", "automate_appointment_invoicing"): + if len(sales_invoice.items) == 1: + sales_invoice.cancel() + return True + return False + + +def check_sales_invoice_exists(appointment): + sales_invoice = frappe.db.get_value( + "Sales Invoice Item", + {"reference_dt": "Patient Appointment", "reference_dn": appointment.name}, + "parent", + ) + + if sales_invoice: + sales_invoice = frappe.get_doc("Sales Invoice", sales_invoice) + return sales_invoice + return False + + +@frappe.whitelist() +def get_availability_data(date, practitioner): + """ + Get availability data of 'practitioner' on 'date' + :param date: Date to check in schedule + :param practitioner: Name of the practitioner + :return: dict containing a list of available slots, list of appointments and time of appointments + """ + + date = getdate(date) + weekday = date.strftime("%A") + + practitioner_doc = frappe.get_doc("Healthcare Practitioner", practitioner) + + check_employee_wise_availability(date, practitioner_doc) + + if practitioner_doc.practitioner_schedules: + slot_details = get_available_slots(practitioner_doc, date) + else: + frappe.throw( + _( + "{0} does not have a Healthcare Practitioner Schedule. Add it in Healthcare Practitioner master" + ).format(practitioner), + title=_("Practitioner Schedule Not Found"), + ) + + if not slot_details: + # TODO: return available slots in nearby dates + frappe.throw( + _("Healthcare Practitioner not available on {0}").format(weekday), title=_("Not Available") + ) + + return {"slot_details": slot_details} + + +def check_employee_wise_availability(date, practitioner_doc): + employee = None + if practitioner_doc.employee: + employee = practitioner_doc.employee + elif practitioner_doc.user_id: + employee = frappe.db.get_value("Employee", {"user_id": practitioner_doc.user_id}, "name") + + if employee: + # check holiday + if is_holiday(employee, date): + frappe.throw(_("{0} is a holiday".format(date)), title=_("Not Available")) + + # check leave status + leave_record = frappe.db.sql( + """select half_day from `tabLeave Application` + where employee = %s and %s between from_date and to_date + and docstatus = 1""", + (employee, date), + as_dict=True, + ) + if leave_record: + if leave_record[0].half_day: + frappe.throw( + _("{0} is on a Half day Leave on {1}").format(practitioner_doc.name, date), + title=_("Not Available"), + ) + else: + frappe.throw( + _("{0} is on Leave on {1}").format(practitioner_doc.name, date), title=_("Not Available") + ) + + +def get_available_slots(practitioner_doc, date): + available_slots = slot_details = [] + weekday = date.strftime("%A") + practitioner = practitioner_doc.name + + for schedule_entry in practitioner_doc.practitioner_schedules: + validate_practitioner_schedules(schedule_entry, practitioner) + practitioner_schedule = frappe.get_doc("Practitioner Schedule", schedule_entry.schedule) + + if practitioner_schedule and not practitioner_schedule.disabled: + available_slots = [] + for time_slot in practitioner_schedule.time_slots: + if weekday == time_slot.day: + available_slots.append(time_slot) + + if available_slots: + appointments = [] + allow_overlap = 0 + service_unit_capacity = 0 + # fetch all appointments to practitioner by service unit + filters = { + "practitioner": practitioner, + "service_unit": schedule_entry.service_unit, + "appointment_date": date, + "status": ["not in", ["Cancelled"]], + } + + if schedule_entry.service_unit: + slot_name = f"{schedule_entry.schedule}" + allow_overlap, service_unit_capacity = frappe.get_value( + "Healthcare Service Unit", + schedule_entry.service_unit, + ["overlap_appointments", "service_unit_capacity"], + ) + if not allow_overlap: + # fetch all appointments to service unit + filters.pop("practitioner") + else: + slot_name = schedule_entry.schedule + # fetch all appointments to practitioner without service unit + filters["practitioner"] = practitioner + filters.pop("service_unit") + + appointments = frappe.get_all( + "Patient Appointment", + filters=filters, + fields=["name", "appointment_time", "duration", "status"], + ) + + slot_details.append( + { + "slot_name": slot_name, + "service_unit": schedule_entry.service_unit, + "avail_slot": available_slots, + "appointments": appointments, + "allow_overlap": allow_overlap, + "service_unit_capacity": service_unit_capacity, + } + ) + + return slot_details + + +def validate_practitioner_schedules(schedule_entry, practitioner): + if schedule_entry.schedule: + if not schedule_entry.service_unit: + frappe.throw( + _( + "Practitioner {0} does not have a Service Unit set against the Practitioner Schedule {1}." + ).format( + get_link_to_form("Healthcare Practitioner", practitioner), + frappe.bold(schedule_entry.schedule), + ), + title=_("Service Unit Not Found"), + ) + + else: + frappe.throw( + _("Practitioner {0} does not have a Practitioner Schedule assigned.").format( + get_link_to_form("Healthcare Practitioner", practitioner) + ), + title=_("Practitioner Schedule Not Found"), + ) + + +@frappe.whitelist() +def update_status(appointment_id, status): + frappe.db.set_value("Patient Appointment", appointment_id, "status", status) + appointment_booked = True + if status == "Cancelled": + appointment_booked = False + cancel_appointment(appointment_id) + + procedure_prescription = frappe.db.get_value( + "Patient Appointment", appointment_id, "procedure_prescription" + ) + if procedure_prescription: + frappe.db.set_value( + "Procedure Prescription", procedure_prescription, "appointment_booked", appointment_booked + ) + + +def send_confirmation_msg(doc): + if frappe.db.get_single_value("Healthcare Settings", "send_appointment_confirmation"): + message = frappe.db.get_single_value("Healthcare Settings", "appointment_confirmation_msg") + try: + send_message(doc, message) + except Exception: + frappe.log_error(frappe.get_traceback(), _("Appointment Confirmation Message Not Sent")) + frappe.msgprint(_("Appointment Confirmation Message Not Sent"), indicator="orange") + + +@frappe.whitelist() +def make_encounter(source_name, target_doc=None): + doc = get_mapped_doc( + "Patient Appointment", + source_name, + { + "Patient Appointment": { + "doctype": "Patient Encounter", + "field_map": [ + ["appointment", "name"], + ["patient", "patient"], + ["practitioner", "practitioner"], + ["medical_department", "department"], + ["patient_sex", "patient_sex"], + ["invoiced", "invoiced"], + ["company", "company"], + ], + } + }, + target_doc, + ) + return doc + + +def send_appointment_reminder(): + if frappe.db.get_single_value("Healthcare Settings", "send_appointment_reminder"): + remind_before = datetime.datetime.strptime( + frappe.db.get_single_value("Healthcare Settings", "remind_before"), "%H:%M:%S" + ) + reminder_dt = datetime.datetime.now() + datetime.timedelta( + hours=remind_before.hour, minutes=remind_before.minute, seconds=remind_before.second + ) + + appointment_list = frappe.db.get_all( + "Patient Appointment", + { + "appointment_datetime": ["between", (datetime.datetime.now(), reminder_dt)], + "reminded": 0, + "status": ["!=", "Cancelled"], + }, + ) + + for appointment in appointment_list: + doc = frappe.get_doc("Patient Appointment", appointment.name) + message = frappe.db.get_single_value("Healthcare Settings", "appointment_reminder_msg") + send_message(doc, message) + frappe.db.set_value("Patient Appointment", doc.name, "reminded", 1) + + +def send_message(doc, message): + patient_mobile = frappe.db.get_value("Patient", doc.patient, "mobile") + if patient_mobile: + context = {"doc": doc, "alert": doc, "comments": None} + if doc.get("_comments"): + context["comments"] = json.loads(doc.get("_comments")) + + # jinja to string convertion happens here + message = frappe.render_template(message, context) + number = [patient_mobile] + try: + send_sms(number, message) + except Exception as e: + frappe.msgprint(_("SMS not sent, please check SMS Settings"), alert=True) + + +@frappe.whitelist() +def get_events(start, end, filters=None): + """Returns events for Gantt / Calendar view rendering. + + :param start: Start date-time. + :param end: End date-time. + :param filters: Filters (JSON). + """ + from frappe.desk.calendar import get_event_conditions + + conditions = get_event_conditions("Patient Appointment", filters) + + data = frappe.db.sql( + """ + select + `tabPatient Appointment`.name, `tabPatient Appointment`.patient, + `tabPatient Appointment`.practitioner, `tabPatient Appointment`.status, + `tabPatient Appointment`.duration, + timestamp(`tabPatient Appointment`.appointment_date, `tabPatient Appointment`.appointment_time) as 'start', + `tabAppointment Type`.color + from + `tabPatient Appointment` + left join `tabAppointment Type` on `tabPatient Appointment`.appointment_type=`tabAppointment Type`.name + where + (`tabPatient Appointment`.appointment_date between %(start)s and %(end)s) + and `tabPatient Appointment`.status != 'Cancelled' and `tabPatient Appointment`.docstatus < 2 {conditions}""".format( + conditions=conditions + ), + {"start": start, "end": end}, + as_dict=True, + update={"allDay": 0}, + ) + + for item in data: + item.end = item.start + datetime.timedelta(minutes=item.duration) + + return data + + +@frappe.whitelist() +def get_procedure_prescribed(patient): + return frappe.db.sql( + """ + SELECT + pp.name, pp.procedure, pp.parent, ct.practitioner, + ct.encounter_date, pp.practitioner, pp.date, pp.department + FROM + `tabPatient Encounter` ct, `tabProcedure Prescription` pp + WHERE + ct.patient=%(patient)s and pp.parent=ct.name and pp.appointment_booked=0 + ORDER BY + ct.creation desc + """, + {"patient": patient}, + ) + + +@frappe.whitelist() +def get_prescribed_therapies(patient): + return frappe.db.sql( + """ + SELECT + t.therapy_type, t.name, t.parent, e.practitioner, + e.encounter_date, e.therapy_plan, e.medical_department + FROM + `tabPatient Encounter` e, `tabTherapy Plan Detail` t + WHERE + e.patient=%(patient)s and t.parent=e.name + ORDER BY + e.creation desc + """, + {"patient": patient}, + ) + + +def update_appointment_status(): + # update the status of appointments daily + appointments = frappe.get_all( + "Patient Appointment", {"status": ("not in", ["Closed", "Cancelled"])}, as_dict=1 + ) + + for appointment in appointments: + frappe.get_doc("Patient Appointment", appointment.name).set_status() diff --git a/healthcare/healthcare/doctype/patient_appointment/patient_appointment_calendar.js b/healthcare/healthcare/doctype/patient_appointment/patient_appointment_calendar.js new file mode 100644 index 0000000..5976cac --- /dev/null +++ b/healthcare/healthcare/doctype/patient_appointment/patient_appointment_calendar.js @@ -0,0 +1,14 @@ + +frappe.views.calendar["Patient Appointment"] = { + field_map: { + "start": "start", + "end": "end", + "id": "name", + "title": "patient", + "allDay": "allDay", + "eventColor": "color" + }, + order_by: "appointment_date", + gantt: true, + get_events_method: "healthcare.healthcare.doctype.patient_appointment.patient_appointment.get_events" +}; diff --git a/healthcare/healthcare/doctype/patient_appointment/patient_appointment_dashboard.py b/healthcare/healthcare/doctype/patient_appointment/patient_appointment_dashboard.py new file mode 100644 index 0000000..3eeb153 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_appointment/patient_appointment_dashboard.py @@ -0,0 +1,14 @@ +from frappe import _ + + +def get_data(): + return { + "fieldname": "appointment", + "non_standard_fieldnames": {"Patient Medical Record": "reference_name"}, + "transactions": [ + { + "label": _("Consultations"), + "items": ["Patient Encounter", "Vital Signs", "Patient Medical Record"], + } + ], + } diff --git a/healthcare/healthcare/doctype/patient_appointment/patient_appointment_list.js b/healthcare/healthcare/doctype/patient_appointment/patient_appointment_list.js new file mode 100644 index 0000000..721887b --- /dev/null +++ b/healthcare/healthcare/doctype/patient_appointment/patient_appointment_list.js @@ -0,0 +1,16 @@ +/* +(c) ESS 2015-16 +*/ +frappe.listview_settings['Patient Appointment'] = { + filters: [["status", "=", "Open"]], + get_indicator: function(doc) { + var colors = { + "Open": "orange", + "Scheduled": "yellow", + "Closed": "green", + "Cancelled": "red", + "Expired": "grey" + }; + return [__(doc.status), colors[doc.status], "status,=," + doc.status]; + } +}; diff --git a/healthcare/healthcare/doctype/patient_appointment/test_patient_appointment.py b/healthcare/healthcare/doctype/patient_appointment/test_patient_appointment.py new file mode 100644 index 0000000..353b62c --- /dev/null +++ b/healthcare/healthcare/doctype/patient_appointment/test_patient_appointment.py @@ -0,0 +1,570 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +import frappe +from frappe.utils import add_days, now_datetime, nowdate + +from erpnext.accounts.doctype.pos_profile.test_pos_profile import make_pos_profile +from healthcare.healthcare.doctype.patient_appointment.patient_appointment import ( + check_is_new_patient, + check_payment_fields_reqd, + make_encounter, + update_status, +) + + +class TestPatientAppointment(FrappeTestCase): + def setUp(self): + frappe.db.sql("""delete from `tabPatient Appointment`""") + frappe.db.sql("""delete from `tabFee Validity`""") + frappe.db.sql("""delete from `tabPatient Encounter`""") + make_pos_profile() + frappe.db.sql("""delete from `tabHealthcare Service Unit` where name like '_Test %'""") + frappe.db.sql( + """delete from `tabHealthcare Service Unit` where name like '_Test Service Unit Type%'""" + ) + + def test_status(self): + patient, practitioner = create_healthcare_docs() + frappe.db.set_value("Healthcare Settings", None, "automate_appointment_invoicing", 0) + appointment = create_appointment(patient, practitioner, nowdate()) + self.assertEqual(appointment.status, "Open") + appointment = create_appointment(patient, practitioner, add_days(nowdate(), 2)) + self.assertEqual(appointment.status, "Scheduled") + encounter = create_encounter(appointment) + self.assertEqual( + frappe.db.get_value("Patient Appointment", appointment.name, "status"), "Closed" + ) + encounter.cancel() + self.assertEqual(frappe.db.get_value("Patient Appointment", appointment.name, "status"), "Open") + + def test_start_encounter(self): + patient, practitioner = create_healthcare_docs() + frappe.db.set_value("Healthcare Settings", None, "automate_appointment_invoicing", 1) + appointment = create_appointment(patient, practitioner, add_days(nowdate(), 4), invoice=1) + appointment.reload() + self.assertEqual(appointment.invoiced, 1) + encounter = make_encounter(appointment.name) + self.assertTrue(encounter) + self.assertEqual(encounter.company, appointment.company) + self.assertEqual(encounter.practitioner, appointment.practitioner) + self.assertEqual(encounter.patient, appointment.patient) + # invoiced flag mapped from appointment + self.assertEqual( + encounter.invoiced, frappe.db.get_value("Patient Appointment", appointment.name, "invoiced") + ) + + def test_auto_invoicing(self): + patient, practitioner = create_healthcare_docs() + frappe.db.set_value("Healthcare Settings", None, "enable_free_follow_ups", 0) + frappe.db.set_value("Healthcare Settings", None, "automate_appointment_invoicing", 0) + appointment = create_appointment(patient, practitioner, nowdate()) + self.assertEqual(frappe.db.get_value("Patient Appointment", appointment.name, "invoiced"), 0) + + frappe.db.set_value("Healthcare Settings", None, "automate_appointment_invoicing", 1) + appointment = create_appointment(patient, practitioner, add_days(nowdate(), 2), invoice=1) + self.assertEqual(frappe.db.get_value("Patient Appointment", appointment.name, "invoiced"), 1) + sales_invoice_name = frappe.db.get_value( + "Sales Invoice Item", {"reference_dn": appointment.name}, "parent" + ) + self.assertTrue(sales_invoice_name) + self.assertEqual( + frappe.db.get_value("Sales Invoice", sales_invoice_name, "company"), appointment.company + ) + self.assertEqual( + frappe.db.get_value("Sales Invoice", sales_invoice_name, "patient"), appointment.patient + ) + self.assertEqual( + frappe.db.get_value("Sales Invoice", sales_invoice_name, "paid_amount"), appointment.paid_amount + ) + + def test_auto_invoicing_based_on_department(self): + patient, practitioner = create_healthcare_docs() + medical_department = create_medical_department() + frappe.db.set_value("Healthcare Settings", None, "enable_free_follow_ups", 0) + frappe.db.set_value("Healthcare Settings", None, "automate_appointment_invoicing", 1) + appointment_type = create_appointment_type({"medical_department": medical_department}) + + appointment = create_appointment( + patient, + practitioner, + add_days(nowdate(), 2), + invoice=1, + appointment_type=appointment_type.name, + department=medical_department, + ) + appointment.reload() + + self.assertEqual(appointment.invoiced, 1) + self.assertEqual(appointment.billing_item, "HLC-SI-001") + self.assertEqual(appointment.paid_amount, 200) + + sales_invoice_name = frappe.db.get_value( + "Sales Invoice Item", {"reference_dn": appointment.name}, "parent" + ) + self.assertTrue(sales_invoice_name) + self.assertEqual( + frappe.db.get_value("Sales Invoice", sales_invoice_name, "paid_amount"), appointment.paid_amount + ) + + def test_auto_invoicing_according_to_appointment_type_charge(self): + patient, practitioner = create_healthcare_docs() + frappe.db.set_value("Healthcare Settings", None, "enable_free_follow_ups", 0) + frappe.db.set_value("Healthcare Settings", None, "automate_appointment_invoicing", 1) + + item = create_healthcare_service_items() + items = [{"op_consulting_charge_item": item, "op_consulting_charge": 300}] + appointment_type = create_appointment_type( + args={"name": "Generic Appointment Type charge", "items": items} + ) + + appointment = create_appointment( + patient, practitioner, add_days(nowdate(), 2), invoice=1, appointment_type=appointment_type.name + ) + appointment.reload() + + self.assertEqual(appointment.invoiced, 1) + self.assertEqual(appointment.billing_item, item) + self.assertEqual(appointment.paid_amount, 300) + + sales_invoice_name = frappe.db.get_value( + "Sales Invoice Item", {"reference_dn": appointment.name}, "parent" + ) + self.assertTrue(sales_invoice_name) + + def test_appointment_cancel(self): + patient, practitioner = create_healthcare_docs() + frappe.db.set_value("Healthcare Settings", None, "enable_free_follow_ups", 1) + appointment = create_appointment(patient, practitioner, nowdate()) + fee_validity = frappe.db.get_value( + "Fee Validity", {"patient": patient, "practitioner": practitioner} + ) + # fee validity created + self.assertTrue(fee_validity) + + # first follow up appointment + appointment = create_appointment(patient, practitioner, add_days(nowdate(), 1)) + self.assertEqual(frappe.db.get_value("Fee Validity", fee_validity, "visited"), 1) + + update_status(appointment.name, "Cancelled") + # check fee validity updated + self.assertEqual(frappe.db.get_value("Fee Validity", fee_validity, "visited"), 0) + + frappe.db.set_value("Healthcare Settings", None, "enable_free_follow_ups", 0) + frappe.db.set_value("Healthcare Settings", None, "automate_appointment_invoicing", 1) + appointment = create_appointment(patient, practitioner, add_days(nowdate(), 1), invoice=1) + update_status(appointment.name, "Cancelled") + # check invoice cancelled + sales_invoice_name = frappe.db.get_value( + "Sales Invoice Item", {"reference_dn": appointment.name}, "parent" + ) + self.assertEqual(frappe.db.get_value("Sales Invoice", sales_invoice_name, "status"), "Cancelled") + + def test_appointment_booking_for_admission_service_unit(self): + from healthcare.healthcare.doctype.inpatient_record.inpatient_record import ( + admit_patient, + discharge_patient, + schedule_discharge, + ) + from healthcare.healthcare.doctype.inpatient_record.test_inpatient_record import ( + create_inpatient, + get_healthcare_service_unit, + mark_invoiced_inpatient_occupancy, + ) + + frappe.db.sql("""delete from `tabInpatient Record`""") + patient, practitioner = create_healthcare_docs() + patient = create_patient() + # Schedule Admission + ip_record = create_inpatient(patient) + ip_record.expected_length_of_stay = 0 + ip_record.save(ignore_permissions=True) + + # Admit + service_unit = get_healthcare_service_unit("_Test Service Unit Ip Occupancy") + admit_patient(ip_record, service_unit, now_datetime()) + + appointment = create_appointment(patient, practitioner, nowdate(), service_unit=service_unit) + self.assertEqual(appointment.service_unit, service_unit) + + # Discharge + schedule_discharge(frappe.as_json({"patient": patient})) + ip_record1 = frappe.get_doc("Inpatient Record", ip_record.name) + mark_invoiced_inpatient_occupancy(ip_record1) + discharge_patient(ip_record1) + + def test_invalid_healthcare_service_unit_validation(self): + from healthcare.healthcare.doctype.inpatient_record.inpatient_record import ( + admit_patient, + discharge_patient, + schedule_discharge, + ) + from healthcare.healthcare.doctype.inpatient_record.test_inpatient_record import ( + create_inpatient, + get_healthcare_service_unit, + mark_invoiced_inpatient_occupancy, + ) + + frappe.db.sql("""delete from `tabInpatient Record`""") + patient, practitioner = create_healthcare_docs() + patient = create_patient() + # Schedule Admission + ip_record = create_inpatient(patient) + ip_record.expected_length_of_stay = 0 + ip_record.save(ignore_permissions=True) + + # Admit + service_unit = get_healthcare_service_unit("_Test Service Unit Ip Occupancy") + admit_patient(ip_record, service_unit, now_datetime()) + + appointment_service_unit = get_healthcare_service_unit( + "_Test Service Unit Ip Occupancy for Appointment" + ) + appointment = create_appointment( + patient, practitioner, nowdate(), service_unit=appointment_service_unit, save=0 + ) + self.assertRaises(frappe.exceptions.ValidationError, appointment.save) + + # Discharge + schedule_discharge(frappe.as_json({"patient": patient})) + ip_record1 = frappe.get_doc("Inpatient Record", ip_record.name) + mark_invoiced_inpatient_occupancy(ip_record1) + discharge_patient(ip_record1) + + def test_payment_should_be_mandatory_for_new_patient_appointment(self): + frappe.db.set_value("Healthcare Settings", None, "enable_free_follow_ups", 1) + frappe.db.set_value("Healthcare Settings", None, "automate_appointment_invoicing", 1) + frappe.db.set_value("Healthcare Settings", None, "max_visits", 3) + frappe.db.set_value("Healthcare Settings", None, "valid_days", 30) + + patient = create_patient() + assert check_is_new_patient(patient) + payment_required = check_payment_fields_reqd(patient) + assert payment_required is True + + def test_sales_invoice_should_be_generated_for_new_patient_appointment(self): + patient, practitioner = create_healthcare_docs() + frappe.db.set_value("Healthcare Settings", None, "automate_appointment_invoicing", 1) + invoice_count = frappe.db.count("Sales Invoice") + + assert check_is_new_patient(patient) + create_appointment(patient, practitioner, nowdate()) + new_invoice_count = frappe.db.count("Sales Invoice") + + assert new_invoice_count == invoice_count + 1 + + def test_patient_appointment_should_consider_permissions_while_fetching_appointments(self): + patient, practitioner = create_healthcare_docs() + create_appointment(patient, practitioner, nowdate()) + + patient, new_practitioner = create_healthcare_docs(id=5) + create_appointment(patient, new_practitioner, nowdate()) + + roles = [{"doctype": "Has Role", "role": "Physician"}] + user = create_user(roles=roles) + new_practitioner = frappe.get_doc("Healthcare Practitioner", new_practitioner) + new_practitioner.user_id = user.email + new_practitioner.save() + + frappe.set_user(user.name) + appointments = frappe.get_list("Patient Appointment") + assert len(appointments) == 1 + + frappe.set_user("Administrator") + appointments = frappe.get_list("Patient Appointment") + assert len(appointments) == 2 + + def test_overlap_appointment(self): + from healthcare.healthcare.doctype.patient_appointment.patient_appointment import OverlapError + + patient, practitioner = create_healthcare_docs(id=1) + patient_1, practitioner_1 = create_healthcare_docs(id=2) + service_unit = create_service_unit(id=0) + service_unit_1 = create_service_unit(id=1) + appointment = create_appointment( + patient, practitioner, nowdate(), service_unit=service_unit + ) # valid + + # patient and practitioner cannot have overlapping appointments + appointment = create_appointment( + patient, practitioner, nowdate(), service_unit=service_unit, save=0 + ) + self.assertRaises(OverlapError, appointment.save) + appointment = create_appointment( + patient, practitioner, nowdate(), service_unit=service_unit_1, save=0 + ) # diff service unit + self.assertRaises(OverlapError, appointment.save) + appointment = create_appointment( + patient, practitioner, nowdate(), save=0 + ) # with no service unit link + self.assertRaises(OverlapError, appointment.save) + + # patient cannot have overlapping appointments with other practitioners + appointment = create_appointment( + patient, practitioner_1, nowdate(), service_unit=service_unit, save=0 + ) + self.assertRaises(OverlapError, appointment.save) + appointment = create_appointment( + patient, practitioner_1, nowdate(), service_unit=service_unit_1, save=0 + ) + self.assertRaises(OverlapError, appointment.save) + appointment = create_appointment(patient, practitioner_1, nowdate(), save=0) + self.assertRaises(OverlapError, appointment.save) + + # practitioner cannot have overlapping appointments with other patients + appointment = create_appointment( + patient_1, practitioner, nowdate(), service_unit=service_unit, save=0 + ) + self.assertRaises(OverlapError, appointment.save) + appointment = create_appointment( + patient_1, practitioner, nowdate(), service_unit=service_unit_1, save=0 + ) + self.assertRaises(OverlapError, appointment.save) + appointment = create_appointment(patient_1, practitioner, nowdate(), save=0) + self.assertRaises(OverlapError, appointment.save) + + def test_service_unit_capacity(self): + from healthcare.healthcare.doctype.patient_appointment.patient_appointment import ( + MaximumCapacityError, + OverlapError, + ) + + practitioner = create_practitioner() + capacity = 3 + overlap_service_unit_type = create_service_unit_type( + id=10, allow_appointments=1, overlap_appointments=1 + ) + overlap_service_unit = create_service_unit( + id=100, service_unit_type=overlap_service_unit_type, service_unit_capacity=capacity + ) + + for i in range(0, capacity): + patient = create_patient(id=i) + create_appointment(patient, practitioner, nowdate(), service_unit=overlap_service_unit) # valid + appointment = create_appointment( + patient, practitioner, nowdate(), service_unit=overlap_service_unit, save=0 + ) # overlap + self.assertRaises(OverlapError, appointment.save) + + patient = create_patient(id=capacity) + appointment = create_appointment( + patient, practitioner, nowdate(), service_unit=overlap_service_unit, save=0 + ) + self.assertRaises(MaximumCapacityError, appointment.save) + + +def create_healthcare_docs(id=0): + patient = create_patient(id) + practitioner = create_practitioner(id) + + return patient, practitioner + + +def create_patient( + id=0, patient_name=None, email=None, mobile=None, customer=None, create_user=False +): + if frappe.db.exists("Patient", {"firstname": f"_Test Patient {str(id)}"}): + patient = frappe.db.get_value("Patient", {"first_name": f"_Test Patient {str(id)}"}, ["name"]) + return patient + + patient = frappe.new_doc("Patient") + patient.first_name = patient_name if patient_name else f"_Test Patient {str(id)}" + patient.sex = "Female" + patient.mobile = mobile + patient.email = email + patient.customer = customer + patient.invite_user = create_user + patient.save(ignore_permissions=True) + + return patient.name + + +def create_medical_department(id=0): + if frappe.db.exists("Medical Department", f"_Test Medical Department {str(id)}"): + return f"_Test Medical Department {str(id)}" + + medical_department = frappe.new_doc("Medical Department") + medical_department.department = f"_Test Medical Department {str(id)}" + medical_department.save(ignore_permissions=True) + + return medical_department.name + + +def create_practitioner(id=0, medical_department=None): + if frappe.db.exists( + "Healthcare Practitioner", {"firstname": f"_Test Healthcare Practitioner {str(id)}"} + ): + practitioner = frappe.db.get_value( + "Healthcare Practitioner", {"firstname": f"_Test Healthcare Practitioner {str(id)}"}, ["name"] + ) + return practitioner + + practitioner = frappe.new_doc("Healthcare Practitioner") + practitioner.first_name = f"_Test Healthcare Practitioner {str(id)}" + practitioner.gender = "Female" + practitioner.department = medical_department or create_medical_department(id) + practitioner.op_consulting_charge = 500 + practitioner.inpatient_visit_charge = 500 + practitioner.save(ignore_permissions=True) + + return practitioner.name + + +def create_encounter(appointment): + if appointment: + encounter = frappe.new_doc("Patient Encounter") + encounter.appointment = appointment.name + encounter.patient = appointment.patient + encounter.practitioner = appointment.practitioner + encounter.encounter_date = appointment.appointment_date + encounter.encounter_time = appointment.appointment_time + encounter.company = appointment.company + encounter.save() + encounter.submit() + + return encounter + + +def create_appointment( + patient, + practitioner, + appointment_date, + invoice=0, + procedure_template=0, + service_unit=None, + appointment_type=None, + save=1, + department=None, +): + item = create_healthcare_service_items() + frappe.db.set_value("Healthcare Settings", None, "inpatient_visit_charge_item", item) + frappe.db.set_value("Healthcare Settings", None, "op_consulting_charge_item", item) + appointment = frappe.new_doc("Patient Appointment") + appointment.patient = patient + appointment.practitioner = practitioner + appointment.department = department or "_Test Medical Department" + appointment.appointment_date = appointment_date + appointment.company = "_Test Company" + appointment.duration = 15 + + if service_unit: + appointment.service_unit = service_unit + if invoice: + appointment.mode_of_payment = "Cash" + if appointment_type: + appointment.appointment_type = appointment_type + if procedure_template: + appointment.procedure_template = create_clinical_procedure_template().get("name") + if save: + appointment.save(ignore_permissions=True) + + return appointment + + +def create_healthcare_service_items(): + if frappe.db.exists("Item", "HLC-SI-001"): + return "HLC-SI-001" + + item = frappe.new_doc("Item") + item.item_code = "HLC-SI-001" + item.item_name = "Consulting Charges" + item.item_group = "Services" + item.is_stock_item = 0 + item.stock_uom = "Nos" + item.save() + + return item.name + + +def create_clinical_procedure_template(): + if frappe.db.exists("Clinical Procedure Template", "Knee Surgery and Rehab"): + return frappe.get_doc("Clinical Procedure Template", "Knee Surgery and Rehab") + + template = frappe.new_doc("Clinical Procedure Template") + template.template = "Knee Surgery and Rehab" + template.item_code = "Knee Surgery and Rehab" + template.item_group = "Services" + template.is_billable = 1 + template.description = "Knee Surgery and Rehab" + template.rate = 50000 + template.save() + + return template + + +def create_appointment_type(args=None): + if not args: + args = frappe.local.form_dict + + name = args.get("name") or "Test Appointment Type wise Charge" + + if frappe.db.exists("Appointment Type", name): + return frappe.get_doc("Appointment Type", name) + + else: + item = create_healthcare_service_items() + items = [ + { + "medical_department": args.get("medical_department") or "_Test Medical Department", + "op_consulting_charge_item": item, + "op_consulting_charge": 200, + } + ] + return frappe.get_doc( + { + "doctype": "Appointment Type", + "appointment_type": args.get("name") or "Test Appointment Type wise Charge", + "default_duration": args.get("default_duration") or 20, + "color": args.get("color") or "#7575ff", + "price_list": args.get("price_list") or frappe.db.get_value("Price List", {"selling": 1}), + "items": args.get("items") or items, + } + ).insert() + + +def create_user(email=None, roles=None): + if not email: + email = "{}@frappe.com".format(frappe.utils.random_string(10)) + user = frappe.db.exists("User", email) + if not user: + user = frappe.get_doc( + { + "doctype": "User", + "email": email, + "first_name": "test_user", + "password": "password", + "roles": roles, + } + ).insert() + return user + + +def create_service_unit_type(id=0, allow_appointments=1, overlap_appointments=0): + if frappe.db.exists("Healthcare Service Unit Type", f"_Test Service Unit Type {str(id)}"): + return f"_Test Service Unit Type {str(id)}" + + service_unit_type = frappe.new_doc("Healthcare Service Unit Type") + service_unit_type.service_unit_type = f"_Test Service Unit Type {str(id)}" + service_unit_type.allow_appointments = allow_appointments + service_unit_type.overlap_appointments = overlap_appointments + service_unit_type.save(ignore_permissions=True) + + return service_unit_type.name + + +def create_service_unit(id=0, service_unit_type=None, service_unit_capacity=0): + if frappe.db.exists("Healthcare Service Unit", f"_Test Service Unit {str(id)}"): + return f"_Test service_unit {str(id)}" + + service_unit = frappe.new_doc("Healthcare Service Unit") + service_unit.is_group = 0 + service_unit.healthcare_service_unit_name = f"_Test Service Unit {str(id)}" + service_unit.service_unit_type = service_unit_type or create_service_unit_type(id) + service_unit.service_unit_capacity = service_unit_capacity + service_unit.save(ignore_permissions=True) + + return service_unit.name diff --git a/healthcare/healthcare/doctype/patient_assessment/__init__.py b/healthcare/healthcare/doctype/patient_assessment/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/patient_assessment/patient_assessment.js b/healthcare/healthcare/doctype/patient_assessment/patient_assessment.js new file mode 100644 index 0000000..0e509f5 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment/patient_assessment.js @@ -0,0 +1,88 @@ +// Copyright (c) 2020, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Patient Assessment', { + refresh: function(frm) { + if (frm.doc.assessment_template) { + frm.trigger('set_score_range'); + } + + if (!frm.doc.__islocal) { + frm.trigger('show_patient_progress'); + } + }, + + assessment_template: function(frm) { + if (frm.doc.assessment_template) { + frappe.call({ + 'method': 'frappe.client.get', + args: { + doctype: 'Patient Assessment Template', + name: frm.doc.assessment_template + }, + callback: function(data) { + frm.doc.assessment_sheet = []; + $.each(data.message.parameters, function(_i, e) { + let entry = frm.add_child('assessment_sheet'); + entry.parameter = e.assessment_parameter; + }); + + frm.set_value('scale_min', data.message.scale_min); + frm.set_value('scale_max', data.message.scale_max); + frm.set_value('assessment_description', data.message.assessment_description); + frm.set_value('total_score', data.message.scale_max * data.message.parameters.length); + frm.trigger('set_score_range'); + refresh_field('assessment_sheet'); + } + }); + } + }, + + set_score_range: function(frm) { + let options = ['']; + for(let i = frm.doc.scale_min; i <= frm.doc.scale_max; i++) { + options.push(i); + } + frm.fields_dict.assessment_sheet.grid.update_docfield_property( + 'score', 'options', options + ); + }, + + calculate_total_score: function(frm, cdt, cdn) { + let row = locals[cdt][cdn]; + let total_score = 0; + $.each(frm.doc.assessment_sheet || [], function(_i, item) { + if (item.score) { + total_score += parseInt(item.score); + } + }); + + frm.set_value('total_score_obtained', total_score); + }, + + show_patient_progress: function(frm) { + let bars = []; + let message = ''; + let added_min = false; + + let title = __('{0} out of {1}', [frm.doc.total_score_obtained, frm.doc.total_score]); + + bars.push({ + 'title': title, + 'width': (frm.doc.total_score_obtained / frm.doc.total_score * 100) + '%', + 'progress_class': 'progress-bar-success' + }); + if (bars[0].width == '0%') { + bars[0].width = '0.5%'; + added_min = 0.5; + } + message = title; + frm.dashboard.add_progress(__('Status'), bars, message); + }, +}); + +frappe.ui.form.on('Patient Assessment Sheet', { + score: function(frm, cdt, cdn) { + frm.events.calculate_total_score(frm, cdt, cdn); + } +}); diff --git a/healthcare/healthcare/doctype/patient_assessment/patient_assessment.json b/healthcare/healthcare/doctype/patient_assessment/patient_assessment.json new file mode 100644 index 0000000..eb0021f --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment/patient_assessment.json @@ -0,0 +1,181 @@ +{ + "actions": [], + "autoname": "naming_series:", + "creation": "2020-04-19 22:45:12.356209", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "naming_series", + "therapy_session", + "patient", + "assessment_template", + "column_break_4", + "company", + "healthcare_practitioner", + "assessment_datetime", + "assessment_description", + "section_break_7", + "assessment_sheet", + "section_break_9", + "total_score_obtained", + "column_break_11", + "total_score", + "scale_min", + "scale_max", + "amended_from" + ], + "fields": [ + { + "fetch_from": "therapy_session.patient", + "fieldname": "patient", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Patient", + "options": "Patient", + "reqd": 1 + }, + { + "fieldname": "assessment_template", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Assessment Template", + "options": "Patient Assessment Template", + "reqd": 1 + }, + { + "fieldname": "therapy_session", + "fieldtype": "Link", + "label": "Therapy Session", + "options": "Therapy Session" + }, + { + "fieldname": "column_break_4", + "fieldtype": "Column Break" + }, + { + "fetch_from": "therapy_session.practitioner", + "fieldname": "healthcare_practitioner", + "fieldtype": "Link", + "label": "Healthcare Practitioner", + "options": "Healthcare Practitioner" + }, + { + "fieldname": "assessment_datetime", + "fieldtype": "Datetime", + "label": "Assessment Datetime", + "reqd": 1 + }, + { + "fieldname": "section_break_7", + "fieldtype": "Section Break" + }, + { + "fieldname": "assessment_sheet", + "fieldtype": "Table", + "label": "Assessment Sheet", + "options": "Patient Assessment Sheet" + }, + { + "fieldname": "section_break_9", + "fieldtype": "Section Break" + }, + { + "fieldname": "total_score", + "fieldtype": "Int", + "label": "Total Score", + "read_only": 1 + }, + { + "fieldname": "column_break_11", + "fieldtype": "Column Break" + }, + { + "fieldname": "total_score_obtained", + "fieldtype": "Int", + "label": "Total Score Obtained", + "read_only": 1 + }, + { + "fieldname": "scale_min", + "fieldtype": "Int", + "hidden": 1, + "label": "Scale Min", + "read_only": 1 + }, + { + "fieldname": "scale_max", + "fieldtype": "Int", + "hidden": 1, + "label": "Scale Max", + "read_only": 1 + }, + { + "fieldname": "naming_series", + "fieldtype": "Select", + "label": "Naming Series", + "options": "HLC-PA-.YYYY.-" + }, + { + "fieldname": "amended_from", + "fieldtype": "Link", + "label": "Amended From", + "no_copy": 1, + "options": "Patient Assessment", + "print_hide": 1, + "read_only": 1 + }, + { + "fieldname": "assessment_description", + "fieldtype": "Small Text", + "label": "Assessment Description" + }, + { + "fieldname": "company", + "fieldtype": "Link", + "in_standard_filter": 1, + "label": "Company", + "options": "Company" + } + ], + "is_submittable": 1, + "links": [], + "modified": "2020-06-25 00:25:13.208400", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient Assessment", + "owner": "Administrator", + "permissions": [ + { + "cancel": 1, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "submit": 1, + "write": 1 + }, + { + "cancel": 1, + "create": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "submit": 1, + "write": 1 + } + ], + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "patient", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/patient_assessment/patient_assessment.py b/healthcare/healthcare/doctype/patient_assessment/patient_assessment.py new file mode 100644 index 0000000..581b400 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment/patient_assessment.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +import frappe +from frappe.model.document import Document +from frappe.model.mapper import get_mapped_doc + + +class PatientAssessment(Document): + def validate(self): + self.set_total_score() + + def set_total_score(self): + total_score = 0 + for entry in self.assessment_sheet: + total_score += int(entry.score) + self.total_score_obtained = total_score + + +@frappe.whitelist() +def create_patient_assessment(source_name, target_doc=None): + doc = get_mapped_doc( + "Therapy Session", + source_name, + { + "Therapy Session": { + "doctype": "Patient Assessment", + "field_map": [ + ["therapy_session", "name"], + ["patient", "patient"], + ["practitioner", "practitioner"], + ], + } + }, + target_doc, + ) + + return doc diff --git a/healthcare/healthcare/doctype/patient_assessment/test_patient_assessment.py b/healthcare/healthcare/doctype/patient_assessment/test_patient_assessment.py new file mode 100644 index 0000000..5cf10d0 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment/test_patient_assessment.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# See license.txt + + +# import frappe +from frappe.tests.utils import FrappeTestCase + + +class TestPatientAssessment(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/patient_assessment_detail/__init__.py b/healthcare/healthcare/doctype/patient_assessment_detail/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/patient_assessment_detail/patient_assessment_detail.json b/healthcare/healthcare/doctype/patient_assessment_detail/patient_assessment_detail.json new file mode 100644 index 0000000..179f441 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment_detail/patient_assessment_detail.json @@ -0,0 +1,32 @@ +{ + "actions": [], + "creation": "2020-04-19 19:33:00.115395", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "assessment_parameter" + ], + "fields": [ + { + "fieldname": "assessment_parameter", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Assessment Parameter", + "options": "Patient Assessment Parameter", + "reqd": 1 + } + ], + "istable": 1, + "links": [], + "modified": "2020-04-19 19:33:00.115395", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient Assessment Detail", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/patient_assessment_detail/patient_assessment_detail.py b/healthcare/healthcare/doctype/patient_assessment_detail/patient_assessment_detail.py new file mode 100644 index 0000000..4c0bec7 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment_detail/patient_assessment_detail.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class PatientAssessmentDetail(Document): + pass diff --git a/healthcare/healthcare/doctype/patient_assessment_parameter/__init__.py b/healthcare/healthcare/doctype/patient_assessment_parameter/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/patient_assessment_parameter/patient_assessment_parameter.js b/healthcare/healthcare/doctype/patient_assessment_parameter/patient_assessment_parameter.js new file mode 100644 index 0000000..049a347 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment_parameter/patient_assessment_parameter.js @@ -0,0 +1,8 @@ +// Copyright (c) 2020, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Patient Assessment Parameter', { + // refresh: function(frm) { + + // } +}); diff --git a/healthcare/healthcare/doctype/patient_assessment_parameter/patient_assessment_parameter.json b/healthcare/healthcare/doctype/patient_assessment_parameter/patient_assessment_parameter.json new file mode 100644 index 0000000..098bdef --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment_parameter/patient_assessment_parameter.json @@ -0,0 +1,45 @@ +{ + "actions": [], + "autoname": "field:assessment_parameter", + "creation": "2020-04-15 14:34:46.551042", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "assessment_parameter" + ], + "fields": [ + { + "fieldname": "assessment_parameter", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Assessment Parameter", + "reqd": 1, + "unique": 1 + } + ], + "links": [], + "modified": "2020-04-20 09:22:19.135196", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient Assessment Parameter", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/patient_assessment_parameter/patient_assessment_parameter.py b/healthcare/healthcare/doctype/patient_assessment_parameter/patient_assessment_parameter.py new file mode 100644 index 0000000..3112fb4 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment_parameter/patient_assessment_parameter.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class PatientAssessmentParameter(Document): + pass diff --git a/healthcare/healthcare/doctype/patient_assessment_parameter/test_patient_assessment_parameter.py b/healthcare/healthcare/doctype/patient_assessment_parameter/test_patient_assessment_parameter.py new file mode 100644 index 0000000..034b874 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment_parameter/test_patient_assessment_parameter.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# See license.txt + + +# import frappe +from frappe.tests.utils import FrappeTestCase + + +class TestPatientAssessmentParameter(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/patient_assessment_sheet/__init__.py b/healthcare/healthcare/doctype/patient_assessment_sheet/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/patient_assessment_sheet/patient_assessment_sheet.json b/healthcare/healthcare/doctype/patient_assessment_sheet/patient_assessment_sheet.json new file mode 100644 index 0000000..64e4aef --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment_sheet/patient_assessment_sheet.json @@ -0,0 +1,57 @@ +{ + "actions": [], + "creation": "2020-04-19 23:07:02.220244", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "parameter", + "score", + "time", + "column_break_4", + "comments" + ], + "fields": [ + { + "fieldname": "parameter", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Parameter", + "options": "Patient Assessment Parameter", + "reqd": 1 + }, + { + "fieldname": "score", + "fieldtype": "Select", + "in_list_view": 1, + "label": "Score", + "reqd": 1 + }, + { + "fieldname": "time", + "fieldtype": "Time", + "label": "Time" + }, + { + "fieldname": "column_break_4", + "fieldtype": "Column Break" + }, + { + "fieldname": "comments", + "fieldtype": "Small Text", + "label": "Comments" + } + ], + "istable": 1, + "links": [], + "modified": "2020-04-20 09:56:28.746619", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient Assessment Sheet", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/patient_assessment_sheet/patient_assessment_sheet.py b/healthcare/healthcare/doctype/patient_assessment_sheet/patient_assessment_sheet.py new file mode 100644 index 0000000..de52ac2 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment_sheet/patient_assessment_sheet.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class PatientAssessmentSheet(Document): + pass diff --git a/healthcare/healthcare/doctype/patient_assessment_template/__init__.py b/healthcare/healthcare/doctype/patient_assessment_template/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/patient_assessment_template/patient_assessment_template.js b/healthcare/healthcare/doctype/patient_assessment_template/patient_assessment_template.js new file mode 100644 index 0000000..072bd9a --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment_template/patient_assessment_template.js @@ -0,0 +1,8 @@ +// Copyright (c) 2020, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Patient Assessment Template', { + // refresh: function(frm) { + + // } +}); diff --git a/healthcare/healthcare/doctype/patient_assessment_template/patient_assessment_template.json b/healthcare/healthcare/doctype/patient_assessment_template/patient_assessment_template.json new file mode 100644 index 0000000..de006b1 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment_template/patient_assessment_template.json @@ -0,0 +1,109 @@ +{ + "actions": [], + "autoname": "field:assessment_name", + "creation": "2020-04-19 19:33:13.204707", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "assessment_name", + "section_break_2", + "parameters", + "assessment_scale_details_section", + "scale_min", + "scale_max", + "column_break_8", + "assessment_description" + ], + "fields": [ + { + "fieldname": "parameters", + "fieldtype": "Table", + "label": "Parameters", + "options": "Patient Assessment Detail" + }, + { + "fieldname": "assessment_name", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Assessment Name", + "reqd": 1, + "unique": 1 + }, + { + "fieldname": "section_break_2", + "fieldtype": "Section Break", + "label": "Assessment Parameters" + }, + { + "fieldname": "assessment_scale_details_section", + "fieldtype": "Section Break", + "label": "Assessment Scale" + }, + { + "fieldname": "scale_min", + "fieldtype": "Int", + "label": "Scale Minimum" + }, + { + "fieldname": "scale_max", + "fieldtype": "Int", + "label": "Scale Maximum" + }, + { + "fieldname": "column_break_8", + "fieldtype": "Column Break" + }, + { + "fieldname": "assessment_description", + "fieldtype": "Small Text", + "label": "Assessment Description" + } + ], + "links": [], + "modified": "2020-04-21 13:14:19.075167", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient Assessment Template", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + }, + { + "create": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "write": 1 + } + ], + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/patient_assessment_template/patient_assessment_template.py b/healthcare/healthcare/doctype/patient_assessment_template/patient_assessment_template.py new file mode 100644 index 0000000..237da9f --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment_template/patient_assessment_template.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class PatientAssessmentTemplate(Document): + pass diff --git a/healthcare/healthcare/doctype/patient_assessment_template/test_patient_assessment_template.py b/healthcare/healthcare/doctype/patient_assessment_template/test_patient_assessment_template.py new file mode 100644 index 0000000..d064dc7 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_assessment_template/test_patient_assessment_template.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# See license.txt + + +# import frappe +from frappe.tests.utils import FrappeTestCase + + +class TestPatientAssessmentTemplate(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/patient_encounter/__init__.py b/healthcare/healthcare/doctype/patient_encounter/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/patient_encounter/patient_encounter.js b/healthcare/healthcare/doctype/patient_encounter/patient_encounter.js new file mode 100644 index 0000000..2fbaea0 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_encounter/patient_encounter.js @@ -0,0 +1,503 @@ +// Copyright (c) 2016, ESS LLP and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Patient Encounter', { + onload: function(frm) { + if (!frm.doc.__islocal && frm.doc.docstatus === 1 && + frm.doc.inpatient_status == 'Admission Scheduled') { + frappe.db.get_value('Inpatient Record', frm.doc.inpatient_record, + ['admission_encounter', 'status']).then(r => { + if (r.message) { + if (r.message.admission_encounter == frm.doc.name && + r.message.status == 'Admission Scheduled') { + frm.add_custom_button(__('Cancel Admission'), function() { + cancel_ip_order(frm); + }); + } + if (r.message.status == 'Admitted') { + frm.add_custom_button(__('Schedule Discharge'), function() { + schedule_discharge(frm); + }); + } + } + }) + } + }, + + setup: function(frm) { + frm.get_field('therapies').grid.editable_fields = [ + {fieldname: 'therapy_type', columns: 8}, + {fieldname: 'no_of_sessions', columns: 2} + ]; + frm.get_field('drug_prescription').grid.editable_fields = [ + {fieldname: 'drug_code', columns: 2}, + {fieldname: 'drug_name', columns: 2}, + {fieldname: 'dosage', columns: 2}, + {fieldname: 'period', columns: 2}, + {fieldname: 'dosage_form', columns: 2} + ]; + frm.get_field('lab_test_prescription').grid.editable_fields = [ + {fieldname: 'lab_test_code', columns: 2}, + {fieldname: 'lab_test_name', columns: 4}, + {fieldname: 'lab_test_comment', columns: 4} + ]; + }, + + refresh: function(frm) { + refresh_field('drug_prescription'); + refresh_field('lab_test_prescription'); + + if (!frm.doc.__islocal) { + if (frm.doc.docstatus === 1) { + if(!['Discharge Scheduled', 'Admission Scheduled', 'Admitted'].includes(frm.doc.inpatient_status)) { + frm.add_custom_button(__('Schedule Admission'), function() { + schedule_inpatient(frm); + }); + } + } + + frm.add_custom_button(__('Patient History'), function() { + if (frm.doc.patient) { + frappe.route_options = {'patient': frm.doc.patient}; + frappe.set_route('patient_history'); + } else { + frappe.msgprint(__('Please select Patient')); + } + },__('View')); + + frm.add_custom_button(__('Vital Signs'), function() { + create_vital_signs(frm); + },__('Create')); + + frm.add_custom_button(__('Medical Record'), function() { + create_medical_record(frm); + },__('Create')); + + frm.add_custom_button(__('Clinical Procedure'), function() { + create_procedure(frm); + },__('Create')); + + if (frm.doc.drug_prescription && frm.doc.inpatient_record && frm.doc.inpatient_status === "Admitted") { + frm.add_custom_button(__('Inpatient Medication Order'), function() { + frappe.model.open_mapped_doc({ + method: 'healthcare.healthcare.doctype.patient_encounter.patient_encounter.make_ip_medication_order', + frm: frm + }); + },__('Create')); + } + + frm.add_custom_button(__('Nursing Tasks'), function() { + create_nursing_tasks(frm); + },__('Create')); + } + + frm.set_query('patient', function() { + return { + filters: {'status': 'Active'} + }; + }); + + frm.set_query('drug_code', 'drug_prescription', function() { + return { + filters: { + is_stock_item: 1 + } + }; + }); + + frm.set_query('lab_test_code', 'lab_test_prescription', function() { + return { + filters: { + is_billable: 1 + } + }; + }); + + frm.set_query('appointment', function() { + return { + filters: { + // Scheduled filter for demo ... + status:['in',['Open','Scheduled']] + } + }; + }); + + frm.set_df_property('patient', 'read_only', frm.doc.appointment ? 1 : 0); + }, + + appointment: function(frm) { + frm.events.set_appointment_fields(frm); + }, + + patient: function(frm) { + frm.events.set_patient_info(frm); + }, + + practitioner: function(frm) { + if (!frm.doc.practitioner) { + frm.set_value('practitioner_name', ''); + } + }, + set_appointment_fields: function(frm) { + if (frm.doc.appointment) { + frappe.call({ + method: 'frappe.client.get', + args: { + doctype: 'Patient Appointment', + name: frm.doc.appointment + }, + callback: function(data) { + let values = { + 'patient':data.message.patient, + 'type': data.message.appointment_type, + 'practitioner': data.message.practitioner, + 'invoiced': data.message.invoiced, + 'company': data.message.company + }; + frm.set_value(values); + frm.set_df_property('patient', 'read_only', 1); + } + }); + } + else { + let values = { + 'patient': '', + 'patient_name': '', + 'type': '', + 'practitioner': '', + 'invoiced': 0, + 'patient_sex': '', + 'patient_age': '', + 'inpatient_record': '', + 'inpatient_status': '' + }; + frm.set_value(values); + frm.set_df_property('patient', 'read_only', 0); + } + }, + + set_patient_info: function(frm) { + if (frm.doc.patient) { + frappe.call({ + method: 'healthcare.healthcare.doctype.patient.patient.get_patient_detail', + args: { + patient: frm.doc.patient + }, + callback: function(data) { + let age = ''; + if (data.message.dob) { + age = calculate_age(data.message.dob); + } + let values = { + 'patient_age': age, + 'patient_name':data.message.patient_name, + 'patient_sex': data.message.sex, + 'inpatient_record': data.message.inpatient_record, + 'inpatient_status': data.message.inpatient_status + }; + frm.set_value(values); + } + }); + } else { + let values = { + 'patient_age': '', + 'patient_name':'', + 'patient_sex': '', + 'inpatient_record': '', + 'inpatient_status': '' + }; + frm.set_value(values); + } + }, + + get_applicable_treatment_plans: function(frm) { + frappe.call({ + method: 'get_applicable_treatment_plans', + doc: frm.doc, + args: {'encounter': frm.doc}, + freeze: true, + freeze_message: __('Fetching Treatment Plans'), + callback: function() { + new frappe.ui.form.MultiSelectDialog({ + doctype: "Treatment Plan Template", + target: this.cur_frm, + setters: { + medical_department: "", + }, + action(selections) { + frappe.call({ + method: 'set_treatment_plans', + doc: frm.doc, + args: selections, + }).then(() => { + frm.refresh_field('drug_prescription'); + frm.refresh_field('procedure_prescription'); + frm.refresh_field('lab_test_prescription'); + frm.refresh_field('therapies'); + }); + cur_dialog.hide(); + } + }); + + + } + }); + }, + +}); + +var schedule_inpatient = function(frm) { + var dialog = new frappe.ui.Dialog({ + title: 'Patient Admission', + fields: [ + {fieldtype: 'Link', label: 'Medical Department', fieldname: 'medical_department', options: 'Medical Department', reqd: 1}, + {fieldtype: 'Link', label: 'Healthcare Practitioner (Primary)', fieldname: 'primary_practitioner', options: 'Healthcare Practitioner', reqd: 1}, + {fieldtype: 'Link', label: 'Healthcare Practitioner (Secondary)', fieldname: 'secondary_practitioner', options: 'Healthcare Practitioner'}, + {fieldtype: 'Link', label: 'Nursing Checklist Template', fieldname: 'admission_nursing_checklist_template', options: 'Nursing Checklist Template'}, + {fieldtype: 'Column Break'}, + {fieldtype: 'Date', label: 'Admission Ordered For', fieldname: 'admission_ordered_for', default: 'Today'}, + {fieldtype: 'Link', label: 'Service Unit Type', fieldname: 'service_unit_type', options: 'Healthcare Service Unit Type'}, + {fieldtype: 'Int', label: 'Expected Length of Stay', fieldname: 'expected_length_of_stay'}, + {fieldtype: 'Section Break'}, + {fieldtype: 'Long Text', label: 'Admission Instructions', fieldname: 'admission_instruction'} + ], + primary_action_label: __('Order Admission'), + primary_action : function() { + var args = { + patient: frm.doc.patient, + admission_encounter: frm.doc.name, + referring_practitioner: frm.doc.practitioner, + company: frm.doc.company, + medical_department: dialog.get_value('medical_department'), + primary_practitioner: dialog.get_value('primary_practitioner'), + secondary_practitioner: dialog.get_value('secondary_practitioner'), + admission_ordered_for: dialog.get_value('admission_ordered_for'), + admission_service_unit_type: dialog.get_value('service_unit_type'), + expected_length_of_stay: dialog.get_value('expected_length_of_stay'), + admission_instruction: dialog.get_value('admission_instruction'), + admission_nursing_checklist_template: dialog.get_value('admission_nursing_checklist_template') + } + frappe.call({ + method: 'healthcare.healthcare.doctype.inpatient_record.inpatient_record.schedule_inpatient', + args: { + args: args + }, + callback: function(data) { + if (!data.exc) { + frm.reload_doc(); + } + }, + freeze: true, + freeze_message: __('Scheduling Patient Admission') + }); + frm.refresh_fields(); + dialog.hide(); + } + }); + + dialog.set_values({ + 'medical_department': frm.doc.medical_department, + 'primary_practitioner': frm.doc.practitioner, + }); + + dialog.fields_dict['service_unit_type'].get_query = function() { + return { + filters: { + 'inpatient_occupancy': 1, + 'allow_appointments': 0 + } + }; + }; + + dialog.show(); + dialog.$wrapper.find('.modal-dialog').css('width', '800px'); +}; + +var schedule_discharge = function(frm) { + var dialog = new frappe.ui.Dialog ({ + title: 'Inpatient Discharge', + fields: [ + {fieldtype: 'Date', label: 'Discharge Ordered Date', fieldname: 'discharge_ordered_date', default: 'Today', read_only: 1}, + {fieldtype: 'Date', label: 'Followup Date', fieldname: 'followup_date'}, + {fieldtype: 'Link', label: 'Nursing Checklist Template', options: 'Nursing Checklist Template', fieldname: 'discharge_nursing_checklist_template'}, + {fieldtype: 'Column Break'}, + {fieldtype: 'Small Text', label: 'Discharge Instructions', fieldname: 'discharge_instructions'}, + {fieldtype: 'Section Break', label:'Discharge Summary'}, + {fieldtype: 'Long Text', label: 'Discharge Note', fieldname: 'discharge_note'} + ], + primary_action_label: __('Order Discharge'), + primary_action : function() { + var args = { + patient: frm.doc.patient, + discharge_encounter: frm.doc.name, + discharge_practitioner: frm.doc.practitioner, + discharge_ordered_date: dialog.get_value('discharge_ordered_date'), + followup_date: dialog.get_value('followup_date'), + discharge_instructions: dialog.get_value('discharge_instructions'), + discharge_note: dialog.get_value('discharge_note'), + discharge_nursing_checklist_template: dialog.get_value('discharge_nursing_checklist_template') + } + frappe.call ({ + method: 'healthcare.healthcare.doctype.inpatient_record.inpatient_record.schedule_discharge', + args: {args}, + callback: function(data) { + if(!data.exc){ + frm.reload_doc(); + } + }, + freeze: true, + freeze_message: 'Scheduling Inpatient Discharge' + }); + frm.refresh_fields(); + dialog.hide(); + } + }); + + dialog.show(); + dialog.$wrapper.find('.modal-dialog').css('width', '800px'); +}; + +let create_medical_record = function(frm) { + if (!frm.doc.patient) { + frappe.throw(__('Please select patient')); + } + frappe.route_options = { + 'patient': frm.doc.patient, + 'status': 'Open', + 'reference_doctype': 'Patient Medical Record', + 'reference_owner': frm.doc.owner + }; + frappe.new_doc('Patient Medical Record'); +}; + +let create_vital_signs = function(frm) { + if (!frm.doc.patient) { + frappe.throw(__('Please select patient')); + } + frappe.route_options = { + 'patient': frm.doc.patient, + 'encounter': frm.doc.name, + 'company': frm.doc.company + }; + frappe.new_doc('Vital Signs'); +}; + +let create_procedure = function(frm) { + if (!frm.doc.patient) { + frappe.throw(__('Please select patient')); + } + frappe.route_options = { + 'patient': frm.doc.patient, + 'medical_department': frm.doc.medical_department, + 'company': frm.doc.company + }; + frappe.new_doc('Clinical Procedure'); +}; + +let create_nursing_tasks = function(frm) { + const d = new frappe.ui.Dialog({ + + title: __('Create Nursing Tasks'), + + fields: [ + { + label: __('Nursing Checklist Template'), + fieldtype: 'Link', + options: 'Nursing Checklist Template', + fieldname: 'template', + reqd: 1, + }, + { + label: __('Start Time'), + fieldtype: 'Datetime', + fieldname: 'start_time', + default: frappe.datetime.now_datetime(), + reqd: 1, + }, + ], + + primary_action_label: __('Create Nursing Tasks'), + + primary_action: () => { + + let values = d.get_values(); + frappe.call({ + method: 'healthcare.healthcare.doctype.nursing_task.nursing_task.create_nursing_tasks_from_template', + args: { + 'template': values.template, + 'doc': frm.doc, + 'start_time': values.start_time + }, + callback: (r) => { + if (r && !r.exc) { + frappe.show_alert({ + message: __('Nursing Tasks Created'), + indicator: 'success' + }); + } + } + }); + + d.hide(); + } + }); + + d.show(); +}; + +frappe.ui.form.on('Drug Prescription', { + dosage: function(frm, cdt, cdn){ + frappe.model.set_value(cdt, cdn, 'update_schedule', 1); + let child = locals[cdt][cdn]; + if (child.dosage) { + frappe.model.set_value(cdt, cdn, 'interval_uom', 'Day'); + frappe.model.set_value(cdt, cdn, 'interval', 1); + } + }, + period: function(frm, cdt, cdn) { + frappe.model.set_value(cdt, cdn, 'update_schedule', 1); + }, + interval_uom: function(frm, cdt, cdn) { + frappe.model.set_value(cdt, cdn, 'update_schedule', 1); + let child = locals[cdt][cdn]; + if (child.interval_uom == 'Hour') { + frappe.model.set_value(cdt, cdn, 'dosage', null); + } + } +}); + +let calculate_age = function(birth) { + let ageMS = Date.parse(Date()) - Date.parse(birth); + let age = new Date(); + age.setTime(ageMS); + let years = age.getFullYear() - 1970; + return `${years} ${__('Years(s)')} ${age.getMonth()} ${__('Month(s)')} ${age.getDate()} ${__('Day(s)')}`; +}; + +let cancel_ip_order = function(frm) { + frappe.prompt([ + { + fieldname: 'reason_for_cancellation', + label: __('Reason for Cancellation'), + fieldtype: 'Small Text', + reqd: 1 + } + ], + function(data) { + frappe.call({ + method: 'healthcare.healthcare.doctype.inpatient_record.inpatient_record.set_ip_order_cancelled', + async: false, + freeze: true, + args: { + inpatient_record: frm.doc.inpatient_record, + reason: data.reason_for_cancellation, + encounter: frm.doc.name + }, + callback: function(r) { + if (!r.exc) { + frm.reload_doc(); + } + } + }); + }, __('Reason for Cancellation'), __('Submit')); +} diff --git a/healthcare/healthcare/doctype/patient_encounter/patient_encounter.json b/healthcare/healthcare/doctype/patient_encounter/patient_encounter.json new file mode 100644 index 0000000..994597d --- /dev/null +++ b/healthcare/healthcare/doctype/patient_encounter/patient_encounter.json @@ -0,0 +1,368 @@ +{ + "actions": [], + "allow_copy": 1, + "allow_import": 1, + "autoname": "naming_series:", + "beta": 1, + "creation": "2016-04-21 10:53:44.637684", + "doctype": "DocType", + "document_type": "Document", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "naming_series", + "title", + "appointment", + "appointment_type", + "patient", + "patient_name", + "patient_sex", + "patient_age", + "inpatient_record", + "inpatient_status", + "column_break_6", + "company", + "encounter_date", + "encounter_time", + "practitioner", + "practitioner_name", + "medical_department", + "invoiced", + "sb_symptoms", + "symptoms", + "symptoms_in_print", + "get_applicable_treatment_plans", + "physical_examination", + "diagnosis", + "diagnosis_in_print", + "codification", + "codification_table", + "sb_drug_prescription", + "drug_prescription", + "sb_test_prescription", + "lab_test_prescription", + "sb_procedures", + "procedure_prescription", + "rehabilitation_section", + "therapy_plan", + "therapies", + "section_break_33", + "encounter_comment", + "sb_refs", + "amended_from" + ], + "fields": [ + { + "allow_on_submit": 1, + "fieldname": "inpatient_record", + "fieldtype": "Link", + "label": "Inpatient Record", + "options": "Inpatient Record", + "read_only": 1 + }, + { + "fieldname": "naming_series", + "fieldtype": "Select", + "label": "Series", + "no_copy": 1, + "options": "HLC-ENC-.YYYY.-", + "set_only_once": 1 + }, + { + "fieldname": "appointment", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "label": "Appointment", + "options": "Patient Appointment", + "search_index": 1, + "set_only_once": 1 + }, + { + "fieldname": "patient", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_standard_filter": 1, + "label": "Patient", + "options": "Patient", + "reqd": 1, + "search_index": 1 + }, + { + "fieldname": "patient_name", + "fieldtype": "Data", + "label": "Patient Name", + "read_only": 1 + }, + { + "fieldname": "patient_age", + "fieldtype": "Data", + "label": "Age", + "read_only": 1 + }, + { + "fieldname": "patient_sex", + "fieldtype": "Link", + "label": "Gender", + "options": "Gender", + "read_only": 1 + }, + { + "fieldname": "company", + "fieldtype": "Link", + "label": "Company", + "options": "Company" + }, + { + "fieldname": "column_break_6", + "fieldtype": "Column Break" + }, + { + "fieldname": "practitioner", + "fieldtype": "Link", + "in_standard_filter": 1, + "label": "Healthcare Practitioner", + "options": "Healthcare Practitioner", + "reqd": 1 + }, + { + "default": "Today", + "fieldname": "encounter_date", + "fieldtype": "Date", + "in_list_view": 1, + "label": "Encounter Date", + "reqd": 1 + }, + { + "fieldname": "encounter_time", + "fieldtype": "Time", + "label": "Encounter Time", + "reqd": 1 + }, + { + "default": "0", + "fieldname": "invoiced", + "fieldtype": "Check", + "label": "Invoiced", + "no_copy": 1, + "read_only": 1 + }, + { + "fieldname": "sb_symptoms", + "fieldtype": "Section Break", + "label": "Encounter Impression" + }, + { + "fieldname": "symptoms", + "fieldtype": "Table MultiSelect", + "ignore_xss_filter": 1, + "label": "Symptoms", + "no_copy": 1, + "options": "Patient Encounter Symptom" + }, + { + "default": "0", + "depends_on": "eval: doc.symptoms != ''", + "fieldname": "symptoms_in_print", + "fieldtype": "Check", + "label": "In print", + "no_copy": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "fieldname": "physical_examination", + "fieldtype": "Column Break" + }, + { + "fieldname": "diagnosis", + "fieldtype": "Table MultiSelect", + "ignore_xss_filter": 1, + "label": "Diagnosis", + "no_copy": 1, + "options": "Patient Encounter Diagnosis" + }, + { + "default": "1", + "depends_on": "eval: doc.diagnosis != ''", + "fieldname": "diagnosis_in_print", + "fieldtype": "Check", + "label": "In print", + "no_copy": 1, + "print_hide": 1, + "report_hide": 1 + }, + { + "collapsible": 1, + "fieldname": "codification", + "fieldtype": "Section Break", + "label": "Medical Coding" + }, + { + "fieldname": "codification_table", + "fieldtype": "Table", + "label": "Medical Codes", + "options": "Codification Table" + }, + { + "fieldname": "sb_drug_prescription", + "fieldtype": "Section Break", + "label": "Medications" + }, + { + "fieldname": "drug_prescription", + "fieldtype": "Table", + "label": "Drug Prescription", + "options": "Drug Prescription" + }, + { + "fieldname": "sb_test_prescription", + "fieldtype": "Section Break", + "label": "Investigations" + }, + { + "fieldname": "lab_test_prescription", + "fieldtype": "Table", + "label": "Lab Tests", + "options": "Lab Prescription" + }, + { + "fieldname": "sb_procedures", + "fieldtype": "Section Break", + "label": "Procedures" + }, + { + "fieldname": "procedure_prescription", + "fieldtype": "Table", + "label": "Clinical Procedures", + "no_copy": 1, + "options": "Procedure Prescription" + }, + { + "fieldname": "encounter_comment", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Review Details", + "no_copy": 1 + }, + { + "fieldname": "amended_from", + "fieldtype": "Link", + "label": "Amended From", + "no_copy": 1, + "options": "Patient Encounter", + "print_hide": 1, + "read_only": 1 + }, + { + "fieldname": "rehabilitation_section", + "fieldtype": "Section Break", + "label": "Rehabilitation" + }, + { + "fieldname": "therapies", + "fieldtype": "Table", + "label": "Therapies", + "options": "Therapy Plan Detail" + }, + { + "fieldname": "section_break_33", + "fieldtype": "Section Break" + }, + { + "fieldname": "therapy_plan", + "fieldtype": "Link", + "hidden": 1, + "label": "Therapy Plan", + "options": "Therapy Plan", + "read_only": 1 + }, + { + "fieldname": "appointment_type", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "label": "Appointment Type", + "no_copy": 1, + "options": "Appointment Type", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "fetch_from": "practitioner.department", + "fieldname": "medical_department", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_standard_filter": 1, + "label": "Department", + "options": "Medical Department", + "read_only": 1 + }, + { + "allow_on_submit": 1, + "fieldname": "inpatient_status", + "fieldtype": "Data", + "label": "Inpatient Status", + "read_only": 1 + }, + { + "fieldname": "sb_refs", + "fieldtype": "Section Break" + }, + { + "fetch_from": "practitioner.practitioner_name", + "fieldname": "practitioner_name", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Practitioner Name", + "read_only": 1 + }, + { + "allow_on_submit": 1, + "fieldname": "title", + "fieldtype": "Data", + "hidden": 1, + "label": "Title", + "no_copy": 1, + "print_hide": 1, + "read_only": 1 + }, + { + "depends_on": "eval:doc.patient", + "fieldname": "get_applicable_treatment_plans", + "fieldtype": "Button", + "label": "Get Applicable Treatment Plans" + } + ], + "is_submittable": 1, + "links": [], + "modified": "2021-07-27 11:39:12.347704", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient Encounter", + "owner": "Administrator", + "permissions": [ + { + "amend": 1, + "cancel": 1, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "submit": 1, + "write": 1 + } + ], + "restrict_to_domain": "Healthcare", + "search_fields": "patient, practitioner, medical_department, encounter_date, encounter_time", + "show_name_in_global_search": 1, + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "title", + "track_changes": 1, + "track_seen": 1 +} diff --git a/healthcare/healthcare/doctype/patient_encounter/patient_encounter.py b/healthcare/healthcare/doctype/patient_encounter/patient_encounter.py new file mode 100644 index 0000000..22cb7ee --- /dev/null +++ b/healthcare/healthcare/doctype/patient_encounter/patient_encounter.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and contributors +# For license information, please see license.txt + + +import frappe +from frappe import _ +from frappe.model.document import Document +from frappe.model.mapper import get_mapped_doc +from frappe.utils import add_days, getdate + + +class PatientEncounter(Document): + def validate(self): + self.set_title() + + def on_update(self): + if self.appointment: + frappe.db.set_value("Patient Appointment", self.appointment, "status", "Closed") + + def on_submit(self): + if self.therapies: + create_therapy_plan(self) + + def on_cancel(self): + if self.appointment: + frappe.db.set_value("Patient Appointment", self.appointment, "status", "Open") + + if self.inpatient_record and self.drug_prescription: + delete_ip_medication_order(self) + + def set_title(self): + self.title = _("{0} with {1}").format( + self.patient_name or self.patient, self.practitioner_name or self.practitioner + )[:100] + + @frappe.whitelist() + @staticmethod + def get_applicable_treatment_plans(encounter): + patient = frappe.get_doc("Patient", encounter["patient"]) + + plan_filters = {} + plan_filters["name"] = ["in", []] + + age = patient.age + if age: + plan_filters["patient_age_from"] = ["<=", age.years] + plan_filters["patient_age_to"] = [">=", age.years] + + gender = patient.sex + if gender: + plan_filters["gender"] = ["in", [gender, None]] + + diagnosis = encounter.get("diagnosis") + if diagnosis: + diagnosis = [_diagnosis["diagnosis"] for _diagnosis in encounter["diagnosis"]] + filters = [ + ["diagnosis", "in", diagnosis], + ["parenttype", "=", "Treatment Plan Template"], + ] + diagnosis = frappe.get_list("Patient Encounter Diagnosis", filters=filters, fields="*") + plan_names = [_diagnosis["parent"] for _diagnosis in diagnosis] + plan_filters["name"][1].extend(plan_names) + + symptoms = encounter.get("symptoms") + if symptoms: + symptoms = [symptom["complaint"] for symptom in encounter["symptoms"]] + filters = [ + ["complaint", "in", symptoms], + ["parenttype", "=", "Treatment Plan Template"], + ] + symptoms = frappe.get_list("Patient Encounter Symptom", filters=filters, fields="*") + plan_names = [symptom["parent"] for symptom in symptoms] + plan_filters["name"][1].extend(plan_names) + + if not plan_filters["name"][1]: + plan_filters.pop("name") + + plans = frappe.get_list("Treatment Plan Template", fields="*", filters=plan_filters) + + return plans + + @frappe.whitelist() + def set_treatment_plans(self, treatment_plans=None): + for treatment_plan in treatment_plans: + self.set_treatment_plan(treatment_plan) + + def set_treatment_plan(self, plan): + plan_items = frappe.get_list( + "Treatment Plan Template Item", filters={"parent": plan}, fields="*" + ) + for plan_item in plan_items: + self.set_treatment_plan_item(plan_item) + + drugs = frappe.get_list("Drug Prescription", filters={"parent": plan}, fields="*") + for drug in drugs: + self.append("drug_prescription", drug) + + self.save() + + def set_treatment_plan_item(self, plan_item): + if plan_item.type == "Clinical Procedure Template": + self.append("procedure_prescription", {"procedure": plan_item.template}) + + if plan_item.type == "Lab Test Template": + self.append("lab_test_prescription", {"lab_test_code": plan_item.template}) + + if plan_item.type == "Therapy Type": + self.append("therapies", {"therapy_type": plan_item.template}) + + +@frappe.whitelist() +def make_ip_medication_order(source_name, target_doc=None): + def set_missing_values(source, target): + target.start_date = source.encounter_date + for entry in source.drug_prescription: + if entry.drug_code: + dosage = frappe.get_doc("Prescription Dosage", entry.dosage) + dates = get_prescription_dates(entry.period, target.start_date) + for date in dates: + for dose in dosage.dosage_strength: + order = target.append("medication_orders") + order.drug = entry.drug_code + order.drug_name = entry.drug_name + order.dosage = dose.strength + order.instructions = entry.comment + order.dosage_form = entry.dosage_form + order.date = date + order.time = dose.strength_time + target.end_date = dates[-1] + + doc = get_mapped_doc( + "Patient Encounter", + source_name, + { + "Patient Encounter": { + "doctype": "Inpatient Medication Order", + "field_map": { + "name": "patient_encounter", + "patient": "patient", + "patient_name": "patient_name", + "patient_age": "patient_age", + "inpatient_record": "inpatient_record", + "practitioner": "practitioner", + "start_date": "encounter_date", + }, + } + }, + target_doc, + set_missing_values, + ) + + return doc + + +def get_prescription_dates(period, start_date): + prescription_duration = frappe.get_doc("Prescription Duration", period) + days = prescription_duration.get_days() + dates = [start_date] + for i in range(1, days): + dates.append(add_days(getdate(start_date), i)) + return dates + + +def create_therapy_plan(encounter): + if len(encounter.therapies): + doc = frappe.new_doc("Therapy Plan") + doc.patient = encounter.patient + doc.start_date = encounter.encounter_date + for entry in encounter.therapies: + doc.append( + "therapy_plan_details", + {"therapy_type": entry.therapy_type, "no_of_sessions": entry.no_of_sessions}, + ) + doc.save(ignore_permissions=True) + if doc.get("name"): + encounter.db_set("therapy_plan", doc.name) + frappe.msgprint( + _("Therapy Plan {0} created successfully.").format(frappe.bold(doc.name)), alert=True + ) + + +def delete_ip_medication_order(encounter): + record = frappe.db.exists("Inpatient Medication Order", {"patient_encounter": encounter.name}) + if record: + frappe.delete_doc("Inpatient Medication Order", record, force=1) diff --git a/healthcare/healthcare/doctype/patient_encounter/patient_encounter_dashboard.py b/healthcare/healthcare/doctype/patient_encounter/patient_encounter_dashboard.py new file mode 100644 index 0000000..8831e3a --- /dev/null +++ b/healthcare/healthcare/doctype/patient_encounter/patient_encounter_dashboard.py @@ -0,0 +1,17 @@ +from frappe import _ + + +def get_data(): + return { + "fieldname": "encounter", + "non_standard_fieldnames": { + "Patient Medical Record": "reference_name", + "Inpatient Medication Order": "patient_encounter", + "Nursing Task": "reference_name", + }, + "transactions": [ + {"label": _("Records"), "items": ["Vital Signs", "Patient Medical Record"]}, + {"label": _("Orders"), "items": ["Inpatient Medication Order", "Nursing Task"]}, + ], + "disable_create_buttons": ["Inpatient Medication Order"], + } diff --git a/healthcare/healthcare/doctype/patient_encounter/patient_encounter_list.js b/healthcare/healthcare/doctype/patient_encounter/patient_encounter_list.js new file mode 100644 index 0000000..d8f63bd --- /dev/null +++ b/healthcare/healthcare/doctype/patient_encounter/patient_encounter_list.js @@ -0,0 +1,6 @@ +/* +(c) ESS 2015-16 +*/ +frappe.listview_settings['Patient Encounter'] = { + filters:[["docstatus","!=","2"]] +}; diff --git a/healthcare/healthcare/doctype/patient_encounter/test_patient_encounter.py b/healthcare/healthcare/doctype/patient_encounter/test_patient_encounter.py new file mode 100644 index 0000000..dbd0eba --- /dev/null +++ b/healthcare/healthcare/doctype/patient_encounter/test_patient_encounter.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018, InfluxERP +# See license.txt + + +import frappe +from frappe.tests.utils import FrappeTestCase + +from healthcare.healthcare.doctype.patient_encounter.patient_encounter import PatientEncounter + + +class TestPatientEncounter(FrappeTestCase): + def setUp(self): + try: + gender_m = frappe.get_doc({"doctype": "Gender", "gender": "MALE"}).insert() + gender_f = frappe.get_doc({"doctype": "Gender", "gender": "FEMALE"}).insert() + except frappe.exceptions.DuplicateEntryError: + gender_m = frappe.get_doc({"doctype": "Gender", "gender": "MALE"}) + gender_f = frappe.get_doc({"doctype": "Gender", "gender": "FEMALE"}) + + self.patient_male = frappe.get_doc( + { + "doctype": "Patient", + "first_name": "John", + "sex": gender_m.gender, + } + ).insert() + self.patient_female = frappe.get_doc( + { + "doctype": "Patient", + "first_name": "Curie", + "sex": gender_f.gender, + } + ).insert() + self.practitioner = frappe.get_doc( + { + "doctype": "Healthcare Practitioner", + "first_name": "Doc", + "sex": "MALE", + } + ).insert() + try: + self.care_plan_male = frappe.get_doc( + { + "doctype": "Treatment Plan Template", + "template_name": "test plan - m", + "gender": gender_m.gender, + } + ).insert() + self.care_plan_female = frappe.get_doc( + { + "doctype": "Treatment Plan Template", + "template_name": "test plan - f", + "gender": gender_f.gender, + } + ).insert() + except frappe.exceptions.DuplicateEntryError: + self.care_plan_male = frappe.get_doc( + { + "doctype": "Treatment Plan Template", + "template_name": "test plan - m", + "gender": gender_m.gender, + } + ) + self.care_plan_female = frappe.get_doc( + { + "doctype": "Treatment Plan Template", + "template_name": "test plan - f", + "gender": gender_f.gender, + } + ) + + def test_treatment_plan_template_filter(self): + encounter = frappe.get_doc( + { + "doctype": "Patient Encounter", + "patient": self.patient_male.name, + "practitioner": self.practitioner.name, + } + ).insert() + plans = PatientEncounter.get_applicable_treatment_plans(encounter.as_dict()) + self.assertEqual(plans[0]["name"], self.care_plan_male.template_name) + + encounter = frappe.get_doc( + { + "doctype": "Patient Encounter", + "patient": self.patient_female.name, + "practitioner": self.practitioner.name, + } + ).insert() + plans = PatientEncounter.get_applicable_treatment_plans(encounter.as_dict()) + self.assertEqual(plans[0]["name"], self.care_plan_female.template_name) diff --git a/healthcare/healthcare/doctype/patient_encounter_diagnosis/__init__.py b/healthcare/healthcare/doctype/patient_encounter_diagnosis/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/patient_encounter_diagnosis/patient_encounter_diagnosis.json b/healthcare/healthcare/doctype/patient_encounter_diagnosis/patient_encounter_diagnosis.json new file mode 100644 index 0000000..00ca309 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_encounter_diagnosis/patient_encounter_diagnosis.json @@ -0,0 +1,33 @@ +{ + "actions": [], + "beta": 1, + "creation": "2020-02-26 16:48:16.835105", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "diagnosis" + ], + "fields": [ + { + "fieldname": "diagnosis", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Diagnosis", + "options": "Diagnosis", + "reqd": 1 + } + ], + "istable": 1, + "links": [], + "modified": "2020-02-26 16:58:16.480583", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient Encounter Diagnosis", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/patient_encounter_diagnosis/patient_encounter_diagnosis.py b/healthcare/healthcare/doctype/patient_encounter_diagnosis/patient_encounter_diagnosis.py new file mode 100644 index 0000000..e2c4454 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_encounter_diagnosis/patient_encounter_diagnosis.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class PatientEncounterDiagnosis(Document): + pass diff --git a/healthcare/healthcare/doctype/patient_encounter_symptom/__init__.py b/healthcare/healthcare/doctype/patient_encounter_symptom/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/patient_encounter_symptom/patient_encounter_symptom.json b/healthcare/healthcare/doctype/patient_encounter_symptom/patient_encounter_symptom.json new file mode 100644 index 0000000..bc92145 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_encounter_symptom/patient_encounter_symptom.json @@ -0,0 +1,33 @@ +{ + "actions": [], + "beta": 1, + "creation": "2020-02-26 16:47:00.525657", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "complaint" + ], + "fields": [ + { + "fieldname": "complaint", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Complaint", + "options": "Complaint", + "reqd": 1 + } + ], + "istable": 1, + "links": [], + "modified": "2020-02-26 16:57:37.997481", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient Encounter Symptom", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/patient_encounter_symptom/patient_encounter_symptom.py b/healthcare/healthcare/doctype/patient_encounter_symptom/patient_encounter_symptom.py new file mode 100644 index 0000000..9e52d50 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_encounter_symptom/patient_encounter_symptom.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class PatientEncounterSymptom(Document): + pass diff --git a/healthcare/healthcare/doctype/patient_history_custom_document_type/__init__.py b/healthcare/healthcare/doctype/patient_history_custom_document_type/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/patient_history_custom_document_type/patient_history_custom_document_type.json b/healthcare/healthcare/doctype/patient_history_custom_document_type/patient_history_custom_document_type.json new file mode 100644 index 0000000..3025c7b --- /dev/null +++ b/healthcare/healthcare/doctype/patient_history_custom_document_type/patient_history_custom_document_type.json @@ -0,0 +1,55 @@ +{ + "actions": [], + "creation": "2020-11-25 13:40:23.054469", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "document_type", + "date_fieldname", + "add_edit_fields", + "selected_fields" + ], + "fields": [ + { + "fieldname": "document_type", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Document Type", + "options": "DocType", + "reqd": 1 + }, + { + "fieldname": "selected_fields", + "fieldtype": "Code", + "label": "Selected Fields", + "read_only": 1 + }, + { + "fieldname": "add_edit_fields", + "fieldtype": "Button", + "in_list_view": 1, + "label": "Add / Edit Fields" + }, + { + "fieldname": "date_fieldname", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Date Fieldname", + "reqd": 1 + } + ], + "index_web_pages_for_search": 1, + "istable": 1, + "links": [], + "modified": "2020-11-30 13:54:37.474671", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient History Custom Document Type", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/patient_history_custom_document_type/patient_history_custom_document_type.py b/healthcare/healthcare/doctype/patient_history_custom_document_type/patient_history_custom_document_type.py new file mode 100644 index 0000000..3ed52ee --- /dev/null +++ b/healthcare/healthcare/doctype/patient_history_custom_document_type/patient_history_custom_document_type.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class PatientHistoryCustomDocumentType(Document): + pass diff --git a/healthcare/healthcare/doctype/patient_history_settings/__init__.py b/healthcare/healthcare/doctype/patient_history_settings/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/patient_history_settings/patient_history_settings.js b/healthcare/healthcare/doctype/patient_history_settings/patient_history_settings.js new file mode 100644 index 0000000..f751933 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_history_settings/patient_history_settings.js @@ -0,0 +1,133 @@ +// Copyright (c) 2020, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Patient History Settings', { + refresh: function(frm) { + frm.set_query('document_type', 'custom_doctypes', () => { + return { + filters: { + custom: 1, + is_submittable: 1, + module: 'Healthcare', + } + }; + }); + }, + + field_selector: function(frm, doc, standard=1) { + let document_fields = []; + if (doc.selected_fields) + document_fields = (JSON.parse(doc.selected_fields)).map(f => f.fieldname); + + frm.call({ + method: 'get_doctype_fields', + doc: frm.doc, + args: { + document_type: doc.document_type, + fields: document_fields + }, + freeze: true, + callback: function(r) { + if (r.message) { + let doctype = 'Patient History Custom Document Type'; + if (standard) + doctype = 'Patient History Standard Document Type'; + + frm.events.show_field_selector_dialog(frm, doc, doctype, r.message); + } + } + }); + }, + + show_field_selector_dialog: function(frm, doc, doctype, doc_fields) { + let d = new frappe.ui.Dialog({ + title: __('{0} Fields', [__(doc.document_type)]), + fields: [ + { + label: __('Select Fields'), + fieldtype: 'MultiCheck', + fieldname: 'fields', + options: doc_fields, + columns: 2 + } + ] + }); + + d.$body.prepend(` + ` + ); + + frappe.utils.setup_search(d.$body, '.unit-checkbox', '.label-area'); + + d.set_primary_action(__('Save'), () => { + let values = d.get_values().fields; + + let selected_fields = []; + + frappe.model.with_doctype(doc.document_type, function() { + for (let idx in values) { + let value = values[idx]; + + let field = frappe.get_meta(doc.document_type).fields.filter((df) => df.fieldname == value)[0]; + if (field) { + selected_fields.push({ + label: field.label, + fieldname: field.fieldname, + fieldtype: field.fieldtype + }); + } + } + + d.refresh(); + frappe.model.set_value(doctype, doc.name, 'selected_fields', JSON.stringify(selected_fields)); + }); + + d.hide(); + }); + + d.show(); + }, + + get_date_field_for_dt: function(frm, row) { + frm.call({ + method: 'get_date_field_for_dt', + doc: frm.doc, + args: { + document_type: row.document_type + }, + callback: function(data) { + if (data.message) { + frappe.model.set_value('Patient History Custom Document Type', + row.name, 'date_fieldname', data.message); + } + } + }); + } +}); + +frappe.ui.form.on('Patient History Custom Document Type', { + document_type: function(frm, cdt, cdn) { + let row = locals[cdt][cdn]; + if (row.document_type) { + frm.events.get_date_field_for_dt(frm, row); + } + }, + + add_edit_fields: function(frm, cdt, cdn) { + let row = locals[cdt][cdn]; + if (row.document_type) { + frm.events.field_selector(frm, row, 0); + } + } +}); + +frappe.ui.form.on('Patient History Standard Document Type', { + add_edit_fields: function(frm, cdt, cdn) { + let row = locals[cdt][cdn]; + if (row.document_type) { + frm.events.field_selector(frm, row); + } + } +}); diff --git a/healthcare/healthcare/doctype/patient_history_settings/patient_history_settings.json b/healthcare/healthcare/doctype/patient_history_settings/patient_history_settings.json new file mode 100644 index 0000000..143e2c9 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_history_settings/patient_history_settings.json @@ -0,0 +1,55 @@ +{ + "actions": [], + "creation": "2020-11-25 13:41:37.675518", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "standard_doctypes", + "section_break_2", + "custom_doctypes" + ], + "fields": [ + { + "fieldname": "section_break_2", + "fieldtype": "Section Break" + }, + { + "fieldname": "custom_doctypes", + "fieldtype": "Table", + "label": "Custom Document Types", + "options": "Patient History Custom Document Type" + }, + { + "fieldname": "standard_doctypes", + "fieldtype": "Table", + "label": "Standard Document Types", + "options": "Patient History Standard Document Type", + "read_only": 1 + } + ], + "index_web_pages_for_search": 1, + "issingle": 1, + "links": [], + "modified": "2020-11-25 13:43:38.511771", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient History Settings", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "print": 1, + "read": 1, + "role": "System Manager", + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/patient_history_settings/patient_history_settings.py b/healthcare/healthcare/doctype/patient_history_settings/patient_history_settings.py new file mode 100644 index 0000000..2eeb730 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_history_settings/patient_history_settings.py @@ -0,0 +1,215 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +import json + +import frappe +from frappe import _ +from frappe.model.document import Document +from frappe.utils import cint, cstr + +from healthcare.healthcare.page.patient_history.patient_history import get_patient_history_doctypes + + +class PatientHistorySettings(Document): + def validate(self): + self.validate_submittable_doctypes() + self.validate_date_fieldnames() + + def validate_submittable_doctypes(self): + for entry in self.custom_doctypes: + if not cint(frappe.db.get_value("DocType", entry.document_type, "is_submittable")): + msg = _("Row #{0}: Document Type {1} is not submittable.").format( + entry.idx, frappe.bold(entry.document_type) + ) + msg += _("Patient Medical Record can only be created for submittable document types.") + frappe.throw(msg) + + def validate_date_fieldnames(self): + for entry in self.custom_doctypes: + field = frappe.get_meta(entry.document_type).get_field(entry.date_fieldname) + if not field: + frappe.throw( + _("Row #{0}: No such Field named {1} found in the Document Type {2}.").format( + entry.idx, frappe.bold(entry.date_fieldname), frappe.bold(entry.document_type) + ) + ) + + if field.fieldtype not in ["Date", "Datetime"]: + frappe.throw( + _("Row #{0}: Field {1} in Document Type {2} is not a Date / Datetime field.").format( + entry.idx, frappe.bold(entry.date_fieldname), frappe.bold(entry.document_type) + ) + ) + + @frappe.whitelist() + def get_doctype_fields(self, document_type, fields): + multicheck_fields = [] + doc_fields = frappe.get_meta(document_type).fields + + for field in doc_fields: + if ( + field.fieldtype not in frappe.model.no_value_fields + or field.fieldtype in frappe.model.table_fields + and not field.hidden + ): + multicheck_fields.append( + { + "label": field.label, + "value": field.fieldname, + "checked": 1 if field.fieldname in fields else 0, + } + ) + + return multicheck_fields + + @frappe.whitelist() + def get_date_field_for_dt(self, document_type): + meta = frappe.get_meta(document_type) + date_fields = meta.get("fields", {"fieldtype": ["in", ["Date", "Datetime"]]}) + + if date_fields: + return date_fields[0].get("fieldname") + + +def create_medical_record(doc, method=None): + medical_record_required = validate_medical_record_required(doc) + if not medical_record_required: + return + + if frappe.db.exists("Patient Medical Record", {"reference_name": doc.name}): + return + + subject = set_subject_field(doc) + date_field = get_date_field(doc.doctype) + medical_record = frappe.new_doc("Patient Medical Record") + medical_record.patient = doc.patient + medical_record.subject = subject + medical_record.status = "Open" + medical_record.communication_date = doc.get(date_field) + medical_record.reference_doctype = doc.doctype + medical_record.reference_name = doc.name + medical_record.reference_owner = doc.owner + medical_record.save(ignore_permissions=True) + + +def update_medical_record(doc, method=None): + medical_record_required = validate_medical_record_required(doc) + if not medical_record_required: + return + + medical_record_id = frappe.db.exists("Patient Medical Record", {"reference_name": doc.name}) + + if medical_record_id: + subject = set_subject_field(doc) + frappe.db.set_value("Patient Medical Record", medical_record_id[0][0], "subject", subject) + else: + create_medical_record(doc) + + +def delete_medical_record(doc, method=None): + medical_record_required = validate_medical_record_required(doc) + if not medical_record_required: + return + + record = frappe.db.exists("Patient Medical Record", {"reference_name": doc.name}) + if record: + frappe.delete_doc("Patient Medical Record", record, force=1) + + +def set_subject_field(doc): + from frappe.utils.formatters import format_value + + meta = frappe.get_meta(doc.doctype) + subject = "" + patient_history_fields = get_patient_history_fields(doc) + + for entry in patient_history_fields: + fieldname = entry.get("fieldname") + if entry.get("fieldtype") == "Table" and doc.get(fieldname): + formatted_value = get_formatted_value_for_table_field( + doc.get(fieldname), meta.get_field(fieldname) + ) + subject += frappe.bold(_(entry.get("label")) + ":") + "
" + cstr(formatted_value) + "
" + + else: + if doc.get(fieldname): + formatted_value = format_value(doc.get(fieldname), meta.get_field(fieldname), doc) + subject += frappe.bold(_(entry.get("label")) + ":") + cstr(formatted_value) + "
" + + return subject + + +def get_date_field(doctype): + dt = get_patient_history_config_dt(doctype) + + return frappe.db.get_value(dt, {"document_type": doctype}, "date_fieldname") + + +def get_patient_history_fields(doc): + dt = get_patient_history_config_dt(doc.doctype) + patient_history_fields = frappe.db.get_value( + dt, {"document_type": doc.doctype}, "selected_fields" + ) + + if patient_history_fields: + return json.loads(patient_history_fields) + + +def get_formatted_value_for_table_field(items, df): + child_meta = frappe.get_meta(df.options) + + table_head = "" + table_row = "" + html = "" + create_head = True + for item in items: + table_row += "" + for cdf in child_meta.fields: + if cdf.in_list_view: + if create_head: + table_head += "" + cdf.label + "" + if item.get(cdf.fieldname): + table_row += "" + str(item.get(cdf.fieldname)) + "" + else: + table_row += "" + create_head = False + table_row += "" + + html += ( + "" + table_head + table_row + "
" + ) + + return html + + +def get_patient_history_config_dt(doctype): + if frappe.db.get_value("DocType", doctype, "custom"): + return "Patient History Custom Document Type" + else: + return "Patient History Standard Document Type" + + +def validate_medical_record_required(doc): + if ( + frappe.flags.in_patch + or frappe.flags.in_install + or frappe.flags.in_setup_wizard + or get_module(doc) != "Healthcare" + ): + return False + + if doc.doctype not in get_patient_history_doctypes(): + return False + + return True + + +def get_module(doc): + module = doc.meta.module + if not module: + module = frappe.db.get_value("DocType", doc.doctype, "module") + + return module diff --git a/healthcare/healthcare/doctype/patient_history_settings/test_patient_history_settings.py b/healthcare/healthcare/doctype/patient_history_settings/test_patient_history_settings.py new file mode 100644 index 0000000..164ee36 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_history_settings/test_patient_history_settings.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# See license.txt + + +import json +from frappe.tests.utils import FrappeTestCase + +import frappe +from frappe.utils import getdate, strip_html + +from healthcare.healthcare.doctype.patient_appointment.test_patient_appointment import ( + create_patient, +) + + +class TestPatientHistorySettings(FrappeTestCase): + def setUp(self): + dt = create_custom_doctype() + settings = frappe.get_single("Patient History Settings") + settings.append( + "custom_doctypes", + { + "document_type": dt.name, + "date_fieldname": "date", + "selected_fields": json.dumps( + [ + {"label": "Date", "fieldname": "date", "fieldtype": "Date"}, + {"label": "Rating", "fieldname": "rating", "fieldtype": "Rating"}, + {"label": "Feedback", "fieldname": "feedback", "fieldtype": "Small Text"}, + ] + ), + }, + ) + settings.save() + + def test_custom_doctype_medical_record(self): + # tests for medical record creation of standard doctypes in test_patient_medical_record.py + patient = create_patient() + doc = create_doc(patient) + # check for medical record + medical_rec = frappe.db.exists( + "Patient Medical Record", {"status": "Open", "reference_name": doc.name} + ) + self.assertTrue(medical_rec) + + medical_rec = frappe.get_doc("Patient Medical Record", medical_rec) + expected_subject = "Date:{0}Rating:3Feedback:Test Patient History Settings".format( + frappe.utils.format_date(getdate()) + ) + self.assertEqual(strip_html(medical_rec.subject), expected_subject) + self.assertEqual(medical_rec.patient, patient) + self.assertEqual(medical_rec.communication_date, getdate()) + + +def create_custom_doctype(): + if not frappe.db.exists("DocType", "Test Patient Feedback"): + doc = frappe.get_doc( + { + "doctype": "DocType", + "module": "Healthcare", + "custom": 1, + "is_submittable": 1, + "fields": [ + {"label": "Date", "fieldname": "date", "fieldtype": "Date"}, + {"label": "Patient", "fieldname": "patient", "fieldtype": "Link", "options": "Patient"}, + {"label": "Rating", "fieldname": "rating", "fieldtype": "Rating"}, + {"label": "Feedback", "fieldname": "feedback", "fieldtype": "Small Text"}, + ], + "permissions": [{"role": "System Manager", "read": 1}], + "name": "Test Patient Feedback", + } + ) + doc.insert() + return doc + else: + return frappe.get_doc("DocType", "Test Patient Feedback") + + +def create_doc(patient): + doc = frappe.get_doc( + { + "doctype": "Test Patient Feedback", + "patient": patient, + "date": getdate(), + "rating": 3, + "feedback": "Test Patient History Settings", + } + ).insert() + doc.submit() + + return doc diff --git a/healthcare/healthcare/doctype/patient_history_standard_document_type/__init__.py b/healthcare/healthcare/doctype/patient_history_standard_document_type/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/patient_history_standard_document_type/patient_history_standard_document_type.json b/healthcare/healthcare/doctype/patient_history_standard_document_type/patient_history_standard_document_type.json new file mode 100644 index 0000000..b43099c --- /dev/null +++ b/healthcare/healthcare/doctype/patient_history_standard_document_type/patient_history_standard_document_type.json @@ -0,0 +1,57 @@ +{ + "actions": [], + "creation": "2020-11-25 13:39:36.014814", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "document_type", + "date_fieldname", + "add_edit_fields", + "selected_fields" + ], + "fields": [ + { + "fieldname": "document_type", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Document Type", + "options": "DocType", + "read_only": 1, + "reqd": 1 + }, + { + "fieldname": "selected_fields", + "fieldtype": "Code", + "label": "Selected Fields", + "read_only": 1 + }, + { + "fieldname": "add_edit_fields", + "fieldtype": "Button", + "in_list_view": 1, + "label": "Add / Edit Fields" + }, + { + "fieldname": "date_fieldname", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Date Fieldname", + "read_only": 1, + "reqd": 1 + } + ], + "index_web_pages_for_search": 1, + "istable": 1, + "links": [], + "modified": "2020-11-30 13:54:56.773325", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient History Standard Document Type", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/patient_history_standard_document_type/patient_history_standard_document_type.py b/healthcare/healthcare/doctype/patient_history_standard_document_type/patient_history_standard_document_type.py new file mode 100644 index 0000000..ab59bc8 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_history_standard_document_type/patient_history_standard_document_type.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class PatientHistoryStandardDocumentType(Document): + pass diff --git a/healthcare/healthcare/doctype/patient_medical_record/__init__.py b/healthcare/healthcare/doctype/patient_medical_record/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/patient_medical_record/patient_medical_record.js b/healthcare/healthcare/doctype/patient_medical_record/patient_medical_record.js new file mode 100644 index 0000000..93ff70e --- /dev/null +++ b/healthcare/healthcare/doctype/patient_medical_record/patient_medical_record.js @@ -0,0 +1,5 @@ +// Copyright (c) 2016, ESS LLP and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Patient Medical Record', { +}); diff --git a/healthcare/healthcare/doctype/patient_medical_record/patient_medical_record.json b/healthcare/healthcare/doctype/patient_medical_record/patient_medical_record.json new file mode 100644 index 0000000..ed82355 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_medical_record/patient_medical_record.json @@ -0,0 +1,155 @@ +{ + "actions": [], + "allow_copy": 1, + "allow_import": 1, + "autoname": "naming_series:", + "beta": 1, + "creation": "2016-06-09 11:30:44.972056", + "doctype": "DocType", + "document_type": "Setup", + "engine": "InnoDB", + "field_order": [ + "naming_series", + "patient", + "status", + "column_break_2", + "attach", + "section_break_4", + "subject", + "section_break_8", + "communication_date", + "reference_doctype", + "reference_name", + "column_break_9", + "reference_owner", + "user" + ], + "fields": [ + { + "fieldname": "naming_series", + "fieldtype": "Select", + "label": "Series", + "options": "HLC-PMR-.YYYY.-", + "print_hide": 1, + "report_hide": 1 + }, + { + "fieldname": "patient", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "label": "Patient", + "options": "Patient", + "search_index": 1 + }, + { + "fieldname": "column_break_2", + "fieldtype": "Column Break" + }, + { + "fieldname": "attach", + "fieldtype": "Attach", + "label": "Attach Medical Record" + }, + { + "fieldname": "section_break_4", + "fieldtype": "Section Break" + }, + { + "fieldname": "subject", + "fieldtype": "Text Editor", + "ignore_xss_filter": 1, + "label": "Subject" + }, + { + "fieldname": "status", + "fieldtype": "Select", + "label": "Status", + "options": "Open\nClose", + "read_only": 1 + }, + { + "default": "Today", + "fieldname": "communication_date", + "fieldtype": "Date", + "in_list_view": 1, + "label": "Datetime", + "read_only": 1 + }, + { + "fieldname": "reference_doctype", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Reference DocType", + "options": "DocType", + "read_only": 1, + "search_index": 1 + }, + { + "fieldname": "reference_name", + "fieldtype": "Dynamic Link", + "in_list_view": 1, + "label": "Reference Name", + "options": "reference_doctype", + "read_only": 1, + "search_index": 1 + }, + { + "fetch_from": "reference_name.owner", + "fieldname": "reference_owner", + "fieldtype": "Data", + "label": "Reference Owner", + "no_copy": 1, + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "default": "__user", + "fieldname": "user", + "fieldtype": "Link", + "label": "User", + "options": "User", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "fieldname": "column_break_9", + "fieldtype": "Column Break" + }, + { + "fieldname": "section_break_8", + "fieldtype": "Section Break" + } + ], + "in_create": 1, + "links": [], + "modified": "2020-04-29 12:26:57.679402", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient Medical Record", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "write": 1 + } + ], + "restrict_to_domain": "Healthcare", + "search_fields": "patient, subject, communication_date, reference_doctype, reference_name", + "show_name_in_global_search": 1, + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "patient", + "track_changes": 1, + "track_seen": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/patient_medical_record/patient_medical_record.py b/healthcare/healthcare/doctype/patient_medical_record/patient_medical_record.py new file mode 100644 index 0000000..a73b544 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_medical_record/patient_medical_record.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and contributors +# For license information, please see license.txt + + +import frappe +from frappe.model.document import Document + + +class PatientMedicalRecord(Document): + def after_insert(self): + if self.reference_doctype == "Patient Medical Record": + frappe.db.set_value("Patient Medical Record", self.name, "reference_name", self.name) diff --git a/healthcare/healthcare/doctype/patient_medical_record/test_patient_medical_record.py b/healthcare/healthcare/doctype/patient_medical_record/test_patient_medical_record.py new file mode 100644 index 0000000..541b212 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_medical_record/test_patient_medical_record.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +import frappe +from frappe.utils import add_days, nowdate + +from erpnext.accounts.doctype.pos_profile.test_pos_profile import make_pos_profile +from healthcare.healthcare.doctype.patient_appointment.test_patient_appointment import ( + create_appointment, + create_encounter, + create_healthcare_docs, + create_medical_department, +) + + +class TestPatientMedicalRecord(FrappeTestCase): + def setUp(self): + frappe.db.set_value("Healthcare Settings", None, "enable_free_follow_ups", 0) + frappe.db.set_value("Healthcare Settings", None, "automate_appointment_invoicing", 1) + make_pos_profile() + + def test_medical_record(self): + patient, practitioner = create_healthcare_docs() + medical_department = create_medical_department() + appointment = create_appointment(patient, practitioner, nowdate(), invoice=1) + encounter = create_encounter(appointment) + + # check for encounter + medical_rec = frappe.db.exists( + "Patient Medical Record", {"status": "Open", "reference_name": encounter.name} + ) + self.assertTrue(medical_rec) + + vital_signs = create_vital_signs(appointment) + # check for vital signs + medical_rec = frappe.db.exists( + "Patient Medical Record", {"status": "Open", "reference_name": vital_signs.name} + ) + self.assertTrue(medical_rec) + + appointment = create_appointment( + patient, practitioner, add_days(nowdate(), 1), invoice=1, procedure_template=1 + ) + procedure = create_procedure(appointment) + procedure.start_procedure() + procedure.complete_procedure() + # check for clinical procedure + medical_rec = frappe.db.exists( + "Patient Medical Record", {"status": "Open", "reference_name": procedure.name} + ) + self.assertTrue(medical_rec) + + template = create_lab_test_template(medical_department) + lab_test = create_lab_test(template.name, patient) + # check for lab test + medical_rec = frappe.db.exists( + "Patient Medical Record", {"status": "Open", "reference_name": lab_test.name} + ) + self.assertTrue(medical_rec) + + +def create_procedure(appointment): + if appointment: + procedure = frappe.new_doc("Clinical Procedure") + procedure.procedure_template = appointment.procedure_template + procedure.appointment = appointment.name + procedure.patient = appointment.patient + procedure.practitioner = appointment.practitioner + procedure.medical_department = appointment.department + procedure.start_dt = appointment.appointment_date + procedure.start_time = appointment.appointment_time + procedure.save() + procedure.submit() + return procedure + + +def create_vital_signs(appointment): + vital_signs = frappe.new_doc("Vital Signs") + vital_signs.patient = appointment.patient + vital_signs.signs_date = appointment.appointment_date + vital_signs.signs_time = appointment.appointment_time + vital_signs.temperature = 38.5 + vital_signs.save() + vital_signs.submit() + return vital_signs + + +def create_lab_test_template(medical_department): + if frappe.db.exists("Lab Test Template", "Blood Test"): + return frappe.get_doc("Lab Test Template", "Blood Test") + + template = frappe.new_doc("Lab Test Template") + template.lab_test_name = "Blood Test" + template.lab_test_code = "Blood Test" + template.lab_test_group = "Services" + template.department = medical_department + template.is_billable = 1 + template.lab_test_rate = 2000 + template.save() + return template + + +def create_lab_test(template, patient): + lab_test = frappe.new_doc("Lab Test") + lab_test.patient = patient + lab_test.patient_sex = frappe.db.get_value("Patient", patient, "sex") + lab_test.template = template + lab_test.save() + lab_test.submit() + return lab_test diff --git a/healthcare/healthcare/doctype/patient_relation/__init__.py b/healthcare/healthcare/doctype/patient_relation/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/patient_relation/patient_relation.json b/healthcare/healthcare/doctype/patient_relation/patient_relation.json new file mode 100644 index 0000000..376f7f7 --- /dev/null +++ b/healthcare/healthcare/doctype/patient_relation/patient_relation.json @@ -0,0 +1,52 @@ +{ + "actions": [], + "allow_copy": 1, + "beta": 1, + "creation": "2017-04-26 15:40:11.561855", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "patient", + "relation", + "description" + ], + "fields": [ + { + "fieldname": "relation", + "fieldtype": "Select", + "in_list_view": 1, + "label": "Relation", + "options": "\nFather\nMother\nSpouse\nSiblings\nFamily\nOther", + "search_index": 1 + }, + { + "fieldname": "patient", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "label": "Patient", + "options": "Patient", + "reqd": 1 + }, + { + "fieldname": "description", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Description" + } + ], + "istable": 1, + "links": [], + "modified": "2020-01-29 12:45:40.081899", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient Relation", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/patient_relation/patient_relation.py b/healthcare/healthcare/doctype/patient_relation/patient_relation.py new file mode 100644 index 0000000..1377aac --- /dev/null +++ b/healthcare/healthcare/doctype/patient_relation/patient_relation.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, ESS LLP and contributors +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class PatientRelation(Document): + pass diff --git a/healthcare/healthcare/doctype/practitioner_schedule/__init__.py b/healthcare/healthcare/doctype/practitioner_schedule/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/practitioner_schedule/practitioner_schedule.js b/healthcare/healthcare/doctype/practitioner_schedule/practitioner_schedule.js new file mode 100644 index 0000000..2e96a49 --- /dev/null +++ b/healthcare/healthcare/doctype/practitioner_schedule/practitioner_schedule.js @@ -0,0 +1,117 @@ +// Copyright (c) 2018, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Practitioner Schedule', { + refresh: function(frm) { + cur_frm.fields_dict["time_slots"].grid.wrapper.find('.grid-add-row').hide(); + cur_frm.fields_dict["time_slots"].grid.add_custom_button(__('Add Time Slots'), () => { + let d = new frappe.ui.Dialog({ + fields: [ + {fieldname: 'days', label: __('Select Days'), fieldtype: 'MultiSelect', + options:[ + {value:'Sunday', label:__('Sunday')}, + {value:'Monday', label:__('Monday')}, + {value:'Tuesday', label:__('Tuesday')}, + {value:'Wednesday', label:__('Wednesday')}, + {value:'Thursday', label:__('Thursday')}, + {value:'Friday', label:__('Friday')}, + {value:'Saturday', label:__('Saturday')}, + ], reqd: 1}, + {fieldname: 'from_time', label: __('From'), fieldtype: 'Time', + 'default': '09:00:00', reqd: 1}, + {fieldname: 'to_time', label: __('To'), fieldtype: 'Time', + 'default': '12:00:00', reqd: 1}, + {fieldname: 'duration', label: __('Appointment Duration (mins)'), + fieldtype:'Int', 'default': 15, reqd: 1}, + ], + primary_action_label: __('Add Timeslots'), + primary_action: () => { + let values = d.get_values(); + if (values) { + let slot_added = false; + values.days.split(',').forEach(function(day){ + day = $.trim(day); + if (['Sunday', 'Monday', 'Tuesday', 'Wednesday', + 'Thursday', 'Friday', 'Saturday'].includes(day)){ + add_slots(day); + } + }); + + function check_overlap_or_add_slot(week_day, cur_time, end_time, add_slots_to_child){ + let overlap = false; + while (cur_time < end_time) { + let add_to_child = true; + let to_time = cur_time.clone().add(values.duration, 'minutes'); + if (to_time <= end_time) { + if (frm.doc.time_slots){ + frm.doc.time_slots.forEach(function(slot) { + if (slot.day == week_day){ + let slot_from_moment = moment(slot.from_time, 'HH:mm:ss'); + let slot_to_moment = moment(slot.to_time, 'HH:mm:ss'); + if (cur_time.isSame(slot_from_moment) || cur_time.isBetween(slot_from_moment, slot_to_moment) || + to_time.isSame(slot_to_moment) || to_time.isBetween(slot_from_moment, slot_to_moment)) { + overlap = true; + if (add_slots_to_child) { + frappe.show_alert({ + message:__('Time slot skiped, the slot {0} to {1} overlap exisiting slot {2} to {3}', + [cur_time.format('HH:mm:ss'), to_time.format('HH:mm:ss'), slot.from_time, slot.to_time]), + indicator:'orange' + }); + add_to_child = false; + } + } + } + }); + } + // add a new timeslot + if (add_to_child && add_slots_to_child) { + frm.add_child('time_slots', { + from_time: cur_time.format('HH:mm:ss'), + to_time: to_time.format('HH:mm:ss'), + day: week_day + }); + slot_added = true; + } + } + cur_time = to_time; + } + return overlap; + } + + function add_slots(week_day) { + let cur_time = moment(values.from_time, 'HH:mm:ss'); + let end_time = moment(values.to_time, 'HH:mm:ss'); + if (check_overlap_or_add_slot(week_day, cur_time, end_time, false)) { + frappe.confirm(__('Schedules for {0} overlaps, do you want to proceed after skipping overlapped slots ?', [week_day]), + function() { + // if Yes + check_overlap_or_add_slot(week_day, cur_time, end_time, true); + }, + function() { + // if No + frappe.show_alert({ + message: __('Slots for {0} are not added to the schedule', [week_day]), + indicator: 'red' + }); + } + ); + } else { + check_overlap_or_add_slot(week_day, cur_time, end_time, true); + } + } + + frm.refresh_field('time_slots'); + + if (slot_added) { + frappe.show_alert({ + message: __('Time slots added'), + indicator: 'green' + }); + } + } + }, + }); + d.show(); + }); + } +}); diff --git a/healthcare/healthcare/doctype/practitioner_schedule/practitioner_schedule.json b/healthcare/healthcare/doctype/practitioner_schedule/practitioner_schedule.json new file mode 100644 index 0000000..a21825e --- /dev/null +++ b/healthcare/healthcare/doctype/practitioner_schedule/practitioner_schedule.json @@ -0,0 +1,71 @@ +{ + "actions": [], + "allow_import": 1, + "allow_rename": 1, + "autoname": "field:schedule_name", + "beta": 1, + "creation": "2017-05-03 17:28:03.926787", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "disabled", + "schedule_details_section", + "schedule_name", + "time_slots" + ], + "fields": [ + { + "fieldname": "schedule_name", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Schedule Name", + "reqd": 1, + "unique": 1 + }, + { + "fieldname": "time_slots", + "fieldtype": "Table", + "label": "Time Slots", + "options": "Healthcare Schedule Time Slot" + }, + { + "default": "0", + "fieldname": "disabled", + "fieldtype": "Check", + "label": "Disabled", + "print_hide": 1 + }, + { + "fieldname": "schedule_details_section", + "fieldtype": "Section Break", + "label": "Schedule Details" + } + ], + "links": [], + "modified": "2020-09-18 17:26:09.703215", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Practitioner Schedule", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + } + ], + "restrict_to_domain": "Healthcare", + "show_name_in_global_search": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/practitioner_schedule/practitioner_schedule.py b/healthcare/healthcare/doctype/practitioner_schedule/practitioner_schedule.py new file mode 100644 index 0000000..bba96bc --- /dev/null +++ b/healthcare/healthcare/doctype/practitioner_schedule/practitioner_schedule.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class PractitionerSchedule(Document): + def autoname(self): + self.name = self.schedule_name diff --git a/healthcare/healthcare/doctype/practitioner_schedule/test_practitioner_schedule.py b/healthcare/healthcare/doctype/practitioner_schedule/test_practitioner_schedule.py new file mode 100644 index 0000000..6322695 --- /dev/null +++ b/healthcare/healthcare/doctype/practitioner_schedule/test_practitioner_schedule.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + + +class TestPractitionerSchedule(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/practitioner_service_unit_schedule/__init__.py b/healthcare/healthcare/doctype/practitioner_service_unit_schedule/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/practitioner_service_unit_schedule/practitioner_service_unit_schedule.json b/healthcare/healthcare/doctype/practitioner_service_unit_schedule/practitioner_service_unit_schedule.json new file mode 100644 index 0000000..4c283aa --- /dev/null +++ b/healthcare/healthcare/doctype/practitioner_service_unit_schedule/practitioner_service_unit_schedule.json @@ -0,0 +1,110 @@ +{ + "allow_copy": 0, + "allow_events_in_timeline": 0, + "allow_guest_to_view": 0, + "allow_import": 0, + "allow_rename": 0, + "beta": 1, + "creation": "2017-11-16 12:19:17.163786", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "", + "editable_grid": 1, + "engine": "InnoDB", + "fields": [ + { + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "schedule", + "fieldtype": "Link", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Schedule", + "length": 0, + "no_copy": 0, + "options": "Practitioner Schedule", + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 0 + }, + { + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "service_unit", + "fieldtype": "Link", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Service Unit", + "length": 0, + "no_copy": 0, + "options": "Healthcare Service Unit", + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 0, + "search_index": 0, + "set_only_once": 0, + "translatable": 0, + "unique": 0 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 1, + "max_attachments": 0, + "modified": "2018-11-04 03:33:07.936958", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Practitioner Service Unit Schedule", + "name_case": "", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "read_only": 0, + "read_only_onload": 0, + "restrict_to_domain": "Healthcare", + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1, + "track_seen": 0, + "track_views": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/practitioner_service_unit_schedule/practitioner_service_unit_schedule.py b/healthcare/healthcare/doctype/practitioner_service_unit_schedule/practitioner_service_unit_schedule.py new file mode 100644 index 0000000..068b14b --- /dev/null +++ b/healthcare/healthcare/doctype/practitioner_service_unit_schedule/practitioner_service_unit_schedule.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class PractitionerServiceUnitSchedule(Document): + pass diff --git a/healthcare/healthcare/doctype/prescription_dosage/__init__.py b/healthcare/healthcare/doctype/prescription_dosage/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/prescription_dosage/prescription_dosage.js b/healthcare/healthcare/doctype/prescription_dosage/prescription_dosage.js new file mode 100644 index 0000000..471ac8f --- /dev/null +++ b/healthcare/healthcare/doctype/prescription_dosage/prescription_dosage.js @@ -0,0 +1,5 @@ +// Copyright (c) 2017, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Prescription Dosage', { +}); diff --git a/healthcare/healthcare/doctype/prescription_dosage/prescription_dosage.json b/healthcare/healthcare/doctype/prescription_dosage/prescription_dosage.json new file mode 100644 index 0000000..9fb0dbc --- /dev/null +++ b/healthcare/healthcare/doctype/prescription_dosage/prescription_dosage.json @@ -0,0 +1,145 @@ +{ + "allow_copy": 0, + "allow_guest_to_view": 0, + "allow_import": 1, + "allow_rename": 1, + "autoname": "field:dosage", + "beta": 1, + "creation": "2016-09-16 15:49:25.327610", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "Document", + "editable_grid": 0, + "fields": [ + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "dosage", + "fieldtype": "Data", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 1, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Dosage", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "unique": 0 + }, + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "dosage_strength", + "fieldtype": "Table", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 0, + "in_standard_filter": 0, + "length": 0, + "no_copy": 0, + "options": "Dosage Strength", + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 0, + "search_index": 0, + "set_only_once": 0, + "unique": 0 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 0, + "max_attachments": 0, + "modified": "2017-10-05 11:20:47.558464", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Prescription Dosage", + "name_case": "", + "owner": "Administrator", + "permissions": [ + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + }, + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + } + ], + "quick_entry": 0, + "read_only": 0, + "read_only_onload": 0, + "restrict_to_domain": "Healthcare", + "search_fields": "dosage", + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "", + "track_changes": 1, + "track_seen": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/prescription_dosage/prescription_dosage.py b/healthcare/healthcare/doctype/prescription_dosage/prescription_dosage.py new file mode 100644 index 0000000..a8f82f4 --- /dev/null +++ b/healthcare/healthcare/doctype/prescription_dosage/prescription_dosage.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class PrescriptionDosage(Document): + pass diff --git a/healthcare/healthcare/doctype/prescription_dosage/test_prescription_dosage.py b/healthcare/healthcare/doctype/prescription_dosage/test_prescription_dosage.py new file mode 100644 index 0000000..3acaec2 --- /dev/null +++ b/healthcare/healthcare/doctype/prescription_dosage/test_prescription_dosage.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + + +class TestPrescriptionDosage(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/prescription_duration/__init__.py b/healthcare/healthcare/doctype/prescription_duration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/prescription_duration/prescription_duration.js b/healthcare/healthcare/doctype/prescription_duration/prescription_duration.js new file mode 100644 index 0000000..22152b5 --- /dev/null +++ b/healthcare/healthcare/doctype/prescription_duration/prescription_duration.js @@ -0,0 +1,5 @@ +// Copyright (c) 2017, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Prescription Duration', { +}); diff --git a/healthcare/healthcare/doctype/prescription_duration/prescription_duration.json b/healthcare/healthcare/doctype/prescription_duration/prescription_duration.json new file mode 100644 index 0000000..c4f6c5f --- /dev/null +++ b/healthcare/healthcare/doctype/prescription_duration/prescription_duration.json @@ -0,0 +1,145 @@ +{ + "allow_copy": 1, + "allow_guest_to_view": 0, + "allow_import": 1, + "allow_rename": 1, + "autoname": "", + "beta": 1, + "creation": "2016-09-16 15:50:28.895789", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "Document", + "editable_grid": 0, + "fields": [ + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "number", + "fieldtype": "Int", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Number", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "unique": 0 + }, + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "period", + "fieldtype": "Select", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Period", + "length": 0, + "no_copy": 0, + "options": "Hour\nDay\nWeek\nMonth", + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "unique": 0 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 0, + "max_attachments": 0, + "modified": "2017-08-31 13:42:51.325725", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Prescription Duration", + "name_case": "", + "owner": "Administrator", + "permissions": [ + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + }, + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + } + ], + "quick_entry": 1, + "read_only": 0, + "read_only_onload": 0, + "restrict_to_domain": "Healthcare", + "search_fields": "", + "show_name_in_global_search": 0, + "sort_field": "", + "sort_order": "ASC", + "track_changes": 1, + "track_seen": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/prescription_duration/prescription_duration.py b/healthcare/healthcare/doctype/prescription_duration/prescription_duration.py new file mode 100644 index 0000000..8b8785d --- /dev/null +++ b/healthcare/healthcare/doctype/prescription_duration/prescription_duration.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document +from frappe.utils import cstr + + +class PrescriptionDuration(Document): + def autoname(self): + self.name = " ".join(filter(None, [cstr(self.get(f)).strip() for f in ["number", "period"]])) + + def get_days(self): + days = 0 + duration = self + if duration.period == "Day": + days = duration.number + if duration.period == "Hour": + days = (duration.number) / 24 + if duration.period == "Week": + days = duration.number * 7 + if duration.period == "Month": + days = duration.number * 30 + return days + + def get_weeks(self): + weeks = 0 + duration = self + if duration.period == "Day": + weeks = (duration.number) / 7 + # if(duration.period == 'Hour'): + # weeks = (duration.number)/x + if duration.period == "Week": + weeks = duration.number + if duration.period == "Month": + weeks = duration.number * 4 + return weeks + + def get_months(self): + months = 0 + duration = self + if duration.period == "Day": + months = (duration.number) / 30 + # if(duration.period == 'Hour'): + # months = (duration.number)/x + if duration.period == "Week": + months = (duration.number) / 4 + if duration.period == "Month": + months = duration.number + return months + + def get_hours(self): + hours = 0 + duration = self + if duration.period == "Day": + hours = duration.number * 24 + if duration.period == "Hour": + hours = duration.number + if duration.period == "Week": + hours = (duration.number * 24) * 7 + if duration.period == "Month": + hours = (duration.number * 24) * 30 + return hours + + def get_minutes(self): + minutes = 0 + duration = self + if duration.period == "Day": + minutes = duration.number * 1440 + if duration.period == "Hour": + minutes = duration.number * 60 + if duration.period == "Week": + minutes = duration.number * 10080 + if duration.period == "Month": + minutes = duration.number * 43800 + return minutes diff --git a/healthcare/healthcare/doctype/prescription_duration/test_prescription_duration.py b/healthcare/healthcare/doctype/prescription_duration/test_prescription_duration.py new file mode 100644 index 0000000..c6e7389 --- /dev/null +++ b/healthcare/healthcare/doctype/prescription_duration/test_prescription_duration.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + + +class TestPrescriptionDuration(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/procedure_prescription/__init__.py b/healthcare/healthcare/doctype/procedure_prescription/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/procedure_prescription/procedure_prescription.json b/healthcare/healthcare/doctype/procedure_prescription/procedure_prescription.json new file mode 100644 index 0000000..e4c01d7 --- /dev/null +++ b/healthcare/healthcare/doctype/procedure_prescription/procedure_prescription.json @@ -0,0 +1,99 @@ +{ + "actions": [], + "allow_copy": 1, + "beta": 1, + "creation": "2017-11-17 15:52:48.324157", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "procedure", + "procedure_name", + "department", + "practitioner", + "date", + "comments", + "appointment_booked", + "procedure_created", + "invoiced" + ], + "fields": [ + { + "fieldname": "procedure", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Clinical Procedure", + "options": "Clinical Procedure Template", + "reqd": 1 + }, + { + "fetch_from": "procedure.template", + "fieldname": "procedure_name", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Procedure Name" + }, + { + "fetch_from": "procedure.medical_department", + "fieldname": "department", + "fieldtype": "Link", + "label": "Department", + "options": "Medical Department" + }, + { + "fieldname": "practitioner", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Referring Practitioner", + "options": "Healthcare Practitioner" + }, + { + "fieldname": "date", + "fieldtype": "Date", + "in_list_view": 1, + "label": "Date" + }, + { + "fieldname": "comments", + "fieldtype": "Data", + "label": "Comments" + }, + { + "default": "0", + "fieldname": "appointment_booked", + "fieldtype": "Check", + "hidden": 1, + "label": "Appointment Booked", + "search_index": 1 + }, + { + "default": "0", + "fieldname": "procedure_created", + "fieldtype": "Check", + "hidden": 1, + "label": "Procedure Created", + "no_copy": 1, + "search_index": 1 + }, + { + "default": "0", + "fieldname": "invoiced", + "fieldtype": "Check", + "label": "Invoiced", + "read_only": 1, + "search_index": 1 + } + ], + "istable": 1, + "links": [], + "modified": "2020-02-26 15:42:33.988081", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Procedure Prescription", + "owner": "Administrator", + "permissions": [], + "restrict_to_domain": "Healthcare", + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/procedure_prescription/procedure_prescription.py b/healthcare/healthcare/doctype/procedure_prescription/procedure_prescription.py new file mode 100644 index 0000000..15474d2 --- /dev/null +++ b/healthcare/healthcare/doctype/procedure_prescription/procedure_prescription.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017, InfluxERP +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class ProcedurePrescription(Document): + pass diff --git a/healthcare/healthcare/doctype/sample_collection/__init__.py b/healthcare/healthcare/doctype/sample_collection/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/sample_collection/sample_collection.js b/healthcare/healthcare/doctype/sample_collection/sample_collection.js new file mode 100644 index 0000000..1bf2fc2 --- /dev/null +++ b/healthcare/healthcare/doctype/sample_collection/sample_collection.js @@ -0,0 +1,40 @@ +// Copyright (c) 2016, ESS and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Sample Collection', { + refresh: function(frm) { + if (frappe.defaults.get_default('create_sample_collection_for_lab_test')) { + frm.add_custom_button(__('View Lab Tests'), function() { + frappe.route_options = {'sample': frm.doc.name}; + frappe.set_route('List', 'Lab Test'); + }); + } + } +}); + +frappe.ui.form.on('Sample Collection', 'patient', function(frm) { + if(frm.doc.patient){ + frappe.call({ + 'method': 'healthcare.healthcare.doctype.patient.patient.get_patient_detail', + args: { + patient: frm.doc.patient + }, + callback: function (data) { + var age = null; + if (data.message.dob){ + age = calculate_age(data.message.dob); + } + frappe.model.set_value(frm.doctype,frm.docname, 'patient_age', age); + frappe.model.set_value(frm.doctype,frm.docname, 'patient_sex', data.message.sex); + } + }); + } +}); + +var calculate_age = function(birth) { + var ageMS = Date.parse(Date()) - Date.parse(birth); + var age = new Date(); + age.setTime(ageMS); + var years = age.getFullYear() - 1970; + return `${years} ${__('Years(s)')} ${age.getMonth()} ${__('Month(s)')} ${age.getDate()} ${__('Day(s)')}`; +}; diff --git a/healthcare/healthcare/doctype/sample_collection/sample_collection.json b/healthcare/healthcare/doctype/sample_collection/sample_collection.json new file mode 100644 index 0000000..83383e3 --- /dev/null +++ b/healthcare/healthcare/doctype/sample_collection/sample_collection.json @@ -0,0 +1,256 @@ +{ + "actions": [], + "allow_copy": 1, + "allow_import": 1, + "autoname": "naming_series:", + "beta": 1, + "creation": "2016-04-05 15:58:18.076977", + "doctype": "DocType", + "document_type": "Document", + "engine": "InnoDB", + "field_order": [ + "patient_details_section", + "naming_series", + "patient", + "patient_name", + "patient_age", + "patient_sex", + "column_break_4", + "inpatient_record", + "company", + "invoiced", + "section_break_6", + "sample", + "sample_uom", + "sample_qty", + "column_break_10", + "collected_by", + "collected_time", + "num_print", + "section_break_15", + "sample_details", + "amended_from" + ], + "fields": [ + { + "fetch_from": "patient.inpatient_record", + "fieldname": "inpatient_record", + "fieldtype": "Link", + "hide_days": 1, + "hide_seconds": 1, + "label": "Inpatient Record", + "options": "Inpatient Record", + "read_only": 1 + }, + { + "bold": 1, + "fieldname": "naming_series", + "fieldtype": "Select", + "hide_days": 1, + "hide_seconds": 1, + "label": "Series", + "no_copy": 1, + "options": "HLC-SC-.YYYY.-", + "print_hide": 1, + "reqd": 1 + }, + { + "default": "0", + "fieldname": "invoiced", + "fieldtype": "Check", + "hide_days": 1, + "hide_seconds": 1, + "label": "Invoiced", + "no_copy": 1, + "read_only": 1, + "search_index": 1 + }, + { + "fetch_from": "inpatient_record.patient", + "fieldname": "patient", + "fieldtype": "Link", + "hide_days": 1, + "hide_seconds": 1, + "ignore_user_permissions": 1, + "in_standard_filter": 1, + "label": "Patient", + "options": "Patient", + "reqd": 1, + "search_index": 1 + }, + { + "fieldname": "column_break_4", + "fieldtype": "Column Break", + "hide_days": 1, + "hide_seconds": 1 + }, + { + "fieldname": "patient_age", + "fieldtype": "Data", + "hide_days": 1, + "hide_seconds": 1, + "label": "Age", + "read_only": 1 + }, + { + "fetch_from": "patient.sex", + "fieldname": "patient_sex", + "fieldtype": "Link", + "hide_days": 1, + "hide_seconds": 1, + "label": "Gender", + "options": "Gender", + "read_only": 1 + }, + { + "fieldname": "company", + "fieldtype": "Link", + "hide_days": 1, + "hide_seconds": 1, + "in_standard_filter": 1, + "label": "Company", + "options": "Company" + }, + { + "fieldname": "section_break_6", + "fieldtype": "Section Break", + "hide_days": 1, + "hide_seconds": 1, + "label": "Sample Details" + }, + { + "fieldname": "sample", + "fieldtype": "Link", + "hide_days": 1, + "hide_seconds": 1, + "ignore_user_permissions": 1, + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Sample", + "options": "Lab Test Sample", + "reqd": 1, + "search_index": 1 + }, + { + "fetch_from": "sample.sample_uom", + "fieldname": "sample_uom", + "fieldtype": "Data", + "hide_days": 1, + "hide_seconds": 1, + "in_list_view": 1, + "label": "UOM", + "read_only": 1 + }, + { + "fieldname": "column_break_10", + "fieldtype": "Column Break", + "hide_days": 1, + "hide_seconds": 1 + }, + { + "fieldname": "collected_by", + "fieldtype": "Link", + "hide_days": 1, + "hide_seconds": 1, + "ignore_user_permissions": 1, + "label": "Collected By", + "options": "User" + }, + { + "fieldname": "collected_time", + "fieldtype": "Datetime", + "hide_days": 1, + "hide_seconds": 1, + "label": "Collected On" + }, + { + "allow_on_submit": 1, + "default": "1", + "description": "Number of prints required for labelling the samples", + "fieldname": "num_print", + "fieldtype": "Int", + "hide_days": 1, + "hide_seconds": 1, + "label": "No. of prints", + "print_hide": 1, + "report_hide": 1 + }, + { + "fieldname": "amended_from", + "fieldtype": "Link", + "hide_days": 1, + "hide_seconds": 1, + "label": "Amended From", + "no_copy": 1, + "options": "Sample Collection", + "print_hide": 1, + "read_only": 1 + }, + { + "fieldname": "section_break_15", + "fieldtype": "Section Break", + "hide_days": 1, + "hide_seconds": 1 + }, + { + "default": "0", + "fieldname": "sample_qty", + "fieldtype": "Float", + "hide_days": 1, + "hide_seconds": 1, + "in_list_view": 1, + "label": "Quantity" + }, + { + "fieldname": "sample_details", + "fieldtype": "Long Text", + "hide_days": 1, + "hide_seconds": 1, + "ignore_xss_filter": 1, + "label": "Collection Details" + }, + { + "fieldname": "patient_details_section", + "fieldtype": "Section Break", + "label": "Patient Details" + }, + { + "fetch_from": "patient.patient_name", + "fieldname": "patient_name", + "fieldtype": "Data", + "label": "Patient Name", + "read_only": 1 + } + ], + "is_submittable": 1, + "links": [], + "modified": "2020-07-30 16:53:13.076104", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Sample Collection", + "owner": "Administrator", + "permissions": [ + { + "amend": 1, + "cancel": 1, + "create": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Laboratory User", + "share": 1, + "submit": 1, + "write": 1 + } + ], + "restrict_to_domain": "Healthcare", + "search_fields": "patient, sample", + "show_name_in_global_search": 1, + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "patient", + "track_changes": 1, + "track_seen": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/sample_collection/sample_collection.py b/healthcare/healthcare/doctype/sample_collection/sample_collection.py new file mode 100644 index 0000000..6ee34e2 --- /dev/null +++ b/healthcare/healthcare/doctype/sample_collection/sample_collection.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS and contributors +# For license information, please see license.txt + + +import frappe +from frappe import _ +from frappe.model.document import Document +from frappe.utils import flt + + +class SampleCollection(Document): + def validate(self): + if flt(self.sample_qty) <= 0: + frappe.throw(_("Sample Quantity cannot be negative or 0"), title=_("Invalid Quantity")) diff --git a/healthcare/healthcare/doctype/sample_collection/test_sample_collection.py b/healthcare/healthcare/doctype/sample_collection/test_sample_collection.py new file mode 100644 index 0000000..2d991d1 --- /dev/null +++ b/healthcare/healthcare/doctype/sample_collection/test_sample_collection.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +# test_records = frappe.get_test_records('Sample Collection') + + +class TestSampleCollection(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/sensitivity/__init__.py b/healthcare/healthcare/doctype/sensitivity/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/sensitivity/sensitivity.js b/healthcare/healthcare/doctype/sensitivity/sensitivity.js new file mode 100644 index 0000000..f9c9002 --- /dev/null +++ b/healthcare/healthcare/doctype/sensitivity/sensitivity.js @@ -0,0 +1,5 @@ +// Copyright (c) 2016, ESS LLP and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Sensitivity', { +}); diff --git a/healthcare/healthcare/doctype/sensitivity/sensitivity.json b/healthcare/healthcare/doctype/sensitivity/sensitivity.json new file mode 100644 index 0000000..eddfda9 --- /dev/null +++ b/healthcare/healthcare/doctype/sensitivity/sensitivity.json @@ -0,0 +1,115 @@ +{ + "allow_copy": 1, + "allow_guest_to_view": 0, + "allow_import": 1, + "allow_rename": 1, + "autoname": "field:sensitivity", + "beta": 1, + "creation": "2016-02-23 11:12:54.623249", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "Setup", + "editable_grid": 0, + "fields": [ + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "sensitivity", + "fieldtype": "Data", + "hidden": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 1, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Sensitivity", + "length": 0, + "no_copy": 0, + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 1, + "search_index": 0, + "set_only_once": 0, + "unique": 0 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 0, + "max_attachments": 0, + "modified": "2017-10-05 11:19:12.110308", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Sensitivity", + "name_case": "", + "owner": "Administrator", + "permissions": [ + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 0, + "delete": 0, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Laboratory User", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 0 + }, + { + "amend": 0, + "apply_user_permissions": 0, + "cancel": 0, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "if_owner": 0, + "import": 0, + "permlevel": 0, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "set_user_permissions": 0, + "share": 1, + "submit": 0, + "write": 1 + } + ], + "quick_entry": 1, + "read_only": 0, + "read_only_onload": 0, + "restrict_to_domain": "Healthcare", + "search_fields": "sensitivity", + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "sensitivity", + "track_changes": 1, + "track_seen": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/sensitivity/sensitivity.py b/healthcare/healthcare/doctype/sensitivity/sensitivity.py new file mode 100644 index 0000000..9db634a --- /dev/null +++ b/healthcare/healthcare/doctype/sensitivity/sensitivity.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS and contributors +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class Sensitivity(Document): + pass diff --git a/healthcare/healthcare/doctype/sensitivity/test_sensitivity.py b/healthcare/healthcare/doctype/sensitivity/test_sensitivity.py new file mode 100644 index 0000000..3fa7722 --- /dev/null +++ b/healthcare/healthcare/doctype/sensitivity/test_sensitivity.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +# test_records = frappe.get_test_records('Sensitivity') + + +class TestSensitivity(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/sensitivity_test_result/__init__.py b/healthcare/healthcare/doctype/sensitivity_test_result/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/sensitivity_test_result/sensitivity_test_result.json b/healthcare/healthcare/doctype/sensitivity_test_result/sensitivity_test_result.json new file mode 100644 index 0000000..768c177 --- /dev/null +++ b/healthcare/healthcare/doctype/sensitivity_test_result/sensitivity_test_result.json @@ -0,0 +1,103 @@ +{ + "allow_copy": 1, + "allow_guest_to_view": 0, + "allow_import": 0, + "allow_rename": 0, + "beta": 1, + "creation": "2016-02-22 15:18:01.769903", + "custom": 0, + "docstatus": 0, + "doctype": "DocType", + "document_type": "Document", + "editable_grid": 1, + "fields": [ + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "antibiotic", + "fieldtype": "Link", + "hidden": 0, + "ignore_user_permissions": 1, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Antibiotic", + "length": 0, + "no_copy": 0, + "options": "Antibiotic", + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 0, + "search_index": 0, + "set_only_once": 0, + "unique": 0 + }, + { + "allow_bulk_edit": 0, + "allow_on_submit": 0, + "bold": 0, + "collapsible": 0, + "columns": 0, + "fieldname": "antibiotic_sensitivity", + "fieldtype": "Link", + "hidden": 0, + "ignore_user_permissions": 1, + "ignore_xss_filter": 0, + "in_filter": 0, + "in_global_search": 0, + "in_list_view": 1, + "in_standard_filter": 0, + "label": "Sensitivity", + "length": 0, + "no_copy": 0, + "options": "Sensitivity", + "permlevel": 0, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "read_only": 0, + "remember_last_selected_value": 0, + "report_hide": 0, + "reqd": 0, + "search_index": 0, + "set_only_once": 0, + "unique": 0 + } + ], + "has_web_view": 0, + "hide_heading": 0, + "hide_toolbar": 0, + "idx": 0, + "image_view": 0, + "in_create": 0, + "is_submittable": 0, + "issingle": 0, + "istable": 1, + "max_attachments": 0, + "modified": "2017-10-05 11:08:06.327972", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Sensitivity Test Result", + "name_case": "", + "owner": "Administrator", + "permissions": [], + "quick_entry": 0, + "read_only": 0, + "read_only_onload": 0, + "restrict_to_domain": "Healthcare", + "show_name_in_global_search": 0, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 0, + "track_seen": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/sensitivity_test_result/sensitivity_test_result.py b/healthcare/healthcare/doctype/sensitivity_test_result/sensitivity_test_result.py new file mode 100644 index 0000000..ffddc81 --- /dev/null +++ b/healthcare/healthcare/doctype/sensitivity_test_result/sensitivity_test_result.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS and contributors +# For license information, please see license.txt + + +from frappe.model.document import Document + + +class SensitivityTestResult(Document): + pass diff --git a/healthcare/healthcare/doctype/therapy_plan/__init__.py b/healthcare/healthcare/doctype/therapy_plan/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/therapy_plan/test_therapy_plan.py b/healthcare/healthcare/doctype/therapy_plan/test_therapy_plan.py new file mode 100644 index 0000000..f881eba --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_plan/test_therapy_plan.py @@ -0,0 +1,119 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +import frappe +from frappe.utils import flt, getdate, nowdate + +from healthcare.healthcare.doctype.patient_appointment.test_patient_appointment import ( + create_appointment, + create_healthcare_docs, + create_medical_department, + create_patient, +) +from healthcare.healthcare.doctype.therapy_plan.therapy_plan import ( + make_sales_invoice, + make_therapy_session, +) +from healthcare.healthcare.doctype.therapy_type.test_therapy_type import create_therapy_type + + +class TestTherapyPlan(FrappeTestCase): + def test_creation_on_encounter_submission(self): + patient, practitioner = create_healthcare_docs() + medical_department = create_medical_department() + encounter = create_encounter(patient, medical_department, practitioner) + self.assertTrue(frappe.db.exists("Therapy Plan", encounter.therapy_plan)) + + def test_status(self): + plan = create_therapy_plan() + self.assertEqual(plan.status, "Not Started") + + session = make_therapy_session(plan.name, plan.patient, "Basic Rehab", "_Test Company") + frappe.get_doc(session).submit() + self.assertEqual(frappe.db.get_value("Therapy Plan", plan.name, "status"), "In Progress") + + session = make_therapy_session(plan.name, plan.patient, "Basic Rehab", "_Test Company") + frappe.get_doc(session).submit() + self.assertEqual(frappe.db.get_value("Therapy Plan", plan.name, "status"), "Completed") + + patient, practitioner = create_healthcare_docs() + appointment = create_appointment(patient, practitioner, nowdate()) + + session = make_therapy_session( + plan.name, plan.patient, "Basic Rehab", "_Test Company", appointment.name + ) + session = frappe.get_doc(session) + session.submit() + self.assertEqual( + frappe.db.get_value("Patient Appointment", appointment.name, "status"), "Closed" + ) + session.cancel() + self.assertEqual(frappe.db.get_value("Patient Appointment", appointment.name, "status"), "Open") + + def test_therapy_plan_from_template(self): + patient = create_patient() + template = create_therapy_plan_template() + # check linked item + self.assertTrue(frappe.db.exists("Therapy Plan Template", {"linked_item": "Complete Rehab"})) + + plan = create_therapy_plan(template) + # invoice + si = make_sales_invoice(plan.name, patient, "_Test Company", template) + si.save() + + therapy_plan_template_amt = frappe.db.get_value( + "Therapy Plan Template", template, "total_amount" + ) + self.assertEqual(si.items[0].amount, therapy_plan_template_amt) + + +def create_therapy_plan(template=None, patient=None): + if not patient: + patient = create_patient() + therapy_type = create_therapy_type() + plan = frappe.new_doc("Therapy Plan") + plan.patient = patient + plan.start_date = getdate() + + if template: + plan.therapy_plan_template = template + plan = plan.set_therapy_details_from_template() + else: + plan.append("therapy_plan_details", {"therapy_type": therapy_type.name, "no_of_sessions": 2}) + + plan.save() + return plan + + +def create_encounter(patient, medical_department, practitioner): + encounter = frappe.new_doc("Patient Encounter") + encounter.patient = patient + encounter.practitioner = practitioner + encounter.medical_department = medical_department + therapy_type = create_therapy_type() + encounter.append("therapies", {"therapy_type": therapy_type.name, "no_of_sessions": 2}) + encounter.save() + encounter.submit() + return encounter + + +def create_therapy_plan_template(): + template_name = frappe.db.exists("Therapy Plan Template", "Complete Rehab") + if not template_name: + therapy_type = create_therapy_type() + template = frappe.new_doc("Therapy Plan Template") + template.plan_name = template.item_code = template.item_name = "Complete Rehab" + template.item_group = "Services" + rate = frappe.db.get_value("Therapy Type", therapy_type.name, "rate") + template.append( + "therapy_types", + {"therapy_type": therapy_type.name, "no_of_sessions": 2, "rate": rate, "amount": 2 * flt(rate)}, + ) + template.save() + template_name = template.name + + return template_name diff --git a/healthcare/healthcare/doctype/therapy_plan/therapy_plan.js b/healthcare/healthcare/doctype/therapy_plan/therapy_plan.js new file mode 100644 index 0000000..f36e77f --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_plan/therapy_plan.js @@ -0,0 +1,133 @@ +// Copyright (c) 2020, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Therapy Plan', { + setup: function(frm) { + frm.get_field('therapy_plan_details').grid.editable_fields = [ + {fieldname: 'therapy_type', columns: 6}, + {fieldname: 'no_of_sessions', columns: 2}, + {fieldname: 'sessions_completed', columns: 2} + ]; + }, + + refresh: function(frm) { + if (!frm.doc.__islocal) { + frm.trigger('show_progress_for_therapies'); + if (frm.doc.status != 'Completed') { + let therapy_types = (frm.doc.therapy_plan_details || []).map(function(d){ return d.therapy_type; }); + const fields = [{ + fieldtype: 'Link', + label: __('Therapy Type'), + fieldname: 'therapy_type', + options: 'Therapy Type', + reqd: 1, + get_query: function() { + return { + filters: { 'therapy_type': ['in', therapy_types]} + }; + } + }]; + + frm.add_custom_button(__('Therapy Session'), function() { + frappe.prompt(fields, data => { + frappe.call({ + method: 'healthcare.healthcare.doctype.therapy_plan.therapy_plan.make_therapy_session', + args: { + therapy_plan: frm.doc.name, + patient: frm.doc.patient, + therapy_type: data.therapy_type, + company: frm.doc.company + }, + freeze: true, + callback: function(r) { + if (r.message) { + frappe.model.sync(r.message); + frappe.set_route('Form', r.message.doctype, r.message.name); + } + } + }); + }, __('Select Therapy Type'), __('Create')); + }, __('Create')); + } + + if (frm.doc.therapy_plan_template && !frm.doc.invoiced) { + frm.add_custom_button(__('Sales Invoice'), function() { + frm.trigger('make_sales_invoice'); + }, __('Create')); + } + } + + if (frm.doc.therapy_plan_template) { + frm.fields_dict.therapy_plan_details.grid.update_docfield_property( + 'therapy_type', 'read_only', 1 + ); + frm.fields_dict.therapy_plan_details.grid.update_docfield_property( + 'no_of_sessions', 'read_only', 1 + ); + } + }, + + make_sales_invoice: function(frm) { + frappe.call({ + args: { + 'reference_name': frm.doc.name, + 'patient': frm.doc.patient, + 'company': frm.doc.company, + 'therapy_plan_template': frm.doc.therapy_plan_template + }, + method: 'healthcare.healthcare.doctype.therapy_plan.therapy_plan.make_sales_invoice', + callback: function(r) { + var doclist = frappe.model.sync(r.message); + frappe.set_route('Form', doclist[0].doctype, doclist[0].name); + } + }); + }, + + therapy_plan_template: function(frm) { + if (frm.doc.therapy_plan_template) { + frappe.call({ + method: 'set_therapy_details_from_template', + doc: frm.doc, + freeze: true, + freeze_message: __('Fetching Template Details'), + callback: function() { + refresh_field('therapy_plan_details'); + } + }); + } + }, + + show_progress_for_therapies: function(frm) { + let bars = []; + let message = ''; + + // completed sessions + let title = __('{0} sessions completed', [frm.doc.total_sessions_completed]); + if (frm.doc.total_sessions_completed === 1) { + title = __('{0} session completed', [frm.doc.total_sessions_completed]); + } + title += __(' out of {0}', [frm.doc.total_sessions]); + + bars.push({ + 'title': title, + 'width': (frm.doc.total_sessions_completed / frm.doc.total_sessions * 100) + '%', + 'progress_class': 'progress-bar-success' + }); + if (bars[0].width == '0%') { + bars[0].width = '0.5%'; + } + message = title; + frm.dashboard.add_progress(__('Status'), bars, message); + }, +}); + +frappe.ui.form.on('Therapy Plan Detail', { + no_of_sessions: function(frm) { + let total = 0; + $.each(frm.doc.therapy_plan_details, function(_i, e) { + total += e.no_of_sessions; + }); + frm.set_value('total_sessions', total); + refresh_field('total_sessions'); + } +}); diff --git a/healthcare/healthcare/doctype/therapy_plan/therapy_plan.json b/healthcare/healthcare/doctype/therapy_plan/therapy_plan.json new file mode 100644 index 0000000..c03e9de --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_plan/therapy_plan.json @@ -0,0 +1,179 @@ +{ + "actions": [], + "autoname": "naming_series:", + "creation": "2020-03-29 20:56:49.758602", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "naming_series", + "patient", + "patient_name", + "invoiced", + "column_break_4", + "company", + "status", + "start_date", + "section_break_3", + "therapy_plan_template", + "therapy_plan_details", + "title", + "section_break_9", + "total_sessions", + "column_break_11", + "total_sessions_completed" + ], + "fields": [ + { + "fieldname": "patient", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Patient", + "options": "Patient", + "reqd": 1 + }, + { + "fieldname": "start_date", + "fieldtype": "Date", + "in_list_view": 1, + "label": "Start Date", + "reqd": 1 + }, + { + "fieldname": "section_break_3", + "fieldtype": "Section Break" + }, + { + "fieldname": "therapy_plan_details", + "fieldtype": "Table", + "label": "Therapy Plan Details", + "options": "Therapy Plan Detail", + "read_only_depends_on": "therapy_plan_template", + "reqd": 1 + }, + { + "fieldname": "naming_series", + "fieldtype": "Select", + "label": "Naming Series", + "options": "HLC-THP-.YYYY.-" + }, + { + "fetch_from": "patient.patient_name", + "fieldname": "patient_name", + "fieldtype": "Data", + "label": "Patient Name", + "read_only": 1 + }, + { + "default": "{patient_name}", + "fieldname": "title", + "fieldtype": "Data", + "hidden": 1, + "label": "Title", + "no_copy": 1 + }, + { + "fieldname": "column_break_4", + "fieldtype": "Column Break" + }, + { + "fieldname": "section_break_9", + "fieldtype": "Section Break" + }, + { + "fieldname": "total_sessions", + "fieldtype": "Int", + "label": "Total Sessions", + "read_only": 1 + }, + { + "fieldname": "column_break_11", + "fieldtype": "Column Break" + }, + { + "fieldname": "total_sessions_completed", + "fieldtype": "Int", + "label": "Total Sessions Completed", + "read_only": 1 + }, + { + "fieldname": "status", + "fieldtype": "Select", + "label": "Status", + "options": "Not Started\nIn Progress\nCompleted\nCancelled", + "read_only": 1 + }, + { + "fieldname": "company", + "fieldtype": "Link", + "in_standard_filter": 1, + "label": "Company", + "options": "Company", + "reqd": 1 + }, + { + "fieldname": "therapy_plan_template", + "fieldtype": "Link", + "label": "Therapy Plan Template", + "options": "Therapy Plan Template", + "set_only_once": 1 + }, + { + "default": "0", + "fieldname": "invoiced", + "fieldtype": "Check", + "label": "Invoiced", + "no_copy": 1, + "print_hide": 1, + "read_only": 1 + } + ], + "links": [], + "modified": "2020-11-04 18:13:13.564999", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Therapy Plan", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + }, + { + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "search_fields": "patient", + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "patient", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/therapy_plan/therapy_plan.py b/healthcare/healthcare/doctype/therapy_plan/therapy_plan.py new file mode 100644 index 0000000..1d5ba8c --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_plan/therapy_plan.py @@ -0,0 +1,110 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +import frappe +from frappe.model.document import Document +from frappe.utils import flt, today +from healthcare.healthcare.doctype.nursing_task.nursing_task import NursingTask +from healthcare.healthcare.utils import validate_nursing_tasks + + +class TherapyPlan(Document): + def validate(self): + self.set_totals() + self.set_status() + + def on_submit(self): + validate_nursing_tasks(self) + + def set_status(self): + if not self.total_sessions_completed: + self.status = "Not Started" + else: + if self.total_sessions_completed < self.total_sessions: + self.status = "In Progress" + elif self.total_sessions_completed == self.total_sessions: + self.status = "Completed" + + def set_totals(self): + total_sessions = 0 + total_sessions_completed = 0 + for entry in self.therapy_plan_details: + if entry.no_of_sessions: + total_sessions += entry.no_of_sessions + if entry.sessions_completed: + total_sessions_completed += entry.sessions_completed + + self.db_set("total_sessions", total_sessions) + self.db_set("total_sessions_completed", total_sessions_completed) + + @frappe.whitelist() + def set_therapy_details_from_template(self): + # Add therapy types in the child table + self.set("therapy_plan_details", []) + therapy_plan_template = frappe.get_doc("Therapy Plan Template", self.therapy_plan_template) + + for data in therapy_plan_template.therapy_types: + self.append( + "therapy_plan_details", + {"therapy_type": data.therapy_type, "no_of_sessions": data.no_of_sessions}, + ) + return self + + +@frappe.whitelist() +def make_therapy_session(therapy_plan, patient, therapy_type, company, appointment=None): + therapy_type = frappe.get_doc("Therapy Type", therapy_type) + + therapy_session = frappe.new_doc("Therapy Session") + therapy_session.therapy_plan = therapy_plan + therapy_session.company = company + therapy_session.patient = patient + therapy_session.therapy_type = therapy_type.name + therapy_session.duration = therapy_type.default_duration + therapy_session.rate = therapy_type.rate + therapy_session.exercises = therapy_type.exercises + therapy_session.appointment = appointment + + if frappe.flags.in_test: + therapy_session.start_date = today() + return therapy_session.as_dict() + + +@frappe.whitelist() +def make_sales_invoice(reference_name, patient, company, therapy_plan_template): + from erpnext.stock.get_item_details import get_item_details + + si = frappe.new_doc("Sales Invoice") + si.company = company + si.patient = patient + si.customer = frappe.db.get_value("Patient", patient, "customer") + + item = frappe.db.get_value("Therapy Plan Template", therapy_plan_template, "linked_item") + price_list, price_list_currency = frappe.db.get_values( + "Price List", {"selling": 1}, ["name", "currency"] + )[0] + args = { + "doctype": "Sales Invoice", + "item_code": item, + "company": company, + "customer": si.customer, + "selling_price_list": price_list, + "price_list_currency": price_list_currency, + "plc_conversion_rate": 1.0, + "conversion_rate": 1.0, + } + + item_line = si.append("items", {}) + item_details = get_item_details(args) + item_line.item_code = item + item_line.qty = 1 + item_line.rate = item_details.price_list_rate + item_line.amount = flt(item_line.rate) * flt(item_line.qty) + item_line.reference_dt = "Therapy Plan" + item_line.reference_dn = reference_name + item_line.description = item_details.description + + si.set_missing_values(for_validate=True) + return si diff --git a/healthcare/healthcare/doctype/therapy_plan/therapy_plan_dashboard.py b/healthcare/healthcare/doctype/therapy_plan/therapy_plan_dashboard.py new file mode 100644 index 0000000..65eb787 --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_plan/therapy_plan_dashboard.py @@ -0,0 +1,13 @@ +from frappe import _ + + +def get_data(): + return { + "fieldname": "therapy_plan", + "non_standard_fieldnames": {"Sales Invoice": "reference_dn"}, + "transactions": [ + {"label": _("Therapy Sessions"), "items": ["Therapy Session"]}, + {"label": _("Billing"), "items": ["Sales Invoice"]}, + ], + "disable_create_buttons": ["Sales Invoice"], + } diff --git a/healthcare/healthcare/doctype/therapy_plan/therapy_plan_list.js b/healthcare/healthcare/doctype/therapy_plan/therapy_plan_list.js new file mode 100644 index 0000000..63967af --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_plan/therapy_plan_list.js @@ -0,0 +1,11 @@ +frappe.listview_settings['Therapy Plan'] = { + get_indicator: function(doc) { + var colors = { + 'Completed': 'green', + 'In Progress': 'orange', + 'Not Started': 'red', + 'Cancelled': 'grey' + }; + return [__(doc.status), colors[doc.status], 'status,=,' + doc.status]; + } +}; diff --git a/healthcare/healthcare/doctype/therapy_plan_detail/__init__.py b/healthcare/healthcare/doctype/therapy_plan_detail/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/therapy_plan_detail/therapy_plan_detail.json b/healthcare/healthcare/doctype/therapy_plan_detail/therapy_plan_detail.json new file mode 100644 index 0000000..77f08af --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_plan_detail/therapy_plan_detail.json @@ -0,0 +1,49 @@ +{ + "actions": [], + "creation": "2020-03-29 20:52:57.068731", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "therapy_type", + "no_of_sessions", + "sessions_completed" + ], + "fields": [ + { + "fieldname": "therapy_type", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Therapy Type", + "options": "Therapy Type", + "reqd": 1 + }, + { + "fieldname": "no_of_sessions", + "fieldtype": "Int", + "in_list_view": 1, + "label": "No of Sessions" + }, + { + "default": "0", + "depends_on": "eval:doc.parenttype=='Therapy Plan';", + "fieldname": "sessions_completed", + "fieldtype": "Int", + "label": "Sessions Completed", + "no_copy": 1, + "read_only": 1 + } + ], + "istable": 1, + "links": [], + "modified": "2020-11-04 18:15:52.173450", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Therapy Plan Detail", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/therapy_plan_detail/therapy_plan_detail.py b/healthcare/healthcare/doctype/therapy_plan_detail/therapy_plan_detail.py new file mode 100644 index 0000000..46aaa6f --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_plan_detail/therapy_plan_detail.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class TherapyPlanDetail(Document): + pass diff --git a/healthcare/healthcare/doctype/therapy_plan_template/__init__.py b/healthcare/healthcare/doctype/therapy_plan_template/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/therapy_plan_template/test_therapy_plan_template.py b/healthcare/healthcare/doctype/therapy_plan_template/test_therapy_plan_template.py new file mode 100644 index 0000000..70c0d5b --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_plan_template/test_therapy_plan_template.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# See license.txt + + +# import frappe +from frappe.tests.utils import FrappeTestCase + + +class TestTherapyPlanTemplate(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/therapy_plan_template/therapy_plan_template.js b/healthcare/healthcare/doctype/therapy_plan_template/therapy_plan_template.js new file mode 100644 index 0000000..90c4b61 --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_plan_template/therapy_plan_template.js @@ -0,0 +1,87 @@ +// Copyright (c) 2020, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Therapy Plan Template', { + refresh: function(frm) { + frm.set_query('therapy_type', 'therapy_types', () => { + return { + filters: { + 'is_billable': 1 + } + }; + }); + + frm.set_query('linked_item', function() { + return { + filters: { + 'disabled': false, + 'is_stock_item': false + } + }; + }); + }, + + set_totals: function (frm) { + let total_sessions = 0; + let total_amount = 0.0; + frm.doc.therapy_types.forEach((d) => { + if (d.no_of_sessions) total_sessions += cint(d.no_of_sessions); + if (d.amount) total_amount += flt(d.amount); + }); + frm.set_value('total_sessions', total_sessions); + frm.set_value('total_amount', total_amount); + frm.refresh_fields(); + }, + + link_existing_item: function (frm) { + if (frm.doc.link_existing_item) { + frm.set_value('item_code', ''); + } else { + frm.set_value('linked_item', ''); + } + }, + + linked_item: function (frm) { + if (frm.doc.linked_item) { + frappe.db.get_value('Item', frm.doc.linked_item, ['item_group', 'description', 'item_name']) + .then(r => { + frm.set_value({ + 'item_group': r.message.item_group, + 'description': r.message.description, + 'item_name': r.message.item_name + }); + }) + } + } +}); + +frappe.ui.form.on('Therapy Plan Template Detail', { + therapy_type: function(frm, cdt, cdn) { + let row = locals[cdt][cdn]; + frappe.call('frappe.client.get', { + doctype: 'Therapy Type', + name: row.therapy_type + }).then((res) => { + row.rate = res.message.rate; + if (!row.no_of_sessions) + row.no_of_sessions = 1; + row.amount = flt(row.rate) * cint(row.no_of_sessions); + frm.refresh_field('therapy_types'); + frm.trigger('set_totals'); + }); + }, + + no_of_sessions: function(frm, cdt, cdn) { + let row = locals[cdt][cdn]; + row.amount = flt(row.rate) * cint(row.no_of_sessions); + frm.refresh_field('therapy_types'); + frm.trigger('set_totals'); + }, + + rate: function(frm, cdt, cdn) { + let row = locals[cdt][cdn]; + row.amount = flt(row.rate) * cint(row.no_of_sessions); + frm.refresh_field('therapy_types'); + frm.trigger('set_totals'); + } +}); diff --git a/healthcare/healthcare/doctype/therapy_plan_template/therapy_plan_template.json b/healthcare/healthcare/doctype/therapy_plan_template/therapy_plan_template.json new file mode 100644 index 0000000..9c46be3 --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_plan_template/therapy_plan_template.json @@ -0,0 +1,149 @@ +{ + "actions": [], + "autoname": "field:plan_name", + "creation": "2022-01-21 19:58:31.906990", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "plan_name", + "linked_item_details_section", + "link_existing_item", + "linked_item", + "item_code", + "item_name", + "item_group", + "column_break_6", + "description", + "therapy_types_section", + "therapy_types", + "section_break_11", + "total_sessions", + "column_break_13", + "total_amount" + ], + "fields": [ + { + "fieldname": "plan_name", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Plan Name", + "reqd": 1, + "unique": 1 + }, + { + "fieldname": "therapy_types_section", + "fieldtype": "Section Break", + "label": "Therapy Types" + }, + { + "fieldname": "therapy_types", + "fieldtype": "Table", + "label": "Therapy Types", + "options": "Therapy Plan Template Detail", + "reqd": 1 + }, + { + "depends_on": "eval: !doc.__islocal || doc.link_existing_item", + "fieldname": "linked_item", + "fieldtype": "Link", + "label": "Item", + "mandatory_depends_on": "eval:doc.link_existing_item", + "options": "Item", + "read_only_depends_on": "eval: !doc.__islocal" + }, + { + "fieldname": "linked_item_details_section", + "fieldtype": "Section Break", + "label": "Linked Item Details" + }, + { + "depends_on": "eval:!doc.link_existing_item || !doc.__islocal", + "fieldname": "item_code", + "fieldtype": "Data", + "label": "Item Code", + "mandatory_depends_on": "eval:!doc.link_existing_item", + "read_only_depends_on": "eval: !doc.__islocal", + "set_only_once": 1 + }, + { + "fieldname": "item_name", + "fieldtype": "Data", + "label": "Item Name", + "read_only_depends_on": "eval:doc.link_existing_item", + "reqd": 1 + }, + { + "fieldname": "item_group", + "fieldtype": "Link", + "label": "Item Group", + "options": "Item Group", + "read_only_depends_on": "eval:doc.link_existing_item", + "reqd": 1 + }, + { + "fieldname": "column_break_6", + "fieldtype": "Column Break" + }, + { + "fieldname": "description", + "fieldtype": "Small Text", + "label": "Item Description", + "read_only_depends_on": "eval:doc.link_existing_item" + }, + { + "fieldname": "total_amount", + "fieldtype": "Currency", + "label": "Total Amount", + "read_only": 1 + }, + { + "fieldname": "section_break_11", + "fieldtype": "Section Break" + }, + { + "fieldname": "total_sessions", + "fieldtype": "Int", + "label": "Total Sessions", + "read_only": 1 + }, + { + "fieldname": "column_break_13", + "fieldtype": "Column Break" + }, + { + "default": "0", + "depends_on": "eval: doc.__islocal", + "fieldname": "link_existing_item", + "fieldtype": "Check", + "label": "Link existing Item" + } + ], + "index_web_pages_for_search": 1, + "links": [], + "modified": "2022-05-31 16:37:04.658515", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Therapy Plan Template", + "naming_rule": "By fieldname", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "states": [], + "track_changes": 1 +} diff --git a/healthcare/healthcare/doctype/therapy_plan_template/therapy_plan_template.py b/healthcare/healthcare/doctype/therapy_plan_template/therapy_plan_template.py new file mode 100644 index 0000000..f2f1d71 --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_plan_template/therapy_plan_template.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +import frappe +from frappe.model.document import Document +from frappe.utils import cint, flt + +from healthcare.healthcare.doctype.therapy_type.therapy_type import make_item_price + + +class TherapyPlanTemplate(Document): + def after_insert(self): + if not self.link_existing_item: + self.create_item_from_template() + elif self.linked_item and self.total_amount: + make_item_price(self.linked_item, self.total_amount) + + def validate(self): + self.set_totals() + + def on_update(self): + doc_before_save = self.get_doc_before_save() + if not doc_before_save: + return + if ( + doc_before_save.item_name != self.item_name + or doc_before_save.item_group != self.item_group + or doc_before_save.description != self.description + ): + self.update_item() + + if doc_before_save.therapy_types != self.therapy_types: + self.update_item_price() + + def set_totals(self): + total_sessions = 0 + total_amount = 0 + + for entry in self.therapy_types: + total_sessions += cint(entry.no_of_sessions) + total_amount += flt(entry.amount) + + self.total_sessions = total_sessions + self.total_amount = total_amount + + def create_item_from_template(self): + uom = frappe.db.exists("UOM", "Nos") or frappe.db.get_single_value("Stock Settings", "stock_uom") + + item = frappe.get_doc( + { + "doctype": "Item", + "item_code": self.item_code, + "item_name": self.item_name, + "item_group": self.item_group, + "description": self.description, + "is_sales_item": 1, + "is_service_item": 1, + "is_purchase_item": 0, + "is_stock_item": 0, + "show_in_website": 0, + "is_pro_applicable": 0, + "stock_uom": uom, + } + ).insert(ignore_permissions=True, ignore_mandatory=True) + + make_item_price(item.name, self.total_amount) + self.db_set("linked_item", item.name) + + def update_item(self): + item_doc = frappe.get_doc("Item", {"item_code": self.linked_item}) + item_doc.item_name = self.item_name + item_doc.item_group = self.item_group + item_doc.description = self.description + item_doc.ignore_mandatory = True + item_doc.save(ignore_permissions=True) + + def update_item_price(self): + item_price = frappe.get_doc("Item Price", {"item_code": self.linked_item}) + item_price.item_name = self.item_name + item_price.price_list_rate = self.total_amount + item_price.ignore_mandatory = True + item_price.save(ignore_permissions=True) diff --git a/healthcare/healthcare/doctype/therapy_plan_template/therapy_plan_template_dashboard.py b/healthcare/healthcare/doctype/therapy_plan_template/therapy_plan_template_dashboard.py new file mode 100644 index 0000000..7c23ae8 --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_plan_template/therapy_plan_template_dashboard.py @@ -0,0 +1,8 @@ +from frappe import _ + + +def get_data(): + return { + "fieldname": "therapy_plan_template", + "transactions": [{"label": _("Therapy Plans"), "items": ["Therapy Plan"]}], + } diff --git a/healthcare/healthcare/doctype/therapy_plan_template_detail/__init__.py b/healthcare/healthcare/doctype/therapy_plan_template_detail/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/therapy_plan_template_detail/therapy_plan_template_detail.json b/healthcare/healthcare/doctype/therapy_plan_template_detail/therapy_plan_template_detail.json new file mode 100644 index 0000000..5553a11 --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_plan_template_detail/therapy_plan_template_detail.json @@ -0,0 +1,54 @@ +{ + "actions": [], + "creation": "2020-10-07 23:04:44.373381", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "therapy_type", + "no_of_sessions", + "rate", + "amount" + ], + "fields": [ + { + "fieldname": "therapy_type", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Therapy Type", + "options": "Therapy Type", + "reqd": 1 + }, + { + "fieldname": "no_of_sessions", + "fieldtype": "Int", + "in_list_view": 1, + "label": "No of Sessions" + }, + { + "fieldname": "rate", + "fieldtype": "Currency", + "in_list_view": 1, + "label": "Rate" + }, + { + "fieldname": "amount", + "fieldtype": "Currency", + "in_list_view": 1, + "label": "Amount", + "read_only": 1 + } + ], + "istable": 1, + "links": [], + "modified": "2020-10-07 23:46:54.296322", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Therapy Plan Template Detail", + "owner": "Administrator", + "permissions": [], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/therapy_plan_template_detail/therapy_plan_template_detail.py b/healthcare/healthcare/doctype/therapy_plan_template_detail/therapy_plan_template_detail.py new file mode 100644 index 0000000..2225a2c --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_plan_template_detail/therapy_plan_template_detail.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +# import frappe +from frappe.model.document import Document + + +class TherapyPlanTemplateDetail(Document): + pass diff --git a/healthcare/healthcare/doctype/therapy_session/__init__.py b/healthcare/healthcare/doctype/therapy_session/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/therapy_session/test_therapy_session.py b/healthcare/healthcare/doctype/therapy_session/test_therapy_session.py new file mode 100644 index 0000000..caa29cc --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_session/test_therapy_session.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +import frappe +from frappe.utils import nowdate + + +class TestTherapySession(FrappeTestCase): + pass + + +def create_therapy_session(patient, therapy_type, therapy_plan, duration=0, start_date=None): + if not start_date: + start_date = nowdate() + therapy_session = frappe.new_doc("Therapy Session") + therapy_session.patient = patient + therapy_session.therapy_type = therapy_type + therapy_session.therapy_plan = therapy_plan + therapy_session.duration = duration + therapy_session.start_date = start_date + therapy_session.save() + + return therapy_session diff --git a/healthcare/healthcare/doctype/therapy_session/therapy_session.js b/healthcare/healthcare/doctype/therapy_session/therapy_session.js new file mode 100644 index 0000000..6338749 --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_session/therapy_session.js @@ -0,0 +1,171 @@ +// Copyright (c) 2020, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Therapy Session', { + setup: function(frm) { + frm.get_field('exercises').grid.editable_fields = [ + {fieldname: 'exercise_type', columns: 7}, + {fieldname: 'counts_target', columns: 1}, + {fieldname: 'counts_completed', columns: 1}, + {fieldname: 'assistance_level', columns: 1} + ]; + + frm.set_query('service_unit', function() { + return { + filters: { + 'is_group': false, + 'allow_appointments': true, + 'company': frm.doc.company + } + }; + }); + + frm.set_query('appointment', function() { + + return { + filters: { + 'status': ['in', ['Open', 'Scheduled']] + } + }; + }); + }, + + refresh: function(frm) { + if (frm.doc.therapy_plan) { + frm.trigger('filter_therapy_types'); + } + + if (!frm.doc.__islocal) { + frm.dashboard.add_indicator(__('Counts Targeted: {0}', [frm.doc.total_counts_targeted]), 'blue'); + frm.dashboard.add_indicator(__('Counts Completed: {0}', [frm.doc.total_counts_completed]), + (frm.doc.total_counts_completed < frm.doc.total_counts_targeted) ? 'orange' : 'green'); + } + + if (frm.doc.docstatus === 1) { + frm.add_custom_button(__('Patient Assessment'), function() { + frappe.model.open_mapped_doc({ + method: 'healthcare.healthcare.doctype.patient_assessment.patient_assessment.create_patient_assessment', + frm: frm, + }) + }, 'Create'); + + frappe.db.get_value('Therapy Plan', {'name': frm.doc.therapy_plan}, 'therapy_plan_template', (r) => { + if (r && !r.therapy_plan_template) { + frm.add_custom_button(__('Sales Invoice'), function() { + frappe.model.open_mapped_doc({ + method: 'healthcare.healthcare.doctype.therapy_session.therapy_session.invoice_therapy_session', + frm: frm, + }); + }, 'Create'); + } + }); + } + }, + + therapy_plan: function(frm) { + if (frm.doc.therapy_plan) { + frm.trigger('filter_therapy_types'); + } + }, + + filter_therapy_types: function(frm) { + frappe.call({ + 'method': 'frappe.client.get', + args: { + doctype: 'Therapy Plan', + name: frm.doc.therapy_plan + }, + callback: function(data) { + let therapy_types = (data.message.therapy_plan_details || []).map(function(d){ return d.therapy_type; }); + frm.set_query('therapy_type', function() { + return { + filters: { 'therapy_type': ['in', therapy_types]} + }; + }); + } + }); + }, + + patient: function(frm) { + if (frm.doc.patient) { + frappe.call({ + 'method': 'healthcare.healthcare.doctype.patient.patient.get_patient_detail', + args: { + patient: frm.doc.patient + }, + callback: function (data) { + let age = ''; + if (data.message.dob) { + age = calculate_age(data.message.dob); + } else if (data.message.age) { + age = data.message.age; + if (data.message.age_as_on) { + age = __('{0} as on {1}', [age, data.message.age_as_on]); + } + } + frm.set_value('patient_age', age); + frm.set_value('gender', data.message.sex); + frm.set_value('patient_name', data.message.patient_name); + } + }); + } else { + frm.set_value('patient_age', ''); + frm.set_value('gender', ''); + frm.set_value('patient_name', ''); + } + }, + + appointment: function(frm) { + if (frm.doc.appointment) { + frappe.call({ + 'method': 'frappe.client.get', + args: { + doctype: 'Patient Appointment', + name: frm.doc.appointment + }, + callback: function(data) { + let values = { + 'patient':data.message.patient, + 'therapy_type': data.message.therapy_type, + 'therapy_plan': data.message.therapy_plan, + 'practitioner': data.message.practitioner, + 'department': data.message.department, + 'start_date': data.message.appointment_date, + 'start_time': data.message.appointment_time, + 'service_unit': data.message.service_unit, + 'company': data.message.company, + 'duration': data.message.duration + }; + frm.set_value(values); + } + }); + } + }, + + therapy_type: function(frm) { + if (frm.doc.therapy_type) { + frappe.call({ + 'method': 'frappe.client.get', + args: { + doctype: 'Therapy Type', + name: frm.doc.therapy_type + }, + callback: function(data) { + frm.set_value('duration', data.message.default_duration); + frm.set_value('rate', data.message.rate); + frm.set_value('service_unit', data.message.healthcare_service_unit); + frm.set_value('department', data.message.medical_department); + frm.doc.exercises = []; + $.each(data.message.exercises, function(_i, e) { + let exercise = frm.add_child('exercises'); + exercise.exercise_type = e.exercise_type; + exercise.difficulty_level = e.difficulty_level; + exercise.counts_target = e.counts_target; + exercise.assistance_level = e.assistance_level; + }); + refresh_field('exercises'); + } + }); + } + } +}); diff --git a/healthcare/healthcare/doctype/therapy_session/therapy_session.json b/healthcare/healthcare/doctype/therapy_session/therapy_session.json new file mode 100644 index 0000000..c57b9bf --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_session/therapy_session.json @@ -0,0 +1,270 @@ +{ + "actions": [], + "autoname": "naming_series:", + "creation": "2020-03-11 08:57:40.669857", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "naming_series", + "appointment", + "patient", + "patient_name", + "patient_age", + "gender", + "column_break_5", + "company", + "therapy_plan", + "therapy_type", + "practitioner", + "department", + "details_section", + "medical_code", + "duration", + "rate", + "location", + "column_break_12", + "service_unit", + "start_date", + "start_time", + "invoiced", + "exercises_section", + "exercises", + "section_break_23", + "total_counts_targeted", + "column_break_25", + "total_counts_completed", + "amended_from" + ], + "fields": [ + { + "fieldname": "naming_series", + "fieldtype": "Select", + "label": "Series", + "options": "HLC-THP-.YYYY.-" + }, + { + "fieldname": "appointment", + "fieldtype": "Link", + "label": "Appointment", + "options": "Patient Appointment", + "set_only_once": 1 + }, + { + "fieldname": "patient", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Patient", + "options": "Patient", + "reqd": 1 + }, + { + "fetch_from": "patient.sex", + "fieldname": "gender", + "fieldtype": "Link", + "label": "Gender", + "options": "Gender", + "read_only": 1 + }, + { + "fieldname": "column_break_5", + "fieldtype": "Column Break" + }, + { + "fieldname": "practitioner", + "fieldtype": "Link", + "label": "Healthcare Practitioner", + "options": "Healthcare Practitioner" + }, + { + "fieldname": "department", + "fieldtype": "Link", + "label": "Medical Department", + "options": "Medical Department" + }, + { + "fieldname": "details_section", + "fieldtype": "Section Break", + "label": "Details" + }, + { + "fetch_from": "therapy_template.default_duration", + "fieldname": "duration", + "fieldtype": "Int", + "label": "Duration", + "reqd": 1 + }, + { + "fieldname": "location", + "fieldtype": "Select", + "label": "Location", + "options": "\nCenter\nHome\nTele" + }, + { + "fieldname": "column_break_12", + "fieldtype": "Column Break" + }, + { + "fetch_from": "therapy_template.rate", + "fieldname": "rate", + "fieldtype": "Currency", + "label": "Rate" + }, + { + "fieldname": "exercises_section", + "fieldtype": "Section Break", + "label": "Exercises" + }, + { + "fieldname": "exercises", + "fieldtype": "Table", + "label": "Exercises", + "options": "Exercise" + }, + { + "depends_on": "eval: doc.therapy_plan", + "fieldname": "therapy_type", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Therapy Type", + "options": "Therapy Type", + "reqd": 1 + }, + { + "fieldname": "therapy_plan", + "fieldtype": "Link", + "label": "Therapy Plan", + "options": "Therapy Plan", + "reqd": 1, + "set_only_once": 1 + }, + { + "fieldname": "amended_from", + "fieldtype": "Link", + "label": "Amended From", + "no_copy": 1, + "options": "Therapy Session", + "print_hide": 1, + "read_only": 1 + }, + { + "fieldname": "service_unit", + "fieldtype": "Link", + "label": "Healthcare Service Unit", + "options": "Healthcare Service Unit" + }, + { + "fieldname": "start_date", + "fieldtype": "Date", + "label": "Start Date", + "reqd": 1 + }, + { + "fieldname": "start_time", + "fieldtype": "Time", + "label": "Start Time" + }, + { + "fieldname": "company", + "fieldtype": "Link", + "label": "Company", + "options": "Company", + "reqd": 1 + }, + { + "default": "0", + "fieldname": "invoiced", + "fieldtype": "Check", + "label": "Invoiced", + "read_only": 1 + }, + { + "fieldname": "patient_age", + "fieldtype": "Data", + "label": "Patient Age", + "read_only": 1 + }, + { + "fieldname": "total_counts_targeted", + "fieldtype": "Int", + "label": "Total Counts Targeted", + "read_only": 1 + }, + { + "fieldname": "total_counts_completed", + "fieldtype": "Int", + "label": "Total Counts Completed", + "no_copy": 1, + "read_only": 1 + }, + { + "fieldname": "section_break_23", + "fieldtype": "Section Break" + }, + { + "fieldname": "column_break_25", + "fieldtype": "Column Break" + }, + { + "fetch_from": "patient.patient_name", + "fieldname": "patient_name", + "fieldtype": "Data", + "label": "Patient Name", + "read_only": 1 + }, + { + "fetch_from": "therapy_type.medical_code", + "fieldname": "medical_code", + "fieldtype": "Link", + "label": "Medical Code", + "options": "Medical Code", + "read_only": 1 + } + ], + "is_submittable": 1, + "links": [ + { + "link_doctype": "Nursing Task", + "link_fieldname": "reference_name" + } + ], + "modified": "2022-01-17 15:11:07.822895", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Therapy Session", + "naming_rule": "By \"Naming Series\" field", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + }, + { + "cancel": 1, + "create": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "submit": 1, + "write": 1 + } + ], + "quick_entry": 1, + "search_fields": "patient,appointment,therapy_plan,therapy_type", + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "patient", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/therapy_session/therapy_session.py b/healthcare/healthcare/doctype/therapy_session/therapy_session.py new file mode 100644 index 0000000..1da96da --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_session/therapy_session.py @@ -0,0 +1,191 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +import datetime + +import frappe +from frappe import _ +from frappe.model.document import Document +from frappe.model.mapper import get_mapped_doc +from frappe.utils import flt, get_link_to_form, get_time, getdate + +from healthcare.healthcare.doctype.healthcare_settings.healthcare_settings import ( + get_income_account, + get_receivable_account, +) +from healthcare.healthcare.doctype.nursing_task.nursing_task import NursingTask +from healthcare.healthcare.utils import validate_nursing_tasks + + +class TherapySession(Document): + def validate(self): + self.validate_duplicate() + self.set_total_counts() + + def validate_duplicate(self): + end_time = datetime.datetime.combine( + getdate(self.start_date), get_time(self.start_time) + ) + datetime.timedelta(minutes=flt(self.duration)) + + overlaps = frappe.db.sql( + """ + select + name + from + `tabTherapy Session` + where + start_date=%s and name!=%s and docstatus!=2 + and (practitioner=%s or patient=%s) and + ((start_time<%s and start_time + INTERVAL duration MINUTE>%s) or + (start_time>%s and start_time<%s) or + (start_time=%s)) + """, + ( + self.start_date, + self.name, + self.practitioner, + self.patient, + self.start_time, + end_time.time(), + self.start_time, + end_time.time(), + self.start_time, + ), + ) + + if overlaps: + overlapping_details = _("Therapy Session overlaps with {0}").format( + get_link_to_form("Therapy Session", overlaps[0][0]) + ) + frappe.throw(overlapping_details, title=_("Therapy Sessions Overlapping")) + + def on_submit(self): + validate_nursing_tasks(self) + self.update_sessions_count_in_therapy_plan() + + def on_update(self): + if self.appointment: + frappe.db.set_value("Patient Appointment", self.appointment, "status", "Closed") + + def on_cancel(self): + if self.appointment: + frappe.db.set_value("Patient Appointment", self.appointment, "status", "Open") + + self.update_sessions_count_in_therapy_plan(on_cancel=True) + + def after_insert(self): + self.create_nursing_tasks(post_event=False) + + def create_nursing_tasks(self, post_event=True): + template = frappe.db.get_value("Therapy Type", self.therapy_type, "nursing_checklist_template") + if template: + NursingTask.create_nursing_tasks_from_template( + template, + self, + start_time=frappe.utils.get_datetime(f"{self.start_date} {self.start_time}"), + post_event=post_event, + ) + + def update_sessions_count_in_therapy_plan(self, on_cancel=False): + therapy_plan = frappe.get_doc("Therapy Plan", self.therapy_plan) + for entry in therapy_plan.therapy_plan_details: + if entry.therapy_type == self.therapy_type: + if on_cancel: + entry.sessions_completed -= 1 + else: + entry.sessions_completed += 1 + therapy_plan.save() + + def set_total_counts(self): + target_total = 0 + counts_completed = 0 + for entry in self.exercises: + if entry.counts_target: + target_total += entry.counts_target + if entry.counts_completed: + counts_completed += entry.counts_completed + + self.db_set("total_counts_targeted", target_total) + self.db_set("total_counts_completed", counts_completed) + + +@frappe.whitelist() +def create_therapy_session(source_name, target_doc=None): + def set_missing_values(source, target): + therapy_type = frappe.get_doc("Therapy Type", source.therapy_type) + target.exercises = therapy_type.exercises + + doc = get_mapped_doc( + "Patient Appointment", + source_name, + { + "Patient Appointment": { + "doctype": "Therapy Session", + "field_map": [ + ["appointment", "name"], + ["patient", "patient"], + ["patient_age", "patient_age"], + ["gender", "patient_sex"], + ["therapy_type", "therapy_type"], + ["therapy_plan", "therapy_plan"], + ["practitioner", "practitioner"], + ["department", "department"], + ["start_date", "appointment_date"], + ["start_time", "appointment_time"], + ["service_unit", "service_unit"], + ["company", "company"], + ["invoiced", "invoiced"], + ], + } + }, + target_doc, + set_missing_values, + ) + + return doc + + +@frappe.whitelist() +def invoice_therapy_session(source_name, target_doc=None): + def set_missing_values(source, target): + target.customer = frappe.db.get_value("Patient", source.patient, "customer") + target.due_date = getdate() + target.debit_to = get_receivable_account(source.company) + item = target.append("items", {}) + item = get_therapy_item(source, item) + target.set_missing_values(for_validate=True) + + doc = get_mapped_doc( + "Therapy Session", + source_name, + { + "Therapy Session": { + "doctype": "Sales Invoice", + "field_map": [ + ["patient", "patient"], + ["referring_practitioner", "practitioner"], + ["company", "company"], + ["due_date", "start_date"], + ], + } + }, + target_doc, + set_missing_values, + ) + + return doc + + +def get_therapy_item(therapy, item): + item.item_code = frappe.db.get_value("Therapy Type", therapy.therapy_type, "item") + item.description = _("Therapy Session Charges: {0}").format(therapy.practitioner) + item.income_account = get_income_account(therapy.practitioner, therapy.company) + item.cost_center = frappe.get_cached_value("Company", therapy.company, "cost_center") + item.rate = therapy.rate + item.amount = therapy.rate + item.qty = 1 + item.reference_dt = "Therapy Session" + item.reference_dn = therapy.name + return item diff --git a/healthcare/healthcare/doctype/therapy_session/therapy_session_dashboard.py b/healthcare/healthcare/doctype/therapy_session/therapy_session_dashboard.py new file mode 100644 index 0000000..9ceb0d7 --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_session/therapy_session_dashboard.py @@ -0,0 +1,8 @@ +from frappe import _ + + +def get_data(): + return { + "fieldname": "therapy_session", + "transactions": [{"label": _("Assessments"), "items": ["Patient Assessment"]}], + } diff --git a/healthcare/healthcare/doctype/therapy_type/__init__.py b/healthcare/healthcare/doctype/therapy_type/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/therapy_type/test_therapy_type.py b/healthcare/healthcare/doctype/therapy_type/test_therapy_type.py new file mode 100644 index 0000000..8619eab --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_type/test_therapy_type.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +import frappe + + +class TestTherapyType(FrappeTestCase): + def test_therapy_type_item(self): + therapy_type = create_therapy_type() + self.assertTrue(frappe.db.exists("Item", therapy_type.item)) + + therapy_type.disabled = 1 + therapy_type.save() + self.assertEqual(frappe.db.get_value("Item", therapy_type.item, "disabled"), 1) + + +def create_therapy_type(): + exercise = create_exercise_type() + therapy_type = frappe.db.exists("Therapy Type", "Basic Rehab") + if not therapy_type: + therapy_type = frappe.new_doc("Therapy Type") + therapy_type.therapy_type = "Basic Rehab" + therapy_type.default_duration = 30 + therapy_type.is_billable = 1 + therapy_type.rate = 5000 + therapy_type.item_code = "Basic Rehab" + therapy_type.item_name = "Basic Rehab" + therapy_type.item_group = "Services" + therapy_type.append( + "exercises", + {"exercise_type": exercise.name, "counts_target": 10, "assistance_level": "Passive"}, + ) + therapy_type.save() + else: + therapy_type = frappe.get_doc("Therapy Type", therapy_type) + + return therapy_type + + +def create_exercise_type(): + exercise_type = frappe.db.exists("Exercise Type", "Sit to Stand") + if not exercise_type: + exercise_type = frappe.new_doc("Exercise Type") + exercise_type.exercise_name = "Sit to Stand" + exercise_type.append("steps_table", {"title": "Step 1", "description": "Squat and Rise"}) + exercise_type.save() + else: + exercise_type = frappe.get_doc("Exercise Type", exercise_type) + + return exercise_type diff --git a/healthcare/healthcare/doctype/therapy_type/therapy_type.js b/healthcare/healthcare/doctype/therapy_type/therapy_type.js new file mode 100644 index 0000000..ae76343 --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_type/therapy_type.js @@ -0,0 +1,103 @@ +// Copyright (c) 2020, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Therapy Type', { + setup: function(frm) { + frm.get_field('exercises').grid.editable_fields = [ + {fieldname: 'exercise_type', columns: 7}, + {fieldname: 'difficulty_level', columns: 1}, + {fieldname: 'counts_target', columns: 1}, + {fieldname: 'assistance_level', columns: 1} + ]; + }, + + refresh: function(frm) { + if (!frm.doc.__islocal) { + cur_frm.add_custom_button(__('Change Item Code'), function() { + change_template_code(frm.doc); + }); + } + }, + + therapy_type: function(frm) { + if (!frm.doc.item_code) + frm.set_value('item_code', frm.doc.therapy_type); + if (!frm.doc.description) + frm.set_value('description', frm.doc.therapy_type); + mark_change_in_item(frm); + }, + + rate: function(frm) { + mark_change_in_item(frm); + }, + + is_billable: function (frm) { + mark_change_in_item(frm); + }, + + item_group: function(frm) { + mark_change_in_item(frm); + }, + + description: function(frm) { + mark_change_in_item(frm); + }, + + medical_department: function(frm) { + mark_change_in_item(frm); + }, + + medical_code: function(frm) { + frm.set_query("medical_code", function() { + return { + filters: { + medical_code_standard: frm.doc.medical_code_standard + } + }; + }); + } +}); + +let mark_change_in_item = function(frm) { + if (!frm.doc.__islocal) { + frm.doc.change_in_item = 1; + } +}; + +let change_template_code = function(doc) { + let d = new frappe.ui.Dialog({ + title:__('Change Item Code'), + fields:[ + { + 'fieldtype': 'Data', + 'label': 'Item Code', + 'fieldname': 'item_code', + reqd: 1 + } + ], + primary_action: function() { + let values = d.get_values(); + + if (values) { + frappe.call({ + 'method': 'healthcare.healthcare.doctype.therapy_type.therapy_type.change_item_code_from_therapy', + 'args': {item_code: values.item_code, doc: doc}, + callback: function () { + cur_frm.reload_doc(); + frappe.show_alert({ + message: 'Item Code renamed successfully', + indicator: 'green' + }); + } + }); + } + d.hide(); + }, + primary_action_label: __('Change Item Code') + }); + d.show(); + + d.set_values({ + 'item_code': doc.item_code + }); +}; diff --git a/healthcare/healthcare/doctype/therapy_type/therapy_type.json b/healthcare/healthcare/doctype/therapy_type/therapy_type.json new file mode 100644 index 0000000..32b4a18 --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_type/therapy_type.json @@ -0,0 +1,242 @@ +{ + "actions": [], + "autoname": "field:therapy_type", + "creation": "2020-03-29 20:48:31.715063", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "disabled", + "section_break_2", + "therapy_type", + "default_duration", + "medical_department", + "nursing_checklist_template", + "column_break_3", + "is_billable", + "rate", + "healthcare_service_unit", + "item_details_section", + "item", + "item_code", + "item_name", + "item_group", + "column_break_12", + "description", + "medical_coding_section", + "medical_code_standard", + "medical_code", + "section_break_18", + "therapy_for", + "add_exercises", + "section_break_6", + "exercises", + "change_in_item" + ], + "fields": [ + { + "fieldname": "therapy_type", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Therapy Type", + "reqd": 1, + "unique": 1 + }, + { + "fieldname": "column_break_3", + "fieldtype": "Column Break" + }, + { + "default": "0", + "fieldname": "is_billable", + "fieldtype": "Check", + "label": "Is Billable" + }, + { + "depends_on": "eval:doc.is_billable;", + "fieldname": "rate", + "fieldtype": "Currency", + "label": "Rate", + "mandatory_depends_on": "eval:doc.is_billable;" + }, + { + "fieldname": "section_break_6", + "fieldtype": "Section Break", + "label": "Exercises" + }, + { + "fieldname": "exercises", + "fieldtype": "Table", + "label": "Exercises", + "options": "Exercise" + }, + { + "fieldname": "default_duration", + "fieldtype": "Int", + "label": "Default Duration (In Minutes)" + }, + { + "default": "0", + "fieldname": "disabled", + "fieldtype": "Check", + "label": "Disabled" + }, + { + "fieldname": "item_details_section", + "fieldtype": "Section Break", + "label": "Item Details" + }, + { + "fieldname": "item", + "fieldtype": "Link", + "label": "Item", + "options": "Item", + "read_only": 1 + }, + { + "fieldname": "item_code", + "fieldtype": "Data", + "label": "Item Code", + "reqd": 1, + "set_only_once": 1 + }, + { + "fieldname": "item_group", + "fieldtype": "Link", + "label": "Item Group", + "options": "Item Group", + "reqd": 1 + }, + { + "fieldname": "item_name", + "fieldtype": "Data", + "label": "Item Name", + "reqd": 1 + }, + { + "fieldname": "column_break_12", + "fieldtype": "Column Break" + }, + { + "fieldname": "description", + "fieldtype": "Small Text", + "label": "Description" + }, + { + "fieldname": "section_break_2", + "fieldtype": "Section Break" + }, + { + "fieldname": "medical_department", + "fieldtype": "Link", + "label": "Medical Department", + "options": "Medical Department" + }, + { + "default": "0", + "fieldname": "change_in_item", + "fieldtype": "Check", + "hidden": 1, + "label": "Change In Item", + "print_hide": 1, + "read_only": 1, + "report_hide": 1 + }, + { + "fieldname": "therapy_for", + "fieldtype": "Table MultiSelect", + "label": "Therapy For", + "options": "Body Part Link" + }, + { + "fieldname": "healthcare_service_unit", + "fieldtype": "Link", + "label": "Healthcare Service Unit", + "options": "Healthcare Service Unit" + }, + { + "depends_on": "eval: doc.therapy_for", + "fieldname": "add_exercises", + "fieldtype": "Button", + "label": "Add Exercises", + "options": "add_exercises" + }, + { + "fieldname": "section_break_18", + "fieldtype": "Section Break" + }, + { + "collapsible": 1, + "fieldname": "medical_coding_section", + "fieldtype": "Section Break", + "label": "Medical Coding", + "options": "Medical Coding" + }, + { + "fieldname": "medical_code_standard", + "fieldtype": "Link", + "label": "Medical Code Standard", + "options": "Medical Code Standard" + }, + { + "depends_on": "medical_code_standard", + "fieldname": "medical_code", + "fieldtype": "Link", + "label": "Medical Code", + "options": "Medical Code" + }, + { + "fieldname": "nursing_checklist_template", + "fieldtype": "Link", + "label": "Nursing Checklist Template", + "options": "Nursing Checklist Template" + } + ], + "links": [], + "modified": "2022-01-17 14:45:27.792677", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Therapy Type", + "naming_rule": "By fieldname", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + }, + { + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "write": 1 + } + ], + "quick_entry": 1, + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/therapy_type/therapy_type.py b/healthcare/healthcare/doctype/therapy_type/therapy_type.py new file mode 100644 index 0000000..f55d872 --- /dev/null +++ b/healthcare/healthcare/doctype/therapy_type/therapy_type.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2020, InfluxERP +# For license information, please see license.txt + + +import json + +import frappe +from frappe import _ +from frappe.model.document import Document +from frappe.model.rename_doc import rename_doc +from frappe.utils import cint + + +class TherapyType(Document): + def validate(self): + self.enable_disable_item() + + def after_insert(self): + create_item_from_therapy(self) + + def on_update(self): + if self.change_in_item: + self.update_item_and_item_price() + + def enable_disable_item(self): + if self.is_billable: + if self.disabled: + frappe.db.set_value("Item", self.item, "disabled", 1) + else: + frappe.db.set_value("Item", self.item, "disabled", 0) + + def update_item_and_item_price(self): + if self.is_billable and self.item: + item_doc = frappe.get_doc("Item", {"item_code": self.item}) + item_doc.item_name = self.item_name + item_doc.item_group = self.item_group + item_doc.description = self.description + item_doc.disabled = 0 + item_doc.ignore_mandatory = True + item_doc.save(ignore_permissions=True) + + if self.rate: + item_price = frappe.get_doc("Item Price", {"item_code": self.item}) + item_price.item_name = self.item_name + item_price.price_list_rate = self.rate + item_price.ignore_mandatory = True + item_price.save() + + elif not self.is_billable and self.item: + frappe.db.set_value("Item", self.item, "disabled", 1) + + self.db_set("change_in_item", 0) + + @frappe.whitelist() + def add_exercises(self): + exercises = self.get_exercises_for_body_parts() + last_idx = max( + [cint(d.idx) for d in self.get("exercises")] + or [ + 0, + ] + ) + for i, d in enumerate(exercises): + ch = self.append("exercises", {}) + ch.exercise_type = d.parent + ch.idx = last_idx + i + 1 + + def get_exercises_for_body_parts(self): + body_parts = [entry.body_part for entry in self.therapy_for] + + exercises = frappe.db.sql( + """ + SELECT DISTINCT + b.parent, e.name, e.difficulty_level + FROM + `tabExercise Type` e, `tabBody Part Link` b + WHERE + b.body_part IN %(body_parts)s AND b.parent=e.name + """, + {"body_parts": body_parts}, + as_dict=1, + ) + + return exercises + + +def create_item_from_therapy(doc): + disabled = doc.disabled + if doc.is_billable and not doc.disabled: + disabled = 0 + + uom = frappe.db.exists("UOM", "Unit") or frappe.db.get_single_value("Stock Settings", "stock_uom") + + item = frappe.get_doc( + { + "doctype": "Item", + "item_code": doc.item_code, + "item_name": doc.item_name, + "item_group": doc.item_group, + "description": doc.description, + "is_sales_item": 1, + "is_service_item": 1, + "is_purchase_item": 0, + "is_stock_item": 0, + "show_in_website": 0, + "is_pro_applicable": 0, + "disabled": disabled, + "stock_uom": uom, + } + ).insert(ignore_permissions=True, ignore_mandatory=True) + + make_item_price(item.name, doc.rate) + doc.db_set("item", item.name) + + +def make_item_price(item, item_price): + price_list_name = frappe.db.get_value("Price List", {"selling": 1}) + frappe.get_doc( + { + "doctype": "Item Price", + "price_list": price_list_name, + "item_code": item, + "price_list_rate": item_price, + } + ).insert(ignore_permissions=True, ignore_mandatory=True) + + +@frappe.whitelist() +def change_item_code_from_therapy(item_code, doc): + doc = frappe._dict(json.loads(doc)) + + if frappe.db.exists("Item", {"item_code": item_code}): + frappe.throw(_("Item with Item Code {0} already exists").format(item_code)) + else: + rename_doc("Item", doc.item, item_code, ignore_permissions=True) + frappe.db.set_value("Therapy Type", doc.name, "item_code", item_code) + return diff --git a/healthcare/healthcare/doctype/treatment_plan_template/__init__.py b/healthcare/healthcare/doctype/treatment_plan_template/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/treatment_plan_template/test_records.json b/healthcare/healthcare/doctype/treatment_plan_template/test_records.json new file mode 100644 index 0000000..d661b43 --- /dev/null +++ b/healthcare/healthcare/doctype/treatment_plan_template/test_records.json @@ -0,0 +1,7 @@ +[ + { + "doctype": "Treatment Plan Template", + "template_name": "Chemo", + "patient_age_from": 21 + } +] diff --git a/healthcare/healthcare/doctype/treatment_plan_template/test_treatment_plan_template.py b/healthcare/healthcare/doctype/treatment_plan_template/test_treatment_plan_template.py new file mode 100644 index 0000000..12ed8d5 --- /dev/null +++ b/healthcare/healthcare/doctype/treatment_plan_template/test_treatment_plan_template.py @@ -0,0 +1,9 @@ +# Copyright (c) 2021, InfluxERP +# See license.txt + +# import frappe +from frappe.tests.utils import FrappeTestCase + + +class TestTreatmentPlanTemplate(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/treatment_plan_template/treatment_plan_template.js b/healthcare/healthcare/doctype/treatment_plan_template/treatment_plan_template.js new file mode 100644 index 0000000..e8de9ab --- /dev/null +++ b/healthcare/healthcare/doctype/treatment_plan_template/treatment_plan_template.js @@ -0,0 +1,14 @@ +// Copyright (c) 2021, InfluxERP +// For license information, please see license.txt + +frappe.ui.form.on('Treatment Plan Template', { + refresh: function (frm) { + frm.set_query('type', 'items', function () { + return { + filters: { + 'name': ['in', ['Lab Test Template', 'Clinical Procedure Template', 'Therapy Type']], + } + }; + }); + }, +}); diff --git a/healthcare/healthcare/doctype/treatment_plan_template/treatment_plan_template.json b/healthcare/healthcare/doctype/treatment_plan_template/treatment_plan_template.json new file mode 100644 index 0000000..85a312f --- /dev/null +++ b/healthcare/healthcare/doctype/treatment_plan_template/treatment_plan_template.json @@ -0,0 +1,189 @@ +{ + "actions": [], + "autoname": "field:template_name", + "creation": "2021-06-10 10:14:17.901273", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "section_break_1", + "template_name", + "description", + "practitioners", + "disabled", + "column_break_1", + "medical_department", + "goal", + "order_group", + "section_break_8", + "patient_age_from", + "complaints", + "gender", + "column_break_12", + "patient_age_to", + "diagnosis", + "plan_items_section", + "items", + "drugs" + ], + "fields": [ + { + "fieldname": "section_break_1", + "fieldtype": "Section Break", + "label": "Plan Details" + }, + { + "fieldname": "medical_department", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Medical Department", + "options": "Medical Department" + }, + { + "fieldname": "description", + "fieldtype": "Small Text", + "label": "Description" + }, + { + "fieldname": "goal", + "fieldtype": "Small Text", + "label": "Goal" + }, + { + "fieldname": "practitioners", + "fieldtype": "Table MultiSelect", + "label": "Practitioners", + "options": "Treatment Plan Template Practitioner" + }, + { + "fieldname": "order_group", + "fieldtype": "Link", + "label": "Order Group", + "options": "Patient Encounter", + "read_only": 1 + }, + { + "fieldname": "section_break_8", + "fieldtype": "Section Break", + "label": "Plan Conditions" + }, + { + "fieldname": "template_name", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Template Name", + "reqd": 1, + "unique": 1 + }, + { + "fieldname": "patient_age_from", + "fieldtype": "Int", + "label": "Patient Age From", + "non_negative": 1 + }, + { + "fieldname": "column_break_12", + "fieldtype": "Column Break" + }, + { + "fieldname": "patient_age_to", + "fieldtype": "Int", + "label": "Patient Age To", + "non_negative": 1 + }, + { + "fieldname": "gender", + "fieldtype": "Link", + "label": "Gender", + "options": "Gender" + }, + { + "fieldname": "complaints", + "fieldtype": "Table MultiSelect", + "label": "Complaints", + "options": "Patient Encounter Symptom" + }, + { + "fieldname": "diagnosis", + "fieldtype": "Table MultiSelect", + "label": "Diagnosis", + "options": "Patient Encounter Diagnosis" + }, + { + "fieldname": "plan_items_section", + "fieldtype": "Section Break", + "label": "Plan Items" + }, + { + "fieldname": "items", + "fieldtype": "Table", + "label": "Items", + "options": "Treatment Plan Template Item" + }, + { + "fieldname": "drugs", + "fieldtype": "Table", + "label": "Drugs", + "options": "Drug Prescription" + }, + { + "default": "0", + "fieldname": "disabled", + "fieldtype": "Check", + "label": "Disabled" + }, + { + "fieldname": "column_break_1", + "fieldtype": "Column Break" + } + ], + "index_web_pages_for_search": 1, + "links": [], + "modified": "2021-08-18 02:41:58.354296", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Treatment Plan Template", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "write": 1 + }, + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Healthcare Administrator", + "share": 1, + "write": 1 + } + ], + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "template_name", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/treatment_plan_template/treatment_plan_template.py b/healthcare/healthcare/doctype/treatment_plan_template/treatment_plan_template.py new file mode 100644 index 0000000..093568e --- /dev/null +++ b/healthcare/healthcare/doctype/treatment_plan_template/treatment_plan_template.py @@ -0,0 +1,19 @@ +# Copyright (c) 2021, InfluxERP +# For license information, please see license.txt + +import frappe +from frappe import _ +from frappe.model.document import Document + + +class TreatmentPlanTemplate(Document): + def validate(self): + self.validate_age() + + def validate_age(self): + if self.patient_age_from and self.patient_age_from < 0: + frappe.throw(_("Patient Age From cannot be less than 0")) + if self.patient_age_to and self.patient_age_to < 0: + frappe.throw(_("Patient Age To cannot be less than 0")) + if self.patient_age_to and self.patient_age_from and self.patient_age_to < self.patient_age_from: + frappe.throw(_("Patient Age To cannot be less than Patient Age From")) diff --git a/healthcare/healthcare/doctype/treatment_plan_template/treatment_plan_template_list.js b/healthcare/healthcare/doctype/treatment_plan_template/treatment_plan_template_list.js new file mode 100644 index 0000000..7ab31df --- /dev/null +++ b/healthcare/healthcare/doctype/treatment_plan_template/treatment_plan_template_list.js @@ -0,0 +1,10 @@ +frappe.listview_settings['Treatment Plan Template'] = { + get_indicator: function(doc) { + var colors = { + 1: 'gray', + 0: 'blue', + }; + let label = doc.disabled == 1 ? 'Disabled' : 'Enabled'; + return [__(label), colors[doc.disabled], 'disable,=,' + doc.disabled]; + } +}; diff --git a/healthcare/healthcare/doctype/treatment_plan_template_item/__init__.py b/healthcare/healthcare/doctype/treatment_plan_template_item/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/treatment_plan_template_item/treatment_plan_template_item.json b/healthcare/healthcare/doctype/treatment_plan_template_item/treatment_plan_template_item.json new file mode 100644 index 0000000..20a9d67 --- /dev/null +++ b/healthcare/healthcare/doctype/treatment_plan_template_item/treatment_plan_template_item.json @@ -0,0 +1,55 @@ +{ + "actions": [], + "creation": "2021-06-10 11:47:29.194795", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "type", + "template", + "qty", + "instructions" + ], + "fields": [ + { + "fieldname": "type", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Type", + "options": "DocType", + "reqd": 1 + }, + { + "fieldname": "template", + "fieldtype": "Dynamic Link", + "in_list_view": 1, + "label": "Template", + "options": "type", + "reqd": 1 + }, + { + "default": "1", + "fieldname": "qty", + "fieldtype": "Int", + "label": "Qty" + }, + { + "fieldname": "instructions", + "fieldtype": "Small Text", + "in_list_view": 1, + "label": "Instructions" + } + ], + "index_web_pages_for_search": 1, + "istable": 1, + "links": [], + "modified": "2021-08-17 11:19:03.515441", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Treatment Plan Template Item", + "owner": "Administrator", + "permissions": [], + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/treatment_plan_template_item/treatment_plan_template_item.py b/healthcare/healthcare/doctype/treatment_plan_template_item/treatment_plan_template_item.py new file mode 100644 index 0000000..03ccfc9 --- /dev/null +++ b/healthcare/healthcare/doctype/treatment_plan_template_item/treatment_plan_template_item.py @@ -0,0 +1,9 @@ +# Copyright (c) 2021, InfluxERP +# For license information, please see license.txt + +# import frappe +from frappe.model.document import Document + + +class TreatmentPlanTemplateItem(Document): + pass diff --git a/healthcare/healthcare/doctype/treatment_plan_template_practitioner/__init__.py b/healthcare/healthcare/doctype/treatment_plan_template_practitioner/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/treatment_plan_template_practitioner/treatment_plan_template_practitioner.json b/healthcare/healthcare/doctype/treatment_plan_template_practitioner/treatment_plan_template_practitioner.json new file mode 100644 index 0000000..04da387 --- /dev/null +++ b/healthcare/healthcare/doctype/treatment_plan_template_practitioner/treatment_plan_template_practitioner.json @@ -0,0 +1,32 @@ +{ + "actions": [], + "creation": "2021-06-10 10:37:56.669416", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "practitioner" + ], + "fields": [ + { + "fieldname": "practitioner", + "fieldtype": "Link", + "in_list_view": 1, + "label": "Practitioner", + "options": "Healthcare Practitioner", + "reqd": 1 + } + ], + "index_web_pages_for_search": 1, + "istable": 1, + "links": [], + "modified": "2021-06-11 16:05:06.733299", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Treatment Plan Template Practitioner", + "owner": "Administrator", + "permissions": [], + "sort_field": "modified", + "sort_order": "DESC", + "track_changes": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/treatment_plan_template_practitioner/treatment_plan_template_practitioner.py b/healthcare/healthcare/doctype/treatment_plan_template_practitioner/treatment_plan_template_practitioner.py new file mode 100644 index 0000000..1269d0f --- /dev/null +++ b/healthcare/healthcare/doctype/treatment_plan_template_practitioner/treatment_plan_template_practitioner.py @@ -0,0 +1,9 @@ +# Copyright (c) 2021, InfluxERP +# For license information, please see license.txt + +# import frappe +from frappe.model.document import Document + + +class TreatmentPlanTemplatePractitioner(Document): + pass diff --git a/healthcare/healthcare/doctype/vital_signs/__init__.py b/healthcare/healthcare/doctype/vital_signs/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/doctype/vital_signs/test_vital_signs.py b/healthcare/healthcare/doctype/vital_signs/test_vital_signs.py new file mode 100644 index 0000000..b9cb358 --- /dev/null +++ b/healthcare/healthcare/doctype/vital_signs/test_vital_signs.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and Contributors +# See license.txt + + +from frappe.tests.utils import FrappeTestCase + +# test_records = frappe.get_test_records('Vital Signs') + + +class TestVitalSigns(FrappeTestCase): + pass diff --git a/healthcare/healthcare/doctype/vital_signs/vital_signs.js b/healthcare/healthcare/doctype/vital_signs/vital_signs.js new file mode 100644 index 0000000..b7a7d63 --- /dev/null +++ b/healthcare/healthcare/doctype/vital_signs/vital_signs.js @@ -0,0 +1,52 @@ +// Copyright (c) 2016, ESS LLP and contributors +// For license information, please see license.txt + +frappe.ui.form.on('Vital Signs', { + height: function(frm) { + if (frm.doc.height && frm.doc.weight) { + calculate_bmi(frm); + } + }, + + weight: function(frm) { + if (frm.doc.height && frm.doc.weight) { + calculate_bmi(frm); + } + }, + + bp_systolic: function(frm) { + if (frm.doc.bp_systolic && frm.doc.bp_diastolic) { + set_bp(frm); + } + }, + + bp_diastolic: function(frm) { + if (frm.doc.bp_systolic && frm.doc.bp_diastolic) { + set_bp(frm); + } + } +}); + +let calculate_bmi = function(frm){ + // Reference https://en.wikipedia.org/wiki/Body_mass_index + // bmi = weight (in Kg) / height * height (in Meter) + let bmi = (frm.doc.weight / (frm.doc.height * frm.doc.height)).toFixed(2); + let bmi_note = null; + + if (bmi<18.5) { + bmi_note = __('Underweight'); + } else if (bmi>=18.5 && bmi<25) { + bmi_note = __('Normal'); + } else if (bmi>=25 && bmi<30) { + bmi_note = __('Overweight'); + } else if (bmi>=30) { + bmi_note = __('Obese'); + } + frappe.model.set_value(frm.doctype,frm.docname, 'bmi', bmi); + frappe.model.set_value(frm.doctype,frm.docname, 'nutrition_note', bmi_note); +}; + +let set_bp = function(frm){ + let bp = frm.doc.bp_systolic+ '/' + frm.doc.bp_diastolic + ' mmHg'; + frappe.model.set_value(frm.doctype,frm.docname, 'bp', bp); +}; diff --git a/healthcare/healthcare/doctype/vital_signs/vital_signs.json b/healthcare/healthcare/doctype/vital_signs/vital_signs.json new file mode 100644 index 0000000..15ab504 --- /dev/null +++ b/healthcare/healthcare/doctype/vital_signs/vital_signs.json @@ -0,0 +1,305 @@ +{ + "actions": [], + "allow_copy": 1, + "allow_import": 1, + "autoname": "naming_series:", + "beta": 1, + "creation": "2017-02-02 11:00:24.853005", + "doctype": "DocType", + "editable_grid": 1, + "engine": "InnoDB", + "field_order": [ + "naming_series", + "title", + "patient", + "patient_name", + "inpatient_record", + "appointment", + "encounter", + "column_break_2", + "company", + "signs_date", + "signs_time", + "sb_vs", + "temperature", + "pulse", + "respiratory_rate", + "tongue", + "abdomen", + "column_break_8", + "reflexes", + "bp_systolic", + "bp_diastolic", + "bp", + "vital_signs_note", + "sb_nutrition_values", + "height", + "weight", + "bmi", + "column_break_14", + "nutrition_note", + "sb_references", + "amended_from" + ], + "fields": [ + { + "fetch_from": "patient.inpatient_record", + "fieldname": "inpatient_record", + "fieldtype": "Link", + "label": "Inpatient Record", + "options": "Inpatient Record", + "read_only": 1 + }, + { + "fetch_from": "inpatient_record.patient", + "fieldname": "patient", + "fieldtype": "Link", + "ignore_user_permissions": 1, + "in_list_view": 1, + "in_standard_filter": 1, + "label": "Patient", + "options": "Patient", + "reqd": 1 + }, + { + "fetch_from": "patient.patient_name", + "fieldname": "patient_name", + "fieldtype": "Data", + "label": "Patient Name", + "read_only": 1 + }, + { + "fieldname": "appointment", + "fieldtype": "Link", + "in_filter": 1, + "label": "Patient Appointment", + "no_copy": 1, + "options": "Patient Appointment", + "print_hide": 1, + "read_only": 1 + }, + { + "fieldname": "encounter", + "fieldtype": "Link", + "in_filter": 1, + "label": "Patient Encounter", + "no_copy": 1, + "options": "Patient Encounter", + "print_hide": 1, + "read_only": 1 + }, + { + "fieldname": "column_break_2", + "fieldtype": "Column Break" + }, + { + "default": "Today", + "fieldname": "signs_date", + "fieldtype": "Date", + "label": "Date", + "reqd": 1 + }, + { + "fieldname": "signs_time", + "fieldtype": "Time", + "label": "Time", + "reqd": 1 + }, + { + "fieldname": "sb_vs", + "fieldtype": "Section Break", + "label": "Vital Signs" + }, + { + "description": "Presence of a fever (temp > 38.5 \u00b0C/101.3 \u00b0F or sustained temp > 38 \u00b0C/100.4 \u00b0F)", + "fieldname": "temperature", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Body Temperature" + }, + { + "description": "Adults' pulse rate is anywhere between 50 and 80 beats per minute.", + "fieldname": "pulse", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Heart Rate / Pulse" + }, + { + "description": "Normal reference range for an adult is 16\u201320 breaths/minute (RCP 2012)", + "fieldname": "respiratory_rate", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Respiratory rate" + }, + { + "fieldname": "tongue", + "fieldtype": "Select", + "label": "Tongue", + "options": "\nCoated\nVery Coated\nNormal\nFurry\nCuts" + }, + { + "fieldname": "abdomen", + "fieldtype": "Select", + "label": "Abdomen", + "options": "\nNormal\nBloated\nFull\nFluid\nConstipated" + }, + { + "fieldname": "column_break_8", + "fieldtype": "Column Break" + }, + { + "fieldname": "reflexes", + "fieldtype": "Select", + "label": "Reflexes", + "options": "\nNormal\nHyper\nVery Hyper\nOne Sided" + }, + { + "fieldname": "bp_systolic", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Blood Pressure (systolic)" + }, + { + "fieldname": "bp_diastolic", + "fieldtype": "Data", + "ignore_xss_filter": 1, + "in_list_view": 1, + "label": "Blood Pressure (diastolic)" + }, + { + "description": "Normal resting blood pressure in an adult is approximately 120 mmHg systolic, and 80 mmHg diastolic, abbreviated \"120/80 mmHg\"", + "fieldname": "bp", + "fieldtype": "Data", + "label": "Blood Pressure", + "read_only": 1 + }, + { + "fieldname": "vital_signs_note", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Notes" + }, + { + "fieldname": "sb_nutrition_values", + "fieldtype": "Section Break", + "label": "Nutrition Values" + }, + { + "fieldname": "height", + "fieldtype": "Float", + "in_list_view": 1, + "label": "Height (In Meter)" + }, + { + "fieldname": "weight", + "fieldtype": "Float", + "in_list_view": 1, + "label": "Weight (In Kilogram)" + }, + { + "default": "0.00", + "fieldname": "bmi", + "fieldtype": "Float", + "in_list_view": 1, + "label": "BMI", + "read_only": 1 + }, + { + "fieldname": "column_break_14", + "fieldtype": "Column Break" + }, + { + "fieldname": "nutrition_note", + "fieldtype": "Small Text", + "ignore_xss_filter": 1, + "label": "Notes" + }, + { + "fieldname": "company", + "fieldtype": "Link", + "label": "Company", + "options": "Company" + }, + { + "fieldname": "amended_from", + "fieldtype": "Link", + "label": "Amended From", + "no_copy": 1, + "options": "Vital Signs", + "print_hide": 1, + "read_only": 1 + }, + { + "collapsible": 1, + "fieldname": "sb_references", + "fieldtype": "Section Break" + }, + { + "fieldname": "naming_series", + "fieldtype": "Select", + "label": "Series", + "options": "HLC-VTS-.YYYY.-", + "reqd": 1 + }, + { + "allow_on_submit": 1, + "columns": 5, + "fieldname": "title", + "fieldtype": "Data", + "hidden": 1, + "label": "Title", + "no_copy": 1, + "print_hide": 1, + "read_only": 1 + } + ], + "is_submittable": 1, + "links": [], + "modified": "2020-05-17 22:23:24.632286", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Vital Signs", + "owner": "Administrator", + "permissions": [ + { + "cancel": 1, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Physician", + "share": 1, + "submit": 1, + "write": 1 + }, + { + "cancel": 1, + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "Nursing User", + "share": 1, + "submit": 1, + "write": 1 + } + ], + "restrict_to_domain": "Healthcare", + "search_fields": "patient, signs_date", + "show_name_in_global_search": 1, + "sort_field": "modified", + "sort_order": "DESC", + "title_field": "title", + "track_changes": 1, + "track_seen": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/doctype/vital_signs/vital_signs.py b/healthcare/healthcare/doctype/vital_signs/vital_signs.py new file mode 100644 index 0000000..41f3d2a --- /dev/null +++ b/healthcare/healthcare/doctype/vital_signs/vital_signs.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, ESS LLP and contributors +# For license information, please see license.txt + + +import frappe +from frappe import _ +from frappe.model.document import Document + + +class VitalSigns(Document): + def validate(self): + self.set_title() + + def set_title(self): + self.title = _("{0} on {1}").format( + self.patient_name or self.patient, frappe.utils.format_date(self.signs_date) + )[:100] diff --git a/healthcare/healthcare/healthcare_dashboard/healthcare/healthcare.json b/healthcare/healthcare/healthcare_dashboard/healthcare/healthcare.json new file mode 100644 index 0000000..2fea668 --- /dev/null +++ b/healthcare/healthcare/healthcare_dashboard/healthcare/healthcare.json @@ -0,0 +1,62 @@ +{ + "cards": [ + { + "card": "Total Patients" + }, + { + "card": "Total Patients Admitted" + }, + { + "card": "Open Appointments" + }, + { + "card": "Appointments to Bill" + } + ], + "charts": [ + { + "chart": "Patient Appointments", + "width": "Full" + }, + { + "chart": "In-Patient Status", + "width": "Half" + }, + { + "chart": "Clinical Procedures Status", + "width": "Half" + }, + { + "chart": "Lab Tests", + "width": "Half" + }, + { + "chart": "Clinical Procedures", + "width": "Half" + }, + { + "chart": "Symptoms", + "width": "Half" + }, + { + "chart": "Diagnoses", + "width": "Half" + }, + { + "chart": "Department wise Patient Appointments", + "width": "Full" + } + ], + "creation": "2020-07-14 18:17:54.823311", + "dashboard_name": "Healthcare", + "docstatus": 0, + "doctype": "Dashboard", + "idx": 0, + "is_default": 0, + "is_standard": 1, + "modified": "2020-07-22 15:36:34.220387", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Healthcare", + "owner": "Administrator" +} \ No newline at end of file diff --git a/healthcare/healthcare/module_onboarding/healthcare/healthcare.json b/healthcare/healthcare/module_onboarding/healthcare/healthcare.json new file mode 100644 index 0000000..e3b120a --- /dev/null +++ b/healthcare/healthcare/module_onboarding/healthcare/healthcare.json @@ -0,0 +1,41 @@ +{ + "allow_roles": [ + { + "role": "Healthcare Administrator" + } + ], + "creation": "2020-05-19 10:32:43.025852", + "docstatus": 0, + "doctype": "Module Onboarding", + "documentation_url": "https://docs.influxerp.com/docs/user/manual/en/healthcare", + "idx": 0, + "is_complete": 0, + "modified": "2021-01-30 19:22:20.273766", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Healthcare", + "owner": "Administrator", + "steps": [ + { + "step": "Create Patient" + }, + { + "step": "Create Practitioner Schedule" + }, + { + "step": "Introduction to Healthcare Practitioner" + }, + { + "step": "Create Healthcare Practitioner" + }, + { + "step": "Explore Healthcare Settings" + }, + { + "step": "Explore Clinical Procedure Templates" + } + ], + "subtitle": "Patients, Practitioner Schedules, Settings, and more.", + "success_message": "The Healthcare Module is all set up!", + "title": "Let's Set Up the Healthcare Module." +} \ No newline at end of file diff --git a/healthcare/healthcare/number_card/appointments_to_bill/appointments_to_bill.json b/healthcare/healthcare/number_card/appointments_to_bill/appointments_to_bill.json new file mode 100644 index 0000000..3e4d4e2 --- /dev/null +++ b/healthcare/healthcare/number_card/appointments_to_bill/appointments_to_bill.json @@ -0,0 +1,21 @@ +{ + "creation": "2020-07-14 18:17:54.792773", + "docstatus": 0, + "doctype": "Number Card", + "document_type": "Patient Appointment", + "dynamic_filters_json": "[[\"Patient Appointment\",\"company\",\"=\",\"frappe.defaults.get_user_default(\\\"Company\\\")\"]]", + "filters_json": "[[\"Patient Appointment\",\"invoiced\",\"=\",0,false]]", + "function": "Count", + "idx": 0, + "is_public": 1, + "is_standard": 1, + "label": "Appointments To Bill", + "modified": "2020-07-22 13:27:58.038577", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Appointments to Bill", + "owner": "Administrator", + "show_percentage_stats": 1, + "stats_time_interval": "Daily", + "type": "Document Type" +} \ No newline at end of file diff --git a/healthcare/healthcare/number_card/open_appointments/open_appointments.json b/healthcare/healthcare/number_card/open_appointments/open_appointments.json new file mode 100644 index 0000000..8d121cc --- /dev/null +++ b/healthcare/healthcare/number_card/open_appointments/open_appointments.json @@ -0,0 +1,21 @@ +{ + "creation": "2020-07-14 18:17:54.771092", + "docstatus": 0, + "doctype": "Number Card", + "document_type": "Patient Appointment", + "dynamic_filters_json": "[[\"Patient Appointment\",\"company\",\"=\",\"frappe.defaults.get_user_default(\\\"Company\\\")\"]]", + "filters_json": "[[\"Patient Appointment\",\"status\",\"=\",\"Open\",false]]", + "function": "Count", + "idx": 0, + "is_public": 1, + "is_standard": 1, + "label": "Open Appointments", + "modified": "2020-07-22 13:27:09.542122", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Open Appointments", + "owner": "Administrator", + "show_percentage_stats": 1, + "stats_time_interval": "Daily", + "type": "Document Type" +} \ No newline at end of file diff --git a/healthcare/healthcare/number_card/total_patients/total_patients.json b/healthcare/healthcare/number_card/total_patients/total_patients.json new file mode 100644 index 0000000..75441a6 --- /dev/null +++ b/healthcare/healthcare/number_card/total_patients/total_patients.json @@ -0,0 +1,20 @@ +{ + "creation": "2020-07-14 18:17:54.727946", + "docstatus": 0, + "doctype": "Number Card", + "document_type": "Patient", + "filters_json": "[[\"Patient\",\"status\",\"=\",\"Active\",false]]", + "function": "Count", + "idx": 0, + "is_public": 1, + "is_standard": 1, + "label": "Total Patients", + "modified": "2020-07-22 13:26:02.643534", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Total Patients", + "owner": "Administrator", + "show_percentage_stats": 1, + "stats_time_interval": "Daily", + "type": "Document Type" +} \ No newline at end of file diff --git a/healthcare/healthcare/number_card/total_patients_admitted/total_patients_admitted.json b/healthcare/healthcare/number_card/total_patients_admitted/total_patients_admitted.json new file mode 100644 index 0000000..69a967d --- /dev/null +++ b/healthcare/healthcare/number_card/total_patients_admitted/total_patients_admitted.json @@ -0,0 +1,20 @@ +{ + "creation": "2020-07-14 18:17:54.749754", + "docstatus": 0, + "doctype": "Number Card", + "document_type": "Patient", + "filters_json": "[[\"Patient\",\"inpatient_status\",\"=\",\"Admitted\",false]]", + "function": "Count", + "idx": 0, + "is_public": 1, + "is_standard": 1, + "label": "Total Patients Admitted", + "modified": "2020-07-22 13:26:20.027788", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Total Patients Admitted", + "owner": "Administrator", + "show_percentage_stats": 1, + "stats_time_interval": "Daily", + "type": "Document Type" +} \ No newline at end of file diff --git a/healthcare/healthcare/onboarding_step/create_healthcare_practitioner/create_healthcare_practitioner.json b/healthcare/healthcare/onboarding_step/create_healthcare_practitioner/create_healthcare_practitioner.json new file mode 100644 index 0000000..3f25a9d --- /dev/null +++ b/healthcare/healthcare/onboarding_step/create_healthcare_practitioner/create_healthcare_practitioner.json @@ -0,0 +1,19 @@ +{ + "action": "Create Entry", + "creation": "2020-05-19 10:39:55.728058", + "docstatus": 0, + "doctype": "Onboarding Step", + "idx": 0, + "is_complete": 0, + "is_single": 0, + "is_skipped": 0, + "modified": "2021-01-30 12:02:22.849260", + "modified_by": "Administrator", + "name": "Create Healthcare Practitioner", + "owner": "Administrator", + "reference_document": "Healthcare Practitioner", + "show_form_tour": 0, + "show_full_form": 1, + "title": "Create Healthcare Practitioner", + "validate_action": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/onboarding_step/create_patient/create_patient.json b/healthcare/healthcare/onboarding_step/create_patient/create_patient.json new file mode 100644 index 0000000..b46bb15 --- /dev/null +++ b/healthcare/healthcare/onboarding_step/create_patient/create_patient.json @@ -0,0 +1,19 @@ +{ + "action": "Create Entry", + "creation": "2020-05-19 10:32:27.648902", + "docstatus": 0, + "doctype": "Onboarding Step", + "idx": 0, + "is_complete": 0, + "is_single": 0, + "is_skipped": 0, + "modified": "2021-01-30 00:09:28.786428", + "modified_by": "ruchamahabal2@gmail.com", + "name": "Create Patient", + "owner": "Administrator", + "reference_document": "Patient", + "show_form_tour": 0, + "show_full_form": 1, + "title": "Create Patient", + "validate_action": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/onboarding_step/create_practitioner_schedule/create_practitioner_schedule.json b/healthcare/healthcare/onboarding_step/create_practitioner_schedule/create_practitioner_schedule.json new file mode 100644 index 0000000..7ce122d --- /dev/null +++ b/healthcare/healthcare/onboarding_step/create_practitioner_schedule/create_practitioner_schedule.json @@ -0,0 +1,19 @@ +{ + "action": "Create Entry", + "creation": "2020-05-19 10:41:19.065753", + "docstatus": 0, + "doctype": "Onboarding Step", + "idx": 0, + "is_complete": 0, + "is_single": 0, + "is_skipped": 0, + "modified": "2021-01-30 00:09:28.794602", + "modified_by": "ruchamahabal2@gmail.com", + "name": "Create Practitioner Schedule", + "owner": "Administrator", + "reference_document": "Practitioner Schedule", + "show_form_tour": 0, + "show_full_form": 1, + "title": "Create Practitioner Schedule", + "validate_action": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/onboarding_step/explore_clinical_procedure_templates/explore_clinical_procedure_templates.json b/healthcare/healthcare/onboarding_step/explore_clinical_procedure_templates/explore_clinical_procedure_templates.json new file mode 100644 index 0000000..dfe9f71 --- /dev/null +++ b/healthcare/healthcare/onboarding_step/explore_clinical_procedure_templates/explore_clinical_procedure_templates.json @@ -0,0 +1,19 @@ +{ + "action": "Show Form Tour", + "creation": "2020-05-19 11:40:51.963741", + "docstatus": 0, + "doctype": "Onboarding Step", + "idx": 0, + "is_complete": 0, + "is_single": 0, + "is_skipped": 0, + "modified": "2021-01-30 19:22:08.257160", + "modified_by": "Administrator", + "name": "Explore Clinical Procedure Templates", + "owner": "Administrator", + "reference_document": "Clinical Procedure Template", + "show_form_tour": 0, + "show_full_form": 0, + "title": "Explore Clinical Procedure Templates", + "validate_action": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/onboarding_step/explore_healthcare_settings/explore_healthcare_settings.json b/healthcare/healthcare/onboarding_step/explore_healthcare_settings/explore_healthcare_settings.json new file mode 100644 index 0000000..2d952f3 --- /dev/null +++ b/healthcare/healthcare/onboarding_step/explore_healthcare_settings/explore_healthcare_settings.json @@ -0,0 +1,19 @@ +{ + "action": "Show Form Tour", + "creation": "2020-05-19 11:14:33.044989", + "docstatus": 0, + "doctype": "Onboarding Step", + "idx": 0, + "is_complete": 0, + "is_single": 1, + "is_skipped": 0, + "modified": "2021-01-30 19:22:07.275735", + "modified_by": "Administrator", + "name": "Explore Healthcare Settings", + "owner": "Administrator", + "reference_document": "Healthcare Settings", + "show_form_tour": 0, + "show_full_form": 0, + "title": "Explore Healthcare Settings", + "validate_action": 1 +} \ No newline at end of file diff --git a/healthcare/healthcare/onboarding_step/introduction_to_healthcare_practitioner/introduction_to_healthcare_practitioner.json b/healthcare/healthcare/onboarding_step/introduction_to_healthcare_practitioner/introduction_to_healthcare_practitioner.json new file mode 100644 index 0000000..baa8358 --- /dev/null +++ b/healthcare/healthcare/onboarding_step/introduction_to_healthcare_practitioner/introduction_to_healthcare_practitioner.json @@ -0,0 +1,20 @@ +{ + "action": "Show Form Tour", + "creation": "2020-05-19 10:43:56.231679", + "docstatus": 0, + "doctype": "Onboarding Step", + "field": "schedule", + "idx": 0, + "is_complete": 0, + "is_single": 0, + "is_skipped": 0, + "modified": "2021-01-30 00:09:28.807129", + "modified_by": "ruchamahabal2@gmail.com", + "name": "Introduction to Healthcare Practitioner", + "owner": "Administrator", + "reference_document": "Healthcare Practitioner", + "show_form_tour": 0, + "show_full_form": 0, + "title": "Introduction to Healthcare Practitioner", + "validate_action": 0 +} \ No newline at end of file diff --git a/healthcare/healthcare/page/__init__.py b/healthcare/healthcare/page/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/healthcare/healthcare/page/__init__.py @@ -0,0 +1 @@ + diff --git a/healthcare/healthcare/page/patient_history/__init__.py b/healthcare/healthcare/page/patient_history/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/page/patient_history/patient_history.css b/healthcare/healthcare/page/patient_history/patient_history.css new file mode 100644 index 0000000..74b5e7e --- /dev/null +++ b/healthcare/healthcare/page/patient_history/patient_history.css @@ -0,0 +1,151 @@ +#page-medical_record .label { + display: inline-block; + margin-right: 7px; +} + +#page-medical_record .list-row { + border: none; + padding: 0px; + cursor: pointer; +} + +.patient-image-container { + margin-top: 17px; + } + +.patient-image { + display: inline-block; + width: 100%; + height: 0; + padding: 50% 0px; + background-size: cover; + background-repeat: no-repeat; + background-position: center center; + border-radius: 4px; +} + +.patient-name { + font-size: 20px; + margin-top: 25px; +} + +.medical_record-label { + max-width: 100px; + margin-bottom: -4px; +} + +.medical_record-row > * { + z-index: -999; +} + +.date-indicator { + background:none; + font-size:12px; + vertical-align:middle; + font-weight:bold; + color:#6c7680; +} +.date-indicator::after { + margin:0 -4px 0 12px; + content:''; + display:inline-block; + height:8px; + width:8px; + border-radius:8px; + background: #d1d8dd; +} + +.date-indicator.blue { + color: #5e64ff; +} + +.div-bg-color { + background: #fafbfc; +} + +.bg-color-white { + background: #FFFFFF; +} + +.d-flex { + display: flex; +} + +.width-full { + width: 100%; +} + +.p-3 { + padding: 16px; +} + +.mt-2 { + margin-top: 8px; +} + +.mr-3 { + margin-right: 16px; +} + +.Box { + background-color: #fff; + border: 1px solid #d1d5da; + border-radius: 3px; +} + +.flex-column { + flex-direction: column; +} + +.avatar { + display: inline-block; + overflow: hidden; + line-height: 1; + vertical-align: middle; + border-radius: 3px; +} + +.py-3 { + padding-top: 16px; + padding-bottom: 16px; +} + +.border-bottom { + border-bottom: 1px #e1e4e8 solid; +} + +.date-indicator.blue::after { + background: #5e64ff; +} + +.medical_record-message { + border-left: 1px solid #d1d8dd; + padding: 15px; + padding-right: 30px; +} + +.medical_record-date { + padding: 15px; + padding-right: 0px; +} + +.patient-history-filter { + margin-left: 35px; + width: 25%; +} + +#page-medical_record .plot-wrapper { + padding: 20px 15px; + border-bottom: 1px solid #d1d8dd; + text-align: center; +} + +#page-medical_record .plot { + height: 140px ; + width: 97% ; + margin: auto; +} + +#page-medical_record .list-filters { + display: none ; +} diff --git a/healthcare/healthcare/page/patient_history/patient_history.html b/healthcare/healthcare/page/patient_history/patient_history.html new file mode 100644 index 0000000..d16b386 --- /dev/null +++ b/healthcare/healthcare/page/patient_history/patient_history.html @@ -0,0 +1,18 @@ +
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+ +
+
diff --git a/healthcare/healthcare/page/patient_history/patient_history.js b/healthcare/healthcare/page/patient_history/patient_history.js new file mode 100644 index 0000000..8924d58 --- /dev/null +++ b/healthcare/healthcare/page/patient_history/patient_history.js @@ -0,0 +1,455 @@ +frappe.provide('frappe.patient_history'); +frappe.pages['patient_history'].on_page_load = function(wrapper) { + frappe.ui.make_app_page({ + parent: wrapper, + title: __('Patient History') + }); + + let patient_history = new PatientHistory(wrapper); + $(wrapper).bind('show', ()=> { + patient_history.show(); + }); +}; + +class PatientHistory { + constructor(wrapper) { + this.wrapper = $(wrapper); + this.page = wrapper.page; + this.sidebar = this.wrapper.find('.layout-side-section'); + this.main_section = this.wrapper.find('.layout-main-section'); + this.start = 0; + } + + show() { + frappe.breadcrumbs.add('Healthcare'); + this.sidebar.empty(); + + let me = this; + let patient = frappe.ui.form.make_control({ + parent: me.sidebar, + df: { + fieldtype: 'Link', + options: 'Patient', + fieldname: 'patient', + placeholder: __('Select Patient'), + only_select: true, + change: () => { + me.patient_id = ''; + if (me.patient_id != patient.get_value() && patient.get_value()) { + me.start = 0; + me.patient_id = patient.get_value(); + me.make_patient_profile(); + } + } + } + }); + patient.refresh(); + + if (frappe.route_options && !this.patient_id) { + patient.set_value(frappe.route_options.patient); + this.patient_id = frappe.route_options.patient; + } + + this.sidebar.find('[data-fieldname="patient"]').append('
'); + } + + make_patient_profile() { + this.page.set_title(__('Patient History')); + this.main_section.empty().append(frappe.render_template('patient_history')); + this.setup_filters(); + this.setup_documents(); + this.show_patient_info(); + this.setup_buttons(); + this.show_patient_vital_charts('bp', 'mmHg', 'Blood Pressure'); + } + + setup_filters() { + $('.doctype-filter').empty(); + let me = this; + + frappe.xcall( + 'healthcare.healthcare.page.patient_history.patient_history.get_patient_history_doctypes' + ).then(document_types => { + let doctype_filter = frappe.ui.form.make_control({ + parent: $('.doctype-filter'), + df: { + fieldtype: 'MultiSelectList', + fieldname: 'document_type', + placeholder: __('Select Document Type'), + change: () => { + me.start = 0; + me.page.main.find('.patient_documents_list').html(''); + this.setup_documents(doctype_filter.get_value(), date_range_field.get_value()); + }, + get_data: () => { + return document_types.map(document_type => { + return { + description: document_type, + value: document_type + }; + }); + }, + } + }); + doctype_filter.refresh(); + + $('.date-filter').empty(); + let date_range_field = frappe.ui.form.make_control({ + df: { + fieldtype: 'DateRange', + fieldname: 'date_range', + placeholder: __('Date Range'), + input_class: 'input-xs', + change: () => { + let selected_date_range = date_range_field.get_value(); + if (selected_date_range && selected_date_range.length === 2) { + me.start = 0; + me.page.main.find('.patient_documents_list').html(''); + this.setup_documents(doctype_filter.get_value(), date_range_field.get_value()); + } + } + }, + parent: $('.date-filter') + }); + date_range_field.refresh(); + }); + } + + setup_documents(document_types="", selected_date_range="") { + let filters = { + name: this.patient_id, + start: this.start, + page_length: 20 + }; + if (document_types) + filters['document_types'] = document_types; + if (selected_date_range) + filters['date_range'] = selected_date_range; + + let me = this; + frappe.call({ + 'method': 'healthcare.healthcare.page.patient_history.patient_history.get_feed', + args: filters, + callback: function(r) { + let data = r.message; + if (data.length) { + me.add_to_records(data); + } else { + me.page.main.find('.patient_documents_list').append(` +
+

${__('No more records..')}

+
`); + me.page.main.find('.btn-get-records').hide(); + } + } + }); + } + + add_to_records(data) { + let details = ""; + let i; + for (i=0; i + ${data[i].reference_name} + `; + + details += ` +
+
`; + + if (data[i].imgsrc) { + details += ` + + `; + } else { + details += ` +
+ ${data[i].practitioner ? data[i].practitioner.charAt(0) : 'U'} +
+
`; + } + + details += `
+
+ `+time_line_heading+` + + ${data[i].date_sep} + +
+
+ ${label} +
+
+ + +
+
+ + +
+
+
+
`; + } + } + + this.page.main.find('.patient_documents_list').append(details); + this.start += data.length; + + if (data.length === 20) { + this.page.main.find(".btn-get-records").show(); + } else { + this.page.main.find(".btn-get-records").hide(); + this.page.main.find(".patient_documents_list").append(` +
+

${__('No more records..')}

+
`); + } + } + + add_date_separator(data) { + let date = frappe.datetime.str_to_obj(data.communication_date); + let pdate = ''; + let diff = frappe.datetime.get_day_diff(frappe.datetime.get_today(), + frappe.datetime.obj_to_str(date)); + + if (diff < 1) { + pdate = __('Today'); + } else if (diff < 2) { + pdate = __('Yesterday'); + } else { + pdate = __('on {0}', [frappe.datetime.global_date_format(date)]); + } + data.date_sep = pdate; + return data; + } + + show_patient_info() { + this.get_patient_info().then(() => { + $('.patient-info').empty().append(frappe.render_template('patient_history_sidebar', { + patient_image: this.patient.image, + patient_name: this.patient.patient_name, + patient_gender: this.patient.sex, + patient_mobile: this.patient.mobile + })); + this.show_patient_details(); + }); + } + + show_patient_details() { + let me = this; + frappe.call({ + 'method': 'healthcare.healthcare.doctype.patient.patient.get_patient_detail', + args: { + patient: me.patient_id + }, + callback: function(r) { + let data = r.message; + let details = ``; + + if (data.occupation) details += `

${__('Occupation')} : ${data.occupation}`; + if (data.blood_group) details += `
${__('Blood Group')} : ${data.blood_group}`; + if (data.allergies) details += `

${__('Allerigies')} : ${data.allergies.replace(/\n/g, ", ")}`; + if (data.medication) details += `
${__('Medication')} : ${data.medication.replace(/\n/g, ", ")}`; + if (data.alcohol_current_use) details += `

${__('Alcohol use')} : ${data.alcohol_current_use}`; + if (data.alcohol_past_use) details += `
${__('Alcohol past use')} : ${data.alcohol_past_use}`; + if (data.tobacco_current_use) details += `
${__('Tobacco use')} : ${data.tobacco_current_use}`; + if (data.tobacco_past_use) details += `
${__('Tobacco past use')} : ${data.tobacco_past_use}`; + if (data.medical_history) details += `

${__('Medical history')} : ${data.medical_history.replace(/\n/g, ", ")}`; + if (data.surgical_history) details += `
${__('Surgical history')} : ${data.surgical_history.replace(/\n/g, ", ")}`; + if (data.surrounding_factors) details += `

${__('Occupational hazards')} : ${data.surrounding_factors.replace(/\n/g, ", ")}`; + if (data.other_risk_factors) details += `
${__('Other risk factors')} : ${data.other_risk_factors.replace(/\n/g, ", ")}`; + if (data.patient_details) details += `

${__('More info')} : ${data.patient_details.replace(/\n/g, ", ")}`; + + if (details) { + details = `
` + details + `
`; + } + + me.sidebar.find('.patient-details').html(details); + } + }); + } + + get_patient_info() { + return frappe.xcall('frappe.client.get', { + doctype: 'Patient', + name: this.patient_id, + }).then((patient) => { + if (patient) { + this.patient = patient; + } + }); + } + + setup_buttons() { + let me = this; + this.page.main.on("click", ".btn-show-chart", function() { + let btn_id = $(this).attr("data-show-chart-id"), scale_unit = $(this).attr("data-pts"); + let title = $(this).attr("data-title"); + me.show_patient_vital_charts(btn_id, scale_unit, title); + }); + + this.page.main.on('click', '.btn-more', function() { + let doctype = $(this).attr('data-doctype'), docname = $(this).attr('data-docname'); + if (me.page.main.find('.'+docname).parent().find('.document-html').attr('data-fetched') == '1') { + me.page.main.find('.'+docname).hide(); + me.page.main.find('.'+docname).parent().find('.document-html').show(); + } else { + if (doctype && docname) { + let exclude = ['patient', 'patient_name', 'patient_sex', 'encounter_date', 'naming_series']; + frappe.call({ + method: 'healthcare.healthcare.utils.render_doc_as_html', + args: { + doctype: doctype, + docname: docname, + exclude_fields: exclude + }, + freeze: true, + callback: function(r) { + if (r.message) { + me.page.main.find('.' + docname).hide(); + + me.page.main.find('.' + docname).parent().find('.document-html').html( + `${r.message.html} +
+
+ + +
+ `); + + me.page.main.find('.' + docname).parent().find('.document-html').attr('hidden', false); + me.page.main.find('.' + docname).parent().find('.document-html').attr('data-fetched', '1'); + } + } + }); + } + } + }); + + this.page.main.on('click', '.btn-less', function() { + let docname = $(this).attr('data-docname'); + me.page.main.find('.' + docname).parent().find('.document-id').show(); + me.page.main.find('.' + docname).parent().find('.document-html').hide(); + }); + + me.page.main.on('click', '.btn-get-records', function() { + this.setup_documents(); + }); + } + + show_patient_vital_charts(btn_id, scale_unit, title) { + let me = this; + + frappe.call({ + method: 'healthcare.healthcare.utils.get_patient_vitals', + args: { + patient: me.patient_id + }, + callback: function(r) { + if (r.message) { + let show_chart_btns_html = ` + `; + + me.page.main.find('.show_chart_btns').html(show_chart_btns_html); + let data = r.message; + let labels = [], datasets = []; + let bp_systolic = [], bp_diastolic = [], temperature = []; + let pulse = [], respiratory_rate = [], bmi = [], height = [], weight = []; + + for (let i=0; i (d + '').toUpperCase(), + formatTooltipY: d => d + ' ' + scale_unit, + } + }); + me.page.main.find('.header-separator').show(); + } else { + me.page.main.find('.patient_vital_charts').html(''); + me.page.main.find('.show_chart_btns').html(''); + me.page.main.find('.header-separator').hide(); + } + } + }); + } +} diff --git a/healthcare/healthcare/page/patient_history/patient_history.json b/healthcare/healthcare/page/patient_history/patient_history.json new file mode 100644 index 0000000..b3892a4 --- /dev/null +++ b/healthcare/healthcare/page/patient_history/patient_history.json @@ -0,0 +1,28 @@ +{ + "content": null, + "creation": "2018-08-08 17:09:13.816199", + "docstatus": 0, + "doctype": "Page", + "icon": "", + "idx": 0, + "modified": "2018-08-08 17:09:55.969424", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "patient_history", + "owner": "Administrator", + "page_name": "patient_history", + "restrict_to_domain": "Healthcare", + "roles": [ + { + "role": "Healthcare Administrator" + }, + { + "role": "Physician" + } + ], + "script": null, + "standard": "Yes", + "style": null, + "system_page": 0, + "title": "Patient History" +} \ No newline at end of file diff --git a/healthcare/healthcare/page/patient_history/patient_history.py b/healthcare/healthcare/page/patient_history/patient_history.py new file mode 100644 index 0000000..a7304da --- /dev/null +++ b/healthcare/healthcare/page/patient_history/patient_history.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018, ESS LLP and contributors +# For license information, please see license.txt + + +import json + +import frappe +from frappe.utils import cint + + +@frappe.whitelist() +def get_feed(name, document_types=None, date_range=None, start=0, page_length=20): + """get feed""" + filters = get_filters(name, document_types, date_range) + + result = frappe.db.get_all( + "Patient Medical Record", + fields=["name", "owner", "communication_date", "reference_doctype", "reference_name", "subject"], + filters=filters, + order_by="communication_date DESC", + limit=cint(page_length), + start=cint(start), + ) + + return result + + +def get_filters(name, document_types=None, date_range=None): + filters = {"patient": name} + if document_types: + document_types = json.loads(document_types) + if len(document_types): + filters["reference_doctype"] = ["IN", document_types] + + if date_range: + try: + date_range = json.loads(date_range) + if date_range: + filters["communication_date"] = ["between", [date_range[0], date_range[1]]] + except json.decoder.JSONDecodeError: + pass + + return filters + + +@frappe.whitelist() +def get_feed_for_dt(doctype, docname): + """get feed""" + result = frappe.db.get_all( + "Patient Medical Record", + fields=["name", "owner", "communication_date", "reference_doctype", "reference_name", "subject"], + filters={"reference_doctype": doctype, "reference_name": docname}, + order_by="communication_date DESC", + ) + + return result + + +@frappe.whitelist() +def get_patient_history_doctypes(): + document_types = [] + settings = frappe.get_single("Patient History Settings") + + for entry in settings.standard_doctypes: + document_types.append(entry.document_type) + + for entry in settings.custom_doctypes: + document_types.append(entry.document_type) + + return document_types diff --git a/healthcare/healthcare/page/patient_history/patient_history_sidebar.html b/healthcare/healthcare/page/patient_history/patient_history_sidebar.html new file mode 100644 index 0000000..fc7eab0 --- /dev/null +++ b/healthcare/healthcare/page/patient_history/patient_history_sidebar.html @@ -0,0 +1,20 @@ +
+
+ {% if patient_image %} +
+ {% endif %} +
+
+ {% if patient_name %} +

{{patient_name}}

+ {% endif %} + {% if patient_gender %} +

{%=__("Gender: ") %} {{patient_gender}}

+ {% endif %} + {% if patient_mobile %} +

{%=__("Contact: ") %} {{patient_mobile}}

+ {% endif %} +
+
+
+
diff --git a/healthcare/healthcare/page/patient_progress/__init__.py b/healthcare/healthcare/page/patient_progress/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/page/patient_progress/patient_progress.css b/healthcare/healthcare/page/patient_progress/patient_progress.css new file mode 100644 index 0000000..737b2e0 --- /dev/null +++ b/healthcare/healthcare/page/patient_progress/patient_progress.css @@ -0,0 +1,171 @@ +/* sidebar */ + +.layout-side-section .frappe-control[data-fieldname='patient'] { + max-width: 300px; +} + +.patient-image-container { + margin-top: 17px; +} + +.patient-image { + display: inline-block; + width: 100%; + height: 0; + padding: 50% 0px; + background-size: cover; + background-repeat: no-repeat; + background-position: center center; + border-radius: 4px; +} + +.patient-details { + margin: -5px 5px; +} + +.important-links { + margin: 30px 5px; +} + +.patient-name { + font-size: 20px; + margin-top: 25px; +} + +/* heatmap */ + +.heatmap-container { + height: 170px; +} + +.patient-heatmap { + width: 80%; + display: inline-block; +} + +.patient-heatmap .chart-container { + margin-left: 30px; +} + +.patient-heatmap .frappe-chart { + margin-top: 5px; +} + +.patient-heatmap .frappe-chart .chart-legend { + display: none; +} + +.heatmap-container .chart-filter { + z-index: 1; + position: relative; + top: 5px; + margin-right: 10px; +} + +/* percentage chart */ + +.percentage-chart-container { + height: 130px; +} + +.percentage-chart-container .chart-filter { + position: relative; + top: 5px; + margin-right: 10px; +} + +.therapy-session-percentage-chart .frappe-chart { + position: absolute; + top: 5px; +} + +/* line charts */ + +.date-field .clearfix { + display: none; +} + +.date-field .help-box { + display: none; +} + +.date-field .frappe-control { + margin-bottom: 0px !important; +} + +.date-field .form-group { + margin-bottom: 0px !important; +} + +/* common */ + +text.title { + text-transform: uppercase; + font-size: 11px; + margin-left: 20px; + margin-top: 20px; + display: block; +} + +.chart-filter-search { + margin-left: 35px; + width: 25%; +} + +.chart-column-container { + margin: 5px 0; +} + +.progress-graphs .progress-container { + margin-bottom: var(--margin-xl); +} + +.line-chart-container .frappe-chart { + margin-top: -20px; +} + +.line-chart-container { + margin-bottom: 20px; +} + +.chart-control { + align-self: center; + display: flex; + flex-direction: row-reverse; + margin-top: -25px; +} + +.chart-control > * { + margin-right: 10px; +} + +/* mobile */ + +@media (max-width: 991px) { + .patient-progress-sidebar { + display: flex; + } + + .percentage-chart-container { + border-top: 1px solid #d1d8dd; + } + + .percentage-chart-container .chart-filter { + z-index: 1; + position: relative; + top: 12px; + margin-right: 10px; + } + + .patient-progress-sidebar .important-links { + margin: 0; + } + + .patient-progress-sidebar .patient-details { + width: 50%; + } + + .chart-filter-search { + width: 40%; + } +} diff --git a/healthcare/healthcare/page/patient_progress/patient_progress.html b/healthcare/healthcare/page/patient_progress/patient_progress.html new file mode 100644 index 0000000..ee60065 --- /dev/null +++ b/healthcare/healthcare/page/patient_progress/patient_progress.html @@ -0,0 +1,69 @@ +
+
+
+ + +
+
+
+ +
+
+ Therapy Progress +
+
+
+ +
+
+
+
+
+
+ +
+
+ Assessment Results +
+
+
+ +
+
+
+
+
+
+ +
+
+ Therapy Type and Assessment Correlation +
+
+
+ +
+
+
+
+
+
+ +
+
+ Assessment Parameter Wise Progress +
+
+
+ +
+
+
+
+
+
+
+
+
diff --git a/healthcare/healthcare/page/patient_progress/patient_progress.js b/healthcare/healthcare/page/patient_progress/patient_progress.js new file mode 100644 index 0000000..16ee0de --- /dev/null +++ b/healthcare/healthcare/page/patient_progress/patient_progress.js @@ -0,0 +1,536 @@ +frappe.pages['patient-progress'].on_page_load = function(wrapper) { + + frappe.ui.make_app_page({ + parent: wrapper, + title: __('Patient Progress') + }); + + let patient_progress = new PatientProgress(wrapper); + $(wrapper).bind('show', ()=> { + patient_progress.show(); + }); +}; + +class PatientProgress { + + constructor(wrapper) { + this.wrapper = $(wrapper); + this.page = wrapper.page; + this.sidebar = this.wrapper.find('.layout-side-section'); + this.main_section = this.wrapper.find('.layout-main-section'); + } + + show() { + frappe.breadcrumbs.add('Healthcare'); + this.sidebar.empty(); + + let me = this; + let patient = frappe.ui.form.make_control({ + parent: me.sidebar, + df: { + fieldtype: 'Link', + options: 'Patient', + fieldname: 'patient', + placeholder: __('Select Patient'), + only_select: true, + change: () => { + me.patient_id = ''; + if (me.patient_id != patient.get_value() && patient.get_value()) { + me.start = 0; + me.patient_id = patient.get_value(); + me.make_patient_profile(); + } + } + } + }); + patient.refresh(); + + if (frappe.route_options && !this.patient) { + patient.set_value(frappe.route_options.patient); + this.patient_id = frappe.route_options.patient; + } + + this.sidebar.find('[data-fieldname="patient"]').append('
'); + } + + make_patient_profile() { + this.page.set_title(__('Patient Progress')); + this.main_section.empty().append(frappe.render_template('patient_progress')); + this.render_patient_details(); + this.render_heatmap(); + this.render_percentage_chart('therapy_type', 'Therapy Type Distribution'); + this.create_percentage_chart_filters(); + this.show_therapy_progress(); + this.show_assessment_results(); + this.show_therapy_assessment_correlation(); + this.show_assessment_parameter_progress(); + } + + get_patient_info() { + return frappe.xcall('frappe.client.get', { + doctype: 'Patient', + name: this.patient_id + }).then((patient) => { + if (patient) { + this.patient = patient; + } + }); + } + + get_therapy_sessions_count() { + return frappe.xcall( + 'healthcare.healthcare.page.patient_progress.patient_progress.get_therapy_sessions_count', { + patient: this.patient_id, + } + ).then(data => { + if (data) { + this.total_therapy_sessions = data.total_therapy_sessions; + this.therapy_sessions_this_month = data.therapy_sessions_this_month; + } + }); + } + + render_patient_details() { + this.get_patient_info().then(() => { + this.get_therapy_sessions_count().then(() => { + $('.patient-info').empty().append(frappe.render_template('patient_progress_sidebar', { + patient_image: this.patient.image, + patient_name: this.patient.patient_name, + patient_gender: this.patient.sex, + patient_mobile: this.patient.mobile, + total_therapy_sessions: this.total_therapy_sessions, + therapy_sessions_this_month: this.therapy_sessions_this_month + })); + + this.setup_patient_profile_links(); + }); + }); + } + + setup_patient_profile_links() { + this.wrapper.find('.patient-profile-link').on('click', () => { + frappe.set_route('Form', 'Patient', this.patient_id); + }); + + this.wrapper.find('.therapy-plan-link').on('click', () => { + frappe.route_options = { + 'patient': this.patient_id, + 'docstatus': 1 + }; + frappe.set_route('List', 'Therapy Plan'); + }); + + this.wrapper.find('.patient-history').on('click', () => { + frappe.route_options = { + 'patient': this.patient_id + }; + frappe.set_route('patient_history'); + }); + } + + render_heatmap() { + this.heatmap = new frappe.Chart('.patient-heatmap', { + type: 'heatmap', + countLabel: 'Interactions', + data: {}, + discreteDomains: 1, + radius: 3, + height: 150 + }); + + this.update_heatmap_data(); + this.create_heatmap_chart_filters(); + } + + update_heatmap_data(date_from) { + frappe.xcall('healthcare.healthcare.page.patient_progress.patient_progress.get_patient_heatmap_data', { + patient: this.patient_id, + date: date_from || frappe.datetime.year_start(), + }).then((data) => { + this.heatmap.update( {dataPoints: data} ); + }); + } + + create_heatmap_chart_filters() { + this.get_patient_info().then(() => { + let filters = [ + { + label: frappe.dashboard_utils.get_year(frappe.datetime.now_date()), + options: frappe.dashboard_utils.get_years_since_creation(this.patient.creation), + action: (selected_item) => { + this.update_heatmap_data(frappe.datetime.obj_to_str(selected_item)); + } + }, + ]; + frappe.dashboard_utils.render_chart_filters(filters, 'chart-filter', '.heatmap-container'); + }); + } + + render_percentage_chart(field, title) { + // REDESIGN-TODO: chart seems to be broken. Enable this once fixed. + this.wrapper.find('.percentage-chart-container').hide(); + // frappe.xcall( + // 'healthcare.healthcare.page.patient_progress.patient_progress.get_therapy_sessions_distribution_data', { + // patient: this.patient_id, + // field: field + // } + // ).then(chart => { + // if (chart.labels.length) { + // this.percentage_chart = new frappe.Chart('.therapy-session-percentage-chart', { + // title: title, + // type: 'percentage', + // data: { + // labels: chart.labels, + // datasets: chart.datasets + // }, + // truncateLegends: 1, + // barOptions: { + // height: 11, + // depth: 1 + // }, + // height: 160, + // maxSlices: 8, + // colors: ['#5e64ff', '#743ee2', '#ff5858', '#ffa00a', '#feef72', '#28a745', '#98d85b', '#a9a7ac'], + // }); + // } else { + // this.wrapper.find('.percentage-chart-container').hide(); + // } + // }); + } + + create_percentage_chart_filters() { + let filters = [ + { + label: 'Therapy Type', + options: ['Therapy Type', 'Exercise Type'], + fieldnames: ['therapy_type', 'exercise_type'], + action: (selected_item, fieldname) => { + let title = selected_item + ' Distribution'; + this.render_percentage_chart(fieldname, title); + } + }, + ]; + frappe.dashboard_utils.render_chart_filters(filters, 'chart-filter', '.percentage-chart-container'); + } + + create_time_span_filters(action_method, parent) { + let chart_control = $(parent).find('.chart-control'); + let filters = [ + { + label: 'Last Month', + options: ['Select Date Range', 'Last Week', 'Last Month', 'Last Quarter', 'Last Year'], + action: (selected_item) => { + if (selected_item === 'Select Date Range') { + this.render_date_range_fields(action_method, chart_control); + } else { + // hide date range field if visible + let date_field = $(parent).find('.date-field'); + if (date_field.is(':visible')) { + date_field.hide(); + } + this[action_method](selected_item); + } + } + } + ]; + frappe.dashboard_utils.render_chart_filters(filters, 'chart-filter', chart_control, 1); + } + + render_date_range_fields(action_method, parent) { + let date_field = $(parent).find('.date-field'); + + if (!date_field.length) { + let date_field_wrapper = $( + `
` + ).appendTo(parent); + + let date_range_field = frappe.ui.form.make_control({ + df: { + fieldtype: 'DateRange', + fieldname: 'from_date', + placeholder: 'Date Range', + input_class: 'input-xs', + reqd: 1, + change: () => { + let selected_date_range = date_range_field.get_value(); + if (selected_date_range && selected_date_range.length === 2) { + this[action_method](selected_date_range); + } + } + }, + parent: date_field_wrapper, + render_input: 1 + }); + } else if (!date_field.is(':visible')) { + date_field.show(); + } + } + + show_therapy_progress() { + let me = this; + let therapy_type = frappe.ui.form.make_control({ + parent: $('.therapy-type-search'), + df: { + fieldtype: 'Link', + options: 'Therapy Type', + fieldname: 'therapy_type', + placeholder: __('Select Therapy Type'), + only_select: true, + change: () => { + if (me.therapy_type != therapy_type.get_value() && therapy_type.get_value()) { + me.therapy_type = therapy_type.get_value(); + me.render_therapy_progress_chart(); + } + } + } + }); + therapy_type.refresh(); + this.create_time_span_filters('render_therapy_progress_chart', '.therapy-progress'); + } + + render_therapy_progress_chart(time_span='Last Month') { + if (!this.therapy_type) return; + + frappe.xcall( + 'healthcare.healthcare.page.patient_progress.patient_progress.get_therapy_progress_data', { + patient: this.patient_id, + therapy_type: this.therapy_type, + time_span: time_span + } + ).then(chart => { + let data = { + labels: chart.labels, + datasets: chart.datasets + } + let parent = '.therapy-progress-line-chart'; + if (!chart.labels.length) { + this.show_null_state(parent); + } else { + if (!this.therapy_line_chart) { + this.therapy_line_chart = new frappe.Chart(parent, { + type: 'axis-mixed', + height: 250, + data: data, + lineOptions: { + regionFill: 1 + }, + axisOptions: { + xIsSeries: 1 + } + }); + } else { + $(parent).find('.chart-container').show(); + $(parent).find('.chart-empty-state').hide(); + this.therapy_line_chart.update(data); + } + } + }); + } + + show_assessment_results() { + let me = this; + let assessment_template = frappe.ui.form.make_control({ + parent: $('.assessment-template-search'), + df: { + fieldtype: 'Link', + options: 'Patient Assessment Template', + fieldname: 'assessment_template', + placeholder: __('Select Assessment Template'), + only_select: true, + change: () => { + if (me.assessment_template != assessment_template.get_value() && assessment_template.get_value()) { + me.assessment_template = assessment_template.get_value(); + me.render_assessment_result_chart(); + } + } + } + }); + assessment_template.refresh(); + this.create_time_span_filters('render_assessment_result_chart', '.assessment-results'); + } + + render_assessment_result_chart(time_span='Last Month') { + if (!this.assessment_template) return; + + frappe.xcall( + 'healthcare.healthcare.page.patient_progress.patient_progress.get_patient_assessment_data', { + patient: this.patient_id, + assessment_template: this.assessment_template, + time_span: time_span + } + ).then(chart => { + let data = { + labels: chart.labels, + datasets: chart.datasets, + yMarkers: [ + { label: 'Max Score', value: chart.max_score } + ], + } + let parent = '.assessment-results-line-chart'; + if (!chart.labels.length) { + this.show_null_state(parent); + } else { + if (!this.assessment_line_chart) { + this.assessment_line_chart = new frappe.Chart(parent, { + type: 'axis-mixed', + height: 250, + data: data, + lineOptions: { + regionFill: 1 + }, + axisOptions: { + xIsSeries: 1 + }, + tooltipOptions: { + formatTooltipY: d => __('{0} out of {1}', [d, chart.max_score]) + } + }); + } else { + $(parent).find('.chart-container').show(); + $(parent).find('.chart-empty-state').hide(); + this.assessment_line_chart.update(data); + } + } + }); + } + + show_therapy_assessment_correlation() { + let me = this; + let assessment = frappe.ui.form.make_control({ + parent: $('.assessment-correlation-template-search'), + df: { + fieldtype: 'Link', + options: 'Patient Assessment Template', + fieldname: 'assessment', + placeholder: __('Select Assessment Template'), + only_select: true, + change: () => { + if (me.assessment != assessment.get_value() && assessment.get_value()) { + me.assessment = assessment.get_value(); + me.render_therapy_assessment_correlation_chart(); + } + } + } + }); + assessment.refresh(); + this.create_time_span_filters('render_therapy_assessment_correlation_chart', '.therapy-assessment-correlation'); + } + + render_therapy_assessment_correlation_chart(time_span='Last Month') { + if (!this.assessment) return; + + frappe.xcall( + 'healthcare.healthcare.page.patient_progress.patient_progress.get_therapy_assessment_correlation_data', { + patient: this.patient_id, + assessment_template: this.assessment, + time_span: time_span + } + ).then(chart => { + let data = { + labels: chart.labels, + datasets: chart.datasets, + yMarkers: [ + { label: 'Max Score', value: chart.max_score } + ], + } + let parent = '.therapy-assessment-correlation-chart'; + if (!chart.labels.length) { + this.show_null_state(parent); + } else { + if (!this.correlation_chart) { + this.correlation_chart = new frappe.Chart(parent, { + type: 'axis-mixed', + height: 300, + data: data, + axisOptions: { + xIsSeries: 1 + } + }); + } else { + $(parent).find('.chart-container').show(); + $(parent).find('.chart-empty-state').hide(); + this.correlation_chart.update(data); + } + } + }); + } + + show_assessment_parameter_progress() { + let me = this; + let parameter = frappe.ui.form.make_control({ + parent: $('.assessment-parameter-search'), + df: { + fieldtype: 'Link', + options: 'Patient Assessment Parameter', + fieldname: 'assessment', + placeholder: __('Select Assessment Parameter'), + only_select: true, + change: () => { + if (me.parameter != parameter.get_value() && parameter.get_value()) { + me.parameter = parameter.get_value(); + me.render_assessment_parameter_progress_chart(); + } + } + } + }); + parameter.refresh(); + this.create_time_span_filters('render_assessment_parameter_progress_chart', '.assessment-parameter-progress'); + } + + render_assessment_parameter_progress_chart(time_span='Last Month') { + if (!this.parameter) return; + + frappe.xcall( + 'healthcare.healthcare.page.patient_progress.patient_progress.get_assessment_parameter_data', { + patient: this.patient_id, + parameter: this.parameter, + time_span: time_span + } + ).then(chart => { + let data = { + labels: chart.labels, + datasets: chart.datasets + } + let parent = '.assessment-parameter-progress-chart'; + if (!chart.labels.length) { + this.show_null_state(parent); + } else { + if (!this.parameter_chart) { + this.parameter_chart = new frappe.Chart(parent, { + type: 'line', + height: 250, + data: data, + lineOptions: { + regionFill: 1 + }, + axisOptions: { + xIsSeries: 1 + }, + tooltipOptions: { + formatTooltipY: d => d + '%' + } + }); + } else { + $(parent).find('.chart-container').show(); + $(parent).find('.chart-empty-state').hide(); + this.parameter_chart.update(data); + } + } + }); + } + + show_null_state(parent) { + let null_state = $(parent).find('.chart-empty-state'); + if (null_state.length) { + $(null_state).show(); + } else { + null_state = $( + `
${__( + "No Data..." + )}
` + ); + $(parent).append(null_state); + } + $(parent).find('.chart-container').hide(); + } +} diff --git a/healthcare/healthcare/page/patient_progress/patient_progress.json b/healthcare/healthcare/page/patient_progress/patient_progress.json new file mode 100644 index 0000000..0175cb9 --- /dev/null +++ b/healthcare/healthcare/page/patient_progress/patient_progress.json @@ -0,0 +1,33 @@ +{ + "content": null, + "creation": "2020-06-12 15:46:23.111928", + "docstatus": 0, + "doctype": "Page", + "idx": 0, + "modified": "2020-07-23 21:45:45.540055", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "patient-progress", + "owner": "Administrator", + "page_name": "patient-progress", + "restrict_to_domain": "Healthcare", + "roles": [ + { + "role": "Healthcare Administrator" + }, + { + "role": "Physician" + }, + { + "role": "Patient" + }, + { + "role": "System Manager" + } + ], + "script": null, + "standard": "Yes", + "style": null, + "system_page": 0, + "title": "Patient Progress" +} \ No newline at end of file diff --git a/healthcare/healthcare/page/patient_progress/patient_progress.py b/healthcare/healthcare/page/patient_progress/patient_progress.py new file mode 100644 index 0000000..8d27c86 --- /dev/null +++ b/healthcare/healthcare/page/patient_progress/patient_progress.py @@ -0,0 +1,232 @@ +import json +from datetime import datetime + +import frappe +from frappe import _ +from frappe.utils import get_timespan_date_range, getdate + + +@frappe.whitelist() +def get_therapy_sessions_count(patient): + total = frappe.db.count("Therapy Session", filters={"docstatus": 1, "patient": patient}) + + month_start = datetime.today().replace(day=1) + this_month = frappe.db.count( + "Therapy Session", filters={"creation": [">", month_start], "docstatus": 1, "patient": patient} + ) + + return {"total_therapy_sessions": total, "therapy_sessions_this_month": this_month} + + +@frappe.whitelist() +def get_patient_heatmap_data(patient, date): + return dict( + frappe.db.sql( + """ + SELECT + unix_timestamp(communication_date), count(*) + FROM + `tabPatient Medical Record` + WHERE + communication_date > subdate(%(date)s, interval 1 year) and + communication_date < subdate(%(date)s, interval -1 year) and + patient = %(patient)s + GROUP BY communication_date + ORDER BY communication_date asc""", + {"date": date, "patient": patient}, + ) + ) + + +@frappe.whitelist() +def get_therapy_sessions_distribution_data(patient, field): + if field == "therapy_type": + result = frappe.db.get_all( + "Therapy Session", + filters={"patient": patient, "docstatus": 1}, + group_by=field, + order_by=field, + fields=[field, "count(*)"], + as_list=True, + ) + + elif field == "exercise_type": + data = frappe.db.get_all( + "Therapy Session", filters={"docstatus": 1, "patient": patient}, as_list=True + ) + therapy_sessions = [entry[0] for entry in data] + + result = frappe.db.get_all( + "Exercise", + filters={"parenttype": "Therapy Session", "parent": ["in", therapy_sessions], "docstatus": 1}, + group_by=field, + order_by=field, + fields=[field, "count(*)"], + as_list=True, + ) + + return { + "labels": [r[0] for r in result if r[0] != None], + "datasets": [{"values": [r[1] for r in result]}], + } + + +@frappe.whitelist() +def get_therapy_progress_data(patient, therapy_type, time_span): + date_range = get_date_range(time_span) + query_values = { + "from_date": date_range[0], + "to_date": date_range[1], + "therapy_type": therapy_type, + "patient": patient, + } + result = frappe.db.sql( + """ + SELECT + start_date, total_counts_targeted, total_counts_completed + FROM + `tabTherapy Session` + WHERE + start_date BETWEEN %(from_date)s AND %(to_date)s and + docstatus = 1 and + therapy_type = %(therapy_type)s and + patient = %(patient)s + ORDER BY start_date""", + query_values, + as_list=1, + ) + + return { + "labels": [r[0] for r in result if r[0] != None], + "datasets": [ + {"name": _("Targetted"), "values": [r[1] for r in result if r[0] != None]}, + {"name": _("Completed"), "values": [r[2] for r in result if r[0] != None]}, + ], + } + + +@frappe.whitelist() +def get_patient_assessment_data(patient, assessment_template, time_span): + date_range = get_date_range(time_span) + query_values = { + "from_date": date_range[0], + "to_date": date_range[1], + "assessment_template": assessment_template, + "patient": patient, + } + result = frappe.db.sql( + """ + SELECT + assessment_datetime, total_score, total_score_obtained + FROM + `tabPatient Assessment` + WHERE + DATE(assessment_datetime) BETWEEN %(from_date)s AND %(to_date)s and + docstatus = 1 and + assessment_template = %(assessment_template)s and + patient = %(patient)s + ORDER BY assessment_datetime""", + query_values, + as_list=1, + ) + + return { + "labels": [getdate(r[0]) for r in result if r[0] != None], + "datasets": [{"name": _("Score Obtained"), "values": [r[2] for r in result if r[0] != None]}], + "max_score": result[0][1] if result else None, + } + + +@frappe.whitelist() +def get_therapy_assessment_correlation_data(patient, assessment_template, time_span): + date_range = get_date_range(time_span) + query_values = { + "from_date": date_range[0], + "to_date": date_range[1], + "assessment": assessment_template, + "patient": patient, + } + result = frappe.db.sql( + """ + SELECT + therapy.therapy_type, count(*), avg(assessment.total_score_obtained), total_score + FROM + `tabPatient Assessment` assessment INNER JOIN `tabTherapy Session` therapy + ON + assessment.therapy_session = therapy.name + WHERE + DATE(assessment.assessment_datetime) BETWEEN %(from_date)s AND %(to_date)s and + assessment.docstatus = 1 and + assessment.patient = %(patient)s and + assessment.assessment_template = %(assessment)s + GROUP BY therapy.therapy_type + """, + query_values, + as_list=1, + ) + + return { + "labels": [r[0] for r in result if r[0] != None], + "datasets": [ + {"name": _("Sessions"), "chartType": "bar", "values": [r[1] for r in result if r[0] != None]}, + { + "name": _("Average Score"), + "chartType": "line", + "values": [round(r[2], 2) for r in result if r[0] != None], + }, + ], + "max_score": result[0][1] if result else None, + } + + +@frappe.whitelist() +def get_assessment_parameter_data(patient, parameter, time_span): + date_range = get_date_range(time_span) + query_values = { + "from_date": date_range[0], + "to_date": date_range[1], + "parameter": parameter, + "patient": patient, + } + results = frappe.db.sql( + """ + SELECT + assessment.assessment_datetime, + sheet.score, + template.scale_max + FROM + `tabPatient Assessment Sheet` sheet + INNER JOIN `tabPatient Assessment` assessment + ON sheet.parent = assessment.name + INNER JOIN `tabPatient Assessment Template` template + ON template.name = assessment.assessment_template + WHERE + DATE(assessment.assessment_datetime) BETWEEN %(from_date)s AND %(to_date)s and + assessment.docstatus = 1 and + sheet.parameter = %(parameter)s and + assessment.patient = %(patient)s + ORDER BY + assessment.assessment_datetime asc + """, + query_values, + as_list=1, + ) + + score_percentages = [] + for r in results: + if r[2] != 0 and r[0] != None: + score = round((int(r[1]) / int(r[2])) * 100, 2) + score_percentages.append(score) + + return { + "labels": [getdate(r[0]) for r in results if r[0] != None], + "datasets": [{"name": _("Score"), "values": score_percentages}], + } + + +def get_date_range(time_span): + try: + time_span = json.loads(time_span) + return time_span + except json.decoder.JSONDecodeError: + return get_timespan_date_range(time_span.lower()) diff --git a/healthcare/healthcare/page/patient_progress/patient_progress_sidebar.html b/healthcare/healthcare/page/patient_progress/patient_progress_sidebar.html new file mode 100644 index 0000000..4ee6573 --- /dev/null +++ b/healthcare/healthcare/page/patient_progress/patient_progress_sidebar.html @@ -0,0 +1,29 @@ +
+
+ {% if patient_image %} +
+ {% endif %} +
+
+ {% if patient_name %} +

{{patient_name}}

+ {% endif %} + {% if patient_gender %} +

{%=__("Gender: ") %} {{patient_gender}}

+ {% endif %} + {% if patient_mobile %} +

{%=__("Contact: ") %} {{patient_mobile}}

+ {% endif %} + {% if total_therapy_sessions %} +

{%=__("Total Therapy Sessions: ") %} {{total_therapy_sessions}}

+ {% endif %} + {% if therapy_sessions_this_month %} +

{%=__("Monthly Therapy Sessions: ") %} {{therapy_sessions_this_month}}

+ {% endif %} +
+ +
diff --git a/healthcare/healthcare/print_format/__init__.py b/healthcare/healthcare/print_format/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/print_format/encounter_print/__init__.py b/healthcare/healthcare/print_format/encounter_print/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/print_format/encounter_print/encounter_print.json b/healthcare/healthcare/print_format/encounter_print/encounter_print.json new file mode 100644 index 0000000..3c90adb --- /dev/null +++ b/healthcare/healthcare/print_format/encounter_print/encounter_print.json @@ -0,0 +1,22 @@ +{ + "align_labels_right": 0, + "creation": "2017-04-10 14:05:53.355863", + "custom_format": 1, + "disabled": 0, + "doc_type": "Patient Encounter", + "docstatus": 0, + "doctype": "Print Format", + "font": "Default", + "html": "
\n {% if letter_head and not no_letterhead -%}\n
{{ letter_head }}
\n
\n {% else %}\n
\n

{{doc.name}}

\n
\n {%- endif %}\n
\n
\n {% if doc.appointment %}\n\t
\n\t\t\t
\n\t\t\t\n\t\t\t
\n\t\t\t
\n\t\t\t: {{doc.appointment}}\n\t\t\t
\n\t\t
\n\t\t{%- endif -%}\n\n
\n\t\t
\n\t\t\t \n\t\t
\n {% if doc.patient %}\n\t\t
\n\t\t\t : {{doc.patient}}\n\t\t
\n {% else %}\n
\n\t\t\t : Patient Name\n\t\t
\n {%- endif -%}\n\t\t
\n\t
\n\t\t\t
\n\t\t\t\t\n\t\t\t
\n\t\t\t
\n\t\t\t : {{doc.patient_age}}\n\t\t\t
\n\t\t
\n\n
\n
\n\t\t\t\t\n\t\t\t
\n\t\t\t
\n\t\t\t : {{doc.patient_sex}}\n\t\t\t
\n
\n\n
\n
\n\n
\n\t
\n\t\t \n\t
\n {% if doc.practitioner %}\n\t
\n\t\t\t: {{doc.practitioner}}\n\t
\n {%- endif -%}\n\t
\n\n {% if doc.encounter_date %}\n\t
\n\t\t
\n\t\t\n\t\t
\n\t\t
\n\t\t: {{doc.encounter_date}}\n\t\t
\n
\n\t {%- endif -%}\n {% if doc.encounter_time %}\n\t
\n\t\t
\n\t\t\n\t\t
\n\t\t
\n\t\t: {{doc.encounter_time}}\n\t\t
\n
\n\t {%- endif -%}\n {% if doc.medical_department %}\n\t
\n\t\t
\n\t\t\n\t\t
\n\t\t
\n\t\t: {{doc.visit_department}}\n\t\t
\n
\n {%- endif -%}\n
\n\n
\n\n
\n
\n
\n {% if doc.symptoms_in_print%}\n {% if doc.symptoms %}\n Complaints:\n {{doc.symptoms}}\n \t
\n {%- endif -%}\n {%- endif -%}\n\n {% if doc.diagnosis_in_print%}\n {% if doc.diagnosis %}\n \t Diagnosis:\n {{doc.diagnosis}}\n
\n {%- endif -%}\n {%- endif -%}\n\n
\n\n
\n {% if doc.drug_prescription %}\n
\n Rx,\n \n \n \n\n {%- for row in doc.drug_prescription -%}\n \n \n \t\n \t\n \n \n\t {%- endfor -%}\n \n
\n {%- if row.drug_name -%}{{ row.drug_name }}{%- endif -%}\n \n {%- if row.dosage -%}{{ row.dosage }}{%- endif -%}\n \n {%- if row.period -%}{{ row.period }}{%- endif -%}\n\t\t \n\t\t\t
\n {%- if row.comment -%}{{ row.comment }}{%- endif -%}\n
\n\t\t
\n\n\n {%- endif -%}\n
\n\n\n
\n {% if doc.lab_test_prescription %}\n Investigations,\n \n \n \n\n {%- for row in doc.lab_test_prescription -%}\n \n \n \n \n\n\t {%- endfor -%}\n \n
\n {%- if row.lab_test_name -%}{{ row.lab_test_name }}{%- endif -%}\n \n\t\t\t
\n {%- if row.lab_test_comment -%}{{ row.lab_test_comment }}{%- endif -%}\n
\n\t\t
\n\n\n {%- endif -%}\n
\n
\n {% if doc.encounter_comment %}\n
\n {{doc.encounter_comment}}\n {%- endif -%}\n
\n", + "idx": 0, + "line_breaks": 0, + "modified": "2018-09-04 11:52:54.473702", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Encounter Print", + "owner": "Administrator", + "print_format_builder": 0, + "print_format_type": "Jinja", + "show_section_headings": 0, + "standard": "Yes" +} \ No newline at end of file diff --git a/healthcare/healthcare/print_format/lab_test_print/__init__.py b/healthcare/healthcare/print_format/lab_test_print/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/print_format/lab_test_print/lab_test_print.json b/healthcare/healthcare/print_format/lab_test_print/lab_test_print.json new file mode 100644 index 0000000..f7d1676 --- /dev/null +++ b/healthcare/healthcare/print_format/lab_test_print/lab_test_print.json @@ -0,0 +1,23 @@ +{ + "align_labels_right": 0, + "creation": "2017-04-24 15:38:45.332473", + "custom_format": 1, + "disabled": 0, + "doc_type": "Lab Test", + "docstatus": 0, + "doctype": "Print Format", + "font": "Default", + "html": "
\n {% if letter_head and not no_letterhead -%}\n
{{ letter_head }}
\n
\n {%- endif %}\n\n {% if (doc.docstatus != 1) %}\n

WORKSHEET

\n\t
\n\t
\n
\n\n
\n
\n \n
\n {% if doc.patient_name %}\n
\n {{ doc.patient_name }}\n
\n {% else %}\n
\n {{ doc.patient }}\n
\n {%- endif -%}\n
\n\n
\n
\n \n
\n
\n {{ doc.patient_age or '' }}\n
\n
\n\n
\n
\n \n
\n
\n {{ doc.patient_sex or '' }}\n
\n
\n\n
\n\n
\n\n
\n
\n \n
\n {% if doc.practitioner_name %}\n
\n {{ doc.practitioner_name }}\n
\n {% else %}\n\t\t\t{% if doc.referring_practitioner_name %}\n
\n {{ doc.referring_practitioner_name }}\n
\n\t\t {% endif %}\n {%- endif -%}\n
\n\n {% if doc.sample_date %}\n
\n
\n \n
\n
\n {{ doc.sample_date }}\n
\n
\n {%- endif -%}\n
\n
\n\n\t
\n

Department of {{ doc.department }}

\n
\n\n\t\n \n {%- if doc.normal_test_items -%}\n \n \n \n \n \n\n {%- if doc.normal_test_items|length > 1 %}\n \n {%- endif -%}\n\n {%- for row in doc.normal_test_items -%}\n \n \n\n \n\n \n \n\n {%- endfor -%}\n {%- endif -%}\n \n
Name of TestResultNormal Range
{{ doc.lab_test_name }}
\n {%- if doc.normal_test_items|length > 1 %}  {%- endif -%}\n {%- if row.lab_test_name -%}{{ row.lab_test_name }}\n {%- else -%}   {%- endif -%}\n {%- if row.lab_test_event -%}   {{ row.lab_test_event }}{%- endif -%}\n \n {%- if row.lab_test_uom -%} {{ row.lab_test_uom }}{%- endif -%}\n \n
\n {%- if row.normal_range -%}{{ row.normal_range }}{%- endif -%}\n
\n
\n\n\t\n \n {%- if doc.descriptive_test_items -%}\n \n \n \n \n \n\t\t\t{% set gr_lab_test_name = {'ltname': ''} %}\n {%- for row in doc.descriptive_test_items -%}\n\t\t\t{%- if row.lab_test_name -%}\n\t\t\t{%- if row.lab_test_name != gr_lab_test_name.ltname -%}\n\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\t{% if gr_lab_test_name.update({'ltname': row.lab_test_name}) %} {% endif %}\n\t\t\t{%- endif -%}\n\t\t\t{%- endif -%}\n \n \n \n \n {%- endfor -%}\n {%- endif -%}\n \n
Name of TestResult
{{ doc.lab_test_name }}
 {{ row.lab_test_name }}
  {{ row.lab_test_particulars }}
\n
\n {% if doc.worksheet_instructions %}\n
\n Instructions\n {{ doc.worksheet_instructions }}\n {%- endif -%}\n
\n {% elif (frappe.db.get_value(\"Healthcare Settings\", \"None\", \"require_test_result_approval\") == '1' and doc.status != \"Approved\") %}\n Lab Tests have to be Approved for Print .. !\n {%- else -%}\n
\n
\n\n
\n
\n \n
\n {% if doc.patient_name %}\n
\n {{ doc.patient_name }}\n
\n {% else %}\n
\n {{ doc.patient }}\n
\n {%- endif -%}\n
\n\n
\n
\n \n
\n
\n {{ doc.patient_age or '' }}\n
\n
\n\n
\n
\n \n
\n
\n {{ doc.patient_sex or '' }}\n
\n
\n\n
\n\n
\n\n
\n
\n \n
\n {% if doc.practitioner_name %}\n
\n {{ doc.practitioner_name }}\n
\n\t\t{% else %}\n\t\t {% if doc.referring_practitioner_name %}\n
\n {{ doc.referring_practitioner_name }}\n
\n\t\t\t{% endif %}\n {%- endif -%}\n
\n\n {% if doc.sample_date %}\n
\n
\n \n
\n
\n {{ doc.sample_date }}\n
\n
\n {%- endif -%}\n\n {% if doc.result_date %}\n
\n
\n \n
\n
\n {{ doc.result_date }}\n
\n
\n {%- endif -%}\n\n
\n\n
\n\n
\n

Department of {{ doc.department }}

\n
\n\n\t
\n\t\t{% if doc.result_legend and (doc.legend_print_position == \"Top\" or doc.legend_print_position == \"Both\")%}\n\t\tResult Legend:\n\t\t{{ doc.result_legend }}\n\t\t{%- endif -%}\n\t
\n\n \n \n {%- if doc.normal_test_items -%}\n \n \n \n \n \n\n {%- if doc.normal_test_items|length > 1 %}\n \n {%- endif -%}\n\n {%- for row in doc.normal_test_items -%}\n \n \n\n \n\n \n \n\n {%- endfor -%}\n {%- endif -%}\n \n
Name of TestResultNormal Range
{{ doc.lab_test_name }}
\n {%- if doc.normal_test_items|length > 1 %}  {%- endif -%}\n {%- if row.lab_test_name -%}{{ row.lab_test_name }}\n {%- else -%}   {%- endif -%}\n {%- if row.lab_test_event -%}   {{ row.lab_test_event }}{%- endif -%}\n \n\t\t\t\t\t{%- if row.result_value -%}\n\t\t\t\t\t\t{%- if row.bold -%}{% endif %}\n\t\t\t\t\t\t{%- if row.underline -%}{% endif %}\n\t\t\t\t\t\t{%- if row.italic -%}{% endif %}\n {{ row.result_value }}\n {%- if row.lab_test_uom -%} {{ row.lab_test_uom }}{%- endif -%}\n\t\t\t\t\t\t{%- if row.italic -%}{% endif %}\n\t\t\t\t\t\t{%- if row.underline -%}{% endif %}\n\t\t\t\t\t\t{%- if row.bold -%}{% endif %}\n\t\t\t\t\t{%- endif -%}\n \n\t\t\t\t\t{%- if row.secondary_uom and row.conversion_factor and row.secondary_uom_result -%}\n\t\t\t\t\t\t
\n\t\t\t\t\t\t{%- if row.bold -%}{% endif %}\n\t\t\t\t\t\t{%- if row.underline -%}{% endif %}\n\t\t\t\t\t\t{%- if row.italic -%}{% endif %}\n {{ row.secondary_uom_result }}\n  {{ row.secondary_uom }}\n\t\t\t\t\t\t{%- if row.italic -%}{% endif %}\n\t\t\t\t\t\t{%- if row.underline -%}{% endif %}\n\t\t\t\t\t\t{%- if row.bold -%}{% endif %}\n\t\t\t\t\t\t \n\t\t\t\t\t{%- endif -%}\n
\n
\n {%- if row.normal_range -%}{{ row.normal_range }}{%- endif -%}\n
\n
\n\n \n \n {%- if doc.descriptive_test_items -%}\n \n \n \n \n \n\t\t\t{% set gr_lab_test_name = {'ltname': ''} %}\n {%- for row in doc.descriptive_test_items -%}\n\t\t\t{%- if row.lab_test_name -%}\n\t\t\t{%- if row.lab_test_name != gr_lab_test_name.ltname -%}\n\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\t{% if gr_lab_test_name.update({'ltname': row.lab_test_name}) %} {% endif %}\n\t\t\t{%- endif -%}\n\t\t\t{%- endif -%}\n \n \n \n \n {%- endfor -%}\n {%- endif -%}\n\n\t\t\t{%- if doc.organisms -%}\n\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\t{%- for row in doc.organisms -%}\n\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\t{%- endfor -%}\n\t\t\t{%- endif -%}\n\n\t\t\t{%- if doc.sensitivity_test_items -%}\n\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\t{%- for row in doc.sensitivity_test_items -%}\n\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\t{%- endfor -%}\n\t\t\t{%- endif -%}\n\n \n
Name of TestResult
{{ doc.lab_test_name }}
 {{ row.lab_test_name }}
  {{ row.lab_test_particulars }} \n {%- if row.result_value -%}{{ row.result_value }}{%- endif -%}\n
OrganismColony Population
{{ row.organism }} \n\t\t\t\t\t{{ row.colony_population }}\n\t\t\t\t\t{% if row.colony_uom %}\n\t\t\t\t\t\t{{ row.colony_uom }}\n\t\t\t\t\t{% endif %}\n\t\t\t\t
AntibioticSensitivity
{{ row.antibiotic }} {{ row.antibiotic_sensitivity }}
\n
\n {% if doc.custom_result %}\n
\n
{{ doc.custom_result }}
\n {%- endif -%}\n
\n\n
\n {% if doc.lab_test_comment %}\n
\n Comments\n {{ doc.lab_test_comment }}\n {%- endif -%}\n
\n\n
\n {%- if (frappe.db.get_value(\"Healthcare Settings\", \"None\", \"employee_name_and_designation_in_print\") == '1') -%}\n {%- if doc.employee_name -%}\n
{{ doc.employee_name }}
\n {%- endif -%}\n {%- if doc.employee_designation -%}\n
{{ doc.employee_designation }}
\n {%- endif -%}\n {%- else -%}\n {%- if frappe.db.get_value(\"Healthcare Settings\", \"None\", \"custom_signature_in_print\") -%}\n
{{ frappe.db.get_value(\"Healthcare Settings\", \"None\", \"custom_signature_in_print\") }}
\n {%- endif -%}\n {%- endif -%}\n
\n\n
\n {% if doc.result_legend and (doc.legend_print_position == \"Bottom\" or doc.legend_print_position == \"Both\" or doc.legend_print_position == \"\")%}\n
\n Result Legend\n {{ doc.result_legend }}\n {%- endif -%}\n
\n {%- endif -%}\n
", + "idx": 0, + "line_breaks": 0, + "modified": "2020-07-08 15:34:28.866798", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Lab Test Print", + "owner": "Administrator", + "print_format_builder": 0, + "print_format_type": "Jinja", + "raw_printing": 0, + "show_section_headings": 0, + "standard": "Yes" +} \ No newline at end of file diff --git a/healthcare/healthcare/print_format/sample_id_print/__init__.py b/healthcare/healthcare/print_format/sample_id_print/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/print_format/sample_id_print/sample_id_print.json b/healthcare/healthcare/print_format/sample_id_print/sample_id_print.json new file mode 100644 index 0000000..4819e6d --- /dev/null +++ b/healthcare/healthcare/print_format/sample_id_print/sample_id_print.json @@ -0,0 +1,22 @@ +{ + "align_labels_left": 0, + "creation": "2017-02-17 17:40:52.967840", + "custom_format": 1, + "disabled": 0, + "doc_type": "Sample Collection", + "docstatus": 0, + "doctype": "Print Format", + "font": "Default", + "html": "\n{% set column = 0 %}\n\n{% for _ in range(0, doc.num_print) %}\n{% if column == 0 -%}{% endif %}\n\t\n{% if column == 0 %}{% set column = column+1 %}\n{% elif column == 2%} {%- set column = 0 %}\n{% else %}{%- set column = column+1 -%}{%- endif %}\n\t\n{% endfor %}\n
{{doc.name}}
{{doc.patient}}
\n{% if doc.patient_age %}{{doc.patient_age}}, {% endif %} {% if doc.patient_sex %}{{doc.patient_sex}}{% endif %}
{% if doc.collected_time %}{{doc.collected_time}} {% endif %}
{% if doc.collected_by %} {{doc.collected_by}} {% endif %}
", + "idx": 0, + "line_breaks": 0, + "modified": "2017-03-30 18:09:39.537609", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Sample ID Print", + "owner": "Administrator", + "print_format_builder": 0, + "print_format_type": "Jinja", + "show_section_headings": 0, + "standard": "Yes" +} diff --git a/healthcare/healthcare/report/__init__.py b/healthcare/healthcare/report/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/report/diagnosis_trends/__init__.py b/healthcare/healthcare/report/diagnosis_trends/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/report/diagnosis_trends/diagnosis_trends.js b/healthcare/healthcare/report/diagnosis_trends/diagnosis_trends.js new file mode 100644 index 0000000..75b1899 --- /dev/null +++ b/healthcare/healthcare/report/diagnosis_trends/diagnosis_trends.js @@ -0,0 +1,93 @@ +// Copyright (c) 2016, InfluxERP +// For license information, please see license.txt +/* eslint-disable */ + +frappe.query_reports['Diagnosis Trends'] = { + "filters": [ + { + fieldname: 'department', + label: __('Medical Department'), + fieldtype: 'Link', + options: 'Medical Department' + }, + { + fieldname: 'from_date', + label: __('From Date'), + fieldtype: 'Date', + default: frappe.defaults.get_user_default('year_start_date'), + reqd: 1 + }, + { + fieldname: 'to_date', + label: __('To Date'), + fieldtype: 'Date', + default: frappe.defaults.get_user_default('year_end_date'), + reqd: 1 + }, + { + fieldname: 'range', + label: __('Range'), + fieldtype: 'Select', + options:[ + {label: __('Weekly'), value: 'Weekly'}, + {label: __('Monthly'), value: 'Monthly'}, + {label: __('Quarterly'), value: 'Quarterly'}, + {label: __('Yearly'), value: 'Yearly'} + ], + default: 'Monthly', + reqd: 1 + } + ], + get_datatable_options(options) { + return Object.assign(options, { + checkboxColumn: true, + events: { + onCheckRow: function(data) { + row_name = data[2].content; + length = data.length; + + row_values = data.slice(3,length-1).map(function (column) { + return column.content; + }) + + entry = { + 'name': row_name, + 'values': row_values + } + + let raw_data = frappe.query_report.chart.data; + let new_datasets = raw_data.datasets; + + let found = false; + for (let i=0; i < new_datasets.length; i++) { + if (new_datasets[i].name == row_name) { + found = true; + new_datasets.splice(i,1); + break; + } + } + + if (!found) { + new_datasets.push(entry); + } + + let new_data = { + labels: raw_data.labels, + datasets: new_datasets + } + + setTimeout(() => { + frappe.query_report.chart.update(new_data) + }, 500) + + + setTimeout(() => { + frappe.query_report.chart.draw(true); + }, 1000) + + frappe.query_report.raw_chart_data = new_data; + }, + } + }) + }, +}; diff --git a/healthcare/healthcare/report/diagnosis_trends/diagnosis_trends.json b/healthcare/healthcare/report/diagnosis_trends/diagnosis_trends.json new file mode 100644 index 0000000..70d8f17 --- /dev/null +++ b/healthcare/healthcare/report/diagnosis_trends/diagnosis_trends.json @@ -0,0 +1,35 @@ +{ + "add_total_row": 0, + "columns": [], + "creation": "2021-09-08 11:21:13.655665", + "disable_prepared_report": 0, + "disabled": 0, + "docstatus": 0, + "doctype": "Report", + "filters": [], + "idx": 0, + "is_standard": "Yes", + "modified": "2021-11-10 09:27:19.153846", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Diagnosis Trends", + "owner": "Administrator", + "prepared_report": 0, + "ref_doctype": "Patient Encounter Diagnosis", + "report_name": "Diagnosis Trends", + "report_type": "Script Report", + "roles": [ + { + "role": "Healthcare Administrator" + }, + { + "role": "Nursing User" + }, + { + "role": "Physician" + }, + { + "role": "System Manager" + } + ] +} \ No newline at end of file diff --git a/healthcare/healthcare/report/diagnosis_trends/diagnosis_trends.py b/healthcare/healthcare/report/diagnosis_trends/diagnosis_trends.py new file mode 100644 index 0000000..789a460 --- /dev/null +++ b/healthcare/healthcare/report/diagnosis_trends/diagnosis_trends.py @@ -0,0 +1,167 @@ +# Copyright (c) 2013, InfluxERP +# For license information, please see license.txt + +import frappe +from frappe import _, scrub +from frappe.database.query import OPERATOR_MAP +from frappe.utils import add_days, add_to_date, flt, getdate + +from erpnext.accounts.utils import get_fiscal_year + + +def execute(filters=None): + return DiagnosisTrends(filters).run() + + +class DiagnosisTrends(object): + """ + Diagnosis Trends Report. + """ + + def __init__(self, filters=None): + self.data = [] + self.periodic_daterange = [] + self.filters = frappe._dict(filters or {}) + self.months = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ] + self.get_period_date_ranges() + + def run(self): + self.get_columns() + self.get_data() + self.get_chart_data() + + return self.columns, self.data, None, self.chart + + def get_period_date_ranges(self): + from dateutil.relativedelta import MO, relativedelta + + from_date, to_date = getdate(self.filters.from_date), getdate(self.filters.to_date) + + increment = {"Monthly": 1, "Quarterly": 3, "Half-Yearly": 6, "Yearly": 12}.get( + self.filters.range, 1 + ) + + if self.filters.range in ["Monthly", "Quarterly"]: + from_date = from_date.replace(day=1) + elif self.filters.range == "Yearly": + from_date = get_fiscal_year(from_date)[1] + else: + from_date = from_date + relativedelta(from_date, weekday=MO(-1)) + + for _ in range(1, 53): + if self.filters.range == "Weekly": + period_end_date = add_days(from_date, 6) + else: + period_end_date = add_to_date(from_date, months=increment, days=-1) + + if period_end_date > to_date: + period_end_date = to_date + + self.periodic_daterange.append(period_end_date) + + from_date = add_days(period_end_date, 1) + if period_end_date == to_date: + break + + def get_columns(self): + self.columns = [] + + self.columns.append( + { + "label": _("Diagnosis"), + "fieldname": "diagnosis", + "fieldtype": "Link", + "options": "Diagnosis", + "width": 150, + } + ) + + for end_date in self.periodic_daterange: + period = self.get_period(end_date) + self.columns.append( + {"label": _(period), "fieldname": scrub(period), "fieldtype": "Int", "width": 120} + ) + + self.columns.append( + {"label": _("Total"), "fieldname": "total", "fieldtype": "Int", "width": 120} + ) + + def get_data(self): + pe_diagnosis = frappe.qb.DocType("Patient Encounter Diagnosis") + query = ( + frappe.qb.from_(pe_diagnosis) + .select("name", "creation", "diagnosis") + .where(pe_diagnosis.creation[self.filters.from_date : self.filters.to_date]) + ) + + department = self.filters.get("department") + + if department: + encounters = frappe.get_all( + "Patient Encounter", filters={"medical_department": department}, pluck="name" + ) + if encounters: + _operator = OPERATOR_MAP["in"] + query = query.where(_operator(pe_diagnosis.parent, encounters)) + + self.entries = query.run(as_dict=True) + self.get_rows() + + def get_period(self, appointment_date): + if self.filters.range == "Weekly": + period = "Week " + str(appointment_date.isocalendar()[1]) + elif self.filters.range == "Monthly": + period = str(self.months[appointment_date.month - 1]) + elif self.filters.range == "Quarterly": + period = "Quarter " + str(((appointment_date.month - 1) // 3) + 1) + else: + year = get_fiscal_year(appointment_date, company=self.filters.company) + period = str(year[0]) + + if getdate(self.filters.from_date).year != getdate(self.filters.to_date).year: + period += " " + str(appointment_date.year) + + return period + + def get_rows(self): + self.get_periodic_data() + + for entity, period_data in self.appointment_periodic_data.items(): + row = {"diagnosis": entity} + + total = 0 + for end_date in self.periodic_daterange: + period = self.get_period(end_date) + amount = flt(period_data.get(period, 0.0)) + row[scrub(period)] = amount + total += amount + + row["total"] = total + + self.data.append(row) + + def get_periodic_data(self): + self.appointment_periodic_data = frappe._dict() + + for d in self.entries: + period = self.get_period(d.get("creation")) + self.appointment_periodic_data.setdefault(d.diagnosis, frappe._dict()).setdefault(period, 0.0) + self.appointment_periodic_data[d.diagnosis][period] += 1 + + def get_chart_data(self): + length = len(self.columns) + labels = [d.get("label") for d in self.columns[1 : length - 1]] + self.chart = {"data": {"labels": labels, "datasets": []}, "type": "line"} diff --git a/healthcare/healthcare/report/diagnosis_trends/test_diagnosis_trends.py b/healthcare/healthcare/report/diagnosis_trends/test_diagnosis_trends.py new file mode 100644 index 0000000..e38995e --- /dev/null +++ b/healthcare/healthcare/report/diagnosis_trends/test_diagnosis_trends.py @@ -0,0 +1,104 @@ +import frappe +from frappe.tests.utils import FrappeTestCase +from frappe import DuplicateEntryError +from frappe.utils import add_months, getdate, add_days +from healthcare.healthcare.doctype.patient_appointment.test_patient_appointment import ( + create_practitioner, +) + +from healthcare.healthcare.report.diagnosis_trends.diagnosis_trends import execute +from healthcare.healthcare.test_utils import create_encounter + +months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + + +class TestDiagnosisTrends(FrappeTestCase): + @classmethod + def setUpClass(cls): + cls.create_diagnosis() + + @classmethod + def create_diagnosis(cls): + medical_department = frappe.get_doc( + {"doctype": "Medical Department", "department": "Cardiology"} + ) + try: + medical_department.insert() + except DuplicateEntryError: + pass + + patient = frappe.get_list("Patient")[0] + practitioner_name = create_practitioner(medical_department=medical_department.name) + encounter_cardiology = create_encounter( + patient=patient.name, + practitioner=practitioner_name, + ) + encounter = frappe.get_list( + "Patient Encounter", + )[0] + + try: + cls.diagnosis = frappe.get_doc( + { + "doctype": "Diagnosis", + "diagnosis": "Fever", + } + ) + cls.diagnosis.insert() + except DuplicateEntryError: + pass + + try: + cls.diagnosis_cardio = frappe.get_doc( + { + "doctype": "Diagnosis", + "diagnosis": "Heart Attack", + } + ) + cls.diagnosis_cardio.insert() + except DuplicateEntryError: + pass + + encounter = frappe.get_doc("Patient Encounter", encounter["name"]) + encounter.append( + "diagnosis", + { + "diagnosis": "Fever", + }, + ) + encounter.save() + + encounter_cardiology.reload() + encounter_cardiology.append( + "diagnosis", + { + "diagnosis": "Heart Attack", + }, + ) + encounter_cardiology.save() + + def test_report_data(self): + filters = { + "from_date": str(add_months(getdate(), -12)), + "to_date": str(add_days(getdate(), 1)), + "range": "Monthly", + } + + report = execute(filters) + data = [i["diagnosis"] for i in report[1]] + self.assertIn(self.diagnosis.diagnosis, data) + + def test_report_data_with_filters(self): + medical_department = frappe.get_doc("Medical Department", "Cardiology") + + filters = { + "from_date": str(add_months(getdate(), -12)), + "to_date": str(add_days(getdate(), 1)), + "range": "Monthly", + "department": medical_department.name, + } + report = execute(filters) + + data = [i["diagnosis"] for i in report[1]] + + self.assertIn(self.diagnosis_cardio.diagnosis, data) diff --git a/healthcare/healthcare/report/inpatient_medication_orders/__init__.py b/healthcare/healthcare/report/inpatient_medication_orders/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/report/inpatient_medication_orders/inpatient_medication_orders.js b/healthcare/healthcare/report/inpatient_medication_orders/inpatient_medication_orders.js new file mode 100644 index 0000000..ce9260a --- /dev/null +++ b/healthcare/healthcare/report/inpatient_medication_orders/inpatient_medication_orders.js @@ -0,0 +1,57 @@ +// Copyright (c) 2016, InfluxERP +// For license information, please see license.txt +/* eslint-disable */ + +frappe.query_reports["Inpatient Medication Orders"] = { + "filters": [ + { + fieldname: "company", + label: __("Company"), + fieldtype: "Link", + options: "Company", + default: frappe.defaults.get_user_default("Company"), + reqd: 1 + }, + { + fieldname: "from_date", + label: __("From Date"), + fieldtype: "Date", + default: frappe.datetime.add_months(frappe.datetime.get_today(), -1), + reqd: 1 + }, + { + fieldname: "to_date", + label: __("To Date"), + fieldtype: "Date", + default: frappe.datetime.now_date(), + reqd: 1 + }, + { + fieldname: "patient", + label: __("Patient"), + fieldtype: "Link", + options: "Patient" + }, + { + fieldname: "service_unit", + label: __("Healthcare Service Unit"), + fieldtype: "Link", + options: "Healthcare Service Unit", + get_query: () => { + var company = frappe.query_report.get_filter_value('company'); + return { + filters: { + 'company': company, + 'is_group': 0 + } + } + } + }, + { + fieldname: "show_completed_orders", + label: __("Show Completed Orders"), + fieldtype: "Check", + default: 1 + } + ] +}; diff --git a/healthcare/healthcare/report/inpatient_medication_orders/inpatient_medication_orders.json b/healthcare/healthcare/report/inpatient_medication_orders/inpatient_medication_orders.json new file mode 100644 index 0000000..9217fa1 --- /dev/null +++ b/healthcare/healthcare/report/inpatient_medication_orders/inpatient_medication_orders.json @@ -0,0 +1,36 @@ +{ + "add_total_row": 0, + "columns": [], + "creation": "2020-11-23 17:25:58.802949", + "disable_prepared_report": 0, + "disabled": 0, + "docstatus": 0, + "doctype": "Report", + "filters": [], + "idx": 0, + "is_standard": "Yes", + "json": "{}", + "modified": "2020-11-23 19:40:20.227591", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Inpatient Medication Orders", + "owner": "Administrator", + "prepared_report": 0, + "ref_doctype": "Inpatient Medication Order", + "report_name": "Inpatient Medication Orders", + "report_type": "Script Report", + "roles": [ + { + "role": "System Manager" + }, + { + "role": "Healthcare Administrator" + }, + { + "role": "Nursing User" + }, + { + "role": "Physician" + } + ] +} \ No newline at end of file diff --git a/healthcare/healthcare/report/inpatient_medication_orders/inpatient_medication_orders.py b/healthcare/healthcare/report/inpatient_medication_orders/inpatient_medication_orders.py new file mode 100644 index 0000000..4bad03c --- /dev/null +++ b/healthcare/healthcare/report/inpatient_medication_orders/inpatient_medication_orders.py @@ -0,0 +1,189 @@ +# Copyright (c) 2013, InfluxERP +# For license information, please see license.txt + + +import frappe + +from healthcare.healthcare.doctype.inpatient_medication_entry.inpatient_medication_entry import ( + get_current_healthcare_service_unit, +) + + +def execute(filters=None): + columns = get_columns() + data = get_data(filters) + chart = get_chart_data(data) + + return columns, data, None, chart + + +def get_columns(): + return [ + { + "fieldname": "patient", + "fieldtype": "Link", + "label": "Patient", + "options": "Patient", + "width": 200, + }, + { + "fieldname": "healthcare_service_unit", + "fieldtype": "Link", + "label": "Healthcare Service Unit", + "options": "Healthcare Service Unit", + "width": 150, + }, + { + "fieldname": "drug", + "fieldtype": "Link", + "label": "Drug Code", + "options": "Item", + "width": 150, + }, + {"fieldname": "drug_name", "fieldtype": "Data", "label": "Drug Name", "width": 150}, + { + "fieldname": "dosage", + "fieldtype": "Link", + "label": "Dosage", + "options": "Prescription Dosage", + "width": 80, + }, + { + "fieldname": "dosage_form", + "fieldtype": "Link", + "label": "Dosage Form", + "options": "Dosage Form", + "width": 100, + }, + {"fieldname": "date", "fieldtype": "Date", "label": "Date", "width": 100}, + {"fieldname": "time", "fieldtype": "Time", "label": "Time", "width": 100}, + {"fieldname": "is_completed", "fieldtype": "Check", "label": "Is Order Completed", "width": 100}, + { + "fieldname": "healthcare_practitioner", + "fieldtype": "Link", + "label": "Healthcare Practitioner", + "options": "Healthcare Practitioner", + "width": 200, + }, + { + "fieldname": "inpatient_medication_entry", + "fieldtype": "Link", + "label": "Inpatient Medication Entry", + "options": "Inpatient Medication Entry", + "width": 200, + }, + { + "fieldname": "inpatient_record", + "fieldtype": "Link", + "label": "Inpatient Record", + "options": "Inpatient Record", + "width": 200, + }, + ] + + +def get_data(filters): + conditions, values = get_conditions(filters) + + data = frappe.db.sql( + """ + SELECT + parent.patient, parent.inpatient_record, parent.practitioner, + child.drug, child.drug_name, child.dosage, child.dosage_form, + child.date, child.time, child.is_completed, child.name + FROM `tabInpatient Medication Order` parent + INNER JOIN `tabInpatient Medication Order Entry` child + ON child.parent = parent.name + WHERE + parent.docstatus = 1 + {conditions} + ORDER BY date, time + """.format( + conditions=conditions + ), + values, + as_dict=1, + ) + + data = get_inpatient_details(data, filters.get("service_unit")) + + return data + + +def get_conditions(filters): + conditions = "" + values = dict() + + if filters.get("company"): + conditions += " AND parent.company = %(company)s" + values["company"] = filters.get("company") + + if filters.get("from_date") and filters.get("to_date"): + conditions += " AND child.date BETWEEN %(from_date)s and %(to_date)s" + values["from_date"] = filters.get("from_date") + values["to_date"] = filters.get("to_date") + + if filters.get("patient"): + conditions += " AND parent.patient = %(patient)s" + values["patient"] = filters.get("patient") + + if not filters.get("show_completed_orders"): + conditions += " AND child.is_completed = 0" + + return conditions, values + + +def get_inpatient_details(data, service_unit): + service_unit_filtered_data = [] + + for entry in data: + entry["healthcare_service_unit"] = get_current_healthcare_service_unit(entry.inpatient_record) + if entry.is_completed: + entry["inpatient_medication_entry"] = get_inpatient_medication_entry(entry.name) + + if ( + service_unit and entry.healthcare_service_unit and service_unit != entry.healthcare_service_unit + ): + service_unit_filtered_data.append(entry) + + entry.pop("name", None) + + for entry in service_unit_filtered_data: + data.remove(entry) + + return data + + +def get_inpatient_medication_entry(order_entry): + return frappe.db.get_value( + "Inpatient Medication Entry Detail", {"against_imoe": order_entry}, "parent" + ) + + +def get_chart_data(data): + if not data: + return None + + labels = ["Pending", "Completed"] + datasets = [] + + status_wise_data = {"Pending": 0, "Completed": 0} + + for d in data: + if d.is_completed: + status_wise_data["Completed"] += 1 + else: + status_wise_data["Pending"] += 1 + + datasets.append( + { + "name": "Inpatient Medication Order Status", + "values": [status_wise_data.get("Pending"), status_wise_data.get("Completed")], + } + ) + + chart = {"data": {"labels": labels, "datasets": datasets}, "type": "donut", "height": 300} + + chart["fieldtype"] = "Data" + + return chart diff --git a/healthcare/healthcare/report/inpatient_medication_orders/test_inpatient_medication_orders.py b/healthcare/healthcare/report/inpatient_medication_orders/test_inpatient_medication_orders.py new file mode 100644 index 0000000..cc9cc0f --- /dev/null +++ b/healthcare/healthcare/report/inpatient_medication_orders/test_inpatient_medication_orders.py @@ -0,0 +1,145 @@ +# Copyright (c) 2018, InfluxERP +# License: GNU General Public License v3. See license.txt + + +import datetime +from frappe.tests.utils import FrappeTestCase + +import frappe +from frappe.utils import getdate, now_datetime + +from healthcare.healthcare.doctype.inpatient_medication_order.test_inpatient_medication_order import ( + create_ipme, + create_ipmo, +) +from healthcare.healthcare.doctype.inpatient_record.inpatient_record import ( + admit_patient, + discharge_patient, + schedule_discharge, +) +from healthcare.healthcare.doctype.inpatient_record.test_inpatient_record import ( + create_inpatient, + create_patient, + get_healthcare_service_unit, + mark_invoiced_inpatient_occupancy, +) +from healthcare.healthcare.report.inpatient_medication_orders.inpatient_medication_orders import ( + execute, +) + + +class TestInpatientMedicationOrders(FrappeTestCase): + @classmethod + def setUpClass(self): + frappe.db.sql("delete from `tabInpatient Medication Order` where company='_Test Company'") + frappe.db.sql("delete from `tabInpatient Medication Entry` where company='_Test Company'") + self.patient = create_patient() + self.ip_record = create_records(self.patient) + + def test_inpatient_medication_orders_report(self): + filters = { + "company": "_Test Company", + "from_date": getdate(), + "to_date": getdate(), + "patient": "_Test IPD Patient", + "service_unit": "_Test Service Unit Ip Occupancy - _TC", + } + + report = execute(filters) + + expected_data = [ + { + "patient": "_Test IPD Patient", + "inpatient_record": self.ip_record.name, + "practitioner": None, + "drug": "Dextromethorphan", + "drug_name": "Dextromethorphan", + "dosage": 1.0, + "dosage_form": "Tablet", + "date": getdate(), + "time": datetime.timedelta(seconds=32400), + "is_completed": 0, + "healthcare_service_unit": "_Test Service Unit Ip Occupancy - _TC", + }, + { + "patient": "_Test IPD Patient", + "inpatient_record": self.ip_record.name, + "practitioner": None, + "drug": "Dextromethorphan", + "drug_name": "Dextromethorphan", + "dosage": 1.0, + "dosage_form": "Tablet", + "date": getdate(), + "time": datetime.timedelta(seconds=50400), + "is_completed": 0, + "healthcare_service_unit": "_Test Service Unit Ip Occupancy - _TC", + }, + { + "patient": "_Test IPD Patient", + "inpatient_record": self.ip_record.name, + "practitioner": None, + "drug": "Dextromethorphan", + "drug_name": "Dextromethorphan", + "dosage": 1.0, + "dosage_form": "Tablet", + "date": getdate(), + "time": datetime.timedelta(seconds=75600), + "is_completed": 0, + "healthcare_service_unit": "_Test Service Unit Ip Occupancy - _TC", + }, + ] + + self.assertEqual(expected_data, report[1]) + + filters = frappe._dict(from_date=getdate(), to_date=getdate(), from_time="", to_time="") + ipme = create_ipme(filters) + ipme.submit() + + filters = { + "company": "_Test Company", + "from_date": getdate(), + "to_date": getdate(), + "patient": "_Test IPD Patient", + "service_unit": "_Test Service Unit Ip Occupancy - _TC", + "show_completed_orders": 0, + } + + report = execute(filters) + self.assertEqual(len(report[1]), 0) + + def tearDown(self): + if frappe.db.get_value("Patient", self.patient, "inpatient_record"): + # cleanup - Discharge + schedule_discharge(frappe.as_json({"patient": self.patient})) + self.ip_record.reload() + mark_invoiced_inpatient_occupancy(self.ip_record) + + self.ip_record.reload() + discharge_patient(self.ip_record) + + for entry in frappe.get_all("Inpatient Medication Entry"): + doc = frappe.get_doc("Inpatient Medication Entry", entry.name) + doc.cancel() + doc.delete() + + for entry in frappe.get_all("Inpatient Medication Order"): + doc = frappe.get_doc("Inpatient Medication Order", entry.name) + doc.cancel() + doc.delete() + + +def create_records(patient): + frappe.db.sql("""delete from `tabInpatient Record`""") + + # Admit + ip_record = create_inpatient(patient) + ip_record.expected_length_of_stay = 0 + ip_record.save() + ip_record.reload() + service_unit = get_healthcare_service_unit("_Test Service Unit Ip Occupancy") + admit_patient(ip_record, service_unit, now_datetime()) + + ipmo = create_ipmo(patient) + ipmo.submit() + + return ip_record diff --git a/healthcare/healthcare/report/lab_test_report/__init__.py b/healthcare/healthcare/report/lab_test_report/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/report/lab_test_report/lab_test_report.js b/healthcare/healthcare/report/lab_test_report/lab_test_report.js new file mode 100644 index 0000000..7754e2e --- /dev/null +++ b/healthcare/healthcare/report/lab_test_report/lab_test_report.js @@ -0,0 +1,57 @@ +// Copyright (c) 2016, ESS +// License: See license.txt + +frappe.query_reports["Lab Test Report"] = { + "filters": [ + { + "fieldname": "from_date", + "label": __("From Date"), + "fieldtype": "Date", + "default": frappe.datetime.add_months(frappe.datetime.get_today(), -1), + "reqd": 1 + }, + { + "fieldname": "to_date", + "label": __("To Date"), + "fieldtype": "Date", + "default": frappe.datetime.now_date(), + "reqd": 1 + }, + { + "fieldname": "company", + "label": __("Company"), + "fieldtype": "Link", + "default": frappe.defaults.get_default("Company"), + "options": "Company" + }, + { + "fieldname": "template", + "label": __("Lab Test Template"), + "fieldtype": "Link", + "options": "Lab Test Template" + }, + { + "fieldname": "patient", + "label": __("Patient"), + "fieldtype": "Link", + "options": "Patient" + }, + { + "fieldname": "department", + "label": __("Medical Department"), + "fieldtype": "Link", + "options": "Medical Department" + }, + { + "fieldname": "status", + "label": __("Status"), + "fieldtype": "Select", + "options": "\nCompleted\nApproved\nRejected" + }, + { + "fieldname": "invoiced", + "label": __("Invoiced"), + "fieldtype": "Check" + } + ] +}; diff --git a/healthcare/healthcare/report/lab_test_report/lab_test_report.json b/healthcare/healthcare/report/lab_test_report/lab_test_report.json new file mode 100644 index 0000000..aeb4289 --- /dev/null +++ b/healthcare/healthcare/report/lab_test_report/lab_test_report.json @@ -0,0 +1,33 @@ +{ + "add_total_row": 0, + "creation": "2013-04-23 18:15:29", + "disable_prepared_report": 0, + "disabled": 0, + "docstatus": 0, + "doctype": "Report", + "idx": 1, + "is_standard": "Yes", + "modified": "2020-07-30 18:53:20.102873", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Lab Test Report", + "owner": "Administrator", + "prepared_report": 0, + "ref_doctype": "Lab Test", + "report_name": "Lab Test Report", + "report_type": "Script Report", + "roles": [ + { + "role": "Laboratory User" + }, + { + "role": "Nursing User" + }, + { + "role": "LabTest Approver" + }, + { + "role": "Healthcare Administrator" + } + ] +} \ No newline at end of file diff --git a/healthcare/healthcare/report/lab_test_report/lab_test_report.py b/healthcare/healthcare/report/lab_test_report/lab_test_report.py new file mode 100644 index 0000000..0d14920 --- /dev/null +++ b/healthcare/healthcare/report/lab_test_report/lab_test_report.py @@ -0,0 +1,207 @@ +# Copyright (c) 2016, ESS +# License: See license.txt + + +import frappe +from frappe import _, msgprint + + +def execute(filters=None): + if not filters: + filters = {} + + data, columns = [], [] + + columns = get_columns() + lab_test_list = get_lab_tests(filters) + + if not lab_test_list: + msgprint(_("No records found")) + return columns, lab_test_list + + data = [] + for lab_test in lab_test_list: + row = frappe._dict( + { + "test": lab_test.name, + "template": lab_test.template, + "company": lab_test.company, + "patient": lab_test.patient, + "patient_name": lab_test.patient_name, + "practitioner": lab_test.practitioner, + "employee": lab_test.employee, + "status": lab_test.status, + "invoiced": lab_test.invoiced, + "result_date": lab_test.result_date, + "department": lab_test.department, + } + ) + data.append(row) + + chart = get_chart_data(data) + report_summary = get_report_summary(data) + return columns, data, None, chart, report_summary + + +def get_columns(): + return [ + { + "fieldname": "test", + "label": _("Lab Test"), + "fieldtype": "Link", + "options": "Lab Test", + "width": "120", + }, + { + "fieldname": "template", + "label": _("Lab Test Template"), + "fieldtype": "Link", + "options": "Lab Test Template", + "width": "120", + }, + { + "fieldname": "company", + "label": _("Company"), + "fieldtype": "Link", + "options": "Company", + "width": "120", + }, + { + "fieldname": "patient", + "label": _("Patient"), + "fieldtype": "Link", + "options": "Patient", + "width": "120", + }, + {"fieldname": "patient_name", "label": _("Patient Name"), "fieldtype": "Data", "width": "120"}, + { + "fieldname": "employee", + "label": _("Lab Technician"), + "fieldtype": "Link", + "options": "Employee", + "width": "120", + }, + {"fieldname": "status", "label": _("Status"), "fieldtype": "Data", "width": "100"}, + {"fieldname": "invoiced", "label": _("Invoiced"), "fieldtype": "Check", "width": "100"}, + {"fieldname": "result_date", "label": _("Result Date"), "fieldtype": "Date", "width": "100"}, + { + "fieldname": "practitioner", + "label": _("Requesting Practitioner"), + "fieldtype": "Link", + "options": "Healthcare Practitioner", + "width": "120", + }, + { + "fieldname": "department", + "label": _("Medical Department"), + "fieldtype": "Link", + "options": "Medical Department", + "width": "100", + }, + ] + + +def get_lab_tests(filters): + conditions = get_conditions(filters) + data = frappe.get_all( + doctype="Lab Test", + fields=[ + "name", + "template", + "company", + "patient", + "patient_name", + "practitioner", + "employee", + "status", + "invoiced", + "result_date", + "department", + ], + filters=conditions, + order_by="submitted_date desc", + ) + return data + + +def get_conditions(filters): + conditions = {"docstatus": ("=", 1)} + + if filters.get("from_date") and filters.get("to_date"): + conditions["result_date"] = ("between", (filters.get("from_date"), filters.get("to_date"))) + filters.pop("from_date") + filters.pop("to_date") + + for key, value in filters.items(): + if filters.get(key): + conditions[key] = value + + return conditions + + +def get_chart_data(data): + if not data: + return None + + labels = ["Completed", "Approved", "Rejected"] + + status_wise_data = {"Completed": 0, "Approved": 0, "Rejected": 0} + + datasets = [] + + for entry in data: + status_wise_data[entry.status] += 1 + + datasets.append( + { + "name": "Lab Test Status", + "values": [ + status_wise_data.get("Completed"), + status_wise_data.get("Approved"), + status_wise_data.get("Rejected"), + ], + } + ) + + chart = { + "data": {"labels": labels, "datasets": datasets}, + "type": "bar", + "height": 300, + } + + return chart + + +def get_report_summary(data): + if not data: + return None + + total_lab_tests = len(data) + invoiced_lab_tests, unbilled_lab_tests = 0, 0 + + for entry in data: + if entry.invoiced: + invoiced_lab_tests += 1 + else: + unbilled_lab_tests += 1 + + return [ + { + "value": total_lab_tests, + "indicator": "Blue", + "label": "Total Lab Tests", + "datatype": "Int", + }, + { + "value": invoiced_lab_tests, + "indicator": "Green", + "label": "Invoiced Lab Tests", + "datatype": "Int", + }, + { + "value": unbilled_lab_tests, + "indicator": "Red", + "label": "Unbilled Lab Tests", + "datatype": "Int", + }, + ] diff --git a/healthcare/healthcare/report/patient_appointment_analytics/__init__.py b/healthcare/healthcare/report/patient_appointment_analytics/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/report/patient_appointment_analytics/patient_appointment_analytics.js b/healthcare/healthcare/report/patient_appointment_analytics/patient_appointment_analytics.js new file mode 100644 index 0000000..63f63c0 --- /dev/null +++ b/healthcare/healthcare/report/patient_appointment_analytics/patient_appointment_analytics.js @@ -0,0 +1,128 @@ +// Copyright (c) 2016, InfluxERP +// For license information, please see license.txt +/* eslint-disable */ + +frappe.query_reports['Patient Appointment Analytics'] = { + "filters": [ + { + fieldname: 'tree_type', + label: __('Tree Type'), + fieldtype: 'Select', + options: ['Healthcare Practitioner', 'Medical Department'], + default: 'Healthcare Practitioner', + reqd: 1 + }, + { + fieldname: 'status', + label: __('Appointment Status'), + fieldtype: 'Select', + options:[ + {label: __('Scheduled'), value: 'Scheduled'}, + {label: __('Open'), value: 'Open'}, + {label: __('Closed'), value: 'Closed'}, + {label: __('Expired'), value: 'Expired'}, + {label: __('Cancelled'), value: 'Cancelled'} + ] + }, + { + fieldname: 'appointment_type', + label: __('Appointment Type'), + fieldtype: 'Link', + options: 'Appointment Type' + }, + { + fieldname: 'practitioner', + label: __('Healthcare Practitioner'), + fieldtype: 'Link', + options: 'Healthcare Practitioner' + }, + { + fieldname: 'department', + label: __('Medical Department'), + fieldtype: 'Link', + options: 'Medical Department' + }, + { + fieldname: 'from_date', + label: __('From Date'), + fieldtype: 'Date', + default: frappe.defaults.get_user_default('year_start_date'), + reqd: 1 + }, + { + fieldname: 'to_date', + label: __('To Date'), + fieldtype: 'Date', + default: frappe.defaults.get_user_default('year_end_date'), + reqd: 1 + }, + { + fieldname: 'range', + label: __('Range'), + fieldtype: 'Select', + options:[ + {label: __('Weekly'), value: 'Weekly'}, + {label: __('Monthly'), value: 'Monthly'}, + {label: __('Quarterly'), value: 'Quarterly'}, + {label: __('Yearly'), value: 'Yearly'} + ], + default: 'Monthly', + reqd: 1 + } + ], + after_datatable_render: function(datatable_obj) { + $(datatable_obj.wrapper).find(".dt-row-0").find('input[type=checkbox]').click(); + }, + get_datatable_options(options) { + return Object.assign(options, { + checkboxColumn: true, + events: { + onCheckRow: function(data) { + row_name = data[2].content; + length = data.length; + + row_values = data.slice(3,length-1).map(function (column) { + return column.content; + }) + + entry = { + 'name': row_name, + 'values': row_values + } + + let raw_data = frappe.query_report.chart.data; + let new_datasets = raw_data.datasets; + + let found = false; + for (let i=0; i < new_datasets.length;i++) { + if (new_datasets[i].name == row_name) { + found = true; + new_datasets.splice(i,1); + break; + } + } + + if (!found) { + new_datasets.push(entry); + } + + let new_data = { + labels: raw_data.labels, + datasets: new_datasets + } + + setTimeout(() => { + frappe.query_report.chart.update(new_data) + }, 500) + + + setTimeout(() => { + frappe.query_report.chart.draw(true); + }, 1000) + + frappe.query_report.raw_chart_data = new_data; + }, + } + }) + }, +}; diff --git a/healthcare/healthcare/report/patient_appointment_analytics/patient_appointment_analytics.json b/healthcare/healthcare/report/patient_appointment_analytics/patient_appointment_analytics.json new file mode 100644 index 0000000..64750c0 --- /dev/null +++ b/healthcare/healthcare/report/patient_appointment_analytics/patient_appointment_analytics.json @@ -0,0 +1,36 @@ +{ + "add_total_row": 1, + "creation": "2020-03-02 15:13:16.273493", + "disable_prepared_report": 0, + "disabled": 0, + "docstatus": 0, + "doctype": "Report", + "idx": 0, + "is_standard": "Yes", + "modified": "2020-03-02 15:13:16.273493", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "Patient Appointment Analytics", + "owner": "Administrator", + "prepared_report": 0, + "ref_doctype": "Patient Appointment", + "report_name": "Patient Appointment Analytics", + "report_type": "Script Report", + "roles": [ + { + "role": "Healthcare Administrator" + }, + { + "role": "LabTest Approver" + }, + { + "role": "Physician" + }, + { + "role": "Nursing User" + }, + { + "role": "Laboratory User" + } + ] +} \ No newline at end of file diff --git a/healthcare/healthcare/report/patient_appointment_analytics/patient_appointment_analytics.py b/healthcare/healthcare/report/patient_appointment_analytics/patient_appointment_analytics.py new file mode 100644 index 0000000..a20f51b --- /dev/null +++ b/healthcare/healthcare/report/patient_appointment_analytics/patient_appointment_analytics.py @@ -0,0 +1,203 @@ +# Copyright (c) 2013, InfluxERP +# For license information, please see license.txt + + +import frappe +from frappe import _, scrub +from frappe.utils import add_days, add_to_date, flt, getdate + +from erpnext.accounts.utils import get_fiscal_year + + +def execute(filters=None): + return Analytics(filters).run() + + +class Analytics(object): + def __init__(self, filters=None): + """Patient Appointment Analytics Report.""" + self.filters = frappe._dict(filters or {}) + self.months = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ] + self.get_period_date_ranges() + + def run(self): + self.get_columns() + self.get_data() + self.get_chart_data() + + return self.columns, self.data, None, self.chart + + def get_period_date_ranges(self): + from dateutil.relativedelta import MO, relativedelta + + from_date, to_date = getdate(self.filters.from_date), getdate(self.filters.to_date) + + increment = {"Monthly": 1, "Quarterly": 3, "Half-Yearly": 6, "Yearly": 12}.get( + self.filters.range, 1 + ) + + if self.filters.range in ["Monthly", "Quarterly"]: + from_date = from_date.replace(day=1) + elif self.filters.range == "Yearly": + from_date = get_fiscal_year(from_date)[1] + else: + from_date = from_date + relativedelta(from_date, weekday=MO(-1)) + + self.periodic_daterange = [] + for dummy in range(1, 53): + if self.filters.range == "Weekly": + period_end_date = add_days(from_date, 6) + else: + period_end_date = add_to_date(from_date, months=increment, days=-1) + + if period_end_date > to_date: + period_end_date = to_date + + self.periodic_daterange.append(period_end_date) + + from_date = add_days(period_end_date, 1) + if period_end_date == to_date: + break + + def get_columns(self): + self.columns = [] + + if self.filters.tree_type == "Healthcare Practitioner": + self.columns.append( + { + "label": _("Healthcare Practitioner"), + "options": "Healthcare Practitioner", + "fieldname": "practitioner", + "fieldtype": "Link", + "width": 200, + } + ) + + elif self.filters.tree_type == "Medical Department": + self.columns.append( + { + "label": _("Medical Department"), + "fieldname": "department", + "fieldtype": "Link", + "options": "Medical Department", + "width": 150, + } + ) + + for end_date in self.periodic_daterange: + period = self.get_period(end_date) + self.columns.append( + {"label": _(period), "fieldname": scrub(period), "fieldtype": "Int", "width": 120} + ) + + self.columns.append( + {"label": _("Total"), "fieldname": "total", "fieldtype": "Int", "width": 120} + ) + + def get_data(self): + if self.filters.tree_type == "Healthcare Practitioner": + self.get_appointments_based_on_healthcare_practitioner() + self.get_rows() + + elif self.filters.tree_type == "Medical Department": + self.get_appointments_based_on_medical_department() + self.get_rows() + + def get_period(self, appointment_date): + if self.filters.range == "Weekly": + period = "Week " + str(appointment_date.isocalendar()[1]) + elif self.filters.range == "Monthly": + period = str(self.months[appointment_date.month - 1]) + elif self.filters.range == "Quarterly": + period = "Quarter " + str(((appointment_date.month - 1) // 3) + 1) + else: + year = get_fiscal_year(appointment_date, company=self.filters.company) + period = str(year[0]) + + if getdate(self.filters.from_date).year != getdate(self.filters.to_date).year: + period += " " + str(appointment_date.year) + + return period + + def get_appointments_based_on_healthcare_practitioner(self): + filters = self.get_common_filters() + + self.entries = frappe.db.get_all( + "Patient Appointment", + fields=["appointment_date", "name", "patient", "practitioner"], + filters=filters, + ) + + def get_appointments_based_on_medical_department(self): + filters = self.get_common_filters() + if not filters.get("department"): + filters["department"] = ("!=", "") + + self.entries = frappe.db.get_all( + "Patient Appointment", + fields=["appointment_date", "name", "patient", "practitioner", "department"], + filters=filters, + ) + + def get_common_filters(self): + filters = {} + filters["appointment_date"] = ("between", [self.filters.from_date, self.filters.to_date]) + for entry in ["appointment_type", "practitioner", "department", "status"]: + if self.filters.get(entry): + filters[entry] = self.filters.get(entry) + + return filters + + def get_rows(self): + self.data = [] + self.get_periodic_data() + + for entity, period_data in self.appointment_periodic_data.items(): + if self.filters.tree_type == "Healthcare Practitioner": + row = {"practitioner": entity} + elif self.filters.tree_type == "Medical Department": + row = {"department": entity} + + total = 0 + for end_date in self.periodic_daterange: + period = self.get_period(end_date) + amount = flt(period_data.get(period, 0.0)) + row[scrub(period)] = amount + total += amount + + row["total"] = total + + self.data.append(row) + + def get_periodic_data(self): + self.appointment_periodic_data = frappe._dict() + + for d in self.entries: + period = self.get_period(d.get("appointment_date")) + if self.filters.tree_type == "Healthcare Practitioner": + self.appointment_periodic_data.setdefault(d.practitioner, frappe._dict()).setdefault( + period, 0.0 + ) + self.appointment_periodic_data[d.practitioner][period] += 1 + + elif self.filters.tree_type == "Medical Department": + self.appointment_periodic_data.setdefault(d.department, frappe._dict()).setdefault(period, 0.0) + self.appointment_periodic_data[d.department][period] += 1 + + def get_chart_data(self): + length = len(self.columns) + labels = [d.get("label") for d in self.columns[1 : length - 1]] + self.chart = {"data": {"labels": labels, "datasets": []}, "type": "line"} diff --git a/healthcare/healthcare/test_utils.py b/healthcare/healthcare/test_utils.py new file mode 100644 index 0000000..7266fb9 --- /dev/null +++ b/healthcare/healthcare/test_utils.py @@ -0,0 +1,12 @@ +import frappe +from frappe import DuplicateEntryError + + +def create_encounter(patient, practitioner, submit=False): + encounter = frappe.new_doc("Patient Encounter") + encounter.patient = patient + encounter.practitioner = practitioner + encounter.save() + if submit: + encounter.submit() + return encounter diff --git a/healthcare/healthcare/utils.py b/healthcare/healthcare/utils.py new file mode 100644 index 0000000..57f7e19 --- /dev/null +++ b/healthcare/healthcare/utils.py @@ -0,0 +1,960 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018, earthians and contributors +# For license information, please see license.txt + + +import json +import math + +import frappe +from frappe import _ +from frappe.utils import cstr, get_link_to_form, rounded, time_diff_in_hours +from frappe.utils.formatters import format_value +from erpnext.setup.utils import insert_record + +from healthcare.healthcare.doctype.fee_validity.fee_validity import create_fee_validity +from healthcare.healthcare.doctype.healthcare_settings.healthcare_settings import ( + get_income_account, +) +from healthcare.healthcare.doctype.lab_test.lab_test import create_multiple +from healthcare.setup import setup_healthcare + + +@frappe.whitelist() +def get_healthcare_services_to_invoice(patient, company): + patient = frappe.get_doc("Patient", patient) + items_to_invoice = [] + if patient: + validate_customer_created(patient) + # Customer validated, build a list of billable services + items_to_invoice += get_appointments_to_invoice(patient, company) + items_to_invoice += get_encounters_to_invoice(patient, company) + items_to_invoice += get_lab_tests_to_invoice(patient, company) + items_to_invoice += get_clinical_procedures_to_invoice(patient, company) + items_to_invoice += get_inpatient_services_to_invoice(patient, company) + items_to_invoice += get_therapy_plans_to_invoice(patient, company) + items_to_invoice += get_therapy_sessions_to_invoice(patient, company) + + return items_to_invoice + + +def validate_customer_created(patient): + if not frappe.db.get_value("Patient", patient.name, "customer"): + msg = _("Please set a Customer linked to the Patient") + msg += " {0}".format(patient.name) + frappe.throw(msg, title=_("Customer Not Found")) + + +def get_appointments_to_invoice(patient, company): + appointments_to_invoice = [] + patient_appointments = frappe.get_list( + "Patient Appointment", + fields="*", + filters={ + "patient": patient.name, + "company": company, + "invoiced": 0, + "status": ["not in", "Cancelled"], + }, + order_by="appointment_date", + ) + + for appointment in patient_appointments: + # Procedure Appointments + if appointment.procedure_template: + if frappe.db.get_value( + "Clinical Procedure Template", appointment.procedure_template, "is_billable" + ): + appointments_to_invoice.append( + { + "reference_type": "Patient Appointment", + "reference_name": appointment.name, + "service": appointment.procedure_template, + } + ) + # Consultation Appointments, should check fee validity + else: + if frappe.db.get_single_value( + "Healthcare Settings", "enable_free_follow_ups" + ) and frappe.db.exists("Fee Validity Reference", {"appointment": appointment.name}): + continue # Skip invoicing, fee validty present + practitioner_charge = 0 + income_account = None + service_item = None + if appointment.practitioner: + details = get_service_item_and_practitioner_charge(appointment) + service_item = details.get("service_item") + practitioner_charge = details.get("practitioner_charge") + income_account = get_income_account(appointment.practitioner, appointment.company) + appointments_to_invoice.append( + { + "reference_type": "Patient Appointment", + "reference_name": appointment.name, + "service": service_item, + "rate": practitioner_charge, + "income_account": income_account, + } + ) + + return appointments_to_invoice + + +def get_encounters_to_invoice(patient, company): + if not isinstance(patient, str): + patient = patient.name + encounters_to_invoice = [] + encounters = frappe.get_list( + "Patient Encounter", + fields=["*"], + filters={"patient": patient, "company": company, "invoiced": False, "docstatus": 1}, + ) + if encounters: + for encounter in encounters: + if not encounter.appointment: + practitioner_charge = 0 + income_account = None + service_item = None + if encounter.practitioner: + if encounter.inpatient_record and frappe.db.get_single_value( + "Healthcare Settings", "do_not_bill_inpatient_encounters" + ): + continue + + details = get_service_item_and_practitioner_charge(encounter) + service_item = details.get("service_item") + practitioner_charge = details.get("practitioner_charge") + income_account = get_income_account(encounter.practitioner, encounter.company) + + encounters_to_invoice.append( + { + "reference_type": "Patient Encounter", + "reference_name": encounter.name, + "service": service_item, + "rate": practitioner_charge, + "income_account": income_account, + } + ) + + return encounters_to_invoice + + +def get_lab_tests_to_invoice(patient, company): + lab_tests_to_invoice = [] + lab_tests = frappe.get_list( + "Lab Test", + fields=["name", "template"], + filters={"patient": patient.name, "company": company, "invoiced": False, "docstatus": 1}, + ) + for lab_test in lab_tests: + item, is_billable = frappe.get_cached_value( + "Lab Test Template", lab_test.template, ["item", "is_billable"] + ) + if is_billable: + lab_tests_to_invoice.append( + {"reference_type": "Lab Test", "reference_name": lab_test.name, "service": item} + ) + + lab_prescriptions = frappe.db.sql( + """ + SELECT + lp.name, lp.lab_test_code + FROM + `tabPatient Encounter` et, `tabLab Prescription` lp + WHERE + et.patient=%s + and lp.parent=et.name + and lp.lab_test_created=0 + and lp.invoiced=0 + """, + (patient.name), + as_dict=1, + ) + + for prescription in lab_prescriptions: + item, is_billable = frappe.get_cached_value( + "Lab Test Template", prescription.lab_test_code, ["item", "is_billable"] + ) + if prescription.lab_test_code and is_billable: + lab_tests_to_invoice.append( + {"reference_type": "Lab Prescription", "reference_name": prescription.name, "service": item} + ) + + return lab_tests_to_invoice + + +def get_clinical_procedures_to_invoice(patient, company): + clinical_procedures_to_invoice = [] + procedures = frappe.get_list( + "Clinical Procedure", + fields="*", + filters={"patient": patient.name, "company": company, "invoiced": False}, + ) + for procedure in procedures: + if not procedure.appointment: + item, is_billable = frappe.get_cached_value( + "Clinical Procedure Template", procedure.procedure_template, ["item", "is_billable"] + ) + if procedure.procedure_template and is_billable: + clinical_procedures_to_invoice.append( + {"reference_type": "Clinical Procedure", "reference_name": procedure.name, "service": item} + ) + + # consumables + if ( + procedure.invoice_separately_as_consumables + and procedure.consume_stock + and procedure.status == "Completed" + and not procedure.consumption_invoiced + ): + + service_item = frappe.db.get_single_value( + "Healthcare Settings", "clinical_procedure_consumable_item" + ) + if not service_item: + frappe.throw( + _("Please configure Clinical Procedure Consumable Item in {0}").format( + frappe.utils.get_link_to_form("Healthcare Settings", "Healthcare Settings") + ), + title=_("Missing Configuration"), + ) + + clinical_procedures_to_invoice.append( + { + "reference_type": "Clinical Procedure", + "reference_name": procedure.name, + "service": service_item, + "rate": procedure.consumable_total_amount, + "description": procedure.consumption_details, + } + ) + + procedure_prescriptions = frappe.db.sql( + """ + SELECT + pp.name, pp.procedure + FROM + `tabPatient Encounter` et, `tabProcedure Prescription` pp + WHERE + et.patient=%s + and pp.parent=et.name + and pp.procedure_created=0 + and pp.invoiced=0 + and pp.appointment_booked=0 + """, + (patient.name), + as_dict=1, + ) + + for prescription in procedure_prescriptions: + item, is_billable = frappe.get_cached_value( + "Clinical Procedure Template", prescription.procedure, ["item", "is_billable"] + ) + if is_billable: + clinical_procedures_to_invoice.append( + { + "reference_type": "Procedure Prescription", + "reference_name": prescription.name, + "service": item, + } + ) + + return clinical_procedures_to_invoice + + +def get_inpatient_services_to_invoice(patient, company): + services_to_invoice = [] + inpatient_services = frappe.db.sql( + """ + SELECT + io.* + FROM + `tabInpatient Record` ip, `tabInpatient Occupancy` io + WHERE + ip.patient=%s + and ip.company=%s + and io.parent=ip.name + and io.left=1 + and io.invoiced=0 + """, + (patient.name, company), + as_dict=1, + ) + + for inpatient_occupancy in inpatient_services: + service_unit_type = frappe.db.get_value( + "Healthcare Service Unit", inpatient_occupancy.service_unit, "service_unit_type" + ) + service_unit_type = frappe.get_cached_doc("Healthcare Service Unit Type", service_unit_type) + if service_unit_type and service_unit_type.is_billable: + hours_occupied = time_diff_in_hours(inpatient_occupancy.check_out, inpatient_occupancy.check_in) + qty = 0.5 + if hours_occupied > 0: + actual_qty = hours_occupied / service_unit_type.no_of_hours + floor = math.floor(actual_qty) + decimal_part = actual_qty - floor + if decimal_part > 0.5: + qty = rounded(floor + 1, 1) + elif decimal_part < 0.5 and decimal_part > 0: + qty = rounded(floor + 0.5, 1) + if qty <= 0: + qty = 0.5 + services_to_invoice.append( + { + "reference_type": "Inpatient Occupancy", + "reference_name": inpatient_occupancy.name, + "service": service_unit_type.item, + "qty": qty, + } + ) + + return services_to_invoice + + +def get_therapy_plans_to_invoice(patient, company): + therapy_plans_to_invoice = [] + therapy_plans = frappe.get_list( + "Therapy Plan", + fields=["therapy_plan_template", "name"], + filters={ + "patient": patient.name, + "invoiced": 0, + "company": company, + "therapy_plan_template": ("!=", ""), + }, + ) + for plan in therapy_plans: + therapy_plans_to_invoice.append( + { + "reference_type": "Therapy Plan", + "reference_name": plan.name, + "service": frappe.db.get_value( + "Therapy Plan Template", plan.therapy_plan_template, "linked_item" + ), + } + ) + + return therapy_plans_to_invoice + + +def get_therapy_sessions_to_invoice(patient, company): + therapy_sessions_to_invoice = [] + therapy_plans = frappe.db.get_all("Therapy Plan", {"therapy_plan_template": ("!=", "")}) + therapy_plans_created_from_template = [] + for entry in therapy_plans: + therapy_plans_created_from_template.append(entry.name) + + therapy_sessions = frappe.get_list( + "Therapy Session", + fields="*", + filters={ + "patient": patient.name, + "invoiced": 0, + "company": company, + "therapy_plan": ("not in", therapy_plans_created_from_template), + }, + ) + for therapy in therapy_sessions: + if not therapy.appointment: + if therapy.therapy_type and frappe.db.get_value( + "Therapy Type", therapy.therapy_type, "is_billable" + ): + therapy_sessions_to_invoice.append( + { + "reference_type": "Therapy Session", + "reference_name": therapy.name, + "service": frappe.db.get_value("Therapy Type", therapy.therapy_type, "item"), + } + ) + + return therapy_sessions_to_invoice + + +@frappe.whitelist() +def get_service_item_and_practitioner_charge(doc): + if isinstance(doc, str): + doc = json.loads(doc) + doc = frappe.get_doc(doc) + + service_item = None + practitioner_charge = None + department = doc.medical_department if doc.doctype == "Patient Encounter" else doc.department + + is_inpatient = doc.inpatient_record + + if doc.get("appointment_type"): + service_item, practitioner_charge = get_appointment_type_service_item( + doc.appointment_type, department, is_inpatient + ) + + if not service_item and not practitioner_charge: + service_item, practitioner_charge = get_practitioner_service_item(doc.practitioner, is_inpatient) + if not service_item: + service_item = get_healthcare_service_item(is_inpatient) + + if not service_item: + throw_config_service_item(is_inpatient) + + if not practitioner_charge: + throw_config_practitioner_charge(is_inpatient, doc.practitioner) + + return {"service_item": service_item, "practitioner_charge": practitioner_charge} + + +def get_appointment_type_service_item(appointment_type, department, is_inpatient): + from healthcare.healthcare.doctype.appointment_type.appointment_type import ( + get_service_item_based_on_department, + ) + + item_list = get_service_item_based_on_department(appointment_type, department) + service_item = None + practitioner_charge = None + + if item_list: + if is_inpatient: + service_item = item_list.get("inpatient_visit_charge_item") + practitioner_charge = item_list.get("inpatient_visit_charge") + else: + service_item = item_list.get("op_consulting_charge_item") + practitioner_charge = item_list.get("op_consulting_charge") + + return service_item, practitioner_charge + + +def throw_config_service_item(is_inpatient): + service_item_label = _("Out Patient Consulting Charge Item") + if is_inpatient: + service_item_label = _("Inpatient Visit Charge Item") + + msg = _( + ("Please Configure {0} in ").format(service_item_label) + + """Healthcare Settings""" + ) + frappe.throw(msg, title=_("Missing Configuration")) + + +def throw_config_practitioner_charge(is_inpatient, practitioner): + charge_name = _("OP Consulting Charge") + if is_inpatient: + charge_name = _("Inpatient Visit Charge") + + msg = _( + ("Please Configure {0} for Healthcare Practitioner").format(charge_name) + + """ {0}""".format(practitioner) + ) + frappe.throw(msg, title=_("Missing Configuration")) + + +def get_practitioner_service_item(practitioner, is_inpatient): + service_item = None + practitioner_charge = None + + if is_inpatient: + service_item, practitioner_charge = frappe.db.get_value( + "Healthcare Practitioner", + practitioner, + ["inpatient_visit_charge_item", "inpatient_visit_charge"], + ) + else: + service_item, practitioner_charge = frappe.db.get_value( + "Healthcare Practitioner", practitioner, ["op_consulting_charge_item", "op_consulting_charge"] + ) + + return service_item, practitioner_charge + + +def get_healthcare_service_item(is_inpatient): + service_item = None + + if is_inpatient: + service_item = frappe.db.get_single_value("Healthcare Settings", "inpatient_visit_charge_item") + else: + service_item = frappe.db.get_single_value("Healthcare Settings", "op_consulting_charge_item") + + return service_item + + +def get_practitioner_charge(practitioner, is_inpatient): + if is_inpatient: + practitioner_charge = frappe.db.get_value( + "Healthcare Practitioner", practitioner, "inpatient_visit_charge" + ) + else: + practitioner_charge = frappe.db.get_value( + "Healthcare Practitioner", practitioner, "op_consulting_charge" + ) + if practitioner_charge: + return practitioner_charge + return False + + +def manage_invoice_submit_cancel(doc, method): + if doc.items: + for item in doc.items: + if item.get("reference_dt") and item.get("reference_dn"): + if frappe.get_meta(item.reference_dt).has_field("invoiced"): + set_invoiced(item, method, doc.name) + + if method == "on_submit" and frappe.db.get_single_value( + "Healthcare Settings", "create_lab_test_on_si_submit" + ): + create_multiple("Sales Invoice", doc.name) + + +def set_invoiced(item, method, ref_invoice=None): + invoiced = False + if method == "on_submit": + validate_invoiced_on_submit(item) + invoiced = True + + if item.reference_dt == "Clinical Procedure": + service_item = frappe.db.get_single_value( + "Healthcare Settings", "clinical_procedure_consumable_item" + ) + if service_item == item.item_code: + frappe.db.set_value(item.reference_dt, item.reference_dn, "consumption_invoiced", invoiced) + else: + frappe.db.set_value(item.reference_dt, item.reference_dn, "invoiced", invoiced) + else: + frappe.db.set_value(item.reference_dt, item.reference_dn, "invoiced", invoiced) + + if item.reference_dt == "Patient Appointment": + if frappe.db.get_value("Patient Appointment", item.reference_dn, "procedure_template"): + dt_from_appointment = "Clinical Procedure" + else: + dt_from_appointment = "Patient Encounter" + manage_doc_for_appointment(dt_from_appointment, item.reference_dn, invoiced) + + elif item.reference_dt == "Lab Prescription": + manage_prescriptions( + invoiced, item.reference_dt, item.reference_dn, "Lab Test", "lab_test_created" + ) + + elif item.reference_dt == "Procedure Prescription": + manage_prescriptions( + invoiced, item.reference_dt, item.reference_dn, "Clinical Procedure", "procedure_created" + ) + + +def validate_invoiced_on_submit(item): + if ( + item.reference_dt == "Clinical Procedure" + and frappe.db.get_single_value("Healthcare Settings", "clinical_procedure_consumable_item") + == item.item_code + ): + is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, "consumption_invoiced") + else: + is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, "invoiced") + if is_invoiced: + frappe.throw( + _("The item referenced by {0} - {1} is already invoiced").format( + item.reference_dt, item.reference_dn + ) + ) + + +def manage_prescriptions(invoiced, ref_dt, ref_dn, dt, created_check_field): + created = frappe.db.get_value(ref_dt, ref_dn, created_check_field) + if created: + # Fetch the doc created for the prescription + doc_created = frappe.db.get_value(dt, {"prescription": ref_dn}) + frappe.db.set_value(dt, doc_created, "invoiced", invoiced) + + +def check_fee_validity(appointment): + if not frappe.db.get_single_value("Healthcare Settings", "enable_free_follow_ups"): + return + + validity = frappe.db.exists( + "Fee Validity", + { + "practitioner": appointment.practitioner, + "patient": appointment.patient, + "valid_till": (">=", appointment.appointment_date), + }, + ) + if not validity: + return + + validity = frappe.get_doc("Fee Validity", validity) + return validity + + +def manage_fee_validity(appointment): + fee_validity = check_fee_validity(appointment) + + if fee_validity: + if appointment.status == "Cancelled" and fee_validity.visited > 0: + fee_validity.visited -= 1 + frappe.db.delete("Fee Validity Reference", {"appointment": appointment.name}) + elif fee_validity.status == "Completed": + return + else: + fee_validity.visited += 1 + fee_validity.append("ref_appointments", {"appointment": appointment.name}) + fee_validity.save(ignore_permissions=True) + else: + fee_validity = create_fee_validity(appointment) + return fee_validity + + +def manage_doc_for_appointment(dt_from_appointment, appointment, invoiced): + dn_from_appointment = frappe.db.get_value( + dt_from_appointment, filters={"appointment": appointment} + ) + if dn_from_appointment: + frappe.db.set_value(dt_from_appointment, dn_from_appointment, "invoiced", invoiced) + + +@frappe.whitelist() +def get_drugs_to_invoice(encounter): + encounter = frappe.get_doc("Patient Encounter", encounter) + if encounter: + patient = frappe.get_doc("Patient", encounter.patient) + if patient: + if patient.customer: + items_to_invoice = [] + for drug_line in encounter.drug_prescription: + if drug_line.drug_code: + qty = 1 + if frappe.db.get_value("Item", drug_line.drug_code, "stock_uom") == "Nos": + qty = drug_line.get_quantity() + + description = "" + if drug_line.dosage and drug_line.period: + description = _("{0} for {1}").format(drug_line.dosage, drug_line.period) + + items_to_invoice.append( + {"drug_code": drug_line.drug_code, "quantity": qty, "description": description} + ) + return items_to_invoice + else: + validate_customer_created(patient) + + +@frappe.whitelist() +def get_children(doctype, parent=None, company=None, is_root=False): + parent_fieldname = "parent_" + doctype.lower().replace(" ", "_") + fields = ["name as value", "is_group as expandable", "lft", "rgt"] + + filters = [["ifnull(`{0}`,'')".format(parent_fieldname), "=", "" if is_root else parent]] + + if is_root: + fields += ["service_unit_type"] if doctype == "Healthcare Service Unit" else [] + filters.append(["company", "=", company]) + else: + fields += ( + ["service_unit_type", "allow_appointments", "inpatient_occupancy", "occupancy_status"] + if doctype == "Healthcare Service Unit" + else [] + ) + fields += [parent_fieldname + " as parent"] + + service_units = frappe.get_list(doctype, fields=fields, filters=filters) + for each in service_units: + if each["expandable"] == 1: # group node + available_count = frappe.db.count( + "Healthcare Service Unit", + filters={"parent_healthcare_service_unit": each["value"], "inpatient_occupancy": 1}, + ) + + if available_count > 0: + occupied_count = frappe.db.count( + "Healthcare Service Unit", + { + "parent_healthcare_service_unit": each["value"], + "inpatient_occupancy": 1, + "occupancy_status": "Occupied", + }, + ) + # set occupancy status of group node + each["occupied_of_available"] = str(occupied_count) + " Occupied of " + str(available_count) + + return service_units + + +@frappe.whitelist() +def get_patient_vitals(patient, from_date=None, to_date=None): + if not patient: + return + + vitals = frappe.db.get_all( + "Vital Signs", + filters={"docstatus": 1, "patient": patient}, + order_by="signs_date, signs_time", + fields=["*"], + ) + + if len(vitals): + return vitals + return False + + +@frappe.whitelist() +def render_docs_as_html(docs): + # docs key value pair {doctype: docname} + docs_html = "
" + for doc in docs: + docs_html += render_doc_as_html(doc["doctype"], doc["docname"])["html"] + "
" + return {"html": docs_html} + + +@frappe.whitelist() +def render_doc_as_html(doctype, docname, exclude_fields=[]): + """ + Render document as HTML + """ + + doc = frappe.get_doc(doctype, docname) + meta = frappe.get_meta(doctype) + doc_html = section_html = section_label = html = "" + sec_on = has_data = False + col_on = 0 + + for df in meta.fields: + # on section break append previous section and html to doc html + if df.fieldtype == "Section Break": + if has_data and col_on and sec_on: + doc_html += section_html + html + "
" + + elif has_data and not col_on and sec_on: + doc_html += """ +
+
+
+ {0} +
+
+
+
+ {1} {2} +
+
+ """.format( + section_label, section_html, html + ) + + # close divs for columns + while col_on: + doc_html += "
" + col_on -= 1 + + sec_on = True + has_data = False + col_on = 0 + section_html = html = "" + + if df.label: + section_label = df.label + continue + + # on column break append html to section html or doc html + if df.fieldtype == "Column Break": + if sec_on and not col_on and has_data: + section_html += """ +
+
+
+ {0} +
+
+
+
+ {1} +
+ """.format( + section_label, html + ) + elif col_on == 1 and has_data: + section_html += "
" + html + "
" + elif col_on > 1 and has_data: + doc_html += "
" + html + "
" + else: + doc_html += """ +
+
+ {0} +
+
+ """.format( + html + ) + + html = "" + col_on += 1 + + if df.label: + html += "
" + df.label + continue + + # on table iterate through items and create table + # based on the in_list_view property + # append to section html or doc html + if df.fieldtype == "Table": + items = doc.get(df.fieldname) + if not items: + continue + child_meta = frappe.get_meta(df.options) + + if not has_data: + has_data = True + table_head = table_row = "" + create_head = True + + for item in items: + table_row += "" + for cdf in child_meta.fields: + if cdf.in_list_view: + if create_head: + table_head += "" + cdf.label + "" + if item.get(cdf.fieldname): + table_row += "" + cstr(item.get(cdf.fieldname)) + "" + else: + table_row += "" + + create_head = False + table_row += "" + + if sec_on: + section_html += """ + + {0} {1} +
+ """.format( + table_head, table_row + ) + else: + html += """ + + {0} {1} +
+ """.format( + table_head, table_row + ) + continue + + # on any other field type add label and value to html + if ( + not df.hidden + and not df.print_hide + and doc.get(df.fieldname) + and df.fieldname not in exclude_fields + ): + formatted_value = format_value(doc.get(df.fieldname), meta.get_field(df.fieldname), doc) + html += "
{0} : {1}".format(df.label or df.fieldname, formatted_value) + + if not has_data: + has_data = True + + if sec_on and col_on and has_data: + doc_html += section_html + html + "
" + elif sec_on and not col_on and has_data: + doc_html += """ +
+
+ {0} {1} +
+
+ """.format( + section_html, html + ) + + return {"html": doc_html} + + +def update_address_links(address, method): + """ + Hook validate Address + If Patient is linked in Address, also link the associated Customer + """ + if "Healthcare" not in frappe.get_active_domains(): + return + + patient_links = list(filter(lambda link: link.get("link_doctype") == "Patient", address.links)) + + for link in patient_links: + customer = frappe.db.get_value("Patient", link.get("link_name"), "customer") + if customer and not address.has_link("Customer", customer): + address.append("links", dict(link_doctype="Customer", link_name=customer)) + + +def update_patient_email_and_phone_numbers(contact, method): + """ + Hook validate Contact + Update linked Patients' primary mobile and phone numbers + """ + if "Healthcare" not in frappe.get_active_domains() or contact.flags.skip_patient_update: + return + + if contact.is_primary_contact and (contact.email_id or contact.mobile_no or contact.phone): + patient_links = list(filter(lambda link: link.get("link_doctype") == "Patient", contact.links)) + + for link in patient_links: + contact_details = frappe.db.get_value( + "Patient", link.get("link_name"), ["email", "mobile", "phone"], as_dict=1 + ) + if contact.email_id and contact.email_id != contact_details.get("email"): + frappe.db.set_value("Patient", link.get("link_name"), "email", contact.email_id) + if contact.mobile_no and contact.mobile_no != contact_details.get("mobile"): + frappe.db.set_value("Patient", link.get("link_name"), "mobile", contact.mobile_no) + if contact.phone and contact.phone != contact_details.get("phone"): + frappe.db.set_value("Patient", link.get("link_name"), "phone", contact.phone) + + +def before_tests(): + # complete setup if missing + from frappe.desk.page.setup_wizard.setup_wizard import setup_complete + + if not frappe.get_list("Company"): + setup_complete( + { + "currency": "INR", + "full_name": "Test User", + "company_name": "InfluxERP Care LLC", + "timezone": "America/New_York", + "company_abbr": "WP", + "industry": "Healthcare", + "country": "United States", + "fy_start_date": "2022-04-01", + "fy_end_date": "2023-03-31", + "language": "english", + "company_tagline": "Testing", + "email": "test@erpnext.com", + "password": "test", + "chart_of_accounts": "Standard", + "domains": ["Healthcare"], + } + ) + + setup_healthcare() + + +def create_healthcare_service_unit_tree_root(doc, method=None): + record = [ + { + "doctype": "Healthcare Service Unit", + "healthcare_service_unit_name": "All Healthcare Service Units", + "is_group": 1, + "company": doc.name, + } + ] + insert_record(record) + + +def validate_nursing_tasks(document): + if not frappe.db.get_single_value("Healthcare Settings", "validate_nursing_checklists"): + return True + + filters = { + "reference_name": document.name, + "mandatory": 1, + "status": ["not in", ["Completed", "Cancelled"]], + } + tasks = frappe.get_all("Nursing Task", filters=filters) + if not tasks: + return True + + frappe.throw( + _("Please complete linked Nursing Tasks before submission: {}").format( + ", ".join(get_link_to_form("Nursing Task", task.name) for task in tasks) + ) + ) diff --git a/healthcare/healthcare/web_form/__init__.py b/healthcare/healthcare/web_form/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/web_form/lab_test/__init__.py b/healthcare/healthcare/web_form/lab_test/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/web_form/lab_test/lab_test.js b/healthcare/healthcare/web_form/lab_test/lab_test.js new file mode 100644 index 0000000..efcd8ab --- /dev/null +++ b/healthcare/healthcare/web_form/lab_test/lab_test.js @@ -0,0 +1,34 @@ +frappe.ready(function() { + // bind events here + var normal_test_items = $('div[data-fieldname = "normal_test_items"]'); + var normal_test_items_add_btn = $('button[data-fieldname = "normal_test_items"]'); + var special_test_items = $('div[data-fieldname = "special_test_items"]'); + var special_test_items_add_btn = $('button[data-fieldname = "special_test_items"]'); + var sensitivity_test_items = $('div[data-fieldname = "sensitivity_test_items"]'); + var sensitivity_test_items_add_btn = $('button[data-fieldname = "sensitivity_test_items"]'); + var sensitivity_toggle = $('input[name = "sensitivity_toggle"]'); + var special_toggle = $('input[name = "special_toggle"]'); + var normal_toggle = $('input[name = "normal_toggle"]'); + if(normal_toggle.val() == 1){ + // normal_test_items[0].style.display = "none"; + // normal_test_items[0].setAttribute("hidden", true); + // normal_test_items_add_btn[0].style.visibility = "hidden"; + special_test_items[0].style.display = "none"; + special_test_items_add_btn[0].style.display = "none"; + sensitivity_test_items[0].style.display = "none"; + sensitivity_test_items_add_btn[0].style.display = "none"; + normal_test_items_add_btn[0].style.display = "none"; + }else if(sensitivity_toggle.val() == 1){ + special_test_items[0].style.display = "none"; + special_test_items_add_btn[0].style.display = "none"; + normal_test_items[0].style.display = "none"; + normal_test_items_add_btn[0].style.display = "none"; + sensitivity_test_items_add_btn[0].style.display = "none"; + }else if(special_toggle.val() == 1){ + normal_test_items[0].style.display = "none"; + normal_test_items_add_btn[0].style.display = "none"; + sensitivity_test_items[0].style.display = "none"; + sensitivity_test_items_add_btn[0].style.display = "none"; + special_test_items_add_btn[0].style.display = "none"; + } +}); diff --git a/healthcare/healthcare/web_form/lab_test/lab_test.json b/healthcare/healthcare/web_form/lab_test/lab_test.json new file mode 100644 index 0000000..3509917 --- /dev/null +++ b/healthcare/healthcare/web_form/lab_test/lab_test.json @@ -0,0 +1,460 @@ +{ + "accept_payment": 0, + "allow_comments": 1, + "allow_delete": 0, + "allow_edit": 1, + "allow_incomplete": 0, + "allow_multiple": 1, + "allow_print": 1, + "amount": 0.0, + "amount_based_on_field": 0, + "creation": "2017-06-06 16:12:33.052258", + "currency": "INR", + "doc_type": "Lab Test", + "docstatus": 0, + "doctype": "Web Form", + "idx": 0, + "introduction_text": "Lab Test", + "is_standard": 1, + "login_required": 1, + "max_attachment_size": 0, + "modified": "2020-06-22 12:59:49.126398", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "lab-test", + "owner": "Administrator", + "payment_button_label": "Buy Now", + "print_format": "Lab Test Print", + "published": 1, + "route": "lab-test", + "route_to_success_link": 0, + "show_attachments": 0, + "show_in_grid": 0, + "show_sidebar": 1, + "sidebar_items": [], + "success_url": "/lab-test", + "title": "Lab Test", + "web_form_fields": [ + { + "allow_read_on_all_link_options": 0, + "fieldname": "lab_test_name", + "fieldtype": "Data", + "hidden": 0, + "label": "Test Name", + "max_length": 0, + "max_value": 0, + "read_only": 1, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "department", + "fieldtype": "Link", + "hidden": 0, + "label": "Department", + "max_length": 0, + "max_value": 0, + "options": "Medical Department", + "read_only": 1, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "column_break_26", + "fieldtype": "Column Break", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "company", + "fieldtype": "Link", + "hidden": 0, + "label": "Company", + "max_length": 0, + "max_value": 0, + "options": "Company", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "status", + "fieldtype": "Select", + "hidden": 0, + "label": "Status", + "max_length": 0, + "max_value": 0, + "options": "Draft\nCompleted\nApproved\nRejected\nCancelled", + "read_only": 1, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "submitted_date", + "fieldtype": "Datetime", + "hidden": 0, + "label": "Submitted Date", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "sb_first", + "fieldtype": "Section Break", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "patient", + "fieldtype": "Link", + "hidden": 0, + "label": "Patient", + "max_length": 0, + "max_value": 0, + "options": "Patient", + "read_only": 0, + "reqd": 1, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "patient_name", + "fieldtype": "Data", + "hidden": 0, + "label": "Patient Name", + "max_length": 0, + "max_value": 0, + "read_only": 1, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "patient_age", + "fieldtype": "Data", + "hidden": 0, + "label": "Age", + "max_length": 0, + "max_value": 0, + "read_only": 1, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "patient_sex", + "fieldtype": "Link", + "hidden": 0, + "label": "Gender", + "max_length": 0, + "max_value": 0, + "options": "Gender", + "read_only": 0, + "reqd": 1, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "inpatient_record", + "fieldtype": "Link", + "hidden": 0, + "label": "Inpatient Record", + "max_length": 0, + "max_value": 0, + "options": "Inpatient Record", + "read_only": 1, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "report_preference", + "fieldtype": "Data", + "hidden": 0, + "label": "Report Preference", + "max_length": 0, + "max_value": 0, + "read_only": 1, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "email", + "fieldtype": "Data", + "hidden": 1, + "label": "Email", + "max_length": 0, + "max_value": 0, + "read_only": 1, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "mobile", + "fieldtype": "Data", + "hidden": 1, + "label": "Mobile", + "max_length": 0, + "max_value": 0, + "read_only": 1, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "c_b", + "fieldtype": "Column Break", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "practitioner", + "fieldtype": "Link", + "hidden": 0, + "label": "Requesting Practitioner", + "max_length": 0, + "max_value": 0, + "options": "Healthcare Practitioner", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "practitioner_name", + "fieldtype": "Data", + "hidden": 0, + "label": "Requesting Practitioner", + "max_length": 0, + "max_value": 0, + "read_only": 1, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "requesting_department", + "fieldtype": "Link", + "hidden": 0, + "label": "Requesting Department", + "max_length": 0, + "max_value": 0, + "options": "Medical Department", + "read_only": 1, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "employee", + "fieldtype": "Link", + "hidden": 0, + "label": "Employee (Lab Technician)", + "max_length": 0, + "max_value": 0, + "options": "Employee", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "employee_name", + "fieldtype": "Data", + "hidden": 0, + "label": "Lab Technician Name", + "max_length": 0, + "max_value": 0, + "read_only": 1, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "employee_designation", + "fieldtype": "Data", + "hidden": 0, + "label": "Lab Technician Designation", + "max_length": 0, + "max_value": 0, + "read_only": 1, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "sb_normal", + "fieldtype": "Section Break", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "lab_test_html", + "fieldtype": "HTML", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "normal_test_items", + "fieldtype": "Table", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "options": "Normal Test Result", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "sb_descriptive", + "fieldtype": "Section Break", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "descriptive_test_items", + "fieldtype": "Table", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "options": "Descriptive Test Result", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "depends_on": "special_toggle", + "fieldname": "organisms_section", + "fieldtype": "Section Break", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "organisms", + "fieldtype": "Table", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "options": "Organism Test Result", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "sb_sensitivity", + "fieldtype": "Section Break", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "sensitivity_test_items", + "fieldtype": "Table", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "options": "Sensitivity Test Result", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "sb_comments", + "fieldtype": "Section Break", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "lab_test_comment", + "fieldtype": "Text", + "hidden": 0, + "label": "Comments", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "sb_customresult", + "fieldtype": "Section Break", + "hidden": 0, + "label": "Custom Result", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "custom_result", + "fieldtype": "Text Editor", + "hidden": 0, + "label": "Custom Result", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + } + ] +} \ No newline at end of file diff --git a/healthcare/healthcare/web_form/lab_test/lab_test.py b/healthcare/healthcare/web_form/lab_test/lab_test.py new file mode 100644 index 0000000..1bccbd4 --- /dev/null +++ b/healthcare/healthcare/web_form/lab_test/lab_test.py @@ -0,0 +1,34 @@ +import frappe + + +def get_context(context): + context.read_only = 1 + + +def get_list_context(context): + context.row_template = "erpnext/templates/includes/healthcare/lab_test_row_template.html" + context.get_list = get_lab_test_list + + +def get_lab_test_list( + doctype, txt, filters, limit_start, limit_page_length=20, order_by="modified desc" +): + patient = get_patient() + lab_tests = frappe.db.sql( + """select * from `tabLab Test` + where patient = %s order by result_date""", + patient, + as_dict=True, + ) + return lab_tests + + +def get_patient(): + return frappe.get_value("Patient", {"email": frappe.session.user}, "name") + + +def has_website_permission(doc, ptype, user, verbose=False): + if doc.patient == get_patient(): + return True + else: + return False diff --git a/healthcare/healthcare/web_form/patient_appointments/__init__.py b/healthcare/healthcare/web_form/patient_appointments/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/web_form/patient_appointments/patient_appointments.js b/healthcare/healthcare/web_form/patient_appointments/patient_appointments.js new file mode 100644 index 0000000..f09e540 --- /dev/null +++ b/healthcare/healthcare/web_form/patient_appointments/patient_appointments.js @@ -0,0 +1,3 @@ +frappe.ready(function() { + // bind events here +}); diff --git a/healthcare/healthcare/web_form/patient_appointments/patient_appointments.json b/healthcare/healthcare/web_form/patient_appointments/patient_appointments.json new file mode 100644 index 0000000..e9cf7a8 --- /dev/null +++ b/healthcare/healthcare/web_form/patient_appointments/patient_appointments.json @@ -0,0 +1,111 @@ +{ + "accept_payment": 0, + "allow_comments": 0, + "allow_delete": 0, + "allow_edit": 1, + "allow_incomplete": 0, + "allow_multiple": 1, + "allow_print": 1, + "amount": 0.0, + "amount_based_on_field": 0, + "creation": "2017-06-07 15:30:44.984832", + "currency": "INR", + "doc_type": "Patient Appointment", + "docstatus": 0, + "doctype": "Web Form", + "idx": 0, + "introduction_text": "Patient Appointments", + "is_standard": 1, + "login_required": 1, + "max_attachment_size": 0, + "modified": "2018-07-16 13:11:08.626316", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "patient-appointments", + "owner": "Administrator", + "payment_button_label": "Buy Now", + "published": 1, + "route": "patient-appointments", + "show_sidebar": 1, + "sidebar_items": [], + "success_url": "/patient-appointments", + "title": "Patient Appointments", + "web_form_fields": [ + { + "fieldname": "patient", + "fieldtype": "Link", + "hidden": 0, + "label": "Patient", + "max_length": 0, + "max_value": 0, + "options": "Patient", + "read_only": 0, + "reqd": 1 + }, + { + "fieldname": "practitioner", + "fieldtype": "Link", + "hidden": 0, + "label": "Healthcare Practitioner", + "max_length": 0, + "max_value": 0, + "options": "Healthcare Practitioner", + "read_only": 0, + "reqd": 1 + }, + { + "fieldname": "appointment_date", + "fieldtype": "Date", + "hidden": 0, + "label": "Date", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 1 + }, + { + "fieldname": "appointment_time", + "fieldtype": "Data", + "hidden": 0, + "label": "Time", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0 + }, + { + "fieldname": "department", + "fieldtype": "Link", + "hidden": 0, + "label": "Department", + "max_length": 0, + "max_value": 0, + "options": "Medical Department", + "read_only": 0, + "reqd": 0 + }, + { + "fieldname": "appointment_type", + "fieldtype": "Link", + "hidden": 0, + "label": "Type", + "max_length": 0, + "max_value": 0, + "options": "Appointment Type", + "read_only": 0, + "reqd": 0 + }, + { + "default": "Scheduled", + "fieldname": "status", + "fieldtype": "Select", + "hidden": 0, + "label": "Status", + "max_length": 0, + "max_value": 0, + "options": "\nScheduled\nOpen\nClosed\nPending\nCancelled", + "read_only": 1, + "reqd": 0 + } + ] +} \ No newline at end of file diff --git a/healthcare/healthcare/web_form/patient_appointments/patient_appointments.py b/healthcare/healthcare/web_form/patient_appointments/patient_appointments.py new file mode 100644 index 0000000..89e8eb1 --- /dev/null +++ b/healthcare/healthcare/web_form/patient_appointments/patient_appointments.py @@ -0,0 +1,34 @@ +import frappe + + +def get_context(context): + context.read_only = 1 + + +def get_list_context(context): + context.row_template = "erpnext/templates/includes/healthcare/appointment_row_template.html" + context.get_list = get_appointment_list + + +def get_appointment_list( + doctype, txt, filters, limit_start, limit_page_length=20, order_by="modified desc" +): + patient = get_patient() + lab_tests = frappe.db.sql( + """select * from `tabPatient Appointment` + where patient = %s and (status = 'Open' or status = 'Scheduled') order by appointment_date""", + patient, + as_dict=True, + ) + return lab_tests + + +def get_patient(): + return frappe.get_value("Patient", {"email": frappe.session.user}, "name") + + +def has_website_permission(doc, ptype, user, verbose=False): + if doc.patient == get_patient(): + return True + else: + return False diff --git a/healthcare/healthcare/web_form/patient_registration/__init__.py b/healthcare/healthcare/web_form/patient_registration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/web_form/patient_registration/patient_registration.js b/healthcare/healthcare/web_form/patient_registration/patient_registration.js new file mode 100644 index 0000000..f09e540 --- /dev/null +++ b/healthcare/healthcare/web_form/patient_registration/patient_registration.js @@ -0,0 +1,3 @@ +frappe.ready(function() { + // bind events here +}); diff --git a/healthcare/healthcare/web_form/patient_registration/patient_registration.json b/healthcare/healthcare/web_form/patient_registration/patient_registration.json new file mode 100644 index 0000000..9ed92de --- /dev/null +++ b/healthcare/healthcare/web_form/patient_registration/patient_registration.json @@ -0,0 +1,397 @@ +{ + "accept_payment": 0, + "allow_comments": 0, + "allow_delete": 0, + "allow_edit": 1, + "allow_incomplete": 0, + "allow_multiple": 0, + "allow_print": 0, + "amount": 0.0, + "amount_based_on_field": 0, + "button_label": "Register", + "creation": "2020-03-03 01:01:16.250607", + "currency": "INR", + "doc_type": "Patient", + "docstatus": 0, + "doctype": "Web Form", + "idx": 0, + "introduction_text": "", + "is_standard": 1, + "login_required": 0, + "max_attachment_size": 0, + "modified": "2020-03-26 17:25:15.361918", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "patient-registration", + "owner": "Administrator", + "payment_button_label": "Buy Now", + "published": 1, + "route": "patient-registration", + "route_to_success_link": 0, + "show_attachments": 0, + "show_in_grid": 0, + "show_sidebar": 1, + "sidebar_items": [], + "success_message": "Registration Successfully. Thank You!", + "success_url": "/patient-registration", + "title": "Patient Registration", + "web_form_fields": [ + { + "allow_read_on_all_link_options": 0, + "fieldname": "basic_info", + "fieldtype": "Section Break", + "hidden": 0, + "label": "Patient Demographics", + "max_length": 0, + "max_value": 0, + "options": "fa fa-user", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "first_name", + "fieldtype": "Data", + "hidden": 0, + "label": "First Name", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 1, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "middle_name", + "fieldtype": "Data", + "hidden": 0, + "label": "Middle Name (optional)", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "last_name", + "fieldtype": "Data", + "hidden": 0, + "label": "Last Name", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 1, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "sex", + "fieldtype": "Link", + "hidden": 0, + "label": "Gender", + "max_length": 0, + "max_value": 0, + "options": "Gender", + "read_only": 0, + "reqd": 1, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "blood_group", + "fieldtype": "Select", + "hidden": 0, + "label": "Blood Group", + "max_length": 0, + "max_value": 0, + "options": "\nA Positive\nA Negative\nAB Positive\nAB Negative\nB Positive\nB Negative\nO Positive\nO Negative", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "", + "fieldtype": "Column Break", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "dob", + "fieldtype": "Date", + "hidden": 0, + "label": "Date of birth", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "mobile", + "fieldtype": "Data", + "hidden": 0, + "label": "Mobile", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "email", + "fieldtype": "Data", + "hidden": 0, + "label": "Email", + "max_length": 0, + "max_value": 0, + "options": "Email", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "phone", + "fieldtype": "Data", + "hidden": 0, + "label": "Phone", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "", + "fieldtype": "Section Break", + "hidden": 0, + "label": "Personal Details", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "occupation", + "fieldtype": "Data", + "hidden": 0, + "label": "Occupation", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "", + "fieldtype": "Column Break", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "marital_status", + "fieldtype": "Select", + "hidden": 0, + "label": "Marital Status", + "max_length": 0, + "max_value": 0, + "options": "\nSingle\nMarried\nDivorced\nWidow", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "allergy_medical_and_surgical_history", + "fieldtype": "Section Break", + "hidden": 0, + "label": "Allergies, Medical and Surgical History", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "allergies", + "fieldtype": "Small Text", + "hidden": 0, + "label": "Allergies", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "medication", + "fieldtype": "Small Text", + "hidden": 0, + "label": "Medication", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "column_break_20", + "fieldtype": "Column Break", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "medical_history", + "fieldtype": "Small Text", + "hidden": 0, + "label": "Medical History", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "surgical_history", + "fieldtype": "Small Text", + "hidden": 0, + "label": "Surgical History", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "risk_factors", + "fieldtype": "Section Break", + "hidden": 0, + "label": "Risk Factors", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "default": "0", + "fieldname": "tobacco_past_use", + "fieldtype": "Check", + "hidden": 0, + "label": "Check if you have a history of Tobacco Consumption", + "max_length": 0, + "max_value": 0, + "options": "", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "default": "0", + "fieldname": "tobacco_current_use", + "fieldtype": "Check", + "hidden": 0, + "label": "Check if you consume Tobacco", + "max_length": 0, + "max_value": 0, + "options": "", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "default": "0", + "fieldname": "alcohol_past_use", + "fieldtype": "Check", + "hidden": 0, + "label": "Check if you have a history of Alcohol Consumption", + "max_length": 0, + "max_value": 0, + "options": "", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "default": "0", + "fieldname": "alcohol_current_use", + "fieldtype": "Check", + "hidden": 0, + "label": "Check if you consume Alcohol", + "max_length": 0, + "max_value": 0, + "options": "", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "column_break_32", + "fieldtype": "Column Break", + "hidden": 0, + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "surrounding_factors", + "fieldtype": "Small Text", + "hidden": 0, + "label": "Occupational Hazards and Environmental Factors", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "allow_read_on_all_link_options": 0, + "fieldname": "other_risk_factors", + "fieldtype": "Small Text", + "hidden": 0, + "label": "Other Risk Factors", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + } + ] +} \ No newline at end of file diff --git a/healthcare/healthcare/web_form/patient_registration/patient_registration.py b/healthcare/healthcare/web_form/patient_registration/patient_registration.py new file mode 100644 index 0000000..02e3e93 --- /dev/null +++ b/healthcare/healthcare/web_form/patient_registration/patient_registration.py @@ -0,0 +1,3 @@ +def get_context(context): + # do your magic here + pass diff --git a/healthcare/healthcare/web_form/personal_details/__init__.py b/healthcare/healthcare/web_form/personal_details/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/web_form/personal_details/personal_details.js b/healthcare/healthcare/web_form/personal_details/personal_details.js new file mode 100644 index 0000000..f09e540 --- /dev/null +++ b/healthcare/healthcare/web_form/personal_details/personal_details.js @@ -0,0 +1,3 @@ +frappe.ready(function() { + // bind events here +}); diff --git a/healthcare/healthcare/web_form/personal_details/personal_details.json b/healthcare/healthcare/web_form/personal_details/personal_details.json new file mode 100644 index 0000000..aad987a --- /dev/null +++ b/healthcare/healthcare/web_form/personal_details/personal_details.json @@ -0,0 +1,87 @@ +{ + "accept_payment": 0, + "allow_comments": 0, + "allow_delete": 0, + "allow_edit": 1, + "allow_incomplete": 0, + "allow_multiple": 0, + "allow_print": 0, + "amount": 0.0, + "amount_based_on_field": 0, + "creation": "2018-07-03 19:33:23.332661", + "currency": "INR", + "doc_type": "Patient", + "docstatus": 0, + "doctype": "Web Form", + "idx": 0, + "introduction_text": "", + "is_standard": 1, + "login_required": 1, + "max_attachment_size": 0, + "modified": "2018-07-04 17:22:28.936442", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "personal-details", + "owner": "Administrator", + "payment_button_label": "Buy Now", + "published": 1, + "route": "personal-details", + "show_sidebar": 1, + "sidebar_items": [], + "success_url": "/personal-details", + "title": "Personal Details", + "web_form_fields": [ + { + "fieldname": "patient_name", + "fieldtype": "Data", + "hidden": 0, + "label": "Full Name", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 1 + }, + { + "fieldname": "sex", + "fieldtype": "Select", + "hidden": 0, + "label": "Gender", + "max_length": 0, + "max_value": 0, + "options": "\nMale\nFemale\nOther", + "read_only": 0, + "reqd": 1 + }, + { + "fieldname": "dob", + "fieldtype": "Date", + "hidden": 0, + "label": "Date of birth", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 1 + }, + { + "fieldname": "mobile", + "fieldtype": "Data", + "hidden": 0, + "label": "Mobile", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0 + }, + { + "fieldname": "email", + "fieldtype": "Data", + "hidden": 0, + "label": "Email", + "max_length": 0, + "max_value": 0, + "options": "Email", + "read_only": 1, + "reqd": 0 + } + ] +} diff --git a/healthcare/healthcare/web_form/personal_details/personal_details.py b/healthcare/healthcare/web_form/personal_details/personal_details.py new file mode 100644 index 0000000..dfbd73e --- /dev/null +++ b/healthcare/healthcare/web_form/personal_details/personal_details.py @@ -0,0 +1,28 @@ +import frappe +from frappe import _ + +no_cache = 1 + + +def get_context(context): + if frappe.session.user == "Guest": + frappe.throw(_("You need to be logged in to access this page"), frappe.PermissionError) + + context.show_sidebar = True + + if frappe.db.exists("Patient", {"email": frappe.session.user}): + patient = frappe.get_doc("Patient", {"email": frappe.session.user}) + context.doc = patient + frappe.form_dict.new = 0 + frappe.form_dict.name = patient.name + + +def get_patient(): + return frappe.get_value("Patient", {"email": frappe.session.user}, "name") + + +def has_website_permission(doc, ptype, user, verbose=False): + if doc.name == get_patient(): + return True + else: + return False diff --git a/healthcare/healthcare/web_form/prescription/__init__.py b/healthcare/healthcare/web_form/prescription/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/healthcare/web_form/prescription/prescription.js b/healthcare/healthcare/web_form/prescription/prescription.js new file mode 100644 index 0000000..f09e540 --- /dev/null +++ b/healthcare/healthcare/web_form/prescription/prescription.js @@ -0,0 +1,3 @@ +frappe.ready(function() { + // bind events here +}); diff --git a/healthcare/healthcare/web_form/prescription/prescription.json b/healthcare/healthcare/web_form/prescription/prescription.json new file mode 100644 index 0000000..8e19e32 --- /dev/null +++ b/healthcare/healthcare/web_form/prescription/prescription.json @@ -0,0 +1,120 @@ +{ + "accept_payment": 0, + "allow_comments": 0, + "allow_delete": 0, + "allow_edit": 1, + "allow_incomplete": 0, + "allow_multiple": 1, + "allow_print": 1, + "amount": 0.0, + "amount_based_on_field": 0, + "creation": "2017-06-06 17:13:19.101374", + "currency": "INR", + "doc_type": "Patient Encounter", + "docstatus": 0, + "doctype": "Web Form", + "idx": 0, + "introduction_text": "Patient Prescriptions", + "is_standard": 1, + "login_required": 1, + "max_attachment_size": 0, + "modified": "2018-09-04 11:53:40.954517", + "modified_by": "Administrator", + "module": "Healthcare", + "name": "prescription", + "owner": "Administrator", + "payment_button_label": "Buy Now", + "print_format": "Encounter Print", + "published": 1, + "route": "prescription", + "show_in_grid": 0, + "show_sidebar": 1, + "sidebar_items": [], + "success_url": "/prescription", + "title": "Prescription", + "web_form_fields": [ + { + "fieldname": "practitioner", + "fieldtype": "Link", + "hidden": 0, + "label": "Healthcare Practitioner", + "max_length": 0, + "max_value": 0, + "options": "Healthcare Practitioner", + "read_only": 0, + "reqd": 1, + "show_in_filter": 0 + }, + { + "fieldname": "visit_department", + "fieldtype": "Link", + "hidden": 0, + "label": "Department", + "max_length": 0, + "max_value": 0, + "options": "Medical Department", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "default": "Today", + "fieldname": "encounter_date", + "fieldtype": "Date", + "hidden": 0, + "label": "Encounter Date", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 1, + "show_in_filter": 0 + }, + { + "default": "", + "fieldname": "encounter_time", + "fieldtype": "Data", + "hidden": 0, + "label": "Encounter Time", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 1, + "show_in_filter": 0 + }, + { + "fieldname": "drug_prescription", + "fieldtype": "Table", + "hidden": 0, + "label": "Drug Prescription", + "max_length": 0, + "max_value": 0, + "options": "Drug Prescription", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "fieldname": "lab_test_prescription", + "fieldtype": "Table", + "hidden": 0, + "label": "Investigations", + "max_length": 0, + "max_value": 0, + "options": "Lab Prescription", + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + }, + { + "fieldname": "encounter_comment", + "fieldtype": "Small Text", + "hidden": 0, + "label": "Review Details", + "max_length": 0, + "max_value": 0, + "read_only": 0, + "reqd": 0, + "show_in_filter": 0 + } + ] +} \ No newline at end of file diff --git a/healthcare/healthcare/web_form/prescription/prescription.py b/healthcare/healthcare/web_form/prescription/prescription.py new file mode 100644 index 0000000..44caeb0 --- /dev/null +++ b/healthcare/healthcare/web_form/prescription/prescription.py @@ -0,0 +1,34 @@ +import frappe + + +def get_context(context): + context.read_only = 1 + + +def get_list_context(context): + context.row_template = "erpnext/templates/includes/healthcare/prescription_row_template.html" + context.get_list = get_encounter_list + + +def get_encounter_list( + doctype, txt, filters, limit_start, limit_page_length=20, order_by="modified desc" +): + patient = get_patient() + encounters = frappe.db.sql( + """select * from `tabPatient Encounter` + where patient = %s order by creation desc""", + patient, + as_dict=True, + ) + return encounters + + +def get_patient(): + return frappe.get_value("Patient", {"email": frappe.session.user}, "name") + + +def has_website_permission(doc, ptype, user, verbose=False): + if doc.patient == get_patient(): + return True + else: + return False diff --git a/healthcare/healthcare/workspace/healthcare/healthcare.json b/healthcare/healthcare/workspace/healthcare/healthcare.json new file mode 100644 index 0000000..83cc13e --- /dev/null +++ b/healthcare/healthcare/workspace/healthcare/healthcare.json @@ -0,0 +1,714 @@ +{ + "charts": [ + { + "chart_name": "Patient Appointments", + "label": "Patient Appointments" + } + ], + "content": "[{\"type\":\"onboarding\",\"data\":{\"onboarding_name\":\"Healthcare\",\"col\":12}},{\"type\":\"chart\",\"data\":{\"chart_name\":\"Patient Appointments\",\"col\":12}},{\"type\":\"spacer\",\"data\":{\"col\":12}},{\"type\":\"header\",\"data\":{\"text\":\"Your Shortcuts\",\"col\":12}},{\"type\":\"shortcut\",\"data\":{\"shortcut_name\":\"Patient Appointment\",\"col\":4}},{\"type\":\"shortcut\",\"data\":{\"shortcut_name\":\"Patient\",\"col\":4}},{\"type\":\"shortcut\",\"data\":{\"shortcut_name\":\"Healthcare Service Unit\",\"col\":4}},{\"type\":\"shortcut\",\"data\":{\"shortcut_name\":\"Healthcare Practitioner\",\"col\":4}},{\"type\":\"shortcut\",\"data\":{\"shortcut_name\":\"Patient History\",\"col\":4}},{\"type\":\"shortcut\",\"data\":{\"shortcut_name\":\"Dashboard\",\"col\":4}},{\"type\":\"spacer\",\"data\":{\"col\":12}},{\"type\":\"header\",\"data\":{\"text\":\"Reports & Masters\",\"col\":12}},{\"type\":\"card\",\"data\":{\"card_name\":\"Masters\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Consultation Setup\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Consultation\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Facility Management\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Settings\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Inpatient\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Laboratory Setup\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Laboratory\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Rehabilitation and Physiotherapy\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Nursing\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Records and History\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Reports\",\"col\":4}}]", + "creation": "2020-03-02 17:23:17.919682", + "docstatus": 0, + "doctype": "Workspace", + "for_user": "", + "hide_custom": 0, + "icon": "healthcare", + "idx": 0, + "label": "Healthcare", + "links": [ + { + "hidden": 0, + "is_query_report": 0, + "label": "Masters", + "link_count": 0, + "onboard": 0, + "type": "Card Break" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Patient", + "link_count": 0, + "link_to": "Patient", + "link_type": "DocType", + "onboard": 1, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Healthcare Practitioner", + "link_count": 0, + "link_to": "Healthcare Practitioner", + "link_type": "DocType", + "onboard": 1, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Practitioner Schedule", + "link_count": 0, + "link_to": "Practitioner Schedule", + "link_type": "DocType", + "onboard": 1, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Medical Department", + "link_count": 0, + "link_to": "Medical Department", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Consultation Setup", + "link_count": 0, + "onboard": 0, + "type": "Card Break" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Appointment Type", + "link_count": 0, + "link_to": "Appointment Type", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Clinical Procedure Template", + "link_count": 0, + "link_to": "Clinical Procedure Template", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Prescription Dosage", + "link_count": 0, + "link_to": "Prescription Dosage", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Prescription Duration", + "link_count": 0, + "link_to": "Prescription Duration", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Antibiotic", + "link_count": 0, + "link_to": "Antibiotic", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Complaint", + "link_count": 0, + "link_to": "Complaint", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Diagnosis", + "link_count": 0, + "link_to": "Diagnosis", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Treatment Plan Template", + "link_count": 0, + "link_to": "Treatment Plan Template", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Consultation", + "link_count": 0, + "onboard": 0, + "type": "Card Break" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Patient Appointment", + "link_count": 0, + "link_to": "Patient Appointment", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Clinical Procedure", + "link_count": 0, + "link_to": "Clinical Procedure", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Patient Encounter", + "link_count": 0, + "link_to": "Patient Encounter", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Vital Signs", + "link_count": 0, + "link_to": "Vital Signs", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Fee Validity", + "link_count": 0, + "link_to": "Fee Validity", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Facility Management", + "link_count": 0, + "link_type": "DocType", + "onboard": 0, + "type": "Card Break" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Healthcare Service Unit Type", + "link_count": 0, + "link_to": "Healthcare Service Unit Type", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Healthcare Service Unit", + "link_count": 0, + "link_to": "Healthcare Service Unit", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Medical Code Standard", + "link_count": 0, + "link_to": "Medical Code Standard", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Medical Code", + "link_count": 0, + "link_to": "Medical Code", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Settings", + "link_count": 0, + "onboard": 0, + "type": "Card Break" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Healthcare Settings", + "link_count": 0, + "link_to": "Healthcare Settings", + "link_type": "DocType", + "onboard": 1, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Patient History Settings", + "link_count": 0, + "link_to": "Patient History Settings", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Laboratory Setup", + "link_count": 0, + "onboard": 0, + "type": "Card Break" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Lab Test Template", + "link_count": 0, + "link_to": "Lab Test Template", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Lab Test Sample", + "link_count": 0, + "link_to": "Lab Test Sample", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Lab Test UOM", + "link_count": 0, + "link_to": "Lab Test UOM", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Sensitivity", + "link_count": 0, + "link_to": "Sensitivity", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Dosage Form", + "link_count": 0, + "link_to": "Dosage Form", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Laboratory", + "link_count": 0, + "onboard": 0, + "type": "Card Break" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Lab Test", + "link_count": 0, + "link_to": "Lab Test", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Sample Collection", + "link_count": 0, + "link_to": "Sample Collection", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Inpatient", + "link_count": 0, + "link_type": "DocType", + "onboard": 0, + "type": "Card Break" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Inpatient Medication Order", + "link_count": 0, + "link_to": "Inpatient Medication Order", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Inpatient Record", + "link_count": 0, + "link_to": "Inpatient Record", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Inpatient Medication Entry", + "link_count": 0, + "link_to": "Inpatient Medication Entry", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Rehabilitation and Physiotherapy", + "link_count": 0, + "onboard": 0, + "type": "Card Break" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Exercise Type", + "link_count": 0, + "link_to": "Exercise Type", + "link_type": "DocType", + "onboard": 1, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Therapy Type", + "link_count": 0, + "link_to": "Therapy Type", + "link_type": "DocType", + "onboard": 1, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Therapy Plan Template", + "link_count": 0, + "link_to": "Therapy Plan Template", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Therapy Plan", + "link_count": 0, + "link_to": "Therapy Plan", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Therapy Session", + "link_count": 0, + "link_to": "Therapy Session", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Patient Assessment Template", + "link_count": 0, + "link_to": "Patient Assessment Template", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Patient Assessment", + "link_count": 0, + "link_to": "Patient Assessment", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Records and History", + "link_count": 0, + "onboard": 0, + "type": "Card Break" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Patient History", + "link_count": 0, + "link_to": "patient_history", + "link_type": "Page", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Patient Progress", + "link_count": 0, + "link_to": "patient-progress", + "link_type": "Page", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Patient Medical Record", + "link_count": 0, + "link_to": "Patient Medical Record", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 0, + "label": "Inpatient Record", + "link_count": 0, + "link_to": "Inpatient Record", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Reports", + "link_count": 3, + "onboard": 0, + "type": "Card Break" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 1, + "label": "Patient Appointment Analytics", + "link_count": 0, + "link_to": "Patient Appointment Analytics", + "link_type": "Report", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 1, + "label": "Lab Test Report", + "link_count": 0, + "link_to": "Lab Test Report", + "link_type": "Report", + "onboard": 0, + "type": "Link" + }, + { + "dependencies": "", + "hidden": 0, + "is_query_report": 1, + "label": "Diagnosis Trends", + "link_count": 0, + "link_to": "Diagnosis Trends", + "link_type": "Report", + "onboard": 0, + "type": "Link" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Nursing", + "link_count": 3, + "onboard": 0, + "type": "Card Break" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Nursing Checklist Template", + "link_count": 0, + "link_to": "Nursing Checklist Template", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Nursing Task", + "link_count": 0, + "link_to": "Nursing Task", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + }, + { + "hidden": 0, + "is_query_report": 0, + "label": "Healthcare Activity", + "link_count": 0, + "link_to": "Healthcare Activity", + "link_type": "DocType", + "onboard": 0, + "type": "Link" + } + ], + "modified": "2022-07-25 20:32:22.664308", + "modified_by": "rucha@frappe.io", + "module": "Healthcare", + "name": "Healthcare", + "owner": "Administrator", + "parent_page": "", + "public": 1, + "quick_lists": [], + "restrict_to_domain": "Healthcare", + "roles": [], + "sequence_id": 13.0, + "shortcuts": [ + { + "color": "Orange", + "format": "{} Open", + "label": "Patient Appointment", + "link_to": "Patient Appointment", + "stats_filter": "{\n \"status\": \"Open\",\n \"company\": [\"like\", '%' + frappe.defaults.get_global_default(\"company\") + '%']\n}", + "type": "DocType" + }, + { + "color": "Orange", + "format": "{} Active", + "label": "Patient", + "link_to": "Patient", + "stats_filter": "{\n \"status\": \"Active\"\n}", + "type": "DocType" + }, + { + "color": "Green", + "format": "{} Vacant", + "label": "Healthcare Service Unit", + "link_to": "Healthcare Service Unit", + "stats_filter": "{\n \"occupancy_status\": \"Vacant\",\n \"is_group\": 0,\n \"company\": [\"like\", \"%\" + frappe.defaults.get_global_default(\"company\") + \"%\"]\n}", + "type": "DocType" + }, + { + "label": "Healthcare Practitioner", + "link_to": "Healthcare Practitioner", + "type": "DocType" + }, + { + "label": "Patient History", + "link_to": "patient_history", + "type": "Page" + }, + { + "label": "Dashboard", + "link_to": "Healthcare", + "type": "Dashboard" + } + ], + "title": "Healthcare" +} \ No newline at end of file diff --git a/healthcare/hooks.py b/healthcare/hooks.py new file mode 100644 index 0000000..1d238df --- /dev/null +++ b/healthcare/hooks.py @@ -0,0 +1,282 @@ +from . import __version__ as app_version +from frappe import _ + + +app_name = "healthcare" +app_title = "Healthcare" +app_publisher = "healthcare" +app_description = "healthcare" +app_icon = "octicon octicon-file-directory" +app_color = "grey" +app_email = "contact@frappe.io" +app_license = "MIT" +required_apps = ["erpnext"] + +# Includes in +# ------------------ + +# include js, css files in header of desk.html +# app_include_css = "/assets/healthcare/css/healthcare.css" +# app_include_js = "/assets/healthcare/js/healthcare.js" + +# include js, css files in header of web template +# web_include_css = "/assets/healthcare/css/healthcare.css" +# web_include_js = "/assets/healthcare/js/healthcare.js" + +# include custom scss in every website theme (without file extension ".scss") +# website_theme_scss = "healthcare/public/scss/website" + +# include js, css files in header of web form +# webform_include_js = {"doctype": "public/js/doctype.js"} +# webform_include_css = {"doctype": "public/css/doctype.css"} + +# include js in page +# page_js = {"page" : "public/js/file.js"} + +# include js in doctype views +doctype_js = {"Sales Invoice": "public/js/sales_invoice.js"} +# doctype_list_js = {"doctype" : "public/js/doctype_list.js"} +# doctype_tree_js = {"doctype" : "public/js/doctype_tree.js"} +# doctype_calendar_js = {"doctype" : "public/js/doctype_calendar.js"} + +# Home Pages +# ---------- + +# application home page (will override Website Settings) +# home_page = "login" + +# website user home page (by Role) +# role_home_page = { +# "Role": "home_page" +# } + +# Generators +# ---------- + +# automatically create page for each record of this doctype +# website_generators = ["Web Page"] + +# Jinja +# ---------- + +# add methods and filters to jinja environment +# jinja = { +# "methods": "healthcare.utils.jinja_methods", +# "filters": "healthcare.utils.jinja_filters" +# } + +# Installation +# ------------ + +# before_install = "healthcare.install.before_install" +after_install = "healthcare.setup.setup_healthcare" + +# Desk Notifications +# ------------------ +# See frappe.core.notifications.get_notification_config + +# notification_config = "healthcare.notifications.get_notification_config" + +# Permissions +# ----------- +# Permissions evaluated in scripted ways + +# permission_query_conditions = { +# "Event": "frappe.desk.doctype.event.event.get_permission_query_conditions", +# } +# +# has_permission = { +# "Event": "frappe.desk.doctype.event.event.has_permission", +# } + +# DocType Class +# --------------- +# Override standard doctype classes + +override_doctype_class = { + "Sales Invoice": "healthcare.healthcare.custom_doctype.sales_invoice.HealthcareSalesInvoice", +} + +# Document Events +# --------------- +# Hook on document methods and events + +doc_events = { + "*": { + "on_submit": "healthcare.healthcare.doctype.patient_history_settings.patient_history_settings.create_medical_record", + "on_cancel": "healthcare.healthcare.doctype.patient_history_settings.patient_history_settings.delete_medical_record", + "on_update_after_submit": "healthcare.healthcare.doctype.patient_history_settings.patient_history_settings.update_medical_record", + }, + "Sales Invoice": { + "on_submit": "healthcare.healthcare.utils.manage_invoice_submit_cancel", + "on_cancel": "healthcare.healthcare.utils.manage_invoice_submit_cancel", + }, + "Company": { + "after_insert": "healthcare.healthcare.utils.create_healthcare_service_unit_tree_root" + }, +} + +scheduler_events = { + "all": [ + "healthcare.healthcare.doctype.patient_appointment.patient_appointment.send_appointment_reminder", + ], + "daily": [ + "healthcare.healthcare.doctype.patient_appointment.patient_appointment.update_appointment_status", + ], +} + +# Scheduled Tasks +# --------------- + +# scheduler_events = { +# "all": [ +# "healthcare.tasks.all" +# ], +# "daily": [ +# "healthcare.tasks.daily" +# ], +# "hourly": [ +# "healthcare.tasks.hourly" +# ], +# "weekly": [ +# "healthcare.tasks.weekly" +# ], +# "monthly": [ +# "healthcare.tasks.monthly" +# ], +# } + +# Testing +# ------- + +before_tests = "healthcare.healthcare.utils.before_tests" + +# Overriding Methods +# ------------------------------ +# +# override_whitelisted_methods = { +# "frappe.desk.doctype.event.event.get_events": "healthcare.event.get_events" +# } +# +# each overriding function accepts a `data` argument; +# generated from the base implementation of the doctype dashboard, +# along with any modifications made in other InfluxERP apps +# override_doctype_dashboards = { +# "Task": "healthcare.task.get_dashboard_data" +# } + +# exempt linked doctypes from being automatically cancelled +# +auto_cancel_exempted_doctypes = [ + "Inpatient Medication Entry", +] + +# User Data Protection +# -------------------- + +# user_data_fields = [ +# { +# "doctype": "{doctype_1}", +# "filter_by": "{filter_by}", +# "redact_fields": ["{field_1}", "{field_2}"], +# "partial": 1, +# }, +# { +# "doctype": "{doctype_2}", +# "filter_by": "{filter_by}", +# "partial": 1, +# }, +# { +# "doctype": "{doctype_3}", +# "strict": False, +# }, +# { +# "doctype": "{doctype_4}" +# } +# ] + +# Authentication and authorization +# -------------------------------- + +# auth_hooks = [ +# "healthcare.auth.validate" +# ] + +global_search_doctypes = { + "Healthcare": [ + {"doctype": "Patient", "index": 1}, + {"doctype": "Medical Department", "index": 2}, + {"doctype": "Vital Signs", "index": 3}, + {"doctype": "Healthcare Practitioner", "index": 4}, + {"doctype": "Patient Appointment", "index": 5}, + {"doctype": "Healthcare Service Unit", "index": 6}, + {"doctype": "Patient Encounter", "index": 7}, + {"doctype": "Antibiotic", "index": 8}, + {"doctype": "Diagnosis", "index": 9}, + {"doctype": "Lab Test", "index": 10}, + {"doctype": "Clinical Procedure", "index": 11}, + {"doctype": "Inpatient Record", "index": 12}, + {"doctype": "Sample Collection", "index": 13}, + {"doctype": "Patient Medical Record", "index": 14}, + {"doctype": "Appointment Type", "index": 15}, + {"doctype": "Fee Validity", "index": 16}, + {"doctype": "Practitioner Schedule", "index": 17}, + {"doctype": "Dosage Form", "index": 18}, + {"doctype": "Lab Test Sample", "index": 19}, + {"doctype": "Prescription Duration", "index": 20}, + {"doctype": "Prescription Dosage", "index": 21}, + {"doctype": "Sensitivity", "index": 22}, + {"doctype": "Complaint", "index": 23}, + {"doctype": "Medical Code", "index": 24}, + ] +} + +domains = { + "Healthcare": "healthcare.setup", +} + +standard_portal_menu_items = [ + { + "title": _("Personal Details"), + "route": "/personal-details", + "reference_doctype": "Patient", + "role": "Patient", + }, + { + "title": _("Timesheets"), + "route": "/timesheets", + "reference_doctype": "Timesheet", + "role": "Customer", + }, + { + "title": _("Lab Test"), + "route": "/lab-test", + "reference_doctype": "Lab Test", + "role": "Patient", + }, + { + "title": _("Prescription"), + "route": "/prescription", + "reference_doctype": "Patient Encounter", + "role": "Patient", + }, + { + "title": _("Patient Appointment"), + "route": "/patient-appointments", + "reference_doctype": "Patient Appointment", + "role": "Patient", + }, +] + +has_website_permission = { + "Issue": "erpnext.support.doctype.issue.issue.has_website_permission", + "Timesheet": "erpnext.controllers.website_list_for_contact.has_website_permission", + "Lab Test": "healthcare.healthcare.web_form.lab_test.lab_test.has_website_permission", + "Patient Encounter": "healthcare.healthcare.web_form.prescription.prescription.has_website_permission", + "Patient Appointment": "healthcare.healthcare.web_form.patient_appointments.patient_appointments.has_website_permission", + "Patient": "healthcare.healthcare.web_form.personal_details.personal_details.has_website_permission", +} + +standard_queries = { + "Healthcare Practitioner": "healthcare.healthcare.doctype.healthcare_practitioner.healthcare_practitioner.get_practitioner_list" +} diff --git a/healthcare/modules.txt b/healthcare/modules.txt new file mode 100644 index 0000000..915d8d2 --- /dev/null +++ b/healthcare/modules.txt @@ -0,0 +1 @@ +Healthcare \ No newline at end of file diff --git a/healthcare/patches.txt b/healthcare/patches.txt new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/public/js/sales_invoice.js b/healthcare/public/js/sales_invoice.js new file mode 100644 index 0000000..cb03cc9 --- /dev/null +++ b/healthcare/public/js/sales_invoice.js @@ -0,0 +1,307 @@ +// Healthcare +frappe.ui.form.on('Sales Invoice', { + refresh(frm) { + if (frm.doc.docstatus === 0 && !frm.doc.is_return) { + frm.add_custom_button(__('Healthcare Services'), function() { + get_healthcare_services_to_invoice(frm); + },__('Get Items From')); + frm.add_custom_button(__('Prescriptions'), function() { + get_drugs_to_invoice(frm); + },__('Get Items From')); + } + }, + + patient(frm) { + if (frm.doc.patient) { + frappe.db.get_value("Patient", frm.doc.patient, "customer") + .then(r => { + if (!r.exc && r.message.customer) { + frm.set_value("customer", r.message.customer); + } else { + frappe.show_alert({ + indicator: "warning", + message: __("Patient {0} is not linked to a Customer", + [`${frm.doc.patient}`] + ), + }); + frm.set_value("customer", ""); + } + frm.set_df_property("customer", "read_only", frm.doc.customer ? 1 : 0); + }) + } else { + frm.set_value("customer", ""); + frm.set_df_property("customer", "read_only", 0); + } + } +}); + +var get_healthcare_services_to_invoice = function(frm) { + var me = this; + let selected_patient = ''; + var dialog = new frappe.ui.Dialog({ + title: __("Get Items from Healthcare Services"), + fields:[ + { + fieldtype: 'Link', + options: 'Patient', + label: 'Patient', + fieldname: "patient", + reqd: true + }, + { fieldtype: 'Section Break' }, + { fieldtype: 'HTML', fieldname: 'results_area' } + ] + }); + var $wrapper; + var $results; + var $placeholder; + dialog.set_values({ + 'patient': frm.doc.patient + }); + dialog.fields_dict["patient"].df.onchange = () => { + var patient = dialog.fields_dict.patient.input.value; + if(patient && patient!=selected_patient){ + selected_patient = patient; + var method = "healthcare.healthcare.utils.get_healthcare_services_to_invoice"; + var args = {patient: patient, company: frm.doc.company}; + var columns = (["service", "reference_name", "reference_type"]); + get_healthcare_items(frm, true, $results, $placeholder, method, args, columns); + } + else if(!patient){ + selected_patient = ''; + $results.empty(); + $results.append($placeholder); + } + } + $wrapper = dialog.fields_dict.results_area.$wrapper.append(`
`); + $results = $wrapper.find('.results'); + $placeholder = $(`
+ + +

No billable Healthcare Services found

+
+
`); + $results.on('click', '.list-item--head :checkbox', (e) => { + $results.find('.list-item-container .list-row-check') + .prop("checked", ($(e.target).is(':checked'))); + }); + set_primary_action(frm, dialog, $results, true); + dialog.show(); +}; + +var get_healthcare_items = function(frm, invoice_healthcare_services, $results, $placeholder, method, args, columns) { + var me = this; + $results.empty(); + frappe.call({ + method: method, + args: args, + callback: function(data) { + if(data.message){ + $results.append(make_list_row(columns, invoice_healthcare_services)); + for(let i=0; i + ${ + head ? `${__(frappe.model.unscrub(column))}` + + :(column !== "name" ? `${__(result[column])}` + : ` + ${__(result[column])}`) + } +
`; + }) + + let $row = $(`
+
+ +
+ ${contents} +
`); + + $row = list_row_data_items(head, $row, result, invoice_healthcare_services); + return $row; +}; + +var set_primary_action= function(frm, dialog, $results, invoice_healthcare_services) { + var me = this; + dialog.set_primary_action(__('Add'), function() { + let checked_values = get_checked_values($results); + if(checked_values.length > 0){ + if(invoice_healthcare_services) { + frm.set_value("patient", dialog.fields_dict.patient.input.value); + } + add_to_item_line(frm, checked_values, invoice_healthcare_services); + dialog.hide(); + } + else{ + if(invoice_healthcare_services){ + frappe.msgprint(__("Please select Healthcare Service")); + } + else{ + frappe.msgprint(__("Please select Drug")); + } + } + }); +}; + +var get_checked_values= function($results) { + return $results.find('.list-item-container').map(function() { + let checked_values = {}; + if ($(this).find('.list-row-check:checkbox:checked').length > 0 ) { + checked_values['dn'] = $(this).attr('data-dn'); + checked_values['dt'] = $(this).attr('data-dt'); + checked_values['item'] = $(this).attr('data-item'); + if($(this).attr('data-rate') != 'undefined'){ + checked_values['rate'] = $(this).attr('data-rate'); + } + else{ + checked_values['rate'] = false; + } + if($(this).attr('data-income-account') != 'undefined'){ + checked_values['income_account'] = $(this).attr('data-income-account'); + } + else{ + checked_values['income_account'] = false; + } + if($(this).attr('data-qty') != 'undefined'){ + checked_values['qty'] = $(this).attr('data-qty'); + } + else{ + checked_values['qty'] = false; + } + if($(this).attr('data-description') != 'undefined'){ + checked_values['description'] = $(this).attr('data-description'); + } + else{ + checked_values['description'] = false; + } + return checked_values; + } + }).get(); +}; + +var get_drugs_to_invoice = function(frm) { + var me = this; + let selected_encounter = ''; + var dialog = new frappe.ui.Dialog({ + title: __("Get Items from Prescriptions"), + fields:[ + { fieldtype: 'Link', options: 'Patient', label: 'Patient', fieldname: "patient", reqd: true }, + { fieldtype: 'Link', options: 'Patient Encounter', label: 'Patient Encounter', fieldname: "encounter", reqd: true, + description:'Quantity will be calculated only for items which has "Nos" as UoM. You may change as required for each invoice item.', + get_query: function(doc) { + return { + filters: { + patient: dialog.get_value("patient"), + company: frm.doc.company, + docstatus: 1 + } + }; + } + }, + { fieldtype: 'Section Break' }, + { fieldtype: 'HTML', fieldname: 'results_area' } + ] + }); + var $wrapper; + var $results; + var $placeholder; + dialog.set_values({ + 'patient': frm.doc.patient, + 'encounter': "" + }); + dialog.fields_dict["encounter"].df.onchange = () => { + var encounter = dialog.fields_dict.encounter.input.value; + if(encounter && encounter!=selected_encounter){ + selected_encounter = encounter; + var method = "healthcare.healthcare.utils.get_drugs_to_invoice"; + var args = {encounter: encounter}; + var columns = (["drug_code", "quantity", "description"]); + get_healthcare_items(frm, false, $results, $placeholder, method, args, columns); + } + else if(!encounter){ + selected_encounter = ''; + $results.empty(); + $results.append($placeholder); + } + } + $wrapper = dialog.fields_dict.results_area.$wrapper.append(`
`); + $results = $wrapper.find('.results'); + $placeholder = $(`
+ + +

No Drug Prescription found

+
+
`); + $results.on('click', '.list-item--head :checkbox', (e) => { + $results.find('.list-item-container .list-row-check') + .prop("checked", ($(e.target).is(':checked'))); + }); + set_primary_action(frm, dialog, $results, false); + dialog.show(); +}; + +var list_row_data_items = function(head, $row, result, invoice_healthcare_services) { + if(invoice_healthcare_services){ + head ? $row.addClass('list-item--head') + : $row = $(`
+
`).append($row); + } + else{ + head ? $row.addClass('list-item--head') + : $row = $(`
+
`).append($row); + } + return $row +}; + +var add_to_item_line = function(frm, checked_values, invoice_healthcare_services){ + if(invoice_healthcare_services){ + frappe.call({ + doc: frm.doc, + method: "set_healthcare_services", + args:{ + checked_values: checked_values + }, + callback: function() { + frm.trigger("validate"); + frm.refresh_fields(); + } + }); + } + else{ + for(let i=0; i 1){ + frappe.model.set_value(si_item.doctype, si_item.name, 'qty', parseFloat(checked_values[i]['qty'])); + } + } + frm.refresh_fields(); + } +}; diff --git a/healthcare/setup.py b/healthcare/setup.py new file mode 100644 index 0000000..46eba2b --- /dev/null +++ b/healthcare/setup.py @@ -0,0 +1,766 @@ +import frappe +from frappe import _ +from erpnext.setup.utils import insert_record + + +data = { + "desktop_icons": [ + "Patient", + "Patient Appointment", + "Patient Encounter", + "Lab Test", + "Healthcare", + "Vital Signs", + "Clinical Procedure", + "Inpatient Record", + "Accounts", + "Buying", + "Stock", + "HR", + "ToDo", + ], + "default_portal_role": "Patient", + "restricted_roles": [ + "Healthcare Administrator", + "LabTest Approver", + "Laboratory User", + "Nursing User", + "Physician", + "Patient", + ], + "custom_fields": { + "Sales Invoice": [ + { + "fieldname": "patient", + "label": "Patient", + "fieldtype": "Link", + "options": "Patient", + "insert_after": "naming_series", + }, + { + "fieldname": "patient_name", + "label": "Patient Name", + "fieldtype": "Data", + "fetch_from": "patient.patient_name", + "insert_after": "patient", + "read_only": True, + }, + { + "fieldname": "ref_practitioner", + "label": "Referring Practitioner", + "fieldtype": "Link", + "options": "Healthcare Practitioner", + "insert_after": "customer", + }, + ], + "Sales Invoice Item": [ + { + "fieldname": "reference_dt", + "label": "Reference DocType", + "fieldtype": "Link", + "options": "DocType", + "insert_after": "edit_references", + }, + { + "fieldname": "reference_dn", + "label": "Reference Name", + "fieldtype": "Dynamic Link", + "options": "reference_dt", + "insert_after": "reference_dt", + }, + ], + "Stock Entry": [ + { + "fieldname": "inpatient_medication_entry", + "label": "Inpatient Medication Entry", + "fieldtype": "Link", + "options": "Inpatient Medication Entry", + "insert_after": "credit_note", + "read_only": True, + } + ], + "Stock Entry Detail": [ + { + "fieldname": "patient", + "label": "Patient", + "fieldtype": "Link", + "options": "Patient", + "insert_after": "po_detail", + "read_only": True, + }, + { + "fieldname": "inpatient_medication_entry_child", + "label": "Inpatient Medication Entry Child", + "fieldtype": "Data", + "insert_after": "patient", + "read_only": True, + }, + ], + }, + "on_setup": "healthcare.setup.setup_healthcare", +} + + +def setup_healthcare(): + if frappe.db.exists("Medical Department", "Cardiology"): + # already setup + return + create_custom_records() + create_default_root_service_units() + + +def create_default_root_service_units(): + from healthcare.healthcare.utils import create_healthcare_service_unit_tree_root + + companies = frappe.get_all("Company") + for company in companies: + create_healthcare_service_unit_tree_root(company) + + +def create_custom_records(): + create_medical_departments() + create_antibiotics() + create_lab_test_uom() + create_duration() + create_dosage() + create_dosage_form() + create_healthcare_item_groups() + create_sensitivity() + setup_patient_history_settings() + + has_domain = frappe.get_doc( + { + "doctype": "Has Domain", + "parent": "Domain Settings", + "parentfield": "active_domains", + "parenttype": "Domain Settings", + "domain": "Healthcare", + } + ) + has_domain.save() + + domain = frappe.get_doc("Domain", "Healthcare") + domain.setup_domain() + + domain_settings = frappe.get_single("Domain Settings") + domain_settings.append("active_domains", dict(domain=domain)) + frappe.clear_cache() + + +def create_medical_departments(): + departments = [ + "Accident And Emergency Care", + "Anaesthetics", + "Biochemistry", + "Cardiology", + "Diabetology", + "Dermatology", + "Diagnostic Imaging", + "ENT", + "Gastroenterology", + "General Surgery", + "Gynaecology", + "Haematology", + "Maternity", + "Microbiology", + "Nephrology", + "Neurology", + "Oncology", + "Orthopaedics", + "Pathology", + "Physiotherapy", + "Rheumatology", + "Serology", + "Urology", + ] + for department in departments: + mediacal_department = frappe.new_doc("Medical Department") + mediacal_department.department = _(department) + try: + mediacal_department.save() + except frappe.DuplicateEntryError: + pass + + +def create_antibiotics(): + abt = [ + "Amoxicillin", + "Ampicillin", + "Bacampicillin", + "Carbenicillin", + "Cloxacillin", + "Dicloxacillin", + "Flucloxacillin", + "Mezlocillin", + "Nafcillin", + "Oxacillin", + "Penicillin G", + "Penicillin V", + "Piperacillin", + "Pivampicillin", + "Pivmecillinam", + "Ticarcillin", + "Cefacetrile (cephacetrile)", + "Cefadroxil (cefadroxyl)", + "Cefalexin (cephalexin)", + "Cefaloglycin (cephaloglycin)", + "Cefalonium (cephalonium)", + "Cefaloridine (cephaloradine)", + "Cefalotin (cephalothin)", + "Cefapirin (cephapirin)", + "Cefatrizine", + "Cefazaflur", + "Cefazedone", + "Cefazolin (cephazolin)", + "Cefradine (cephradine)", + "Cefroxadine", + "Ceftezole", + "Cefaclor", + "Cefamandole", + "Cefmetazole", + "Cefonicid", + "Cefotetan", + "Cefoxitin", + "Cefprozil (cefproxil)", + "Cefuroxime", + "Cefuzonam", + "Cefcapene", + "Cefdaloxime", + "Cefdinir", + "Cefditoren", + "Cefetamet", + "Cefixime", + "Cefmenoxime", + "Cefodizime", + "Cefotaxime", + "Cefpimizole", + "Cefpodoxime", + "Cefteram", + "Ceftibuten", + "Ceftiofur", + "Ceftiolene", + "Ceftizoxime", + "Ceftriaxone", + "Cefoperazone", + "Ceftazidime", + "Cefclidine", + "Cefepime", + "Cefluprenam", + "Cefoselis", + "Cefozopran", + "Cefpirome", + "Cefquinome", + "Ceftobiprole", + "Ceftaroline", + "Cefaclomezine", + "Cefaloram", + "Cefaparole", + "Cefcanel", + "Cefedrolor", + "Cefempidone", + "Cefetrizole", + "Cefivitril", + "Cefmatilen", + "Cefmepidium", + "Cefovecin", + "Cefoxazole", + "Cefrotil", + "Cefsumide", + "Cefuracetime", + "Ceftioxide", + "Ceftazidime/Avibactam", + "Ceftolozane/Tazobactam", + "Aztreonam", + "Imipenem", + "Imipenem/cilastatin", + "Doripenem", + "Meropenem", + "Ertapenem", + "Azithromycin", + "Erythromycin", + "Clarithromycin", + "Dirithromycin", + "Roxithromycin", + "Telithromycin", + "Clindamycin", + "Lincomycin", + "Pristinamycin", + "Quinupristin/dalfopristin", + "Amikacin", + "Gentamicin", + "Kanamycin", + "Neomycin", + "Netilmicin", + "Paromomycin", + "Streptomycin", + "Tobramycin", + "Flumequine", + "Nalidixic acid", + "Oxolinic acid", + "Piromidic acid", + "Pipemidic acid", + "Rosoxacin", + "Ciprofloxacin", + "Enoxacin", + "Lomefloxacin", + "Nadifloxacin", + "Norfloxacin", + "Ofloxacin", + "Pefloxacin", + "Rufloxacin", + "Balofloxacin", + "Gatifloxacin", + "Grepafloxacin", + "Levofloxacin", + "Moxifloxacin", + "Pazufloxacin", + "Sparfloxacin", + "Temafloxacin", + "Tosufloxacin", + "Besifloxacin", + "Clinafloxacin", + "Gemifloxacin", + "Sitafloxacin", + "Trovafloxacin", + "Prulifloxacin", + "Sulfamethizole", + "Sulfamethoxazole", + "Sulfisoxazole", + "Trimethoprim-Sulfamethoxazole", + "Demeclocycline", + "Doxycycline", + "Minocycline", + "Oxytetracycline", + "Tetracycline", + "Tigecycline", + "Chloramphenicol", + "Metronidazole", + "Tinidazole", + "Nitrofurantoin", + "Vancomycin", + "Teicoplanin", + "Telavancin", + "Linezolid", + "Cycloserine 2", + "Rifampin", + "Rifabutin", + "Rifapentine", + "Rifalazil", + "Bacitracin", + "Polymyxin B", + "Viomycin", + "Capreomycin", + ] + + for a in abt: + antibiotic = frappe.new_doc("Antibiotic") + antibiotic.antibiotic_name = a + try: + antibiotic.save() + except frappe.DuplicateEntryError: + pass + + +def create_lab_test_uom(): + records = [ + {"doctype": "Lab Test UOM", "name": "umol/L", "lab_test_uom": "umol/L", "uom_description": None}, + {"doctype": "Lab Test UOM", "name": "mg/L", "lab_test_uom": "mg/L", "uom_description": None}, + { + "doctype": "Lab Test UOM", + "name": "mg / dl", + "lab_test_uom": "mg / dl", + "uom_description": None, + }, + { + "doctype": "Lab Test UOM", + "name": "pg / ml", + "lab_test_uom": "pg / ml", + "uom_description": None, + }, + {"doctype": "Lab Test UOM", "name": "U/ml", "lab_test_uom": "U/ml", "uom_description": None}, + {"doctype": "Lab Test UOM", "name": "/HPF", "lab_test_uom": "/HPF", "uom_description": None}, + { + "doctype": "Lab Test UOM", + "name": "Million Cells / cumm", + "lab_test_uom": "Million Cells / cumm", + "uom_description": None, + }, + { + "doctype": "Lab Test UOM", + "name": "Lakhs Cells / cumm", + "lab_test_uom": "Lakhs Cells / cumm", + "uom_description": None, + }, + {"doctype": "Lab Test UOM", "name": "U / L", "lab_test_uom": "U / L", "uom_description": None}, + {"doctype": "Lab Test UOM", "name": "g / L", "lab_test_uom": "g / L", "uom_description": None}, + { + "doctype": "Lab Test UOM", + "name": "IU / ml", + "lab_test_uom": "IU / ml", + "uom_description": None, + }, + {"doctype": "Lab Test UOM", "name": "gm %", "lab_test_uom": "gm %", "uom_description": None}, + { + "doctype": "Lab Test UOM", + "name": "Microgram", + "lab_test_uom": "Microgram", + "uom_description": None, + }, + {"doctype": "Lab Test UOM", "name": "Micron", "lab_test_uom": "Micron", "uom_description": None}, + { + "doctype": "Lab Test UOM", + "name": "Cells / cumm", + "lab_test_uom": "Cells / cumm", + "uom_description": None, + }, + {"doctype": "Lab Test UOM", "name": "%", "lab_test_uom": "%", "uom_description": None}, + { + "doctype": "Lab Test UOM", + "name": "mm / dl", + "lab_test_uom": "mm / dl", + "uom_description": None, + }, + { + "doctype": "Lab Test UOM", + "name": "mm / hr", + "lab_test_uom": "mm / hr", + "uom_description": None, + }, + { + "doctype": "Lab Test UOM", + "name": "ulU / ml", + "lab_test_uom": "ulU / ml", + "uom_description": None, + }, + { + "doctype": "Lab Test UOM", + "name": "ng / ml", + "lab_test_uom": "ng / ml", + "uom_description": None, + }, + { + "doctype": "Lab Test UOM", + "name": "ng / dl", + "lab_test_uom": "ng / dl", + "uom_description": None, + }, + { + "doctype": "Lab Test UOM", + "name": "ug / dl", + "lab_test_uom": "ug / dl", + "uom_description": None, + }, + ] + + insert_record(records) + + +def create_duration(): + records = [ + {"doctype": "Prescription Duration", "name": "3 Month", "number": "3", "period": "Month"}, + {"doctype": "Prescription Duration", "name": "2 Month", "number": "2", "period": "Month"}, + {"doctype": "Prescription Duration", "name": "1 Month", "number": "1", "period": "Month"}, + {"doctype": "Prescription Duration", "name": "12 Hour", "number": "12", "period": "Hour"}, + {"doctype": "Prescription Duration", "name": "11 Hour", "number": "11", "period": "Hour"}, + {"doctype": "Prescription Duration", "name": "10 Hour", "number": "10", "period": "Hour"}, + {"doctype": "Prescription Duration", "name": "9 Hour", "number": "9", "period": "Hour"}, + {"doctype": "Prescription Duration", "name": "8 Hour", "number": "8", "period": "Hour"}, + {"doctype": "Prescription Duration", "name": "7 Hour", "number": "7", "period": "Hour"}, + {"doctype": "Prescription Duration", "name": "6 Hour", "number": "6", "period": "Hour"}, + {"doctype": "Prescription Duration", "name": "5 Hour", "number": "5", "period": "Hour"}, + {"doctype": "Prescription Duration", "name": "4 Hour", "number": "4", "period": "Hour"}, + {"doctype": "Prescription Duration", "name": "3 Hour", "number": "3", "period": "Hour"}, + {"doctype": "Prescription Duration", "name": "2 Hour", "number": "2", "period": "Hour"}, + {"doctype": "Prescription Duration", "name": "1 Hour", "number": "1", "period": "Hour"}, + {"doctype": "Prescription Duration", "name": "5 Week", "number": "5", "period": "Week"}, + {"doctype": "Prescription Duration", "name": "4 Week", "number": "4", "period": "Week"}, + {"doctype": "Prescription Duration", "name": "3 Week", "number": "3", "period": "Week"}, + {"doctype": "Prescription Duration", "name": "2 Week", "number": "2", "period": "Week"}, + {"doctype": "Prescription Duration", "name": "1 Week", "number": "1", "period": "Week"}, + {"doctype": "Prescription Duration", "name": "6 Day", "number": "6", "period": "Day"}, + {"doctype": "Prescription Duration", "name": "5 Day", "number": "5", "period": "Day"}, + {"doctype": "Prescription Duration", "name": "4 Day", "number": "4", "period": "Day"}, + {"doctype": "Prescription Duration", "name": "3 Day", "number": "3", "period": "Day"}, + {"doctype": "Prescription Duration", "name": "2 Day", "number": "2", "period": "Day"}, + {"doctype": "Prescription Duration", "name": "1 Day", "number": "1", "period": "Day"}, + ] + insert_record(records) + + +def create_dosage(): + records = [ + { + "doctype": "Prescription Dosage", + "name": "1-1-1-1", + "dosage": "1-1-1-1", + "dosage_strength": [ + {"strength": "1.0", "strength_time": "9:00:00"}, + {"strength": "1.0", "strength_time": "13:00:00"}, + {"strength": "1.0", "strength_time": "17:00:00"}, + {"strength": "1.0", "strength_time": "21:00:00"}, + ], + }, + { + "doctype": "Prescription Dosage", + "name": "0-0-1", + "dosage": "0-0-1", + "dosage_strength": [{"strength": "1.0", "strength_time": "21:00:00"}], + }, + { + "doctype": "Prescription Dosage", + "name": "1-0-0", + "dosage": "1-0-0", + "dosage_strength": [{"strength": "1.0", "strength_time": "9:00:00"}], + }, + { + "doctype": "Prescription Dosage", + "name": "0-1-0", + "dosage": "0-1-0", + "dosage_strength": [{"strength": "1.0", "strength_time": "14:00:00"}], + }, + { + "doctype": "Prescription Dosage", + "name": "1-1-1", + "dosage": "1-1-1", + "dosage_strength": [ + {"strength": "1.0", "strength_time": "9:00:00"}, + {"strength": "1.0", "strength_time": "14:00:00"}, + {"strength": "1.0", "strength_time": "21:00:00"}, + ], + }, + { + "doctype": "Prescription Dosage", + "name": "1-0-1", + "dosage": "1-0-1", + "dosage_strength": [ + {"strength": "1.0", "strength_time": "9:00:00"}, + {"strength": "1.0", "strength_time": "21:00:00"}, + ], + }, + { + "doctype": "Prescription Dosage", + "name": "Once Bedtime", + "dosage": "Once Bedtime", + "dosage_strength": [{"strength": "1.0", "strength_time": "21:00:00"}], + }, + { + "doctype": "Prescription Dosage", + "name": "5 times a day", + "dosage": "5 times a day", + "dosage_strength": [ + {"strength": "1.0", "strength_time": "5:00:00"}, + {"strength": "1.0", "strength_time": "9:00:00"}, + {"strength": "1.0", "strength_time": "13:00:00"}, + {"strength": "1.0", "strength_time": "17:00:00"}, + {"strength": "1.0", "strength_time": "21:00:00"}, + ], + }, + { + "doctype": "Prescription Dosage", + "name": "QID", + "dosage": "QID", + "dosage_strength": [ + {"strength": "1.0", "strength_time": "9:00:00"}, + {"strength": "1.0", "strength_time": "13:00:00"}, + {"strength": "1.0", "strength_time": "17:00:00"}, + {"strength": "1.0", "strength_time": "21:00:00"}, + ], + }, + { + "doctype": "Prescription Dosage", + "name": "TID", + "dosage": "TID", + "dosage_strength": [ + {"strength": "1.0", "strength_time": "9:00:00"}, + {"strength": "1.0", "strength_time": "14:00:00"}, + {"strength": "1.0", "strength_time": "21:00:00"}, + ], + }, + { + "doctype": "Prescription Dosage", + "name": "BID", + "dosage": "BID", + "dosage_strength": [ + {"strength": "1.0", "strength_time": "9:00:00"}, + {"strength": "1.0", "strength_time": "21:00:00"}, + ], + }, + { + "doctype": "Prescription Dosage", + "name": "Once Daily", + "dosage": "Once Daily", + "dosage_strength": [{"strength": "1.0", "strength_time": "9:00:00"}], + }, + ] + insert_record(records) + + +def create_dosage_form(): + records = [ + { + "doctype": "Dosage Form", + "dosage_form": "Tablet", + }, + { + "doctype": "Dosage Form", + "dosage_form": "Syrup", + }, + { + "doctype": "Dosage Form", + "dosage_form": "Injection", + }, + { + "doctype": "Dosage Form", + "dosage_form": "Capsule", + }, + { + "doctype": "Dosage Form", + "dosage_form": "Cream", + }, + ] + insert_record(records) + + +def create_healthcare_item_groups(): + item_group = { + "doctype": "Item Group", + "item_group_name": _("All Item Groups"), + "is_group": 0, + "parent_item_group": "", + } + if not frappe.db.exists(item_group["doctype"], item_group["item_group_name"]): + insert_record([item_group]) + + records = [ + { + "doctype": "Item Group", + "item_group_name": _("Laboratory"), + "is_group": 0, + "parent_item_group": _("All Item Groups"), + }, + { + "doctype": "Item Group", + "item_group_name": _("Drug"), + "is_group": 0, + "parent_item_group": _("All Item Groups"), + }, + ] + insert_record(records) + + +def create_sensitivity(): + records = [ + {"doctype": "Sensitivity", "sensitivity": _("Low Sensitivity")}, + {"doctype": "Sensitivity", "sensitivity": _("High Sensitivity")}, + {"doctype": "Sensitivity", "sensitivity": _("Moderate Sensitivity")}, + {"doctype": "Sensitivity", "sensitivity": _("Susceptible")}, + {"doctype": "Sensitivity", "sensitivity": _("Resistant")}, + {"doctype": "Sensitivity", "sensitivity": _("Intermediate")}, + ] + insert_record(records) + + +def setup_patient_history_settings(): + import json + + settings = frappe.get_single("Patient History Settings") + configuration = get_patient_history_config() + for dt, config in configuration.items(): + settings.append( + "standard_doctypes", + {"document_type": dt, "date_fieldname": config[0], "selected_fields": json.dumps(config[1])}, + ) + settings.save() + + +def get_patient_history_config(): + return { + "Patient Encounter": ( + "encounter_date", + [ + {"label": "Healthcare Practitioner", "fieldname": "practitioner", "fieldtype": "Link"}, + {"label": "Symptoms", "fieldname": "symptoms", "fieldtype": "Table Multiselect"}, + {"label": "Diagnosis", "fieldname": "diagnosis", "fieldtype": "Table Multiselect"}, + {"label": "Drug Prescription", "fieldname": "drug_prescription", "fieldtype": "Table"}, + {"label": "Lab Tests", "fieldname": "lab_test_prescription", "fieldtype": "Table"}, + {"label": "Clinical Procedures", "fieldname": "procedure_prescription", "fieldtype": "Table"}, + {"label": "Therapies", "fieldname": "therapies", "fieldtype": "Table"}, + {"label": "Review Details", "fieldname": "encounter_comment", "fieldtype": "Small Text"}, + ], + ), + "Clinical Procedure": ( + "start_date", + [ + {"label": "Procedure Template", "fieldname": "procedure_template", "fieldtype": "Link"}, + {"label": "Healthcare Practitioner", "fieldname": "practitioner", "fieldtype": "Link"}, + {"label": "Notes", "fieldname": "notes", "fieldtype": "Small Text"}, + {"label": "Service Unit", "fieldname": "service_unit", "fieldtype": "Healthcare Service Unit"}, + {"label": "Start Time", "fieldname": "start_time", "fieldtype": "Time"}, + {"label": "Sample", "fieldname": "sample", "fieldtype": "Link"}, + ], + ), + "Lab Test": ( + "result_date", + [ + {"label": "Test Template", "fieldname": "template", "fieldtype": "Link"}, + {"label": "Healthcare Practitioner", "fieldname": "practitioner", "fieldtype": "Link"}, + {"label": "Test Name", "fieldname": "lab_test_name", "fieldtype": "Data"}, + {"label": "Lab Technician Name", "fieldname": "employee_name", "fieldtype": "Data"}, + {"label": "Sample ID", "fieldname": "sample", "fieldtype": "Link"}, + {"label": "Normal Test Result", "fieldname": "normal_test_items", "fieldtype": "Table"}, + { + "label": "Descriptive Test Result", + "fieldname": "descriptive_test_items", + "fieldtype": "Table", + }, + {"label": "Organism Test Result", "fieldname": "organism_test_items", "fieldtype": "Table"}, + { + "label": "Sensitivity Test Result", + "fieldname": "sensitivity_test_items", + "fieldtype": "Table", + }, + {"label": "Comments", "fieldname": "lab_test_comment", "fieldtype": "Table"}, + ], + ), + "Therapy Session": ( + "start_date", + [ + {"label": "Therapy Type", "fieldname": "therapy_type", "fieldtype": "Link"}, + {"label": "Healthcare Practitioner", "fieldname": "practitioner", "fieldtype": "Link"}, + {"label": "Therapy Plan", "fieldname": "therapy_plan", "fieldtype": "Link"}, + {"label": "Duration", "fieldname": "duration", "fieldtype": "Int"}, + {"label": "Location", "fieldname": "location", "fieldtype": "Link"}, + {"label": "Healthcare Service Unit", "fieldname": "service_unit", "fieldtype": "Link"}, + {"label": "Start Time", "fieldname": "start_time", "fieldtype": "Time"}, + {"label": "Exercises", "fieldname": "exercises", "fieldtype": "Table"}, + {"label": "Total Counts Targeted", "fieldname": "total_counts_targeted", "fieldtype": "Int"}, + {"label": "Total Counts Completed", "fieldname": "total_counts_completed", "fieldtype": "Int"}, + ], + ), + "Vital Signs": ( + "signs_date", + [ + {"label": "Body Temperature", "fieldname": "temperature", "fieldtype": "Data"}, + {"label": "Heart Rate / Pulse", "fieldname": "pulse", "fieldtype": "Data"}, + {"label": "Respiratory rate", "fieldname": "respiratory_rate", "fieldtype": "Data"}, + {"label": "Tongue", "fieldname": "tongue", "fieldtype": "Select"}, + {"label": "Abdomen", "fieldname": "abdomen", "fieldtype": "Select"}, + {"label": "Reflexes", "fieldname": "reflexes", "fieldtype": "Select"}, + {"label": "Blood Pressure", "fieldname": "bp", "fieldtype": "Data"}, + {"label": "Notes", "fieldname": "vital_signs_note", "fieldtype": "Small Text"}, + {"label": "Height (In Meter)", "fieldname": "height", "fieldtype": "Float"}, + {"label": "Weight (In Kilogram)", "fieldname": "weight", "fieldtype": "Float"}, + {"label": "BMI", "fieldname": "bmi", "fieldtype": "Float"}, + ], + ), + "Inpatient Medication Order": ( + "start_date", + [ + {"label": "Healthcare Practitioner", "fieldname": "practitioner", "fieldtype": "Link"}, + {"label": "Start Date", "fieldname": "start_date", "fieldtype": "Date"}, + {"label": "End Date", "fieldname": "end_date", "fieldtype": "Date"}, + {"label": "Medication Orders", "fieldname": "medication_orders", "fieldtype": "Table"}, + {"label": "Total Orders", "fieldname": "total_orders", "fieldtype": "Float"}, + ], + ), + } diff --git a/healthcare/templates/__init__.py b/healthcare/templates/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/healthcare/templates/pages/__init__.py b/healthcare/templates/pages/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/key-features.png b/key-features.png new file mode 100644 index 0000000..801536a Binary files /dev/null and b/key-features.png differ diff --git a/license.txt b/license.txt new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/license.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..8043dd9 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,11 @@ +[tool.black] +line-length = 99 + +[tool.isort] +line_length = 99 +multi_line_output = 3 +include_trailing_comma = true +force_grid_wrap = 0 +use_parentheses = true +ensure_newline_before_comments = true +indent = "\t" diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..7668191 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +# frappe -- https://github.com/frappe/frappe is installed via 'bench init' \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..1a0b2cc --- /dev/null +++ b/setup.py @@ -0,0 +1,19 @@ +from setuptools import setup, find_packages + +with open("requirements.txt") as f: + install_requires = f.read().strip().split("\n") + +# get version from __version__ variable in healthcare/__init__.py +from healthcare import __version__ as version + +setup( + name="healthcare", + version=version, + description="healthcare", + author="healthcare", + author_email="healthcare", + packages=find_packages(), + zip_safe=False, + include_package_data=True, + install_requires=install_requires, +)