blob: a3e7070acd50a04408d822eb965c50bcc84ce797 [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
Jamsheerba119722018-07-06 15:58:13 +05308from frappe import _
Rucha Mahabal197165f2020-03-26 17:29:50 +05309from frappe.utils import time_diff_in_hours, rounded
Jamsheerba119722018-07-06 15:58:13 +053010from erpnext.healthcare.doctype.healthcare_settings.healthcare_settings import get_income_account
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +053011from erpnext.healthcare.doctype.fee_validity.fee_validity import create_fee_validity
Jamsheer0ae100b2018-08-01 14:29:43 +053012from erpnext.healthcare.doctype.lab_test.lab_test import create_multiple
Jamsheerba119722018-07-06 15:58:13 +053013
14@frappe.whitelist()
anoop93d0c782020-04-13 16:42:03 +053015def get_healthcare_services_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +053016 patient = frappe.get_doc('Patient', patient)
anoop93d0c782020-04-13 16:42:03 +053017 items_to_invoice = []
Jamsheerba119722018-07-06 15:58:13 +053018 if patient:
Rucha Mahabal27512c82020-03-09 17:29:23 +053019 validate_customer_created(patient)
anoop93d0c782020-04-13 16:42:03 +053020 # Customer validated, build a list of billable services
21 items_to_invoice += get_appointments_to_invoice(patient, company)
22 items_to_invoice += get_encounters_to_invoice(patient, company)
23 items_to_invoice += get_lab_tests_to_invoice(patient, company)
24 items_to_invoice += get_clinical_procedures_to_invoice(patient, company)
25 items_to_invoice += get_inpatient_services_to_invoice(patient, company)
Rucha Mahabal434791e2020-10-24 14:20:38 +053026 items_to_invoice += get_therapy_plans_to_invoice(patient, company)
Rucha Mahabald7304512020-04-23 00:52:47 +053027 items_to_invoice += get_therapy_sessions_to_invoice(patient, company)
Jamsheerba119722018-07-06 15:58:13 +053028
Rucha Mahabal27512c82020-03-09 17:29:23 +053029 return items_to_invoice
Jamsheerba119722018-07-06 15:58:13 +053030
anoop93d0c782020-04-13 16:42:03 +053031
Rucha Mahabal27512c82020-03-09 17:29:23 +053032def validate_customer_created(patient):
33 if not frappe.db.get_value('Patient', patient.name, 'customer'):
34 msg = _("Please set a Customer linked to the Patient")
Rushabh Mehta542bc012020-11-18 15:00:34 +053035 msg += " <b><a href='/app/Form/Patient/{0}'>{0}</a></b>".format(patient.name)
Rucha Mahabal27512c82020-03-09 17:29:23 +053036 frappe.throw(msg, title=_('Customer Not Found'))
Jamsheer8da6f4e2018-07-26 21:03:17 +053037
Rucha Mahabal434791e2020-10-24 14:20:38 +053038
anoop93d0c782020-04-13 16:42:03 +053039def get_appointments_to_invoice(patient, company):
40 appointments_to_invoice = []
41 patient_appointments = frappe.get_list(
42 'Patient Appointment',
43 fields = '*',
anoop59030022020-07-28 21:15:54 +053044 filters = {'patient': patient.name, 'company': company, 'invoiced': 0, 'status': ['not in', 'Cancelled']},
anoop93d0c782020-04-13 16:42:03 +053045 order_by = 'appointment_date'
46 )
47
Rucha Mahabal27512c82020-03-09 17:29:23 +053048 for appointment in patient_appointments:
anoop93d0c782020-04-13 16:42:03 +053049 # Procedure Appointments
Rucha Mahabal27512c82020-03-09 17:29:23 +053050 if appointment.procedure_template:
51 if frappe.db.get_value('Clinical Procedure Template', appointment.procedure_template, 'is_billable'):
anoop93d0c782020-04-13 16:42:03 +053052 appointments_to_invoice.append({
Rucha Mahabal27512c82020-03-09 17:29:23 +053053 'reference_type': 'Patient Appointment',
54 'reference_name': appointment.name,
55 'service': appointment.procedure_template
56 })
anoop93d0c782020-04-13 16:42:03 +053057 # Consultation Appointments, should check fee validity
Jamsheerba119722018-07-06 15:58:13 +053058 else:
anoop93d0c782020-04-13 16:42:03 +053059 if frappe.db.get_single_value('Healthcare Settings', 'enable_free_follow_ups') and \
60 frappe.db.exists('Fee Validity Reference', {'appointment': appointment.name}):
61 continue # Skip invoicing, fee validty present
62 practitioner_charge = 0
63 income_account = None
64 service_item = None
65 if appointment.practitioner:
66 service_item, practitioner_charge = get_service_item_and_practitioner_charge(appointment)
67 income_account = get_income_account(appointment.practitioner, appointment.company)
68 appointments_to_invoice.append({
69 'reference_type': 'Patient Appointment',
70 'reference_name': appointment.name,
71 'service': service_item,
72 'rate': practitioner_charge,
73 'income_account': income_account
74 })
Rucha Mahabal27512c82020-03-09 17:29:23 +053075
anoop93d0c782020-04-13 16:42:03 +053076 return appointments_to_invoice
Rucha Mahabal27512c82020-03-09 17:29:23 +053077
78
anoop93d0c782020-04-13 16:42:03 +053079def get_encounters_to_invoice(patient, company):
Rucha Mahabal0f059252021-01-13 09:46:33 +053080 if not isinstance(patient, str):
81 patient = patient.name
Rucha Mahabal27512c82020-03-09 17:29:23 +053082 encounters_to_invoice = []
83 encounters = frappe.get_list(
84 'Patient Encounter',
85 fields=['*'],
Rucha Mahabal0f059252021-01-13 09:46:33 +053086 filters={'patient': patient, 'company': company, 'invoiced': False, 'docstatus': 1}
Rucha Mahabal27512c82020-03-09 17:29:23 +053087 )
88 if encounters:
89 for encounter in encounters:
90 if not encounter.appointment:
91 practitioner_charge = 0
92 income_account = None
93 service_item = None
94 if encounter.practitioner:
Rucha Mahabal13541972021-01-13 09:12:50 +053095 if encounter.inpatient_record and \
96 frappe.db.get_single_value('Healthcare Settings', 'do_not_bill_inpatient_encounters'):
97 continue
98
Rucha Mahabal27512c82020-03-09 17:29:23 +053099 service_item, practitioner_charge = get_service_item_and_practitioner_charge(encounter)
100 income_account = get_income_account(encounter.practitioner, encounter.company)
101
102 encounters_to_invoice.append({
103 'reference_type': 'Patient Encounter',
104 'reference_name': encounter.name,
105 'service': service_item,
106 'rate': practitioner_charge,
107 'income_account': income_account
108 })
109
110 return encounters_to_invoice
111
112
anoop93d0c782020-04-13 16:42:03 +0530113def get_lab_tests_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530114 lab_tests_to_invoice = []
115 lab_tests = frappe.get_list(
116 'Lab Test',
117 fields=['name', 'template'],
anoop93d0c782020-04-13 16:42:03 +0530118 filters={'patient': patient.name, 'company': company, 'invoiced': False, 'docstatus': 1}
Rucha Mahabal27512c82020-03-09 17:29:23 +0530119 )
120 for lab_test in lab_tests:
Rucha Mahabal131452c2020-04-27 10:52:38 +0530121 item, is_billable = frappe.get_cached_value('Lab Test Template', lab_test.template, ['item', 'is_billable'])
Rucha Mahabalced978e2020-04-02 18:45:53 +0530122 if is_billable:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530123 lab_tests_to_invoice.append({
124 'reference_type': 'Lab Test',
125 'reference_name': lab_test.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530126 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530127 })
128
Rucha Mahabalced978e2020-04-02 18:45:53 +0530129 lab_prescriptions = frappe.db.sql(
130 '''
131 SELECT
132 lp.name, lp.lab_test_code
133 FROM
134 `tabPatient Encounter` et, `tabLab Prescription` lp
135 WHERE
136 et.patient=%s
137 and lp.parent=et.name
138 and lp.lab_test_created=0
139 and lp.invoiced=0
140 ''', (patient.name), as_dict=1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530141
142 for prescription in lab_prescriptions:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530143 item, is_billable = frappe.get_cached_value('Lab Test Template', prescription.lab_test_code, ['item', 'is_billable'])
144 if prescription.lab_test_code and is_billable:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530145 lab_tests_to_invoice.append({
146 'reference_type': 'Lab Prescription',
147 'reference_name': prescription.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530148 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530149 })
150
151 return lab_tests_to_invoice
152
153
anoop93d0c782020-04-13 16:42:03 +0530154def get_clinical_procedures_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530155 clinical_procedures_to_invoice = []
156 procedures = frappe.get_list(
157 'Clinical Procedure',
158 fields='*',
anoop93d0c782020-04-13 16:42:03 +0530159 filters={'patient': patient.name, 'company': company, 'invoiced': False}
Rucha Mahabal27512c82020-03-09 17:29:23 +0530160 )
161 for procedure in procedures:
162 if not procedure.appointment:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530163 item, is_billable = frappe.get_cached_value('Clinical Procedure Template', procedure.procedure_template, ['item', 'is_billable'])
164 if procedure.procedure_template and is_billable:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530165 clinical_procedures_to_invoice.append({
166 'reference_type': 'Clinical Procedure',
167 'reference_name': procedure.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530168 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530169 })
170
171 # consumables
172 if procedure.invoice_separately_as_consumables and procedure.consume_stock \
173 and procedure.status == 'Completed' and not procedure.consumption_invoiced:
174
175 service_item = get_healthcare_service_item('clinical_procedure_consumable_item')
176 if not service_item:
177 msg = _('Please Configure Clinical Procedure Consumable Item in ')
Rushabh Mehta542bc012020-11-18 15:00:34 +0530178 msg += '''<b><a href='/app/Form/Healthcare Settings'>Healthcare Settings</a></b>'''
Rucha Mahabal27512c82020-03-09 17:29:23 +0530179 frappe.throw(msg, title=_('Missing Configuration'))
180
181 clinical_procedures_to_invoice.append({
182 'reference_type': 'Clinical Procedure',
183 'reference_name': procedure.name,
184 'service': service_item,
185 'rate': procedure.consumable_total_amount,
186 'description': procedure.consumption_details
187 })
188
Rucha Mahabalced978e2020-04-02 18:45:53 +0530189 procedure_prescriptions = frappe.db.sql(
190 '''
191 SELECT
192 pp.name, pp.procedure
193 FROM
194 `tabPatient Encounter` et, `tabProcedure Prescription` pp
195 WHERE
196 et.patient=%s
197 and pp.parent=et.name
198 and pp.procedure_created=0
199 and pp.invoiced=0
200 and pp.appointment_booked=0
201 ''', (patient.name), as_dict=1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530202
203 for prescription in procedure_prescriptions:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530204 item, is_billable = frappe.get_cached_value('Clinical Procedure Template', prescription.procedure, ['item', 'is_billable'])
205 if is_billable:
Rucha Mahabal197165f2020-03-26 17:29:50 +0530206 clinical_procedures_to_invoice.append({
Rucha Mahabal27512c82020-03-09 17:29:23 +0530207 'reference_type': 'Procedure Prescription',
208 'reference_name': prescription.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530209 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530210 })
211
212 return clinical_procedures_to_invoice
213
214
anoop93d0c782020-04-13 16:42:03 +0530215def get_inpatient_services_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530216 services_to_invoice = []
Rucha Mahabalced978e2020-04-02 18:45:53 +0530217 inpatient_services = frappe.db.sql(
218 '''
219 SELECT
220 io.*
221 FROM
222 `tabInpatient Record` ip, `tabInpatient Occupancy` io
223 WHERE
224 ip.patient=%s
anoop93d0c782020-04-13 16:42:03 +0530225 and ip.company=%s
Rucha Mahabalced978e2020-04-02 18:45:53 +0530226 and io.parent=ip.name
227 and io.left=1
228 and io.invoiced=0
anoop93d0c782020-04-13 16:42:03 +0530229 ''', (patient.name, company), as_dict=1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530230
231 for inpatient_occupancy in inpatient_services:
232 service_unit_type = frappe.db.get_value('Healthcare Service Unit', inpatient_occupancy.service_unit, 'service_unit_type')
Rucha Mahabalced978e2020-04-02 18:45:53 +0530233 service_unit_type = frappe.get_cached_doc('Healthcare Service Unit Type', service_unit_type)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530234 if service_unit_type and service_unit_type.is_billable:
235 hours_occupied = time_diff_in_hours(inpatient_occupancy.check_out, inpatient_occupancy.check_in)
236 qty = 0.5
237 if hours_occupied > 0:
238 actual_qty = hours_occupied / service_unit_type.no_of_hours
239 floor = math.floor(actual_qty)
240 decimal_part = actual_qty - floor
241 if decimal_part > 0.5:
242 qty = rounded(floor + 1, 1)
243 elif decimal_part < 0.5 and decimal_part > 0:
244 qty = rounded(floor + 0.5, 1)
245 if qty <= 0:
246 qty = 0.5
247 services_to_invoice.append({
248 'reference_type': 'Inpatient Occupancy',
249 'reference_name': inpatient_occupancy.name,
250 'service': service_unit_type.item, 'qty': qty
251 })
252
253 return services_to_invoice
254
Jamsheerba119722018-07-06 15:58:13 +0530255
Rucha Mahabal434791e2020-10-24 14:20:38 +0530256def get_therapy_plans_to_invoice(patient, company):
257 therapy_plans_to_invoice = []
258 therapy_plans = frappe.get_list(
259 'Therapy Plan',
260 fields=['therapy_plan_template', 'name'],
261 filters={
262 'patient': patient.name,
263 'invoiced': 0,
264 'company': company,
265 'therapy_plan_template': ('!=', '')
266 }
267 )
268 for plan in therapy_plans:
269 therapy_plans_to_invoice.append({
270 'reference_type': 'Therapy Plan',
271 'reference_name': plan.name,
272 'service': frappe.db.get_value('Therapy Plan Template', plan.therapy_plan_template, 'linked_item')
273 })
274
275 return therapy_plans_to_invoice
276
277
Rucha Mahabald7304512020-04-23 00:52:47 +0530278def get_therapy_sessions_to_invoice(patient, company):
Rucha Mahabaleaa956b2020-04-22 13:07:12 +0530279 therapy_sessions_to_invoice = []
Rucha Mahabal434791e2020-10-24 14:20:38 +0530280 therapy_plans = frappe.db.get_all('Therapy Plan', {'therapy_plan_template': ('!=', '')})
281 therapy_plans_created_from_template = []
282 for entry in therapy_plans:
283 therapy_plans_created_from_template.append(entry.name)
284
Rucha Mahabaleaa956b2020-04-22 13:07:12 +0530285 therapy_sessions = frappe.get_list(
286 'Therapy Session',
287 fields='*',
Rucha Mahabal434791e2020-10-24 14:20:38 +0530288 filters={
289 'patient': patient.name,
290 'invoiced': 0,
291 'company': company,
292 'therapy_plan': ('not in', therapy_plans_created_from_template)
293 }
Rucha Mahabaleaa956b2020-04-22 13:07:12 +0530294 )
295 for therapy in therapy_sessions:
296 if not therapy.appointment:
297 if therapy.therapy_type and frappe.db.get_value('Therapy Type', therapy.therapy_type, 'is_billable'):
298 therapy_sessions_to_invoice.append({
299 'reference_type': 'Therapy Session',
300 'reference_name': therapy.name,
301 'service': frappe.db.get_value('Therapy Type', therapy.therapy_type, 'item')
302 })
303
304 return therapy_sessions_to_invoice
305
306
Rucha Mahabal24055e12020-02-24 19:09:50 +0530307def get_service_item_and_practitioner_charge(doc):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530308 is_inpatient = doc.inpatient_record
Rucha Mahabal24055e12020-02-24 19:09:50 +0530309 if is_inpatient:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530310 service_item = get_practitioner_service_item(doc.practitioner, 'inpatient_visit_charge_item')
Jamsheeree5f9c72018-07-30 12:42:06 +0530311 if not service_item:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530312 service_item = get_healthcare_service_item('inpatient_visit_charge_item')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530313 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530314 service_item = get_practitioner_service_item(doc.practitioner, 'op_consulting_charge_item')
Jamsheeree5f9c72018-07-30 12:42:06 +0530315 if not service_item:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530316 service_item = get_healthcare_service_item('op_consulting_charge_item')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530317 if not service_item:
Rucha Mahabal24055e12020-02-24 19:09:50 +0530318 throw_config_service_item(is_inpatient)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530319
Rucha Mahabal24055e12020-02-24 19:09:50 +0530320 practitioner_charge = get_practitioner_charge(doc.practitioner, is_inpatient)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530321 if not practitioner_charge:
Rucha Mahabal24055e12020-02-24 19:09:50 +0530322 throw_config_practitioner_charge(is_inpatient, doc.practitioner)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530323
324 return service_item, practitioner_charge
325
Jamsheer8da6f4e2018-07-26 21:03:17 +0530326
Rucha Mahabal27512c82020-03-09 17:29:23 +0530327def throw_config_service_item(is_inpatient):
Rucha Mahabalced978e2020-04-02 18:45:53 +0530328 service_item_label = _('Out Patient Consulting Charge Item')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530329 if is_inpatient:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530330 service_item_label = _('Inpatient Visit Charge Item')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530331
Rucha Mahabal4f9a1472020-03-23 10:40:39 +0530332 msg = _(('Please Configure {0} in ').format(service_item_label) \
Rushabh Mehta542bc012020-11-18 15:00:34 +0530333 + '''<b><a href='/app/Form/Healthcare Settings'>Healthcare Settings</a></b>''')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530334 frappe.throw(msg, title=_('Missing Configuration'))
335
Jamsheer8da6f4e2018-07-26 21:03:17 +0530336
Rucha Mahabal24055e12020-02-24 19:09:50 +0530337def throw_config_practitioner_charge(is_inpatient, practitioner):
Rucha Mahabalced978e2020-04-02 18:45:53 +0530338 charge_name = _('OP Consulting Charge')
Rucha Mahabal24055e12020-02-24 19:09:50 +0530339 if is_inpatient:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530340 charge_name = _('Inpatient Visit Charge')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530341
Rucha Mahabal27512c82020-03-09 17:29:23 +0530342 msg = _(('Please Configure {0} for Healthcare Practitioner').format(charge_name) \
Rushabh Mehta542bc012020-11-18 15:00:34 +0530343 + ''' <b><a href='/app/Form/Healthcare Practitioner/{0}'>{0}</a></b>'''.format(practitioner))
Rucha Mahabal27512c82020-03-09 17:29:23 +0530344 frappe.throw(msg, title=_('Missing Configuration'))
345
Jamsheer8da6f4e2018-07-26 21:03:17 +0530346
Jamsheeree5f9c72018-07-30 12:42:06 +0530347def get_practitioner_service_item(practitioner, service_item_field):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530348 return frappe.db.get_value('Healthcare Practitioner', practitioner, service_item_field)
349
Jamsheeree5f9c72018-07-30 12:42:06 +0530350
Jamsheer8da6f4e2018-07-26 21:03:17 +0530351def get_healthcare_service_item(service_item_field):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530352 return frappe.db.get_single_value('Healthcare Settings', service_item_field)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530353
Jamsheer8da6f4e2018-07-26 21:03:17 +0530354
Rucha Mahabal24055e12020-02-24 19:09:50 +0530355def get_practitioner_charge(practitioner, is_inpatient):
356 if is_inpatient:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530357 practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, 'inpatient_visit_charge')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530358 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530359 practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, 'op_consulting_charge')
Jamsheerba119722018-07-06 15:58:13 +0530360 if practitioner_charge:
361 return practitioner_charge
Jamsheer8da6f4e2018-07-26 21:03:17 +0530362 return False
Jamsheerba119722018-07-06 15:58:13 +0530363
Rucha Mahabal27512c82020-03-09 17:29:23 +0530364
Jamsheerba119722018-07-06 15:58:13 +0530365def manage_invoice_submit_cancel(doc, method):
366 if doc.items:
367 for item in doc.items:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530368 if item.get('reference_dt') and item.get('reference_dn'):
369 if frappe.get_meta(item.reference_dt).has_field('invoiced'):
Jamsheer146683b2018-07-25 11:30:30 +0530370 set_invoiced(item, method, doc.name)
Jamsheerba119722018-07-06 15:58:13 +0530371
Rucha Mahabal27512c82020-03-09 17:29:23 +0530372 if method=='on_submit' and frappe.db.get_single_value('Healthcare Settings', 'create_lab_test_on_si_submit'):
373 create_multiple('Sales Invoice', doc.name)
374
Jamsheer0ae100b2018-08-01 14:29:43 +0530375
Jamsheer146683b2018-07-25 11:30:30 +0530376def set_invoiced(item, method, ref_invoice=None):
Jamsheerba119722018-07-06 15:58:13 +0530377 invoiced = False
Rucha Mahabal27512c82020-03-09 17:29:23 +0530378 if method=='on_submit':
Jamsheerba119722018-07-06 15:58:13 +0530379 validate_invoiced_on_submit(item)
380 invoiced = True
381
Jamsheer8da6f4e2018-07-26 21:03:17 +0530382 if item.reference_dt == 'Clinical Procedure':
383 if get_healthcare_service_item('clinical_procedure_consumable_item') == item.item_code:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530384 frappe.db.set_value(item.reference_dt, item.reference_dn, 'consumption_invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530385 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530386 frappe.db.set_value(item.reference_dt, item.reference_dn, 'invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530387 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530388 frappe.db.set_value(item.reference_dt, item.reference_dn, 'invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530389
Jamsheerba119722018-07-06 15:58:13 +0530390 if item.reference_dt == 'Patient Appointment':
391 if frappe.db.get_value('Patient Appointment', item.reference_dn, 'procedure_template'):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530392 dt_from_appointment = 'Clinical Procedure'
Jamsheerba119722018-07-06 15:58:13 +0530393 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530394 dt_from_appointment = 'Patient Encounter'
Rucha Mahabal06d1b042020-03-12 12:16:23 +0530395 manage_doc_for_appointment(dt_from_appointment, item.reference_dn, invoiced)
Jamsheerba119722018-07-06 15:58:13 +0530396
397 elif item.reference_dt == 'Lab Prescription':
Rucha Mahabal27512c82020-03-09 17:29:23 +0530398 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, 'Lab Test', 'lab_test_created')
Jamsheerba119722018-07-06 15:58:13 +0530399
400 elif item.reference_dt == 'Procedure Prescription':
Rucha Mahabal27512c82020-03-09 17:29:23 +0530401 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, 'Clinical Procedure', 'procedure_created')
402
Jamsheerba119722018-07-06 15:58:13 +0530403
404def validate_invoiced_on_submit(item):
Jamsheer8da6f4e2018-07-26 21:03:17 +0530405 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 +0530406 is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, 'consumption_invoiced')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530407 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530408 is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, 'invoiced')
409 if is_invoiced:
Rucha Mahabal434791e2020-10-24 14:20:38 +0530410 frappe.throw(_('The item referenced by {0} - {1} is already invoiced').format(
411 item.reference_dt, item.reference_dn))
Jamsheerba119722018-07-06 15:58:13 +0530412
Rucha Mahabal27512c82020-03-09 17:29:23 +0530413
Jamsheerba119722018-07-06 15:58:13 +0530414def manage_prescriptions(invoiced, ref_dt, ref_dn, dt, created_check_field):
415 created = frappe.db.get_value(ref_dt, ref_dn, created_check_field)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530416 if created:
Jamsheerba119722018-07-06 15:58:13 +0530417 # Fetch the doc created for the prescription
Jamsheereafb0462018-07-25 13:15:12 +0530418 doc_created = frappe.db.get_value(dt, {'prescription': ref_dn})
Jamsheerba119722018-07-06 15:58:13 +0530419 frappe.db.set_value(dt, doc_created, 'invoiced', invoiced)
420
Rucha Mahabal27512c82020-03-09 17:29:23 +0530421
Rucha Mahabalcd319962020-03-13 15:39:31 +0530422def check_fee_validity(appointment):
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530423 if not frappe.db.get_single_value('Healthcare Settings', 'enable_free_follow_ups'):
424 return
425
Rucha Mahabalcd319962020-03-13 15:39:31 +0530426 validity = frappe.db.exists('Fee Validity', {
427 'practitioner': appointment.practitioner,
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530428 'patient': appointment.patient,
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530429 'valid_till': ('>=', appointment.appointment_date)
Rucha Mahabalcd319962020-03-13 15:39:31 +0530430 })
431 if not validity:
432 return
433
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530434 validity = frappe.get_doc('Fee Validity', validity)
435 return validity
436
Rucha Mahabal27512c82020-03-09 17:29:23 +0530437
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530438def manage_fee_validity(appointment):
439 fee_validity = check_fee_validity(appointment)
anoop93d0c782020-04-13 16:42:03 +0530440
Rucha Mahabalcd319962020-03-13 15:39:31 +0530441 if fee_validity:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530442 if appointment.status == 'Cancelled' and fee_validity.visited > 0:
443 fee_validity.visited -= 1
444 frappe.db.delete('Fee Validity Reference', {'appointment': appointment.name})
Rucha Mahabal2cec6bd2020-03-26 14:38:12 +0530445 elif fee_validity.status == 'Completed':
446 return
Rucha Mahabalcd319962020-03-13 15:39:31 +0530447 else:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530448 fee_validity.visited += 1
449 fee_validity.append('ref_appointments', {
450 'appointment': appointment.name
451 })
452 fee_validity.save(ignore_permissions=True)
Jamsheerba119722018-07-06 15:58:13 +0530453 else:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530454 fee_validity = create_fee_validity(appointment)
455 return fee_validity
Rucha Mahabal27512c82020-03-09 17:29:23 +0530456
Jamsheerba119722018-07-06 15:58:13 +0530457
Rucha Mahabal06d1b042020-03-12 12:16:23 +0530458def manage_doc_for_appointment(dt_from_appointment, appointment, invoiced):
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530459 dn_from_appointment = frappe.db.get_value(
460 dt_from_appointment,
Rucha Mahabal27512c82020-03-09 17:29:23 +0530461 filters={'appointment': appointment}
Jamsheerba119722018-07-06 15:58:13 +0530462 )
463 if dn_from_appointment:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530464 frappe.db.set_value(dt_from_appointment, dn_from_appointment, 'invoiced', invoiced)
465
Jamsheere82f27a2018-07-30 11:28:37 +0530466
467@frappe.whitelist()
468def get_drugs_to_invoice(encounter):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530469 encounter = frappe.get_doc('Patient Encounter', encounter)
Jamsheere82f27a2018-07-30 11:28:37 +0530470 if encounter:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530471 patient = frappe.get_doc('Patient', encounter.patient)
472 if patient:
473 if patient.customer:
474 items_to_invoice = []
Jamsheere82f27a2018-07-30 11:28:37 +0530475 for drug_line in encounter.drug_prescription:
476 if drug_line.drug_code:
477 qty = 1
Rucha Mahabal27512c82020-03-09 17:29:23 +0530478 if frappe.db.get_value('Item', drug_line.drug_code, 'stock_uom') == 'Nos':
Jamsheere82f27a2018-07-30 11:28:37 +0530479 qty = drug_line.get_quantity()
Rucha Mahabal27512c82020-03-09 17:29:23 +0530480
481 description = ''
482 if drug_line.dosage and drug_line.period:
483 description = _('{0} for {1}').format(drug_line.dosage, drug_line.period)
484
485 items_to_invoice.append({
486 'drug_code': drug_line.drug_code,
487 'quantity': qty,
488 'description': description
489 })
490 return items_to_invoice
491 else:
492 validate_customer_created(patient)
493
Jamsheer4371c7e2018-08-01 18:40:05 +0530494
495@frappe.whitelist()
496def get_children(doctype, parent, company, is_root=False):
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530497 parent_fieldname = "parent_" + doctype.lower().replace(" ", "_")
Jamsheer4371c7e2018-08-01 18:40:05 +0530498 fields = [
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530499 "name as value",
500 "is_group as expandable",
501 "lft",
502 "rgt"
Jamsheer4371c7e2018-08-01 18:40:05 +0530503 ]
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530504 # fields = [ "name", "is_group", "lft", "rgt" ]
505 filters = [["ifnull(`{0}`,'')".format(parent_fieldname), "=", "" if is_root else parent]]
Jamsheer4371c7e2018-08-01 18:40:05 +0530506
507 if is_root:
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530508 fields += ["service_unit_type"] if doctype == "Healthcare Service Unit" else []
509 filters.append(["company", "=", company])
Jamsheer4371c7e2018-08-01 18:40:05 +0530510
511 else:
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530512 fields += ["service_unit_type", "allow_appointments", "inpatient_occupancy", "occupancy_status"] if doctype == "Healthcare Service Unit" else []
513 fields += [parent_fieldname + " as parent"]
Jamsheer4371c7e2018-08-01 18:40:05 +0530514
515 hc_service_units = frappe.get_list(doctype, fields=fields, filters=filters)
516
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530517 if doctype == "Healthcare Service Unit":
Jamsheer4371c7e2018-08-01 18:40:05 +0530518 for each in hc_service_units:
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530519 occupancy_msg = ""
520 if each["expandable"] == 1:
Jamsheer4371c7e2018-08-01 18:40:05 +0530521 occupied = False
522 vacant = False
Rucha Mahabalced978e2020-04-02 18:45:53 +0530523 child_list = frappe.db.sql(
524 '''
525 SELECT
526 name, occupancy_status
527 FROM
528 `tabHealthcare Service Unit`
529 WHERE
530 inpatient_occupancy = 1
531 and lft > %s and rgt < %s
532 ''', (each['lft'], each['rgt']))
533
Jamsheer4371c7e2018-08-01 18:40:05 +0530534 for child in child_list:
Jamsheer4371c7e2018-08-01 18:40:05 +0530535 if not occupied:
536 occupied = 0
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530537 if child[1] == "Occupied":
Jamsheer4371c7e2018-08-01 18:40:05 +0530538 occupied += 1
539 if not vacant:
540 vacant = 0
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530541 if child[1] == "Vacant":
Jamsheer4371c7e2018-08-01 18:40:05 +0530542 vacant += 1
543 if vacant and occupied:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530544 occupancy_total = vacant + occupied
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530545 occupancy_msg = str(occupied) + " Occupied out of " + str(occupancy_total)
546 each["occupied_out_of_vacant"] = occupancy_msg
Jamsheer4371c7e2018-08-01 18:40:05 +0530547 return hc_service_units
Jamsheer5073ac42019-07-12 12:28:34 +0530548
Rucha Mahabal27512c82020-03-09 17:29:23 +0530549
Jamsheer5073ac42019-07-12 12:28:34 +0530550@frappe.whitelist()
551def get_patient_vitals(patient, from_date=None, to_date=None):
552 if not patient: return
Rucha Mahabal27512c82020-03-09 17:29:23 +0530553
Rucha Mahabal4dd6b992020-05-25 18:42:01 +0530554 vitals = frappe.db.get_all('Vital Signs', filters={
Rucha Mahabal27512c82020-03-09 17:29:23 +0530555 'docstatus': 1,
556 'patient': patient
Rucha Mahabal4dd6b992020-05-25 18:42:01 +0530557 }, order_by='signs_date, signs_time', fields=['*'])
Rucha Mahabal27512c82020-03-09 17:29:23 +0530558
559 if len(vitals):
Jamsheer5073ac42019-07-12 12:28:34 +0530560 return vitals
Rucha Mahabal27512c82020-03-09 17:29:23 +0530561 return False
562
Jamsheer5073ac42019-07-12 12:28:34 +0530563
564@frappe.whitelist()
565def render_docs_as_html(docs):
566 # docs key value pair {doctype: docname}
567 docs_html = "<div class='col-md-12 col-sm-12 text-muted'>"
568 for doc in docs:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530569 docs_html += render_doc_as_html(doc['doctype'], doc['docname'])['html'] + '<br/>'
Jamsheer5073ac42019-07-12 12:28:34 +0530570 return {'html': docs_html}
571
Rucha Mahabal27512c82020-03-09 17:29:23 +0530572
Jamsheer5073ac42019-07-12 12:28:34 +0530573@frappe.whitelist()
574def render_doc_as_html(doctype, docname, exclude_fields = []):
575 #render document as html, three column layout will break
576 doc = frappe.get_doc(doctype, docname)
577 meta = frappe.get_meta(doctype)
578 doc_html = "<div class='col-md-12 col-sm-12'>"
Rucha Mahabal27512c82020-03-09 17:29:23 +0530579 section_html = ''
580 section_label = ''
581 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530582 sec_on = False
583 col_on = 0
584 has_data = False
585 for df in meta.fields:
586 #on section break append append previous section and html to doc html
587 if df.fieldtype == "Section Break":
588 if has_data and col_on and sec_on:
589 doc_html += section_html + html + "</div>"
590 elif has_data and not col_on and sec_on:
591 doc_html += "<div class='col-md-12 col-sm-12'\
592 ><div class='col-md-12 col-sm-12'>" \
593 + section_html + html +"</div></div>"
594 while col_on:
595 doc_html += "</div>"
596 col_on -= 1
597 sec_on = True
598 has_data= False
599 col_on = 0
Rucha Mahabal27512c82020-03-09 17:29:23 +0530600 section_html = ''
601 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530602 if df.label:
603 section_label = df.label
604 continue
605 #on column break append html to section html or doc html
606 if df.fieldtype == "Column Break":
607 if sec_on and has_data:
608 section_html += "<div class='col-md-12 col-sm-12'\
609 ><div class='col-md-6 col\
610 -sm-6'><b>" + section_label + "</b>" + html + "</div><div \
611 class='col-md-6 col-sm-6'>"
612 elif has_data:
613 doc_html += "<div class='col-md-12 col-sm-12'><div class='col-m\
614 d-6 col-sm-6'>" + html + "</div><div class='col-md-6 col-sm-6'>"
615 elif sec_on and not col_on:
616 section_html += "<div class='col-md-6 col-sm-6'>"
Rucha Mahabal27512c82020-03-09 17:29:23 +0530617 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530618 col_on += 1
619 if df.label:
620 html += '<br>' + df.label
621 continue
622 #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 +0530623 if df.fieldtype == 'Table':
Jamsheer5073ac42019-07-12 12:28:34 +0530624 items = doc.get(df.fieldname)
625 if not items: continue
626 child_meta = frappe.get_meta(df.options)
627 if not has_data : has_data = True
Rucha Mahabal27512c82020-03-09 17:29:23 +0530628 table_head = ''
629 table_row = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530630 create_head = True
631 for item in items:
632 table_row += '<tr>'
633 for cdf in child_meta.fields:
634 if cdf.in_list_view:
635 if create_head:
636 table_head += '<th>' + cdf.label + '</th>'
637 if item.get(cdf.fieldname):
638 table_row += '<td>' + str(item.get(cdf.fieldname)) \
639 + '</td>'
640 else:
641 table_row += '<td></td>'
642 create_head = False
643 table_row += '</tr>'
644 if sec_on:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530645 section_html += "<table class='table table-condensed \
646 bordered'>" + table_head + table_row + '</table>'
Jamsheer5073ac42019-07-12 12:28:34 +0530647 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530648 html += "<table class='table table-condensed table-bordered'>" \
649 + table_head + table_row + "</table>"
Jamsheer5073ac42019-07-12 12:28:34 +0530650 continue
651 #on other field types add label and value to html
652 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 +0530653 html += '<br>{0} : {1}'.format(df.label or df.fieldname, \
Jamsheer5073ac42019-07-12 12:28:34 +0530654 doc.get(df.fieldname))
655 if not has_data : has_data = True
656 if sec_on and col_on and has_data:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530657 doc_html += section_html + html + '</div></div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530658 elif sec_on and not col_on and has_data:
659 doc_html += "<div class='col-md-12 col-sm-12'\
660 ><div class='col-md-12 col-sm-12'>" \
Rucha Mahabal27512c82020-03-09 17:29:23 +0530661 + section_html + html +'</div></div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530662 if doc_html:
Rushabh Mehta542bc012020-11-18 15:00:34 +0530663 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 +0530664
665 return {'html': doc_html}