Merge branch 'rebrand-ui' of https://github.com/frappe/erpnext into desk-enhancements

This commit is contained in:
Shivam Mishra
2020-12-16 13:21:10 +05:30
311 changed files with 9144 additions and 2211 deletions

View File

@@ -85,8 +85,7 @@ frappe.ui.form.on('Clinical Procedure', {
callback: function(r) {
if (r.message) {
frappe.show_alert({
message: __('Stock Entry {0} created',
['<a class="bold" href="/desk/Form/Stock Entry/'+ r.message + '">' + r.message + '</a>']),
message: __('Stock Entry {0} created', ['<a class="bold" href="/app/stock-entry/'+ r.message + '">' + r.message + '</a>']),
indicator: 'green'
});
}
@@ -105,8 +104,7 @@ frappe.ui.form.on('Clinical 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()]);
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() {

View File

@@ -7,6 +7,7 @@ import frappe
import unittest
from frappe.utils import nowdate, add_days
from erpnext.healthcare.doctype.patient_appointment.test_patient_appointment import create_healthcare_docs, create_appointment, create_healthcare_service_items
from erpnext.accounts.doctype.pos_profile.test_pos_profile import make_pos_profile
test_dependencies = ["Company"]
@@ -15,6 +16,7 @@ class TestFeeValidity(unittest.TestCase):
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()

View File

@@ -29,6 +29,29 @@ frappe.ui.form.on('Inpatient Medication Entry', {
}
};
});
if (frm.doc.__islocal || frm.doc.docstatus !== 0 || !frm.doc.update_stock)
return;
frm.add_custom_button(__('Make Stock Entry'), function() {
frappe.call({
method: 'erpnext.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) {

View File

@@ -142,25 +142,32 @@ class InpatientMedicationEntry(Document):
return orders, order_entry_map
def check_stock_qty(self):
from erpnext.stock.stock_ledger import NegativeStockError
drug_shortage = get_drug_shortage_map(self.medication_orders, self.warehouse)
drug_availability = dict()
for d in self.medication_orders:
if not drug_availability.get(d.drug_code):
drug_availability[d.drug_code] = 0
drug_availability[d.drug_code] += flt(d.dosage)
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.')
for drug, dosage in drug_availability.items():
available_qty = get_latest_stock_qty(drug, self.warehouse)
formatted_item_rows = ''
# validate qty
if flt(available_qty) < flt(dosage):
frappe.throw(_('Quantity not available for {0} in warehouse {1}').format(
frappe.bold(drug), frappe.bold(self.warehouse))
+ '<br><br>' + _('Available quantity is {0}, you need {1}').format(
frappe.bold(available_qty), frappe.bold(dosage))
+ '<br><br>' + _('Please enable Allow Negative Stock in Stock Settings or create Stock Entry to proceed.'),
NegativeStockError, title=_('Insufficient Stock'))
for drug, shortage_qty in drug_shortage.items():
item_link = get_link_to_form('Item', drug)
formatted_item_rows += """
<td>{0}</td>
<td>{1}</td>
</tr>""".format(item_link, frappe.bold(shortage_qty))
message += """
<table class='table'>
<thead>
<th>{0}</th>
<th>{1}</th>
</thead>
{2}
</table>
""".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')
@@ -223,7 +230,8 @@ def get_pending_medication_orders(entry):
for doc in data:
inpatient_record = doc.inpatient_record
doc['service_unit'] = get_current_healthcare_service_unit(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)
@@ -274,4 +282,57 @@ def get_filters(entry):
def get_current_healthcare_service_unit(inpatient_record):
ip_record = frappe.get_doc('Inpatient Record', inpatient_record)
return ip_record.inpatient_occupancies[-1].service_unit
if 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

View File

@@ -9,6 +9,7 @@ from frappe.utils import add_days, getdate, now_datetime
from erpnext.healthcare.doctype.inpatient_record.test_inpatient_record import create_patient, create_inpatient, get_healthcare_service_unit, mark_invoiced_inpatient_occupancy
from erpnext.healthcare.doctype.inpatient_record.inpatient_record import admit_patient, discharge_patient, schedule_discharge
from erpnext.healthcare.doctype.inpatient_medication_order.test_inpatient_medication_order import create_ipmo, create_ipme
from erpnext.healthcare.doctype.inpatient_medication_entry.inpatient_medication_entry import get_drug_shortage_map, make_difference_stock_entry
from erpnext.healthcare.doctype.healthcare_settings.healthcare_settings import get_account
class TestInpatientMedicationEntry(unittest.TestCase):
@@ -82,6 +83,39 @@ class TestInpatientMedicationEntry(unittest.TestCase):
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}))
@@ -94,15 +128,12 @@ class TestInpatientMedicationEntry(unittest.TestCase):
for entry in frappe.get_all('Inpatient Medication Entry'):
doc = frappe.get_doc('Inpatient Medication Entry', entry.name)
doc.cancel()
frappe.db.delete('Stock Entry', {'inpatient_medication_entry': doc.name})
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 make_stock_entry():
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'
@@ -110,7 +141,7 @@ def make_stock_entry():
stock_entry = frappe.new_doc('Stock Entry')
stock_entry.stock_entry_type = 'Material Receipt'
stock_entry.company = '_Test Company'
stock_entry.to_warehouse = 'Stores - _TC'
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'

View File

@@ -18,6 +18,10 @@ def get_data():
{
'label': _('Billing'),
'items': ['Sales Invoice']
},
{
'label': _('Orders'),
'items': ['Inpatient Medication Order']
}
]
}

View File

@@ -7,12 +7,14 @@ import frappe
from erpnext.healthcare.doctype.patient_appointment.patient_appointment import update_status, make_encounter
from frappe.utils import nowdate, add_days
from frappe.utils.make_random import get_random
from erpnext.accounts.doctype.pos_profile.test_pos_profile import make_pos_profile
class TestPatientAppointment(unittest.TestCase):
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()
def test_status(self):
patient, medical_department, practitioner = create_healthcare_docs()

View File

@@ -6,11 +6,13 @@ import unittest
import frappe
from frappe.utils import nowdate
from erpnext.healthcare.doctype.patient_appointment.test_patient_appointment import create_encounter, create_healthcare_docs, create_appointment
from erpnext.accounts.doctype.pos_profile.test_pos_profile import make_pos_profile
class TestPatientMedicalRecord(unittest.TestCase):
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, medical_department, practitioner = create_healthcare_docs()

View File

@@ -0,0 +1,57 @@
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
// 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
}
]
};

View File

@@ -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"
}
]
}

View File

@@ -0,0 +1,198 @@
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from erpnext.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

View File

@@ -0,0 +1,128 @@
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import unittest
import frappe
import datetime
from frappe.utils import getdate, now_datetime
from erpnext.healthcare.doctype.inpatient_record.test_inpatient_record import create_patient, create_inpatient, get_healthcare_service_unit, mark_invoiced_inpatient_occupancy
from erpnext.healthcare.doctype.inpatient_record.inpatient_record import admit_patient, discharge_patient, schedule_discharge
from erpnext.healthcare.doctype.inpatient_medication_order.test_inpatient_medication_order import create_ipmo, create_ipme
from erpnext.healthcare.report.inpatient_medication_orders.inpatient_medication_orders import execute
class TestInpatientMedicationOrders(unittest.TestCase):
@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()
admit_patient(ip_record, service_unit, now_datetime())
ipmo = create_ipmo(patient)
ipmo.submit()
return ip_record