blob: 40db1b7d78c1036123b5ed8cfd2e50db4f5015d4 [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
Jamsheerba119722018-07-06 15:58:13 +053012from erpnext.healthcare.doctype.fee_validity.fee_validity import create_fee_validity, update_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):
45 fee_validity_details = []
46 items_to_invoice = []
47 valid_days = frappe.db.get_single_value('Healthcare Settings', 'valid_days')
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +053048 max_visits = frappe.db.get_single_value('Healthcare Settings', 'max_visits')
Rucha Mahabal27512c82020-03-09 17:29:23 +053049 for appointment in patient_appointments:
50 if appointment.procedure_template:
51 if frappe.db.get_value('Clinical Procedure Template', appointment.procedure_template, 'is_billable'):
52 items_to_invoice.append({
53 'reference_type': 'Patient Appointment',
54 'reference_name': appointment.name,
55 'service': appointment.procedure_template
56 })
Jamsheerba119722018-07-06 15:58:13 +053057 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +053058 practitioner_exist_in_list = False
59 skip_invoice = False
60 if fee_validity_details:
61 for validity in fee_validity_details:
62 if validity['practitioner'] == appointment.practitioner:
63 practitioner_exist_in_list = True
64 if validity['valid_till'] >= appointment.appointment_date:
65 validity['visits'] = validity['visits'] + 1
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +053066 if int(max_visits) > validity['visits']:
Rucha Mahabal27512c82020-03-09 17:29:23 +053067 skip_invoice = True
68 if not skip_invoice:
69 validity['visits'] = 1
70 validity['valid_till'] = appointment.appointment_date + datetime.timedelta(days=int(valid_days))
71
72 if not practitioner_exist_in_list:
73 valid_till = appointment.appointment_date + datetime.timedelta(days=int(valid_days))
74 visits = 0
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +053075 validity = check_validity_exists(appointment.practitioner, appointment.patient)
76 if validity:
77 fee_validity = frappe.get_doc('Fee Validity', validity)
Rucha Mahabal27512c82020-03-09 17:29:23 +053078 valid_till = fee_validity.valid_till
79 visits = fee_validity.visited
80 fee_validity_details.append({'practitioner': appointment.practitioner,
81 'valid_till': valid_till, 'visits': visits})
82
83 if not skip_invoice:
84 practitioner_charge = 0
85 income_account = None
86 service_item = None
87 if appointment.practitioner:
88 service_item, practitioner_charge = get_service_item_and_practitioner_charge(appointment)
89 income_account = get_income_account(appointment.practitioner, appointment.company)
90 items_to_invoice.append({'reference_type': 'Patient Appointment', 'reference_name': appointment.name,
91 'service': service_item, 'rate': practitioner_charge,
92 'income_account': income_account})
93
94 return items_to_invoice
95
96
97def get_encounters_to_invoice(patient):
98 encounters_to_invoice = []
99 encounters = frappe.get_list(
100 'Patient Encounter',
101 fields=['*'],
102 filters={'patient': patient.name, 'invoiced': False, 'docstatus': 1}
103 )
104 if encounters:
105 for encounter in encounters:
106 if not encounter.appointment:
107 practitioner_charge = 0
108 income_account = None
109 service_item = None
110 if encounter.practitioner:
111 service_item, practitioner_charge = get_service_item_and_practitioner_charge(encounter)
112 income_account = get_income_account(encounter.practitioner, encounter.company)
113
114 encounters_to_invoice.append({
115 'reference_type': 'Patient Encounter',
116 'reference_name': encounter.name,
117 'service': service_item,
118 'rate': practitioner_charge,
119 'income_account': income_account
120 })
121
122 return encounters_to_invoice
123
124
125def get_lab_tests_to_invoice(patient):
126 lab_tests_to_invoice = []
127 lab_tests = frappe.get_list(
128 'Lab Test',
129 fields=['name', 'template'],
130 filters={'patient': patient.name, 'invoiced': False, 'docstatus': 1}
131 )
132 for lab_test in lab_tests:
133 if frappe.db.get_value('Lab Test Template', lab_test.template, 'is_billable'):
134 lab_tests_to_invoice.append({
135 'reference_type': 'Lab Test',
136 'reference_name': lab_test.name,
137 'service': frappe.db.get_value('Lab Test Template', lab_test.template, 'item')
138 })
139
140 lab_prescriptions = frappe.db.sql('''select lp.name, lp.lab_test_code from `tabPatient Encounter` et, `tabLab Prescription` lp
141 where et.patient=%s and lp.parent=et.name and lp.lab_test_created=0 and lp.invoiced=0''', (patient.name), as_dict=1)
142
143 for prescription in lab_prescriptions:
144 if prescription.lab_test_code and frappe.db.get_value('Lab Test Template', prescription.lab_test_code, 'is_billable'):
145 lab_tests_to_invoice.append({
146 'reference_type': 'Lab Prescription',
147 'reference_name': prescription.name,
148 'service': frappe.db.get_value('Lab Test Template', prescription.lab_test_code, 'item')
149 })
150
151 return lab_tests_to_invoice
152
153
154def get_clinical_procedures_to_invoice(patient):
155 clinical_procedures_to_invoice = []
156 procedures = frappe.get_list(
157 'Clinical Procedure',
158 fields='*',
159 filters={'patient': patient.name, 'invoiced': False}
160 )
161 for procedure in procedures:
162 if not procedure.appointment:
163 if procedure.procedure_template and frappe.db.get_value('Clinical Procedure Template', procedure.procedure_template, 'is_billable'):
164 clinical_procedures_to_invoice.append({
165 'reference_type': 'Clinical Procedure',
166 'reference_name': procedure.name,
167 'service': frappe.db.get_value('Clinical Procedure Template', procedure.procedure_template, 'item')
168 })
169
170 # consumables
171 if procedure.invoice_separately_as_consumables and procedure.consume_stock \
172 and procedure.status == 'Completed' and not procedure.consumption_invoiced:
173
174 service_item = get_healthcare_service_item('clinical_procedure_consumable_item')
175 if not service_item:
176 msg = _('Please Configure Clinical Procedure Consumable Item in ')
177 msg += '''<b><a href='#Form/Healthcare Settings'>Healthcare Settings</a></b>'''
178 frappe.throw(msg, title=_('Missing Configuration'))
179
180 clinical_procedures_to_invoice.append({
181 'reference_type': 'Clinical Procedure',
182 'reference_name': procedure.name,
183 'service': service_item,
184 'rate': procedure.consumable_total_amount,
185 'description': procedure.consumption_details
186 })
187
188 procedure_prescriptions = frappe.db.sql('''select pp.name, pp.procedure from `tabPatient Encounter` et,
189 `tabProcedure Prescription` pp where et.patient=%s and pp.parent=et.name and
190 pp.procedure_created=0 and pp.invoiced=0 and pp.appointment_booked=0''', (patient.name), as_dict=1)
191
192 for prescription in procedure_prescriptions:
193 if frappe.db.get_value('Clinical Procedure Template', prescription.procedure, 'is_billable'):
194 items_to_invoice.append({
195 'reference_type': 'Procedure Prescription',
196 'reference_name': prescription.name,
197 'service': frappe.db.get_value('Clinical Procedure Template', prescription.procedure, 'item')
198 })
199
200 return clinical_procedures_to_invoice
201
202
203def get_inpatient_services_to_invoice(patient):
204 services_to_invoice = []
205 inpatient_services = frappe.db.sql('''select io.* from `tabInpatient Record` ip,
206 `tabInpatient Occupancy` io where ip.patient=%s and io.parent=ip.name and
207 io.left=1 and io.invoiced=0''', (patient.name), as_dict=1)
208
209 for inpatient_occupancy in inpatient_services:
210 service_unit_type = frappe.db.get_value('Healthcare Service Unit', inpatient_occupancy.service_unit, 'service_unit_type')
211 service_unit_type = frappe.get_doc('Healthcare Service Unit Type', service_unit_type)
212 if service_unit_type and service_unit_type.is_billable:
213 hours_occupied = time_diff_in_hours(inpatient_occupancy.check_out, inpatient_occupancy.check_in)
214 qty = 0.5
215 if hours_occupied > 0:
216 actual_qty = hours_occupied / service_unit_type.no_of_hours
217 floor = math.floor(actual_qty)
218 decimal_part = actual_qty - floor
219 if decimal_part > 0.5:
220 qty = rounded(floor + 1, 1)
221 elif decimal_part < 0.5 and decimal_part > 0:
222 qty = rounded(floor + 0.5, 1)
223 if qty <= 0:
224 qty = 0.5
225 services_to_invoice.append({
226 'reference_type': 'Inpatient Occupancy',
227 'reference_name': inpatient_occupancy.name,
228 'service': service_unit_type.item, 'qty': qty
229 })
230
231 return services_to_invoice
232
Jamsheerba119722018-07-06 15:58:13 +0530233
Rucha Mahabal24055e12020-02-24 19:09:50 +0530234def get_service_item_and_practitioner_charge(doc):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530235 is_inpatient = doc.inpatient_record
Rucha Mahabal24055e12020-02-24 19:09:50 +0530236 if is_inpatient:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530237 service_item = get_practitioner_service_item(doc.practitioner, 'inpatient_visit_charge_item')
Jamsheeree5f9c72018-07-30 12:42:06 +0530238 if not service_item:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530239 service_item = get_healthcare_service_item('inpatient_visit_charge_item')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530240 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530241 service_item = get_practitioner_service_item(doc.practitioner, 'op_consulting_charge_item')
Jamsheeree5f9c72018-07-30 12:42:06 +0530242 if not service_item:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530243 service_item = get_healthcare_service_item('op_consulting_charge_item')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530244 if not service_item:
Rucha Mahabal24055e12020-02-24 19:09:50 +0530245 throw_config_service_item(is_inpatient)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530246
Rucha Mahabal24055e12020-02-24 19:09:50 +0530247 practitioner_charge = get_practitioner_charge(doc.practitioner, is_inpatient)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530248 if not practitioner_charge:
Rucha Mahabal24055e12020-02-24 19:09:50 +0530249 throw_config_practitioner_charge(is_inpatient, doc.practitioner)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530250
251 return service_item, practitioner_charge
252
Jamsheer8da6f4e2018-07-26 21:03:17 +0530253
Rucha Mahabal27512c82020-03-09 17:29:23 +0530254def throw_config_service_item(is_inpatient):
255 service_item_lable = 'Out Patient Consulting Charge Item'
256 if is_inpatient:
257 service_item_lable = 'Inpatient Visit Charge Item'
258
259 msg = _(('Please Configure {0} in ').format(service_item_lable) \
260 + '''<b><a href='#Form/Healthcare Settings'>Healthcare Settings</a></b>''')
261 frappe.throw(msg, title=_('Missing Configuration'))
262
Jamsheer8da6f4e2018-07-26 21:03:17 +0530263
Rucha Mahabal24055e12020-02-24 19:09:50 +0530264def throw_config_practitioner_charge(is_inpatient, practitioner):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530265 charge_name = 'OP Consulting Charge'
Rucha Mahabal24055e12020-02-24 19:09:50 +0530266 if is_inpatient:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530267 charge_name = 'Inpatient Visit Charge'
Jamsheer8da6f4e2018-07-26 21:03:17 +0530268
Rucha Mahabal27512c82020-03-09 17:29:23 +0530269 msg = _(('Please Configure {0} for Healthcare Practitioner').format(charge_name) \
270 + ''' <b><a href='#Form/Healthcare Practitioner/{0}'>{0}</a></b>'''.format(practitioner))
271 frappe.throw(msg, title=_('Missing Configuration'))
272
Jamsheer8da6f4e2018-07-26 21:03:17 +0530273
Jamsheeree5f9c72018-07-30 12:42:06 +0530274def get_practitioner_service_item(practitioner, service_item_field):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530275 return frappe.db.get_value('Healthcare Practitioner', practitioner, service_item_field)
276
Jamsheeree5f9c72018-07-30 12:42:06 +0530277
Jamsheer8da6f4e2018-07-26 21:03:17 +0530278def get_healthcare_service_item(service_item_field):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530279 return frappe.db.get_single_value('Healthcare Settings', service_item_field)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530280
Jamsheer8da6f4e2018-07-26 21:03:17 +0530281
Rucha Mahabal24055e12020-02-24 19:09:50 +0530282def get_practitioner_charge(practitioner, is_inpatient):
283 if is_inpatient:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530284 practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, 'inpatient_visit_charge')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530285 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530286 practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, 'op_consulting_charge')
Jamsheerba119722018-07-06 15:58:13 +0530287 if practitioner_charge:
288 return practitioner_charge
Jamsheer8da6f4e2018-07-26 21:03:17 +0530289 return False
Jamsheerba119722018-07-06 15:58:13 +0530290
Rucha Mahabal27512c82020-03-09 17:29:23 +0530291
Jamsheerba119722018-07-06 15:58:13 +0530292def manage_invoice_submit_cancel(doc, method):
293 if doc.items:
294 for item in doc.items:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530295 if item.get('reference_dt') and item.get('reference_dn'):
296 if frappe.get_meta(item.reference_dt).has_field('invoiced'):
Jamsheer146683b2018-07-25 11:30:30 +0530297 set_invoiced(item, method, doc.name)
Jamsheerba119722018-07-06 15:58:13 +0530298
Rucha Mahabal27512c82020-03-09 17:29:23 +0530299 if method=='on_submit' and frappe.db.get_single_value('Healthcare Settings', 'create_lab_test_on_si_submit'):
300 create_multiple('Sales Invoice', doc.name)
301
Jamsheer0ae100b2018-08-01 14:29:43 +0530302
Jamsheer146683b2018-07-25 11:30:30 +0530303def set_invoiced(item, method, ref_invoice=None):
Jamsheerba119722018-07-06 15:58:13 +0530304 invoiced = False
Rucha Mahabal27512c82020-03-09 17:29:23 +0530305 if method=='on_submit':
Jamsheerba119722018-07-06 15:58:13 +0530306 validate_invoiced_on_submit(item)
307 invoiced = True
308
Jamsheer8da6f4e2018-07-26 21:03:17 +0530309 if item.reference_dt == 'Clinical Procedure':
310 if get_healthcare_service_item('clinical_procedure_consumable_item') == item.item_code:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530311 frappe.db.set_value(item.reference_dt, item.reference_dn, 'consumption_invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530312 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530313 frappe.db.set_value(item.reference_dt, item.reference_dn, '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
Jamsheerba119722018-07-06 15:58:13 +0530317 if item.reference_dt == 'Patient Appointment':
318 if frappe.db.get_value('Patient Appointment', item.reference_dn, 'procedure_template'):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530319 dt_from_appointment = 'Clinical Procedure'
Jamsheerba119722018-07-06 15:58:13 +0530320 else:
Jamsheer146683b2018-07-25 11:30:30 +0530321 manage_fee_validity(item.reference_dn, method, ref_invoice)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530322 dt_from_appointment = 'Patient Encounter'
Jamsheerba119722018-07-06 15:58:13 +0530323 manage_doc_for_appoitnment(dt_from_appointment, item.reference_dn, invoiced)
324
325 elif item.reference_dt == 'Lab Prescription':
Rucha Mahabal27512c82020-03-09 17:29:23 +0530326 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, 'Lab Test', 'lab_test_created')
Jamsheerba119722018-07-06 15:58:13 +0530327
328 elif item.reference_dt == 'Procedure Prescription':
Rucha Mahabal27512c82020-03-09 17:29:23 +0530329 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, 'Clinical Procedure', 'procedure_created')
330
Jamsheerba119722018-07-06 15:58:13 +0530331
332def validate_invoiced_on_submit(item):
Jamsheer8da6f4e2018-07-26 21:03:17 +0530333 if item.reference_dt == 'Clinical Procedure' and get_healthcare_service_item('clinical_procedure_consumable_item') == item.item_code:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530334 is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, 'consumption_invoiced')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530335 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530336 is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, 'invoiced')
337 if is_invoiced:
338 frappe.throw(_('The item referenced by {0} - {1} is already invoiced'\
Jamsheerba119722018-07-06 15:58:13 +0530339 ).format(item.reference_dt, item.reference_dn))
340
Rucha Mahabal27512c82020-03-09 17:29:23 +0530341
Jamsheerba119722018-07-06 15:58:13 +0530342def manage_prescriptions(invoiced, ref_dt, ref_dn, dt, created_check_field):
343 created = frappe.db.get_value(ref_dt, ref_dn, created_check_field)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530344 if created:
Jamsheerba119722018-07-06 15:58:13 +0530345 # Fetch the doc created for the prescription
Jamsheereafb0462018-07-25 13:15:12 +0530346 doc_created = frappe.db.get_value(dt, {'prescription': ref_dn})
Jamsheerba119722018-07-06 15:58:13 +0530347 frappe.db.set_value(dt, doc_created, 'invoiced', invoiced)
348
Rucha Mahabal27512c82020-03-09 17:29:23 +0530349
Rucha Mahabal24055e12020-02-24 19:09:50 +0530350def check_validity_exists(practitioner, patient):
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530351 return frappe.db.get_value('Fee Validity', {'practitioner': practitioner, 'patient': patient}, 'name')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530352
Jamsheer363deb62018-08-04 12:56:36 +0530353
Jamsheer146683b2018-07-25 11:30:30 +0530354def manage_fee_validity(appointment_name, method, ref_invoice=None):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530355 appointment_doc = frappe.get_doc('Patient Appointment', appointment_name)
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530356 validity = check_validity_exists(appointment_doc.practitioner, appointment_doc.patient)
Jamsheerba119722018-07-06 15:58:13 +0530357 do_not_update = False
358 visited = 0
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530359 if validity:
360 fee_validity = frappe.get_doc('Fee Validity', validity)
Jamsheerba119722018-07-06 15:58:13 +0530361 # Check if the validity is valid
Rucha Mahabal27512c82020-03-09 17:29:23 +0530362 if fee_validity.valid_till >= appointment_doc.appointment_date:
363 if method == 'on_cancel' and appointment_doc.status != 'Closed':
Jamsheer363deb62018-08-04 12:56:36 +0530364 if ref_invoice == fee_validity.ref_invoice:
365 visited = fee_validity.visited - 1
366 if visited < 0:
367 visited = 0
Rucha Mahabal27512c82020-03-09 17:29:23 +0530368 frappe.db.set_value('Fee Validity', fee_validity.name, 'visited', visited)
Jamsheerba119722018-07-06 15:58:13 +0530369 do_not_update = True
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530370 elif method == 'on_submit' and fee_validity.visited < fee_validity.max_visits:
Jamsheerba119722018-07-06 15:58:13 +0530371 visited = fee_validity.visited + 1
Rucha Mahabal27512c82020-03-09 17:29:23 +0530372 frappe.db.set_value('Fee Validity', fee_validity.name, 'visited', visited)
Jamsheerba119722018-07-06 15:58:13 +0530373 do_not_update = True
374 else:
375 do_not_update = False
376
377 if not do_not_update:
Jamsheer146683b2018-07-25 11:30:30 +0530378 fee_validity = update_fee_validity(fee_validity, appointment_doc.appointment_date, ref_invoice)
Jamsheerba119722018-07-06 15:58:13 +0530379 else:
Jamsheer146683b2018-07-25 11:30:30 +0530380 fee_validity = create_fee_validity(appointment_doc.practitioner, appointment_doc.patient, appointment_doc.appointment_date, ref_invoice)
Jamsheerba119722018-07-06 15:58:13 +0530381
Rucha Mahabal27512c82020-03-09 17:29:23 +0530382 visited = fee_validity.visited
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530383 mark_appointments_as_invoiced(fee_validity, ref_invoice, method, appointment_doc)
Jamsheer363deb62018-08-04 12:56:36 +0530384
Rucha Mahabal27512c82020-03-09 17:29:23 +0530385 if method == 'on_cancel':
386 ref_invoice_in_fee_validity = frappe.db.get_value('Fee Validity', fee_validity.name, 'ref_invoice')
387 if ref_invoice_in_fee_validity == ref_invoice:
388 frappe.delete_doc('Fee Validity', fee_validity.name)
389
390
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530391def mark_appointments_as_invoiced(fee_validity, ref_invoice, method, appointment_doc):
392 if method == 'on_cancel':
393 invoiced = True
394 else:
395 invoiced = False
396
Jamsheer363deb62018-08-04 12:56:36 +0530397 patient_appointments = appointments_valid_in_fee_validity(appointment_doc, invoiced)
Jamsheerba119722018-07-06 15:58:13 +0530398 if patient_appointments and fee_validity:
399 visit = visited
400 for appointment in patient_appointments:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530401 if method == 'on_cancel' and appointment.status != 'Closed':
Jamsheer363deb62018-08-04 12:56:36 +0530402 if ref_invoice == fee_validity.ref_invoice:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530403 visited -= 1
Jamsheer363deb62018-08-04 12:56:36 +0530404 if visited < 0:
405 visited = 0
Rucha Mahabal27512c82020-03-09 17:29:23 +0530406 frappe.db.set_value('Fee Validity', fee_validity.name, 'visited', visited)
407 frappe.db.set_value('Patient Appointment', appointment.name, 'invoiced', False)
408 manage_doc_for_appoitnment('Patient Encounter', appointment.name, False)
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530409 elif method == 'on_submit' and int(fee_validity.max_visits) > visit:
Jamsheer363deb62018-08-04 12:56:36 +0530410 if ref_invoice == fee_validity.ref_invoice:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530411 visited += 1
412 frappe.db.set_value('Fee Validity', fee_validity.name, 'visited', visited)
413 frappe.db.set_value('Patient Appointment', appointment.name, 'invoiced', True)
414 manage_doc_for_appoitnment('Patient Encounter', appointment.name, True)
Jamsheer363deb62018-08-04 12:56:36 +0530415 if ref_invoice == fee_validity.ref_invoice:
416 visit = visit + 1
417
Jamsheer363deb62018-08-04 12:56:36 +0530418
419def appointments_valid_in_fee_validity(appointment, invoiced):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530420 valid_days = frappe.db.get_single_value('Healthcare Settings', 'valid_days')
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530421 max_visits = frappe.db.get_single_value('Healthcare Settings', 'max_visits')
422 if int(max_visits) < 1:
423 max_visits = 1
Jamsheer363deb62018-08-04 12:56:36 +0530424 valid_days_date = add_days(getdate(appointment.appointment_date), int(valid_days))
Rucha Mahabal27512c82020-03-09 17:29:23 +0530425
426 return frappe.get_list('Patient Appointment',{
427 'patient': appointment.patient,
428 'invoiced': invoiced,
429 'appointment_date':('<=', valid_days_date),
430 'appointment_date':('>=', getdate(appointment.appointment_date)),
431 'practitioner': appointment.practitioner
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530432 }, order_by='appointment_date', limit=int(max_visits)-1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530433
Jamsheerba119722018-07-06 15:58:13 +0530434
435def manage_doc_for_appoitnment(dt_from_appointment, appointment, invoiced):
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530436 dn_from_appointment = frappe.db.get_value(
437 dt_from_appointment,
Rucha Mahabal27512c82020-03-09 17:29:23 +0530438 filters={'appointment': appointment}
Jamsheerba119722018-07-06 15:58:13 +0530439 )
440 if dn_from_appointment:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530441 frappe.db.set_value(dt_from_appointment, dn_from_appointment, 'invoiced', invoiced)
442
Jamsheere82f27a2018-07-30 11:28:37 +0530443
444@frappe.whitelist()
445def get_drugs_to_invoice(encounter):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530446 encounter = frappe.get_doc('Patient Encounter', encounter)
Jamsheere82f27a2018-07-30 11:28:37 +0530447 if encounter:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530448 patient = frappe.get_doc('Patient', encounter.patient)
449 if patient:
450 if patient.customer:
451 items_to_invoice = []
Jamsheere82f27a2018-07-30 11:28:37 +0530452 for drug_line in encounter.drug_prescription:
453 if drug_line.drug_code:
454 qty = 1
Rucha Mahabal27512c82020-03-09 17:29:23 +0530455 if frappe.db.get_value('Item', drug_line.drug_code, 'stock_uom') == 'Nos':
Jamsheere82f27a2018-07-30 11:28:37 +0530456 qty = drug_line.get_quantity()
Rucha Mahabal27512c82020-03-09 17:29:23 +0530457
458 description = ''
459 if drug_line.dosage and drug_line.period:
460 description = _('{0} for {1}').format(drug_line.dosage, drug_line.period)
461
462 items_to_invoice.append({
463 'drug_code': drug_line.drug_code,
464 'quantity': qty,
465 'description': description
466 })
467 return items_to_invoice
468 else:
469 validate_customer_created(patient)
470
Jamsheer4371c7e2018-08-01 18:40:05 +0530471
472@frappe.whitelist()
473def get_children(doctype, parent, company, is_root=False):
474 parent_fieldname = 'parent_' + doctype.lower().replace(' ', '_')
475 fields = [
476 'name as value',
477 'is_group as expandable',
478 'lft',
479 'rgt'
480 ]
481 # fields = [ 'name', 'is_group', 'lft', 'rgt' ]
Rucha Mahabal27512c82020-03-09 17:29:23 +0530482 filters = [['ifnull(`{0}`,'')'.format(parent_fieldname), '=', '' if is_root else parent]]
Jamsheer4371c7e2018-08-01 18:40:05 +0530483
484 if is_root:
485 fields += ['service_unit_type'] if doctype == 'Healthcare Service Unit' else []
486 filters.append(['company', '=', company])
487
488 else:
489 fields += ['service_unit_type', 'allow_appointments', 'inpatient_occupancy', 'occupancy_status'] if doctype == 'Healthcare Service Unit' else []
490 fields += [parent_fieldname + ' as parent']
491
492 hc_service_units = frappe.get_list(doctype, fields=fields, filters=filters)
493
494 if doctype == 'Healthcare Service Unit':
495 for each in hc_service_units:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530496 occupancy_msg = ''
Jamsheer4371c7e2018-08-01 18:40:05 +0530497 if each['expandable'] == 1:
498 occupied = False
499 vacant = False
Rucha Mahabal27512c82020-03-09 17:29:23 +0530500 child_list = frappe.db.sql('''
Jamsheer4371c7e2018-08-01 18:40:05 +0530501 select name, occupancy_status from `tabHealthcare Service Unit`
502 where inpatient_occupancy = 1 and
Rucha Mahabal27512c82020-03-09 17:29:23 +0530503 lft > %s and rgt < %s''',
Jamsheer4371c7e2018-08-01 18:40:05 +0530504 (each['lft'], each['rgt']))
505 for child in child_list:
Jamsheer4371c7e2018-08-01 18:40:05 +0530506 if not occupied:
507 occupied = 0
Rucha Mahabal27512c82020-03-09 17:29:23 +0530508 if child[1] == 'Occupied':
Jamsheer4371c7e2018-08-01 18:40:05 +0530509 occupied += 1
510 if not vacant:
511 vacant = 0
Rucha Mahabal27512c82020-03-09 17:29:23 +0530512 if child[1] == 'Vacant':
Jamsheer4371c7e2018-08-01 18:40:05 +0530513 vacant += 1
514 if vacant and occupied:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530515 occupancy_total = vacant + occupied
516 occupancy_msg = str(occupied) + ' Occupied out of ' + str(occupancy_total)
517 each['occupied_out_of_vacant'] = occupancy_msg
Jamsheer4371c7e2018-08-01 18:40:05 +0530518 return hc_service_units
Jamsheer5073ac42019-07-12 12:28:34 +0530519
Rucha Mahabal27512c82020-03-09 17:29:23 +0530520
Jamsheer5073ac42019-07-12 12:28:34 +0530521@frappe.whitelist()
522def get_patient_vitals(patient, from_date=None, to_date=None):
523 if not patient: return
Rucha Mahabal27512c82020-03-09 17:29:23 +0530524
525 vitals = frappe.db.get_all('Vital Signs', {
526 'docstatus': 1,
527 'patient': patient
528 }, order_by='signs_date signs_time')
529
530 if len(vitals):
Jamsheer5073ac42019-07-12 12:28:34 +0530531 return vitals
Rucha Mahabal27512c82020-03-09 17:29:23 +0530532 return False
533
Jamsheer5073ac42019-07-12 12:28:34 +0530534
535@frappe.whitelist()
536def render_docs_as_html(docs):
537 # docs key value pair {doctype: docname}
538 docs_html = "<div class='col-md-12 col-sm-12 text-muted'>"
539 for doc in docs:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530540 docs_html += render_doc_as_html(doc['doctype'], doc['docname'])['html'] + '<br/>'
Jamsheer5073ac42019-07-12 12:28:34 +0530541 return {'html': docs_html}
542
Rucha Mahabal27512c82020-03-09 17:29:23 +0530543
Jamsheer5073ac42019-07-12 12:28:34 +0530544@frappe.whitelist()
545def render_doc_as_html(doctype, docname, exclude_fields = []):
546 #render document as html, three column layout will break
547 doc = frappe.get_doc(doctype, docname)
548 meta = frappe.get_meta(doctype)
549 doc_html = "<div class='col-md-12 col-sm-12'>"
Rucha Mahabal27512c82020-03-09 17:29:23 +0530550 section_html = ''
551 section_label = ''
552 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530553 sec_on = False
554 col_on = 0
555 has_data = False
556 for df in meta.fields:
557 #on section break append append previous section and html to doc html
558 if df.fieldtype == "Section Break":
559 if has_data and col_on and sec_on:
560 doc_html += section_html + html + "</div>"
561 elif has_data and not col_on and sec_on:
562 doc_html += "<div class='col-md-12 col-sm-12'\
563 ><div class='col-md-12 col-sm-12'>" \
564 + section_html + html +"</div></div>"
565 while col_on:
566 doc_html += "</div>"
567 col_on -= 1
568 sec_on = True
569 has_data= False
570 col_on = 0
Rucha Mahabal27512c82020-03-09 17:29:23 +0530571 section_html = ''
572 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530573 if df.label:
574 section_label = df.label
575 continue
576 #on column break append html to section html or doc html
577 if df.fieldtype == "Column Break":
578 if sec_on and has_data:
579 section_html += "<div class='col-md-12 col-sm-12'\
580 ><div class='col-md-6 col\
581 -sm-6'><b>" + section_label + "</b>" + html + "</div><div \
582 class='col-md-6 col-sm-6'>"
583 elif has_data:
584 doc_html += "<div class='col-md-12 col-sm-12'><div class='col-m\
585 d-6 col-sm-6'>" + html + "</div><div class='col-md-6 col-sm-6'>"
586 elif sec_on and not col_on:
587 section_html += "<div class='col-md-6 col-sm-6'>"
Rucha Mahabal27512c82020-03-09 17:29:23 +0530588 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530589 col_on += 1
590 if df.label:
591 html += '<br>' + df.label
592 continue
593 #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 +0530594 if df.fieldtype == 'Table':
Jamsheer5073ac42019-07-12 12:28:34 +0530595 items = doc.get(df.fieldname)
596 if not items: continue
597 child_meta = frappe.get_meta(df.options)
598 if not has_data : has_data = True
Rucha Mahabal27512c82020-03-09 17:29:23 +0530599 table_head = ''
600 table_row = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530601 create_head = True
602 for item in items:
603 table_row += '<tr>'
604 for cdf in child_meta.fields:
605 if cdf.in_list_view:
606 if create_head:
607 table_head += '<th>' + cdf.label + '</th>'
608 if item.get(cdf.fieldname):
609 table_row += '<td>' + str(item.get(cdf.fieldname)) \
610 + '</td>'
611 else:
612 table_row += '<td></td>'
613 create_head = False
614 table_row += '</tr>'
615 if sec_on:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530616 section_html += "<table class='table table-condensed \
617 bordered'>" + table_head + table_row + '</table>'
Jamsheer5073ac42019-07-12 12:28:34 +0530618 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530619 html += "<table class='table table-condensed table-bordered'>" \
620 + table_head + table_row + "</table>"
Jamsheer5073ac42019-07-12 12:28:34 +0530621 continue
622 #on other field types add label and value to html
623 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 +0530624 html += '<br>{0} : {1}'.format(df.label or df.fieldname, \
Jamsheer5073ac42019-07-12 12:28:34 +0530625 doc.get(df.fieldname))
626 if not has_data : has_data = True
627 if sec_on and col_on and has_data:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530628 doc_html += section_html + html + '</div></div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530629 elif sec_on and not col_on and has_data:
630 doc_html += "<div class='col-md-12 col-sm-12'\
631 ><div class='col-md-12 col-sm-12'>" \
Rucha Mahabal27512c82020-03-09 17:29:23 +0530632 + section_html + html +'</div></div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530633 if doc_html:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530634 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 +0530635
636 return {'html': doc_html}