blob: ffecf4dce29460db696faada3af50526fe40e109 [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
anoop93d0c782020-04-13 16:42:03 +05306import math
Jamsheerba119722018-07-06 15:58:13 +05307import frappe
Rucha Mahabalccc80922021-02-18 16:41:10 +05308import json
Jamsheerba119722018-07-06 15:58:13 +05309from frappe import _
Rucha Mahabal5e3c51b2020-11-30 13:35:00 +053010from frappe.utils.formatters import format_value
Rucha Mahabal197165f2020-03-26 17:29:50 +053011from frappe.utils import time_diff_in_hours, rounded
Rucha Mahabalccc80922021-02-18 16:41:10 +053012from six import string_types
Jamsheerba119722018-07-06 15:58:13 +053013from erpnext.healthcare.doctype.healthcare_settings.healthcare_settings import get_income_account
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +053014from erpnext.healthcare.doctype.fee_validity.fee_validity import create_fee_validity
Jamsheer0ae100b2018-08-01 14:29:43 +053015from erpnext.healthcare.doctype.lab_test.lab_test import create_multiple
Jamsheerba119722018-07-06 15:58:13 +053016
17@frappe.whitelist()
anoop93d0c782020-04-13 16:42:03 +053018def get_healthcare_services_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +053019 patient = frappe.get_doc('Patient', patient)
anoop93d0c782020-04-13 16:42:03 +053020 items_to_invoice = []
Jamsheerba119722018-07-06 15:58:13 +053021 if patient:
Rucha Mahabal27512c82020-03-09 17:29:23 +053022 validate_customer_created(patient)
anoop93d0c782020-04-13 16:42:03 +053023 # Customer validated, build a list of billable services
24 items_to_invoice += get_appointments_to_invoice(patient, company)
25 items_to_invoice += get_encounters_to_invoice(patient, company)
26 items_to_invoice += get_lab_tests_to_invoice(patient, company)
27 items_to_invoice += get_clinical_procedures_to_invoice(patient, company)
28 items_to_invoice += get_inpatient_services_to_invoice(patient, company)
Rucha Mahabal434791e2020-10-24 14:20:38 +053029 items_to_invoice += get_therapy_plans_to_invoice(patient, company)
Rucha Mahabald7304512020-04-23 00:52:47 +053030 items_to_invoice += get_therapy_sessions_to_invoice(patient, company)
Jamsheerba119722018-07-06 15:58:13 +053031
Rucha Mahabal27512c82020-03-09 17:29:23 +053032 return items_to_invoice
Jamsheerba119722018-07-06 15:58:13 +053033
anoop93d0c782020-04-13 16:42:03 +053034
Rucha Mahabal27512c82020-03-09 17:29:23 +053035def validate_customer_created(patient):
36 if not frappe.db.get_value('Patient', patient.name, 'customer'):
37 msg = _("Please set a Customer linked to the Patient")
Rushabh Mehta542bc012020-11-18 15:00:34 +053038 msg += " <b><a href='/app/Form/Patient/{0}'>{0}</a></b>".format(patient.name)
Rucha Mahabal27512c82020-03-09 17:29:23 +053039 frappe.throw(msg, title=_('Customer Not Found'))
Jamsheer8da6f4e2018-07-26 21:03:17 +053040
Rucha Mahabal434791e2020-10-24 14:20:38 +053041
anoop93d0c782020-04-13 16:42:03 +053042def get_appointments_to_invoice(patient, company):
43 appointments_to_invoice = []
44 patient_appointments = frappe.get_list(
45 'Patient Appointment',
46 fields = '*',
anoop59030022020-07-28 21:15:54 +053047 filters = {'patient': patient.name, 'company': company, 'invoiced': 0, 'status': ['not in', 'Cancelled']},
anoop93d0c782020-04-13 16:42:03 +053048 order_by = 'appointment_date'
49 )
50
Rucha Mahabal27512c82020-03-09 17:29:23 +053051 for appointment in patient_appointments:
anoop93d0c782020-04-13 16:42:03 +053052 # Procedure Appointments
Rucha Mahabal27512c82020-03-09 17:29:23 +053053 if appointment.procedure_template:
54 if frappe.db.get_value('Clinical Procedure Template', appointment.procedure_template, 'is_billable'):
anoop93d0c782020-04-13 16:42:03 +053055 appointments_to_invoice.append({
Rucha Mahabal27512c82020-03-09 17:29:23 +053056 'reference_type': 'Patient Appointment',
57 'reference_name': appointment.name,
58 'service': appointment.procedure_template
59 })
anoop93d0c782020-04-13 16:42:03 +053060 # Consultation Appointments, should check fee validity
Jamsheerba119722018-07-06 15:58:13 +053061 else:
anoop93d0c782020-04-13 16:42:03 +053062 if frappe.db.get_single_value('Healthcare Settings', 'enable_free_follow_ups') and \
63 frappe.db.exists('Fee Validity Reference', {'appointment': appointment.name}):
64 continue # Skip invoicing, fee validty present
65 practitioner_charge = 0
66 income_account = None
67 service_item = None
68 if appointment.practitioner:
Rucha Mahabalccc80922021-02-18 16:41:10 +053069 details = get_service_item_and_practitioner_charge(appointment)
70 service_item = details.get('service_item')
71 practitioner_charge = details.get('practitioner_charge')
anoop93d0c782020-04-13 16:42:03 +053072 income_account = get_income_account(appointment.practitioner, appointment.company)
73 appointments_to_invoice.append({
74 'reference_type': 'Patient Appointment',
75 'reference_name': appointment.name,
76 'service': service_item,
77 'rate': practitioner_charge,
78 'income_account': income_account
79 })
Rucha Mahabal27512c82020-03-09 17:29:23 +053080
anoop93d0c782020-04-13 16:42:03 +053081 return appointments_to_invoice
Rucha Mahabal27512c82020-03-09 17:29:23 +053082
83
anoop93d0c782020-04-13 16:42:03 +053084def get_encounters_to_invoice(patient, company):
Rucha Mahabal0f059252021-01-13 09:46:33 +053085 if not isinstance(patient, str):
86 patient = patient.name
Rucha Mahabal27512c82020-03-09 17:29:23 +053087 encounters_to_invoice = []
88 encounters = frappe.get_list(
89 'Patient Encounter',
90 fields=['*'],
Rucha Mahabal0f059252021-01-13 09:46:33 +053091 filters={'patient': patient, 'company': company, 'invoiced': False, 'docstatus': 1}
Rucha Mahabal27512c82020-03-09 17:29:23 +053092 )
93 if encounters:
94 for encounter in encounters:
95 if not encounter.appointment:
96 practitioner_charge = 0
97 income_account = None
98 service_item = None
99 if encounter.practitioner:
Rucha Mahabal13541972021-01-13 09:12:50 +0530100 if encounter.inpatient_record and \
101 frappe.db.get_single_value('Healthcare Settings', 'do_not_bill_inpatient_encounters'):
102 continue
103
Rucha Mahabalccc80922021-02-18 16:41:10 +0530104 details = get_service_item_and_practitioner_charge(encounter)
105 service_item = details.get('service_item')
106 practitioner_charge = details.get('practitioner_charge')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530107 income_account = get_income_account(encounter.practitioner, encounter.company)
108
109 encounters_to_invoice.append({
110 'reference_type': 'Patient Encounter',
111 'reference_name': encounter.name,
112 'service': service_item,
113 'rate': practitioner_charge,
114 'income_account': income_account
115 })
116
117 return encounters_to_invoice
118
119
anoop93d0c782020-04-13 16:42:03 +0530120def get_lab_tests_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530121 lab_tests_to_invoice = []
122 lab_tests = frappe.get_list(
123 'Lab Test',
124 fields=['name', 'template'],
anoop93d0c782020-04-13 16:42:03 +0530125 filters={'patient': patient.name, 'company': company, 'invoiced': False, 'docstatus': 1}
Rucha Mahabal27512c82020-03-09 17:29:23 +0530126 )
127 for lab_test in lab_tests:
Rucha Mahabal131452c2020-04-27 10:52:38 +0530128 item, is_billable = frappe.get_cached_value('Lab Test Template', lab_test.template, ['item', 'is_billable'])
Rucha Mahabalced978e2020-04-02 18:45:53 +0530129 if is_billable:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530130 lab_tests_to_invoice.append({
131 'reference_type': 'Lab Test',
132 'reference_name': lab_test.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530133 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530134 })
135
Rucha Mahabalced978e2020-04-02 18:45:53 +0530136 lab_prescriptions = frappe.db.sql(
137 '''
138 SELECT
139 lp.name, lp.lab_test_code
140 FROM
141 `tabPatient Encounter` et, `tabLab Prescription` lp
142 WHERE
143 et.patient=%s
144 and lp.parent=et.name
145 and lp.lab_test_created=0
146 and lp.invoiced=0
147 ''', (patient.name), as_dict=1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530148
149 for prescription in lab_prescriptions:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530150 item, is_billable = frappe.get_cached_value('Lab Test Template', prescription.lab_test_code, ['item', 'is_billable'])
151 if prescription.lab_test_code and is_billable:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530152 lab_tests_to_invoice.append({
153 'reference_type': 'Lab Prescription',
154 'reference_name': prescription.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530155 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530156 })
157
158 return lab_tests_to_invoice
159
160
anoop93d0c782020-04-13 16:42:03 +0530161def get_clinical_procedures_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530162 clinical_procedures_to_invoice = []
163 procedures = frappe.get_list(
164 'Clinical Procedure',
165 fields='*',
anoop93d0c782020-04-13 16:42:03 +0530166 filters={'patient': patient.name, 'company': company, 'invoiced': False}
Rucha Mahabal27512c82020-03-09 17:29:23 +0530167 )
168 for procedure in procedures:
169 if not procedure.appointment:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530170 item, is_billable = frappe.get_cached_value('Clinical Procedure Template', procedure.procedure_template, ['item', 'is_billable'])
171 if procedure.procedure_template and is_billable:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530172 clinical_procedures_to_invoice.append({
173 'reference_type': 'Clinical Procedure',
174 'reference_name': procedure.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530175 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530176 })
177
178 # consumables
179 if procedure.invoice_separately_as_consumables and procedure.consume_stock \
180 and procedure.status == 'Completed' and not procedure.consumption_invoiced:
181
Rucha Mahabalccc80922021-02-18 16:41:10 +0530182 service_item = frappe.db.get_single_value('Healthcare Settings', 'clinical_procedure_consumable_item')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530183 if not service_item:
184 msg = _('Please Configure Clinical Procedure Consumable Item in ')
Rushabh Mehta542bc012020-11-18 15:00:34 +0530185 msg += '''<b><a href='/app/Form/Healthcare Settings'>Healthcare Settings</a></b>'''
Rucha Mahabal27512c82020-03-09 17:29:23 +0530186 frappe.throw(msg, title=_('Missing Configuration'))
187
188 clinical_procedures_to_invoice.append({
189 'reference_type': 'Clinical Procedure',
190 'reference_name': procedure.name,
191 'service': service_item,
192 'rate': procedure.consumable_total_amount,
193 'description': procedure.consumption_details
194 })
195
Rucha Mahabalced978e2020-04-02 18:45:53 +0530196 procedure_prescriptions = frappe.db.sql(
197 '''
198 SELECT
199 pp.name, pp.procedure
200 FROM
201 `tabPatient Encounter` et, `tabProcedure Prescription` pp
202 WHERE
203 et.patient=%s
204 and pp.parent=et.name
205 and pp.procedure_created=0
206 and pp.invoiced=0
207 and pp.appointment_booked=0
208 ''', (patient.name), as_dict=1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530209
210 for prescription in procedure_prescriptions:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530211 item, is_billable = frappe.get_cached_value('Clinical Procedure Template', prescription.procedure, ['item', 'is_billable'])
212 if is_billable:
Rucha Mahabal197165f2020-03-26 17:29:50 +0530213 clinical_procedures_to_invoice.append({
Rucha Mahabal27512c82020-03-09 17:29:23 +0530214 'reference_type': 'Procedure Prescription',
215 'reference_name': prescription.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530216 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530217 })
218
219 return clinical_procedures_to_invoice
220
221
anoop93d0c782020-04-13 16:42:03 +0530222def get_inpatient_services_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530223 services_to_invoice = []
Rucha Mahabalced978e2020-04-02 18:45:53 +0530224 inpatient_services = frappe.db.sql(
225 '''
226 SELECT
227 io.*
228 FROM
229 `tabInpatient Record` ip, `tabInpatient Occupancy` io
230 WHERE
231 ip.patient=%s
anoop93d0c782020-04-13 16:42:03 +0530232 and ip.company=%s
Rucha Mahabalced978e2020-04-02 18:45:53 +0530233 and io.parent=ip.name
234 and io.left=1
235 and io.invoiced=0
anoop93d0c782020-04-13 16:42:03 +0530236 ''', (patient.name, company), as_dict=1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530237
238 for inpatient_occupancy in inpatient_services:
239 service_unit_type = frappe.db.get_value('Healthcare Service Unit', inpatient_occupancy.service_unit, 'service_unit_type')
Rucha Mahabalced978e2020-04-02 18:45:53 +0530240 service_unit_type = frappe.get_cached_doc('Healthcare Service Unit Type', service_unit_type)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530241 if service_unit_type and service_unit_type.is_billable:
242 hours_occupied = time_diff_in_hours(inpatient_occupancy.check_out, inpatient_occupancy.check_in)
243 qty = 0.5
244 if hours_occupied > 0:
245 actual_qty = hours_occupied / service_unit_type.no_of_hours
246 floor = math.floor(actual_qty)
247 decimal_part = actual_qty - floor
248 if decimal_part > 0.5:
249 qty = rounded(floor + 1, 1)
250 elif decimal_part < 0.5 and decimal_part > 0:
251 qty = rounded(floor + 0.5, 1)
252 if qty <= 0:
253 qty = 0.5
254 services_to_invoice.append({
255 'reference_type': 'Inpatient Occupancy',
256 'reference_name': inpatient_occupancy.name,
257 'service': service_unit_type.item, 'qty': qty
258 })
259
260 return services_to_invoice
261
Jamsheerba119722018-07-06 15:58:13 +0530262
Rucha Mahabal434791e2020-10-24 14:20:38 +0530263def get_therapy_plans_to_invoice(patient, company):
264 therapy_plans_to_invoice = []
265 therapy_plans = frappe.get_list(
266 'Therapy Plan',
267 fields=['therapy_plan_template', 'name'],
268 filters={
269 'patient': patient.name,
270 'invoiced': 0,
271 'company': company,
272 'therapy_plan_template': ('!=', '')
273 }
274 )
275 for plan in therapy_plans:
276 therapy_plans_to_invoice.append({
277 'reference_type': 'Therapy Plan',
278 'reference_name': plan.name,
279 'service': frappe.db.get_value('Therapy Plan Template', plan.therapy_plan_template, 'linked_item')
280 })
281
282 return therapy_plans_to_invoice
283
284
Rucha Mahabald7304512020-04-23 00:52:47 +0530285def get_therapy_sessions_to_invoice(patient, company):
Rucha Mahabaleaa956b2020-04-22 13:07:12 +0530286 therapy_sessions_to_invoice = []
Rucha Mahabal434791e2020-10-24 14:20:38 +0530287 therapy_plans = frappe.db.get_all('Therapy Plan', {'therapy_plan_template': ('!=', '')})
288 therapy_plans_created_from_template = []
289 for entry in therapy_plans:
290 therapy_plans_created_from_template.append(entry.name)
291
Rucha Mahabaleaa956b2020-04-22 13:07:12 +0530292 therapy_sessions = frappe.get_list(
293 'Therapy Session',
294 fields='*',
Rucha Mahabal434791e2020-10-24 14:20:38 +0530295 filters={
296 'patient': patient.name,
297 'invoiced': 0,
298 'company': company,
299 'therapy_plan': ('not in', therapy_plans_created_from_template)
300 }
Rucha Mahabaleaa956b2020-04-22 13:07:12 +0530301 )
302 for therapy in therapy_sessions:
303 if not therapy.appointment:
304 if therapy.therapy_type and frappe.db.get_value('Therapy Type', therapy.therapy_type, 'is_billable'):
305 therapy_sessions_to_invoice.append({
306 'reference_type': 'Therapy Session',
307 'reference_name': therapy.name,
308 'service': frappe.db.get_value('Therapy Type', therapy.therapy_type, 'item')
309 })
310
311 return therapy_sessions_to_invoice
312
Rucha Mahabalccc80922021-02-18 16:41:10 +0530313@frappe.whitelist()
Rucha Mahabal24055e12020-02-24 19:09:50 +0530314def get_service_item_and_practitioner_charge(doc):
Rucha Mahabalccc80922021-02-18 16:41:10 +0530315 if isinstance(doc, string_types):
316 doc = json.loads(doc)
317 doc = frappe.get_doc(doc)
318
319 service_item = None
320 practitioner_charge = None
321 department = doc.medical_department if doc.doctype == 'Patient Encounter' else doc.department
322
Rucha Mahabal27512c82020-03-09 17:29:23 +0530323 is_inpatient = doc.inpatient_record
Rucha Mahabalccc80922021-02-18 16:41:10 +0530324
325 if doc.get('appointment_type'):
326 service_item, practitioner_charge = get_appointment_type_service_item(doc.appointment_type, department, is_inpatient)
327
328 if not service_item and not practitioner_charge:
329 service_item, practitioner_charge = get_practitioner_service_item(doc.practitioner, is_inpatient)
Jamsheeree5f9c72018-07-30 12:42:06 +0530330 if not service_item:
Rucha Mahabalccc80922021-02-18 16:41:10 +0530331 service_item = get_healthcare_service_item(is_inpatient)
332
Jamsheer8da6f4e2018-07-26 21:03:17 +0530333 if not service_item:
Rucha Mahabal24055e12020-02-24 19:09:50 +0530334 throw_config_service_item(is_inpatient)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530335
Jamsheer8da6f4e2018-07-26 21:03:17 +0530336 if not practitioner_charge:
Rucha Mahabal24055e12020-02-24 19:09:50 +0530337 throw_config_practitioner_charge(is_inpatient, doc.practitioner)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530338
Rucha Mahabalccc80922021-02-18 16:41:10 +0530339 return {'service_item': service_item, 'practitioner_charge': practitioner_charge}
340
341
342def get_appointment_type_service_item(appointment_type, department, is_inpatient):
343 from erpnext.healthcare.doctype.appointment_type.appointment_type import get_service_item_based_on_department
344
345 item_list = get_service_item_based_on_department(appointment_type, department)
346 service_item = None
347 practitioner_charge = None
348
349 if item_list:
350 if is_inpatient:
351 service_item = item_list.get('inpatient_visit_charge_item')
352 practitioner_charge = item_list.get('inpatient_visit_charge')
353 else:
354 service_item = item_list.get('op_consulting_charge_item')
355 practitioner_charge = item_list.get('op_consulting_charge')
356
Jamsheer8da6f4e2018-07-26 21:03:17 +0530357 return service_item, practitioner_charge
358
Jamsheer8da6f4e2018-07-26 21:03:17 +0530359
Rucha Mahabal27512c82020-03-09 17:29:23 +0530360def throw_config_service_item(is_inpatient):
Rucha Mahabalced978e2020-04-02 18:45:53 +0530361 service_item_label = _('Out Patient Consulting Charge Item')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530362 if is_inpatient:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530363 service_item_label = _('Inpatient Visit Charge Item')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530364
Rucha Mahabal4f9a1472020-03-23 10:40:39 +0530365 msg = _(('Please Configure {0} in ').format(service_item_label) \
Rushabh Mehta542bc012020-11-18 15:00:34 +0530366 + '''<b><a href='/app/Form/Healthcare Settings'>Healthcare Settings</a></b>''')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530367 frappe.throw(msg, title=_('Missing Configuration'))
368
Jamsheer8da6f4e2018-07-26 21:03:17 +0530369
Rucha Mahabal24055e12020-02-24 19:09:50 +0530370def throw_config_practitioner_charge(is_inpatient, practitioner):
Rucha Mahabalced978e2020-04-02 18:45:53 +0530371 charge_name = _('OP Consulting Charge')
Rucha Mahabal24055e12020-02-24 19:09:50 +0530372 if is_inpatient:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530373 charge_name = _('Inpatient Visit Charge')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530374
Rucha Mahabal27512c82020-03-09 17:29:23 +0530375 msg = _(('Please Configure {0} for Healthcare Practitioner').format(charge_name) \
Rushabh Mehta542bc012020-11-18 15:00:34 +0530376 + ''' <b><a href='/app/Form/Healthcare Practitioner/{0}'>{0}</a></b>'''.format(practitioner))
Rucha Mahabal27512c82020-03-09 17:29:23 +0530377 frappe.throw(msg, title=_('Missing Configuration'))
378
Jamsheer8da6f4e2018-07-26 21:03:17 +0530379
Rucha Mahabalccc80922021-02-18 16:41:10 +0530380def get_practitioner_service_item(practitioner, is_inpatient):
381 service_item = None
382 practitioner_charge = None
383
384 if is_inpatient:
385 service_item, practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, ['inpatient_visit_charge_item', 'inpatient_visit_charge'])
386 else:
387 service_item, practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, ['op_consulting_charge_item', 'op_consulting_charge'])
388
389 return service_item, practitioner_charge
Rucha Mahabal27512c82020-03-09 17:29:23 +0530390
Jamsheeree5f9c72018-07-30 12:42:06 +0530391
Rucha Mahabalccc80922021-02-18 16:41:10 +0530392def get_healthcare_service_item(is_inpatient):
393 service_item = None
394
395 if is_inpatient:
396 service_item = frappe.db.get_single_value('Healthcare Settings', 'inpatient_visit_charge_item')
397 else:
398 service_item = frappe.db.get_single_value('Healthcare Settings', 'op_consulting_charge_item')
399
400 return service_item
Jamsheer8da6f4e2018-07-26 21:03:17 +0530401
Jamsheer8da6f4e2018-07-26 21:03:17 +0530402
Rucha Mahabal24055e12020-02-24 19:09:50 +0530403def get_practitioner_charge(practitioner, is_inpatient):
404 if is_inpatient:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530405 practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, 'inpatient_visit_charge')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530406 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530407 practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, 'op_consulting_charge')
Jamsheerba119722018-07-06 15:58:13 +0530408 if practitioner_charge:
409 return practitioner_charge
Jamsheer8da6f4e2018-07-26 21:03:17 +0530410 return False
Jamsheerba119722018-07-06 15:58:13 +0530411
Rucha Mahabal27512c82020-03-09 17:29:23 +0530412
Jamsheerba119722018-07-06 15:58:13 +0530413def manage_invoice_submit_cancel(doc, method):
414 if doc.items:
415 for item in doc.items:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530416 if item.get('reference_dt') and item.get('reference_dn'):
417 if frappe.get_meta(item.reference_dt).has_field('invoiced'):
Jamsheer146683b2018-07-25 11:30:30 +0530418 set_invoiced(item, method, doc.name)
Jamsheerba119722018-07-06 15:58:13 +0530419
Rucha Mahabal27512c82020-03-09 17:29:23 +0530420 if method=='on_submit' and frappe.db.get_single_value('Healthcare Settings', 'create_lab_test_on_si_submit'):
421 create_multiple('Sales Invoice', doc.name)
422
Jamsheer0ae100b2018-08-01 14:29:43 +0530423
Jamsheer146683b2018-07-25 11:30:30 +0530424def set_invoiced(item, method, ref_invoice=None):
Jamsheerba119722018-07-06 15:58:13 +0530425 invoiced = False
Rucha Mahabal27512c82020-03-09 17:29:23 +0530426 if method=='on_submit':
Jamsheerba119722018-07-06 15:58:13 +0530427 validate_invoiced_on_submit(item)
428 invoiced = True
429
Jamsheer8da6f4e2018-07-26 21:03:17 +0530430 if item.reference_dt == 'Clinical Procedure':
Rucha Mahabalccc80922021-02-18 16:41:10 +0530431 service_item = frappe.db.get_single_value('Healthcare Settings', 'clinical_procedure_consumable_item')
432 if service_item == item.item_code:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530433 frappe.db.set_value(item.reference_dt, item.reference_dn, 'consumption_invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530434 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530435 frappe.db.set_value(item.reference_dt, item.reference_dn, 'invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530436 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530437 frappe.db.set_value(item.reference_dt, item.reference_dn, 'invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530438
Jamsheerba119722018-07-06 15:58:13 +0530439 if item.reference_dt == 'Patient Appointment':
440 if frappe.db.get_value('Patient Appointment', item.reference_dn, 'procedure_template'):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530441 dt_from_appointment = 'Clinical Procedure'
Jamsheerba119722018-07-06 15:58:13 +0530442 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530443 dt_from_appointment = 'Patient Encounter'
Rucha Mahabal06d1b042020-03-12 12:16:23 +0530444 manage_doc_for_appointment(dt_from_appointment, item.reference_dn, invoiced)
Jamsheerba119722018-07-06 15:58:13 +0530445
446 elif item.reference_dt == 'Lab Prescription':
Rucha Mahabal27512c82020-03-09 17:29:23 +0530447 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, 'Lab Test', 'lab_test_created')
Jamsheerba119722018-07-06 15:58:13 +0530448
449 elif item.reference_dt == 'Procedure Prescription':
Rucha Mahabal27512c82020-03-09 17:29:23 +0530450 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, 'Clinical Procedure', 'procedure_created')
451
Jamsheerba119722018-07-06 15:58:13 +0530452
453def validate_invoiced_on_submit(item):
Rucha Mahabalccc80922021-02-18 16:41:10 +0530454 if item.reference_dt == 'Clinical Procedure' and \
455 frappe.db.get_single_value('Healthcare Settings', 'clinical_procedure_consumable_item') == item.item_code:
Rucha Mahabal06d1b042020-03-12 12:16:23 +0530456 is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, 'consumption_invoiced')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530457 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530458 is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, 'invoiced')
459 if is_invoiced:
Rucha Mahabal434791e2020-10-24 14:20:38 +0530460 frappe.throw(_('The item referenced by {0} - {1} is already invoiced').format(
461 item.reference_dt, item.reference_dn))
Jamsheerba119722018-07-06 15:58:13 +0530462
Rucha Mahabal27512c82020-03-09 17:29:23 +0530463
Jamsheerba119722018-07-06 15:58:13 +0530464def manage_prescriptions(invoiced, ref_dt, ref_dn, dt, created_check_field):
465 created = frappe.db.get_value(ref_dt, ref_dn, created_check_field)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530466 if created:
Jamsheerba119722018-07-06 15:58:13 +0530467 # Fetch the doc created for the prescription
Jamsheereafb0462018-07-25 13:15:12 +0530468 doc_created = frappe.db.get_value(dt, {'prescription': ref_dn})
Jamsheerba119722018-07-06 15:58:13 +0530469 frappe.db.set_value(dt, doc_created, 'invoiced', invoiced)
470
Rucha Mahabal27512c82020-03-09 17:29:23 +0530471
Rucha Mahabalcd319962020-03-13 15:39:31 +0530472def check_fee_validity(appointment):
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530473 if not frappe.db.get_single_value('Healthcare Settings', 'enable_free_follow_ups'):
474 return
475
Rucha Mahabalcd319962020-03-13 15:39:31 +0530476 validity = frappe.db.exists('Fee Validity', {
477 'practitioner': appointment.practitioner,
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530478 'patient': appointment.patient,
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530479 'valid_till': ('>=', appointment.appointment_date)
Rucha Mahabalcd319962020-03-13 15:39:31 +0530480 })
481 if not validity:
482 return
483
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530484 validity = frappe.get_doc('Fee Validity', validity)
485 return validity
486
Rucha Mahabal27512c82020-03-09 17:29:23 +0530487
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530488def manage_fee_validity(appointment):
489 fee_validity = check_fee_validity(appointment)
anoop93d0c782020-04-13 16:42:03 +0530490
Rucha Mahabalcd319962020-03-13 15:39:31 +0530491 if fee_validity:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530492 if appointment.status == 'Cancelled' and fee_validity.visited > 0:
493 fee_validity.visited -= 1
494 frappe.db.delete('Fee Validity Reference', {'appointment': appointment.name})
Rucha Mahabal2cec6bd2020-03-26 14:38:12 +0530495 elif fee_validity.status == 'Completed':
496 return
Rucha Mahabalcd319962020-03-13 15:39:31 +0530497 else:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530498 fee_validity.visited += 1
499 fee_validity.append('ref_appointments', {
500 'appointment': appointment.name
501 })
502 fee_validity.save(ignore_permissions=True)
Jamsheerba119722018-07-06 15:58:13 +0530503 else:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530504 fee_validity = create_fee_validity(appointment)
505 return fee_validity
Rucha Mahabal27512c82020-03-09 17:29:23 +0530506
Jamsheerba119722018-07-06 15:58:13 +0530507
Rucha Mahabal06d1b042020-03-12 12:16:23 +0530508def manage_doc_for_appointment(dt_from_appointment, appointment, invoiced):
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530509 dn_from_appointment = frappe.db.get_value(
510 dt_from_appointment,
Rucha Mahabal27512c82020-03-09 17:29:23 +0530511 filters={'appointment': appointment}
Jamsheerba119722018-07-06 15:58:13 +0530512 )
513 if dn_from_appointment:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530514 frappe.db.set_value(dt_from_appointment, dn_from_appointment, 'invoiced', invoiced)
515
Jamsheere82f27a2018-07-30 11:28:37 +0530516
517@frappe.whitelist()
518def get_drugs_to_invoice(encounter):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530519 encounter = frappe.get_doc('Patient Encounter', encounter)
Jamsheere82f27a2018-07-30 11:28:37 +0530520 if encounter:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530521 patient = frappe.get_doc('Patient', encounter.patient)
522 if patient:
523 if patient.customer:
524 items_to_invoice = []
Jamsheere82f27a2018-07-30 11:28:37 +0530525 for drug_line in encounter.drug_prescription:
526 if drug_line.drug_code:
527 qty = 1
Rucha Mahabal27512c82020-03-09 17:29:23 +0530528 if frappe.db.get_value('Item', drug_line.drug_code, 'stock_uom') == 'Nos':
Jamsheere82f27a2018-07-30 11:28:37 +0530529 qty = drug_line.get_quantity()
Rucha Mahabal27512c82020-03-09 17:29:23 +0530530
531 description = ''
532 if drug_line.dosage and drug_line.period:
533 description = _('{0} for {1}').format(drug_line.dosage, drug_line.period)
534
535 items_to_invoice.append({
536 'drug_code': drug_line.drug_code,
537 'quantity': qty,
538 'description': description
539 })
540 return items_to_invoice
541 else:
542 validate_customer_created(patient)
543
Jamsheer4371c7e2018-08-01 18:40:05 +0530544
545@frappe.whitelist()
Rucha Mahabal212eb4b2021-08-30 13:10:18 +0530546def get_children(doctype, parent=None, company=None, is_root=False):
547 parent_fieldname = 'parent_' + doctype.lower().replace(' ', '_')
Jamsheer4371c7e2018-08-01 18:40:05 +0530548 fields = [
Rucha Mahabal212eb4b2021-08-30 13:10:18 +0530549 'name as value',
550 'is_group as expandable',
551 'lft',
552 'rgt'
Jamsheer4371c7e2018-08-01 18:40:05 +0530553 ]
Rucha Mahabal212eb4b2021-08-30 13:10:18 +0530554
555 filters = [["ifnull(`{0}`,'')".format(parent_fieldname),
556 '=', '' if is_root else parent]]
Jamsheer4371c7e2018-08-01 18:40:05 +0530557
558 if is_root:
Rucha Mahabal212eb4b2021-08-30 13:10:18 +0530559 fields += ['service_unit_type'] if doctype == 'Healthcare Service Unit' else []
560 filters.append(['company', '=', company])
Jamsheer4371c7e2018-08-01 18:40:05 +0530561 else:
Rucha Mahabal212eb4b2021-08-30 13:10:18 +0530562 fields += ['service_unit_type', 'allow_appointments', 'inpatient_occupancy',
563 'occupancy_status'] if doctype == 'Healthcare Service Unit' else []
564 fields += [parent_fieldname + ' as parent']
Jamsheer4371c7e2018-08-01 18:40:05 +0530565
Rucha Mahabal212eb4b2021-08-30 13:10:18 +0530566 service_units = frappe.get_list(doctype, fields=fields, filters=filters)
567 for each in service_units:
568 if each['expandable'] == 1: # group node
569 available_count = frappe.db.count('Healthcare Service Unit', filters={
570 'parent_healthcare_service_unit': each['value'],
571 'inpatient_occupancy': 1})
Jamsheer4371c7e2018-08-01 18:40:05 +0530572
Rucha Mahabal212eb4b2021-08-30 13:10:18 +0530573 if available_count > 0:
574 occupied_count = frappe.db.count('Healthcare Service Unit', {
575 'parent_healthcare_service_unit': each['value'],
576 'inpatient_occupancy': 1,
577 'occupancy_status': 'Occupied'})
578 # set occupancy status of group node
579 each['occupied_of_available'] = str(
580 occupied_count) + ' Occupied of ' + str(available_count)
Rucha Mahabalced978e2020-04-02 18:45:53 +0530581
Rucha Mahabal212eb4b2021-08-30 13:10:18 +0530582 return service_units
Jamsheer5073ac42019-07-12 12:28:34 +0530583
Rucha Mahabal27512c82020-03-09 17:29:23 +0530584
Jamsheer5073ac42019-07-12 12:28:34 +0530585@frappe.whitelist()
586def get_patient_vitals(patient, from_date=None, to_date=None):
587 if not patient: return
Rucha Mahabal27512c82020-03-09 17:29:23 +0530588
Rucha Mahabal4dd6b992020-05-25 18:42:01 +0530589 vitals = frappe.db.get_all('Vital Signs', filters={
Rucha Mahabal27512c82020-03-09 17:29:23 +0530590 'docstatus': 1,
591 'patient': patient
Rucha Mahabal4dd6b992020-05-25 18:42:01 +0530592 }, order_by='signs_date, signs_time', fields=['*'])
Rucha Mahabal27512c82020-03-09 17:29:23 +0530593
594 if len(vitals):
Jamsheer5073ac42019-07-12 12:28:34 +0530595 return vitals
Rucha Mahabal27512c82020-03-09 17:29:23 +0530596 return False
597
Jamsheer5073ac42019-07-12 12:28:34 +0530598
599@frappe.whitelist()
600def render_docs_as_html(docs):
601 # docs key value pair {doctype: docname}
602 docs_html = "<div class='col-md-12 col-sm-12 text-muted'>"
603 for doc in docs:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530604 docs_html += render_doc_as_html(doc['doctype'], doc['docname'])['html'] + '<br/>'
Jamsheer5073ac42019-07-12 12:28:34 +0530605 return {'html': docs_html}
606
Rucha Mahabal27512c82020-03-09 17:29:23 +0530607
Jamsheer5073ac42019-07-12 12:28:34 +0530608@frappe.whitelist()
609def render_doc_as_html(doctype, docname, exclude_fields = []):
610 #render document as html, three column layout will break
611 doc = frappe.get_doc(doctype, docname)
612 meta = frappe.get_meta(doctype)
613 doc_html = "<div class='col-md-12 col-sm-12'>"
Rucha Mahabal27512c82020-03-09 17:29:23 +0530614 section_html = ''
615 section_label = ''
616 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530617 sec_on = False
618 col_on = 0
619 has_data = False
620 for df in meta.fields:
621 #on section break append append previous section and html to doc html
622 if df.fieldtype == "Section Break":
623 if has_data and col_on and sec_on:
624 doc_html += section_html + html + "</div>"
625 elif has_data and not col_on and sec_on:
626 doc_html += "<div class='col-md-12 col-sm-12'\
627 ><div class='col-md-12 col-sm-12'>" \
628 + section_html + html +"</div></div>"
629 while col_on:
630 doc_html += "</div>"
631 col_on -= 1
632 sec_on = True
633 has_data= False
634 col_on = 0
Rucha Mahabal27512c82020-03-09 17:29:23 +0530635 section_html = ''
636 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530637 if df.label:
638 section_label = df.label
639 continue
640 #on column break append html to section html or doc html
641 if df.fieldtype == "Column Break":
642 if sec_on and has_data:
643 section_html += "<div class='col-md-12 col-sm-12'\
644 ><div class='col-md-6 col\
645 -sm-6'><b>" + section_label + "</b>" + html + "</div><div \
646 class='col-md-6 col-sm-6'>"
647 elif has_data:
648 doc_html += "<div class='col-md-12 col-sm-12'><div class='col-m\
649 d-6 col-sm-6'>" + html + "</div><div class='col-md-6 col-sm-6'>"
650 elif sec_on and not col_on:
651 section_html += "<div class='col-md-6 col-sm-6'>"
Rucha Mahabal27512c82020-03-09 17:29:23 +0530652 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530653 col_on += 1
654 if df.label:
655 html += '<br>' + df.label
656 continue
657 #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 +0530658 if df.fieldtype == 'Table':
Jamsheer5073ac42019-07-12 12:28:34 +0530659 items = doc.get(df.fieldname)
660 if not items: continue
661 child_meta = frappe.get_meta(df.options)
662 if not has_data : has_data = True
Rucha Mahabal27512c82020-03-09 17:29:23 +0530663 table_head = ''
664 table_row = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530665 create_head = True
666 for item in items:
667 table_row += '<tr>'
668 for cdf in child_meta.fields:
669 if cdf.in_list_view:
670 if create_head:
671 table_head += '<th>' + cdf.label + '</th>'
672 if item.get(cdf.fieldname):
673 table_row += '<td>' + str(item.get(cdf.fieldname)) \
674 + '</td>'
675 else:
676 table_row += '<td></td>'
677 create_head = False
678 table_row += '</tr>'
679 if sec_on:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530680 section_html += "<table class='table table-condensed \
681 bordered'>" + table_head + table_row + '</table>'
Jamsheer5073ac42019-07-12 12:28:34 +0530682 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530683 html += "<table class='table table-condensed table-bordered'>" \
684 + table_head + table_row + "</table>"
Jamsheer5073ac42019-07-12 12:28:34 +0530685 continue
Rucha Mahabal5e3c51b2020-11-30 13:35:00 +0530686
Jamsheer5073ac42019-07-12 12:28:34 +0530687 #on other field types add label and value to html
688 if not df.hidden and not df.print_hide and doc.get(df.fieldname) and df.fieldname not in exclude_fields:
Rucha Mahabal5e3c51b2020-11-30 13:35:00 +0530689 if doc.get(df.fieldname):
690 formatted_value = format_value(doc.get(df.fieldname), meta.get_field(df.fieldname), doc)
691 html += '<br>{0} : {1}'.format(df.label or df.fieldname, formatted_value)
692
Jamsheer5073ac42019-07-12 12:28:34 +0530693 if not has_data : has_data = True
Rucha Mahabal5e3c51b2020-11-30 13:35:00 +0530694
Jamsheer5073ac42019-07-12 12:28:34 +0530695 if sec_on and col_on and has_data:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530696 doc_html += section_html + html + '</div></div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530697 elif sec_on and not col_on and has_data:
698 doc_html += "<div class='col-md-12 col-sm-12'\
699 ><div class='col-md-12 col-sm-12'>" \
Rucha Mahabal27512c82020-03-09 17:29:23 +0530700 + section_html + html +'</div></div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530701 if doc_html:
Rushabh Mehta542bc012020-11-18 15:00:34 +0530702 doc_html = "<div class='small'><div class='col-md-12 text-right'><a class='btn btn-default btn-xs' href='/app/Form/%s/%s'></a></div>" %(doctype, docname) + doc_html + '</div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530703
704 return {'html': doc_html}
Rucha Mahabal212eb4b2021-08-30 13:10:18 +0530705
706
707def update_address_links(address, method):
708 '''
709 Hook validate Address
710 If Patient is linked in Address, also link the associated Customer
711 '''
712 if 'Healthcare' not in frappe.get_active_domains():
713 return
714
715 patient_links = list(filter(lambda link: link.get('link_doctype') == 'Patient', address.links))
716
717 for link in patient_links:
718 customer = frappe.db.get_value('Patient', link.get('link_name'), 'customer')
719 if customer and not address.has_link('Customer', customer):
720 address.append('links', dict(link_doctype = 'Customer', link_name = customer))
721
722
723def update_patient_email_and_phone_numbers(contact, method):
724 '''
725 Hook validate Contact
726 Update linked Patients' primary mobile and phone numbers
727 '''
728 if 'Healthcare' not in frappe.get_active_domains():
729 return
730
731 if contact.is_primary_contact and (contact.email_id or contact.mobile_no or contact.phone):
732 patient_links = list(filter(lambda link: link.get('link_doctype') == 'Patient', contact.links))
733
734 for link in patient_links:
735 contact_details = frappe.db.get_value('Patient', link.get('link_name'), ['email', 'mobile', 'phone'], as_dict=1)
736 if contact.email_id and contact.email_id != contact_details.get('email'):
737 frappe.db.set_value('Patient', link.get('link_name'), 'email', contact.email_id)
738 if contact.mobile_no and contact.mobile_no != contact_details.get('mobile'):
739 frappe.db.set_value('Patient', link.get('link_name'), 'mobile', contact.mobile_no)
740 if contact.phone and contact.phone != contact_details.get('phone'):
741 frappe.db.set_value('Patient', link.get('link_name'), 'phone', contact.phone)