blob: 1912270e0e6186a3cea0b5fefbc8928671669808 [file] [log] [blame]
Jamsheerba119722018-07-06 15:58:13 +05301# -*- coding: utf-8 -*-
2# Copyright (c) 2018, earthians and contributors
3# For license information, please see license.txt
4
5from __future__ import unicode_literals
6import frappe
7import datetime
8from frappe import _
Jamsheer25dda3a2018-07-30 14:50:16 +05309import math
Jamsheer363deb62018-08-04 12:56:36 +053010from frappe.utils import time_diff_in_hours, rounded, getdate, add_days
Jamsheerba119722018-07-06 15:58:13 +053011from erpnext.healthcare.doctype.healthcare_settings.healthcare_settings import get_income_account
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +053012from erpnext.healthcare.doctype.fee_validity.fee_validity import create_fee_validity
Jamsheer0ae100b2018-08-01 14:29:43 +053013from erpnext.healthcare.doctype.lab_test.lab_test import create_multiple
Jamsheerba119722018-07-06 15:58:13 +053014
15@frappe.whitelist()
16def get_healthcare_services_to_invoice(patient):
Rucha Mahabal27512c82020-03-09 17:29:23 +053017 patient = frappe.get_doc('Patient', patient)
Jamsheerba119722018-07-06 15:58:13 +053018 if patient:
Rucha Mahabal27512c82020-03-09 17:29:23 +053019 validate_customer_created(patient)
20 items_to_invoice = []
21 patient_appointments = frappe.get_list(
22 'Patient Appointment',
23 fields='*',
24 filters={'patient': patient.name, 'invoiced': False},
25 order_by='appointment_date'
26 )
27 if patient_appointments:
28 items_to_invoice = get_fee_validity(patient_appointments)
Jamsheerba119722018-07-06 15:58:13 +053029
Rucha Mahabal27512c82020-03-09 17:29:23 +053030 encounters = get_encounters_to_invoice(patient)
31 lab_tests = get_lab_tests_to_invoice(patient)
32 clinical_procedures = get_clinical_procedures_to_invoice(patient)
33 inpatient_services = get_inpatient_services_to_invoice(patient)
Jamsheerba119722018-07-06 15:58:13 +053034
Rucha Mahabal27512c82020-03-09 17:29:23 +053035 items_to_invoice = encounters + lab_tests + clinical_procedures + inpatient_services
36 return items_to_invoice
Jamsheerba119722018-07-06 15:58:13 +053037
Rucha Mahabal27512c82020-03-09 17:29:23 +053038def validate_customer_created(patient):
39 if not frappe.db.get_value('Patient', patient.name, 'customer'):
40 msg = _("Please set a Customer linked to the Patient")
41 msg += " <b><a href='#Form/Patient/{0}'>{0}</a></b>".format(patient.name)
42 frappe.throw(msg, title=_('Customer Not Found'))
Jamsheer8da6f4e2018-07-26 21:03:17 +053043
Rucha Mahabal27512c82020-03-09 17:29:23 +053044def get_fee_validity(patient_appointments):
Rucha Mahabalf2574dd2020-03-17 19:28:18 +053045 if not frappe.db.get_single_value('Healthcare Settings', 'enable_free_follow_ups'):
46 return
47
Rucha Mahabal27512c82020-03-09 17:29:23 +053048 fee_validity_details = []
49 items_to_invoice = []
50 valid_days = frappe.db.get_single_value('Healthcare Settings', 'valid_days')
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +053051 max_visits = frappe.db.get_single_value('Healthcare Settings', 'max_visits')
Rucha Mahabal27512c82020-03-09 17:29:23 +053052 for appointment in patient_appointments:
53 if appointment.procedure_template:
54 if frappe.db.get_value('Clinical Procedure Template', appointment.procedure_template, 'is_billable'):
55 items_to_invoice.append({
56 'reference_type': 'Patient Appointment',
57 'reference_name': appointment.name,
58 'service': appointment.procedure_template
59 })
Jamsheerba119722018-07-06 15:58:13 +053060 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +053061 practitioner_exist_in_list = False
62 skip_invoice = False
63 if fee_validity_details:
64 for validity in fee_validity_details:
65 if validity['practitioner'] == appointment.practitioner:
66 practitioner_exist_in_list = True
67 if validity['valid_till'] >= appointment.appointment_date:
68 validity['visits'] = validity['visits'] + 1
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +053069 if int(max_visits) > validity['visits']:
Rucha Mahabal27512c82020-03-09 17:29:23 +053070 skip_invoice = True
71 if not skip_invoice:
72 validity['visits'] = 1
73 validity['valid_till'] = appointment.appointment_date + datetime.timedelta(days=int(valid_days))
74
75 if not practitioner_exist_in_list:
76 valid_till = appointment.appointment_date + datetime.timedelta(days=int(valid_days))
77 visits = 0
Rucha Mahabalcd319962020-03-13 15:39:31 +053078 fee_validity = check_fee_validity(appointment)
79 if fee_validity:
Rucha Mahabal27512c82020-03-09 17:29:23 +053080 valid_till = fee_validity.valid_till
81 visits = fee_validity.visited
Rucha Mahabalcd319962020-03-13 15:39:31 +053082 fee_validity_details.append({'practitioner': appointment.practitioner,
83 'valid_till': valid_till, 'visits': visits})
Rucha Mahabal27512c82020-03-09 17:29:23 +053084
85 if not skip_invoice:
86 practitioner_charge = 0
87 income_account = None
88 service_item = None
89 if appointment.practitioner:
90 service_item, practitioner_charge = get_service_item_and_practitioner_charge(appointment)
91 income_account = get_income_account(appointment.practitioner, appointment.company)
92 items_to_invoice.append({'reference_type': 'Patient Appointment', 'reference_name': appointment.name,
93 'service': service_item, 'rate': practitioner_charge,
94 'income_account': income_account})
95
96 return items_to_invoice
97
98
99def get_encounters_to_invoice(patient):
100 encounters_to_invoice = []
101 encounters = frappe.get_list(
102 'Patient Encounter',
103 fields=['*'],
104 filters={'patient': patient.name, 'invoiced': False, 'docstatus': 1}
105 )
106 if encounters:
107 for encounter in encounters:
108 if not encounter.appointment:
109 practitioner_charge = 0
110 income_account = None
111 service_item = None
112 if encounter.practitioner:
113 service_item, practitioner_charge = get_service_item_and_practitioner_charge(encounter)
114 income_account = get_income_account(encounter.practitioner, encounter.company)
115
116 encounters_to_invoice.append({
117 'reference_type': 'Patient Encounter',
118 'reference_name': encounter.name,
119 'service': service_item,
120 'rate': practitioner_charge,
121 'income_account': income_account
122 })
123
124 return encounters_to_invoice
125
126
127def get_lab_tests_to_invoice(patient):
128 lab_tests_to_invoice = []
129 lab_tests = frappe.get_list(
130 'Lab Test',
131 fields=['name', 'template'],
132 filters={'patient': patient.name, 'invoiced': False, 'docstatus': 1}
133 )
134 for lab_test in lab_tests:
135 if frappe.db.get_value('Lab Test Template', lab_test.template, 'is_billable'):
136 lab_tests_to_invoice.append({
137 'reference_type': 'Lab Test',
138 'reference_name': lab_test.name,
139 'service': frappe.db.get_value('Lab Test Template', lab_test.template, 'item')
140 })
141
142 lab_prescriptions = frappe.db.sql('''select lp.name, lp.lab_test_code from `tabPatient Encounter` et, `tabLab Prescription` lp
143 where et.patient=%s and lp.parent=et.name and lp.lab_test_created=0 and lp.invoiced=0''', (patient.name), as_dict=1)
144
145 for prescription in lab_prescriptions:
146 if prescription.lab_test_code and frappe.db.get_value('Lab Test Template', prescription.lab_test_code, 'is_billable'):
147 lab_tests_to_invoice.append({
148 'reference_type': 'Lab Prescription',
149 'reference_name': prescription.name,
150 'service': frappe.db.get_value('Lab Test Template', prescription.lab_test_code, 'item')
151 })
152
153 return lab_tests_to_invoice
154
155
156def get_clinical_procedures_to_invoice(patient):
157 clinical_procedures_to_invoice = []
158 procedures = frappe.get_list(
159 'Clinical Procedure',
160 fields='*',
161 filters={'patient': patient.name, 'invoiced': False}
162 )
163 for procedure in procedures:
164 if not procedure.appointment:
165 if procedure.procedure_template and frappe.db.get_value('Clinical Procedure Template', procedure.procedure_template, 'is_billable'):
166 clinical_procedures_to_invoice.append({
167 'reference_type': 'Clinical Procedure',
168 'reference_name': procedure.name,
169 'service': frappe.db.get_value('Clinical Procedure Template', procedure.procedure_template, 'item')
170 })
171
172 # consumables
173 if procedure.invoice_separately_as_consumables and procedure.consume_stock \
174 and procedure.status == 'Completed' and not procedure.consumption_invoiced:
175
176 service_item = get_healthcare_service_item('clinical_procedure_consumable_item')
177 if not service_item:
178 msg = _('Please Configure Clinical Procedure Consumable Item in ')
179 msg += '''<b><a href='#Form/Healthcare Settings'>Healthcare Settings</a></b>'''
180 frappe.throw(msg, title=_('Missing Configuration'))
181
182 clinical_procedures_to_invoice.append({
183 'reference_type': 'Clinical Procedure',
184 'reference_name': procedure.name,
185 'service': service_item,
186 'rate': procedure.consumable_total_amount,
187 'description': procedure.consumption_details
188 })
189
190 procedure_prescriptions = frappe.db.sql('''select pp.name, pp.procedure from `tabPatient Encounter` et,
191 `tabProcedure Prescription` pp where et.patient=%s and pp.parent=et.name and
192 pp.procedure_created=0 and pp.invoiced=0 and pp.appointment_booked=0''', (patient.name), as_dict=1)
193
194 for prescription in procedure_prescriptions:
195 if frappe.db.get_value('Clinical Procedure Template', prescription.procedure, 'is_billable'):
196 items_to_invoice.append({
197 'reference_type': 'Procedure Prescription',
198 'reference_name': prescription.name,
199 'service': frappe.db.get_value('Clinical Procedure Template', prescription.procedure, 'item')
200 })
201
202 return clinical_procedures_to_invoice
203
204
205def get_inpatient_services_to_invoice(patient):
206 services_to_invoice = []
207 inpatient_services = frappe.db.sql('''select io.* from `tabInpatient Record` ip,
208 `tabInpatient Occupancy` io where ip.patient=%s and io.parent=ip.name and
209 io.left=1 and io.invoiced=0''', (patient.name), as_dict=1)
210
211 for inpatient_occupancy in inpatient_services:
212 service_unit_type = frappe.db.get_value('Healthcare Service Unit', inpatient_occupancy.service_unit, 'service_unit_type')
213 service_unit_type = frappe.get_doc('Healthcare Service Unit Type', service_unit_type)
214 if service_unit_type and service_unit_type.is_billable:
215 hours_occupied = time_diff_in_hours(inpatient_occupancy.check_out, inpatient_occupancy.check_in)
216 qty = 0.5
217 if hours_occupied > 0:
218 actual_qty = hours_occupied / service_unit_type.no_of_hours
219 floor = math.floor(actual_qty)
220 decimal_part = actual_qty - floor
221 if decimal_part > 0.5:
222 qty = rounded(floor + 1, 1)
223 elif decimal_part < 0.5 and decimal_part > 0:
224 qty = rounded(floor + 0.5, 1)
225 if qty <= 0:
226 qty = 0.5
227 services_to_invoice.append({
228 'reference_type': 'Inpatient Occupancy',
229 'reference_name': inpatient_occupancy.name,
230 'service': service_unit_type.item, 'qty': qty
231 })
232
233 return services_to_invoice
234
Jamsheerba119722018-07-06 15:58:13 +0530235
Rucha Mahabal24055e12020-02-24 19:09:50 +0530236def get_service_item_and_practitioner_charge(doc):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530237 is_inpatient = doc.inpatient_record
Rucha Mahabal24055e12020-02-24 19:09:50 +0530238 if is_inpatient:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530239 service_item = get_practitioner_service_item(doc.practitioner, 'inpatient_visit_charge_item')
Jamsheeree5f9c72018-07-30 12:42:06 +0530240 if not service_item:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530241 service_item = get_healthcare_service_item('inpatient_visit_charge_item')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530242 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530243 service_item = get_practitioner_service_item(doc.practitioner, 'op_consulting_charge_item')
Jamsheeree5f9c72018-07-30 12:42:06 +0530244 if not service_item:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530245 service_item = get_healthcare_service_item('op_consulting_charge_item')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530246 if not service_item:
Rucha Mahabal24055e12020-02-24 19:09:50 +0530247 throw_config_service_item(is_inpatient)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530248
Rucha Mahabal24055e12020-02-24 19:09:50 +0530249 practitioner_charge = get_practitioner_charge(doc.practitioner, is_inpatient)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530250 if not practitioner_charge:
Rucha Mahabal24055e12020-02-24 19:09:50 +0530251 throw_config_practitioner_charge(is_inpatient, doc.practitioner)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530252
253 return service_item, practitioner_charge
254
Jamsheer8da6f4e2018-07-26 21:03:17 +0530255
Rucha Mahabal27512c82020-03-09 17:29:23 +0530256def throw_config_service_item(is_inpatient):
257 service_item_lable = 'Out Patient Consulting Charge Item'
258 if is_inpatient:
259 service_item_lable = 'Inpatient Visit Charge Item'
260
261 msg = _(('Please Configure {0} in ').format(service_item_lable) \
262 + '''<b><a href='#Form/Healthcare Settings'>Healthcare Settings</a></b>''')
263 frappe.throw(msg, title=_('Missing Configuration'))
264
Jamsheer8da6f4e2018-07-26 21:03:17 +0530265
Rucha Mahabal24055e12020-02-24 19:09:50 +0530266def throw_config_practitioner_charge(is_inpatient, practitioner):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530267 charge_name = 'OP Consulting Charge'
Rucha Mahabal24055e12020-02-24 19:09:50 +0530268 if is_inpatient:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530269 charge_name = 'Inpatient Visit Charge'
Jamsheer8da6f4e2018-07-26 21:03:17 +0530270
Rucha Mahabal27512c82020-03-09 17:29:23 +0530271 msg = _(('Please Configure {0} for Healthcare Practitioner').format(charge_name) \
272 + ''' <b><a href='#Form/Healthcare Practitioner/{0}'>{0}</a></b>'''.format(practitioner))
273 frappe.throw(msg, title=_('Missing Configuration'))
274
Jamsheer8da6f4e2018-07-26 21:03:17 +0530275
Jamsheeree5f9c72018-07-30 12:42:06 +0530276def get_practitioner_service_item(practitioner, service_item_field):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530277 return frappe.db.get_value('Healthcare Practitioner', practitioner, service_item_field)
278
Jamsheeree5f9c72018-07-30 12:42:06 +0530279
Jamsheer8da6f4e2018-07-26 21:03:17 +0530280def get_healthcare_service_item(service_item_field):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530281 return frappe.db.get_single_value('Healthcare Settings', service_item_field)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530282
Jamsheer8da6f4e2018-07-26 21:03:17 +0530283
Rucha Mahabal24055e12020-02-24 19:09:50 +0530284def get_practitioner_charge(practitioner, is_inpatient):
285 if is_inpatient:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530286 practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, 'inpatient_visit_charge')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530287 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530288 practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, 'op_consulting_charge')
Jamsheerba119722018-07-06 15:58:13 +0530289 if practitioner_charge:
290 return practitioner_charge
Jamsheer8da6f4e2018-07-26 21:03:17 +0530291 return False
Jamsheerba119722018-07-06 15:58:13 +0530292
Rucha Mahabal27512c82020-03-09 17:29:23 +0530293
Jamsheerba119722018-07-06 15:58:13 +0530294def manage_invoice_submit_cancel(doc, method):
295 if doc.items:
296 for item in doc.items:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530297 if item.get('reference_dt') and item.get('reference_dn'):
298 if frappe.get_meta(item.reference_dt).has_field('invoiced'):
Jamsheer146683b2018-07-25 11:30:30 +0530299 set_invoiced(item, method, doc.name)
Jamsheerba119722018-07-06 15:58:13 +0530300
Rucha Mahabal27512c82020-03-09 17:29:23 +0530301 if method=='on_submit' and frappe.db.get_single_value('Healthcare Settings', 'create_lab_test_on_si_submit'):
302 create_multiple('Sales Invoice', doc.name)
303
Jamsheer0ae100b2018-08-01 14:29:43 +0530304
Jamsheer146683b2018-07-25 11:30:30 +0530305def set_invoiced(item, method, ref_invoice=None):
Jamsheerba119722018-07-06 15:58:13 +0530306 invoiced = False
Rucha Mahabal27512c82020-03-09 17:29:23 +0530307 if method=='on_submit':
Jamsheerba119722018-07-06 15:58:13 +0530308 validate_invoiced_on_submit(item)
309 invoiced = True
310
Jamsheer8da6f4e2018-07-26 21:03:17 +0530311 if item.reference_dt == 'Clinical Procedure':
312 if get_healthcare_service_item('clinical_procedure_consumable_item') == item.item_code:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530313 frappe.db.set_value(item.reference_dt, item.reference_dn, 'consumption_invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530314 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530315 frappe.db.set_value(item.reference_dt, item.reference_dn, 'invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530316 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530317 frappe.db.set_value(item.reference_dt, item.reference_dn, 'invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530318
Jamsheerba119722018-07-06 15:58:13 +0530319 if item.reference_dt == 'Patient Appointment':
320 if frappe.db.get_value('Patient Appointment', item.reference_dn, 'procedure_template'):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530321 dt_from_appointment = 'Clinical Procedure'
Jamsheerba119722018-07-06 15:58:13 +0530322 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530323 dt_from_appointment = 'Patient Encounter'
Rucha Mahabal06d1b042020-03-12 12:16:23 +0530324 manage_doc_for_appointment(dt_from_appointment, item.reference_dn, invoiced)
Jamsheerba119722018-07-06 15:58:13 +0530325
326 elif item.reference_dt == 'Lab Prescription':
Rucha Mahabal27512c82020-03-09 17:29:23 +0530327 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, 'Lab Test', 'lab_test_created')
Jamsheerba119722018-07-06 15:58:13 +0530328
329 elif item.reference_dt == 'Procedure Prescription':
Rucha Mahabal27512c82020-03-09 17:29:23 +0530330 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, 'Clinical Procedure', 'procedure_created')
331
Jamsheerba119722018-07-06 15:58:13 +0530332
333def validate_invoiced_on_submit(item):
Jamsheer8da6f4e2018-07-26 21:03:17 +0530334 if item.reference_dt == 'Clinical Procedure' and get_healthcare_service_item('clinical_procedure_consumable_item') == item.item_code:
Rucha Mahabal06d1b042020-03-12 12:16:23 +0530335 is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, 'consumption_invoiced')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530336 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530337 is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, 'invoiced')
338 if is_invoiced:
339 frappe.throw(_('The item referenced by {0} - {1} is already invoiced'\
Jamsheerba119722018-07-06 15:58:13 +0530340 ).format(item.reference_dt, item.reference_dn))
341
Rucha Mahabal27512c82020-03-09 17:29:23 +0530342
Jamsheerba119722018-07-06 15:58:13 +0530343def manage_prescriptions(invoiced, ref_dt, ref_dn, dt, created_check_field):
344 created = frappe.db.get_value(ref_dt, ref_dn, created_check_field)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530345 if created:
Jamsheerba119722018-07-06 15:58:13 +0530346 # Fetch the doc created for the prescription
Jamsheereafb0462018-07-25 13:15:12 +0530347 doc_created = frappe.db.get_value(dt, {'prescription': ref_dn})
Jamsheerba119722018-07-06 15:58:13 +0530348 frappe.db.set_value(dt, doc_created, 'invoiced', invoiced)
349
Rucha Mahabal27512c82020-03-09 17:29:23 +0530350
Rucha Mahabalcd319962020-03-13 15:39:31 +0530351def check_fee_validity(appointment):
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530352 if not frappe.db.get_single_value('Healthcare Settings', 'enable_free_follow_ups'):
353 return
354
Rucha Mahabalcd319962020-03-13 15:39:31 +0530355 validity = frappe.db.exists('Fee Validity', {
356 'practitioner': appointment.practitioner,
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530357 'patient': appointment.patient,
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530358 'status': 'Pending',
359 'valid_till': ('>=', appointment.appointment_date)
Rucha Mahabalcd319962020-03-13 15:39:31 +0530360 })
361 if not validity:
362 return
363
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530364 validity = frappe.get_doc('Fee Validity', validity)
365 return validity
366
Rucha Mahabal27512c82020-03-09 17:29:23 +0530367
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530368def manage_fee_validity(appointment):
369 fee_validity = check_fee_validity(appointment)
Rucha Mahabalcd319962020-03-13 15:39:31 +0530370 if fee_validity:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530371 if appointment.status == 'Cancelled' and fee_validity.visited > 0:
372 fee_validity.visited -= 1
373 frappe.db.delete('Fee Validity Reference', {'appointment': appointment.name})
Rucha Mahabalcd319962020-03-13 15:39:31 +0530374 else:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530375 fee_validity.visited += 1
376 fee_validity.append('ref_appointments', {
377 'appointment': appointment.name
378 })
379 fee_validity.save(ignore_permissions=True)
Jamsheerba119722018-07-06 15:58:13 +0530380 else:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530381 fee_validity = create_fee_validity(appointment)
382 return fee_validity
Rucha Mahabal27512c82020-03-09 17:29:23 +0530383
Jamsheerba119722018-07-06 15:58:13 +0530384
Rucha Mahabal06d1b042020-03-12 12:16:23 +0530385def manage_doc_for_appointment(dt_from_appointment, appointment, invoiced):
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530386 dn_from_appointment = frappe.db.get_value(
387 dt_from_appointment,
Rucha Mahabal27512c82020-03-09 17:29:23 +0530388 filters={'appointment': appointment}
Jamsheerba119722018-07-06 15:58:13 +0530389 )
390 if dn_from_appointment:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530391 frappe.db.set_value(dt_from_appointment, dn_from_appointment, 'invoiced', invoiced)
392
Jamsheere82f27a2018-07-30 11:28:37 +0530393
394@frappe.whitelist()
395def get_drugs_to_invoice(encounter):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530396 encounter = frappe.get_doc('Patient Encounter', encounter)
Jamsheere82f27a2018-07-30 11:28:37 +0530397 if encounter:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530398 patient = frappe.get_doc('Patient', encounter.patient)
399 if patient:
400 if patient.customer:
401 items_to_invoice = []
Jamsheere82f27a2018-07-30 11:28:37 +0530402 for drug_line in encounter.drug_prescription:
403 if drug_line.drug_code:
404 qty = 1
Rucha Mahabal27512c82020-03-09 17:29:23 +0530405 if frappe.db.get_value('Item', drug_line.drug_code, 'stock_uom') == 'Nos':
Jamsheere82f27a2018-07-30 11:28:37 +0530406 qty = drug_line.get_quantity()
Rucha Mahabal27512c82020-03-09 17:29:23 +0530407
408 description = ''
409 if drug_line.dosage and drug_line.period:
410 description = _('{0} for {1}').format(drug_line.dosage, drug_line.period)
411
412 items_to_invoice.append({
413 'drug_code': drug_line.drug_code,
414 'quantity': qty,
415 'description': description
416 })
417 return items_to_invoice
418 else:
419 validate_customer_created(patient)
420
Jamsheer4371c7e2018-08-01 18:40:05 +0530421
422@frappe.whitelist()
423def get_children(doctype, parent, company, is_root=False):
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530424 parent_fieldname = "parent_" + doctype.lower().replace(" ", "_")
Jamsheer4371c7e2018-08-01 18:40:05 +0530425 fields = [
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530426 "name as value",
427 "is_group as expandable",
428 "lft",
429 "rgt"
Jamsheer4371c7e2018-08-01 18:40:05 +0530430 ]
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530431 # fields = [ "name", "is_group", "lft", "rgt" ]
432 filters = [["ifnull(`{0}`,'')".format(parent_fieldname), "=", "" if is_root else parent]]
Jamsheer4371c7e2018-08-01 18:40:05 +0530433
434 if is_root:
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530435 fields += ["service_unit_type"] if doctype == "Healthcare Service Unit" else []
436 filters.append(["company", "=", company])
Jamsheer4371c7e2018-08-01 18:40:05 +0530437
438 else:
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530439 fields += ["service_unit_type", "allow_appointments", "inpatient_occupancy", "occupancy_status"] if doctype == "Healthcare Service Unit" else []
440 fields += [parent_fieldname + " as parent"]
Jamsheer4371c7e2018-08-01 18:40:05 +0530441
442 hc_service_units = frappe.get_list(doctype, fields=fields, filters=filters)
443
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530444 if doctype == "Healthcare Service Unit":
Jamsheer4371c7e2018-08-01 18:40:05 +0530445 for each in hc_service_units:
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530446 occupancy_msg = ""
447 if each["expandable"] == 1:
Jamsheer4371c7e2018-08-01 18:40:05 +0530448 occupied = False
449 vacant = False
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530450 child_list = frappe.db.sql("""
Jamsheer4371c7e2018-08-01 18:40:05 +0530451 select name, occupancy_status from `tabHealthcare Service Unit`
452 where inpatient_occupancy = 1 and
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530453 lft > %s and rgt < %s""",
454 (each["lft"], each["rgt"]))
Jamsheer4371c7e2018-08-01 18:40:05 +0530455 for child in child_list:
Jamsheer4371c7e2018-08-01 18:40:05 +0530456 if not occupied:
457 occupied = 0
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530458 if child[1] == "Occupied":
Jamsheer4371c7e2018-08-01 18:40:05 +0530459 occupied += 1
460 if not vacant:
461 vacant = 0
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530462 if child[1] == "Vacant":
Jamsheer4371c7e2018-08-01 18:40:05 +0530463 vacant += 1
464 if vacant and occupied:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530465 occupancy_total = vacant + occupied
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530466 occupancy_msg = str(occupied) + " Occupied out of " + str(occupancy_total)
467 each["occupied_out_of_vacant"] = occupancy_msg
Jamsheer4371c7e2018-08-01 18:40:05 +0530468 return hc_service_units
Jamsheer5073ac42019-07-12 12:28:34 +0530469
Rucha Mahabal27512c82020-03-09 17:29:23 +0530470
Jamsheer5073ac42019-07-12 12:28:34 +0530471@frappe.whitelist()
472def get_patient_vitals(patient, from_date=None, to_date=None):
473 if not patient: return
Rucha Mahabal27512c82020-03-09 17:29:23 +0530474
475 vitals = frappe.db.get_all('Vital Signs', {
476 'docstatus': 1,
477 'patient': patient
Rucha Mahabal06d1b042020-03-12 12:16:23 +0530478 }, order_by='signs_date, signs_time')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530479
480 if len(vitals):
Jamsheer5073ac42019-07-12 12:28:34 +0530481 return vitals
Rucha Mahabal27512c82020-03-09 17:29:23 +0530482 return False
483
Jamsheer5073ac42019-07-12 12:28:34 +0530484
485@frappe.whitelist()
486def render_docs_as_html(docs):
487 # docs key value pair {doctype: docname}
488 docs_html = "<div class='col-md-12 col-sm-12 text-muted'>"
489 for doc in docs:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530490 docs_html += render_doc_as_html(doc['doctype'], doc['docname'])['html'] + '<br/>'
Jamsheer5073ac42019-07-12 12:28:34 +0530491 return {'html': docs_html}
492
Rucha Mahabal27512c82020-03-09 17:29:23 +0530493
Jamsheer5073ac42019-07-12 12:28:34 +0530494@frappe.whitelist()
495def render_doc_as_html(doctype, docname, exclude_fields = []):
496 #render document as html, three column layout will break
497 doc = frappe.get_doc(doctype, docname)
498 meta = frappe.get_meta(doctype)
499 doc_html = "<div class='col-md-12 col-sm-12'>"
Rucha Mahabal27512c82020-03-09 17:29:23 +0530500 section_html = ''
501 section_label = ''
502 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530503 sec_on = False
504 col_on = 0
505 has_data = False
506 for df in meta.fields:
507 #on section break append append previous section and html to doc html
508 if df.fieldtype == "Section Break":
509 if has_data and col_on and sec_on:
510 doc_html += section_html + html + "</div>"
511 elif has_data and not col_on and sec_on:
512 doc_html += "<div class='col-md-12 col-sm-12'\
513 ><div class='col-md-12 col-sm-12'>" \
514 + section_html + html +"</div></div>"
515 while col_on:
516 doc_html += "</div>"
517 col_on -= 1
518 sec_on = True
519 has_data= False
520 col_on = 0
Rucha Mahabal27512c82020-03-09 17:29:23 +0530521 section_html = ''
522 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530523 if df.label:
524 section_label = df.label
525 continue
526 #on column break append html to section html or doc html
527 if df.fieldtype == "Column Break":
528 if sec_on and has_data:
529 section_html += "<div class='col-md-12 col-sm-12'\
530 ><div class='col-md-6 col\
531 -sm-6'><b>" + section_label + "</b>" + html + "</div><div \
532 class='col-md-6 col-sm-6'>"
533 elif has_data:
534 doc_html += "<div class='col-md-12 col-sm-12'><div class='col-m\
535 d-6 col-sm-6'>" + html + "</div><div class='col-md-6 col-sm-6'>"
536 elif sec_on and not col_on:
537 section_html += "<div class='col-md-6 col-sm-6'>"
Rucha Mahabal27512c82020-03-09 17:29:23 +0530538 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530539 col_on += 1
540 if df.label:
541 html += '<br>' + df.label
542 continue
543 #on table iterate in items and create table based on in_list_view, append to section html or doc html
Rucha Mahabal27512c82020-03-09 17:29:23 +0530544 if df.fieldtype == 'Table':
Jamsheer5073ac42019-07-12 12:28:34 +0530545 items = doc.get(df.fieldname)
546 if not items: continue
547 child_meta = frappe.get_meta(df.options)
548 if not has_data : has_data = True
Rucha Mahabal27512c82020-03-09 17:29:23 +0530549 table_head = ''
550 table_row = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530551 create_head = True
552 for item in items:
553 table_row += '<tr>'
554 for cdf in child_meta.fields:
555 if cdf.in_list_view:
556 if create_head:
557 table_head += '<th>' + cdf.label + '</th>'
558 if item.get(cdf.fieldname):
559 table_row += '<td>' + str(item.get(cdf.fieldname)) \
560 + '</td>'
561 else:
562 table_row += '<td></td>'
563 create_head = False
564 table_row += '</tr>'
565 if sec_on:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530566 section_html += "<table class='table table-condensed \
567 bordered'>" + table_head + table_row + '</table>'
Jamsheer5073ac42019-07-12 12:28:34 +0530568 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530569 html += "<table class='table table-condensed table-bordered'>" \
570 + table_head + table_row + "</table>"
Jamsheer5073ac42019-07-12 12:28:34 +0530571 continue
572 #on other field types add label and value to html
573 if not df.hidden and not df.print_hide and doc.get(df.fieldname) and df.fieldname not in exclude_fields:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530574 html += '<br>{0} : {1}'.format(df.label or df.fieldname, \
Jamsheer5073ac42019-07-12 12:28:34 +0530575 doc.get(df.fieldname))
576 if not has_data : has_data = True
577 if sec_on and col_on and has_data:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530578 doc_html += section_html + html + '</div></div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530579 elif sec_on and not col_on and has_data:
580 doc_html += "<div class='col-md-12 col-sm-12'\
581 ><div class='col-md-12 col-sm-12'>" \
Rucha Mahabal27512c82020-03-09 17:29:23 +0530582 + section_html + html +'</div></div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530583 if doc_html:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530584 doc_html = "<div class='small'><div class='col-md-12 text-right'><a class='btn btn-default btn-xs' href='#Form/%s/%s'></a></div>" %(doctype, docname) + doc_html + '</div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530585
586 return {'html': doc_html}