blob: dbd3b83f09b2e3f4782d36dd12710b1b9ba89680 [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 Mahabald7304512020-04-23 00:52:47 +053026 items_to_invoice += get_therapy_sessions_to_invoice(patient, company)
Jamsheerba119722018-07-06 15:58:13 +053027
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")
35 msg += " <b><a href='#Form/Patient/{0}'>{0}</a></b>".format(patient.name)
36 frappe.throw(msg, title=_('Customer Not Found'))
Jamsheer8da6f4e2018-07-26 21:03:17 +053037
anoop93d0c782020-04-13 16:42:03 +053038def get_appointments_to_invoice(patient, company):
39 appointments_to_invoice = []
40 patient_appointments = frappe.get_list(
41 'Patient Appointment',
42 fields = '*',
anoop59030022020-07-28 21:15:54 +053043 filters = {'patient': patient.name, 'company': company, 'invoiced': 0, 'status': ['not in', 'Cancelled']},
anoop93d0c782020-04-13 16:42:03 +053044 order_by = 'appointment_date'
45 )
46
Rucha Mahabal27512c82020-03-09 17:29:23 +053047 for appointment in patient_appointments:
anoop93d0c782020-04-13 16:42:03 +053048 # Procedure Appointments
Rucha Mahabal27512c82020-03-09 17:29:23 +053049 if appointment.procedure_template:
50 if frappe.db.get_value('Clinical Procedure Template', appointment.procedure_template, 'is_billable'):
anoop93d0c782020-04-13 16:42:03 +053051 appointments_to_invoice.append({
Rucha Mahabal27512c82020-03-09 17:29:23 +053052 'reference_type': 'Patient Appointment',
53 'reference_name': appointment.name,
54 'service': appointment.procedure_template
55 })
anoop93d0c782020-04-13 16:42:03 +053056 # Consultation Appointments, should check fee validity
Jamsheerba119722018-07-06 15:58:13 +053057 else:
anoop93d0c782020-04-13 16:42:03 +053058 if frappe.db.get_single_value('Healthcare Settings', 'enable_free_follow_ups') and \
59 frappe.db.exists('Fee Validity Reference', {'appointment': appointment.name}):
60 continue # Skip invoicing, fee validty present
61 practitioner_charge = 0
62 income_account = None
63 service_item = None
64 if appointment.practitioner:
65 service_item, practitioner_charge = get_service_item_and_practitioner_charge(appointment)
66 income_account = get_income_account(appointment.practitioner, appointment.company)
67 appointments_to_invoice.append({
68 'reference_type': 'Patient Appointment',
69 'reference_name': appointment.name,
70 'service': service_item,
71 'rate': practitioner_charge,
72 'income_account': income_account
73 })
Rucha Mahabal27512c82020-03-09 17:29:23 +053074
anoop93d0c782020-04-13 16:42:03 +053075 return appointments_to_invoice
Rucha Mahabal27512c82020-03-09 17:29:23 +053076
77
anoop93d0c782020-04-13 16:42:03 +053078def get_encounters_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +053079 encounters_to_invoice = []
80 encounters = frappe.get_list(
81 'Patient Encounter',
82 fields=['*'],
anoop93d0c782020-04-13 16:42:03 +053083 filters={'patient': patient.name, 'company': company, 'invoiced': False, 'docstatus': 1}
Rucha Mahabal27512c82020-03-09 17:29:23 +053084 )
85 if encounters:
86 for encounter in encounters:
87 if not encounter.appointment:
88 practitioner_charge = 0
89 income_account = None
90 service_item = None
91 if encounter.practitioner:
92 service_item, practitioner_charge = get_service_item_and_practitioner_charge(encounter)
93 income_account = get_income_account(encounter.practitioner, encounter.company)
94
95 encounters_to_invoice.append({
96 'reference_type': 'Patient Encounter',
97 'reference_name': encounter.name,
98 'service': service_item,
99 'rate': practitioner_charge,
100 'income_account': income_account
101 })
102
103 return encounters_to_invoice
104
105
anoop93d0c782020-04-13 16:42:03 +0530106def get_lab_tests_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530107 lab_tests_to_invoice = []
108 lab_tests = frappe.get_list(
109 'Lab Test',
110 fields=['name', 'template'],
anoop93d0c782020-04-13 16:42:03 +0530111 filters={'patient': patient.name, 'company': company, 'invoiced': False, 'docstatus': 1}
Rucha Mahabal27512c82020-03-09 17:29:23 +0530112 )
113 for lab_test in lab_tests:
Rucha Mahabal131452c2020-04-27 10:52:38 +0530114 item, is_billable = frappe.get_cached_value('Lab Test Template', lab_test.template, ['item', 'is_billable'])
Rucha Mahabalced978e2020-04-02 18:45:53 +0530115 if is_billable:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530116 lab_tests_to_invoice.append({
117 'reference_type': 'Lab Test',
118 'reference_name': lab_test.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530119 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530120 })
121
Rucha Mahabalced978e2020-04-02 18:45:53 +0530122 lab_prescriptions = frappe.db.sql(
123 '''
124 SELECT
125 lp.name, lp.lab_test_code
126 FROM
127 `tabPatient Encounter` et, `tabLab Prescription` lp
128 WHERE
129 et.patient=%s
130 and lp.parent=et.name
131 and lp.lab_test_created=0
132 and lp.invoiced=0
133 ''', (patient.name), as_dict=1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530134
135 for prescription in lab_prescriptions:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530136 item, is_billable = frappe.get_cached_value('Lab Test Template', prescription.lab_test_code, ['item', 'is_billable'])
137 if prescription.lab_test_code and is_billable:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530138 lab_tests_to_invoice.append({
139 'reference_type': 'Lab Prescription',
140 'reference_name': prescription.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530141 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530142 })
143
144 return lab_tests_to_invoice
145
146
anoop93d0c782020-04-13 16:42:03 +0530147def get_clinical_procedures_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530148 clinical_procedures_to_invoice = []
149 procedures = frappe.get_list(
150 'Clinical Procedure',
151 fields='*',
anoop93d0c782020-04-13 16:42:03 +0530152 filters={'patient': patient.name, 'company': company, 'invoiced': False}
Rucha Mahabal27512c82020-03-09 17:29:23 +0530153 )
154 for procedure in procedures:
155 if not procedure.appointment:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530156 item, is_billable = frappe.get_cached_value('Clinical Procedure Template', procedure.procedure_template, ['item', 'is_billable'])
157 if procedure.procedure_template and is_billable:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530158 clinical_procedures_to_invoice.append({
159 'reference_type': 'Clinical Procedure',
160 'reference_name': procedure.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530161 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530162 })
163
164 # consumables
165 if procedure.invoice_separately_as_consumables and procedure.consume_stock \
166 and procedure.status == 'Completed' and not procedure.consumption_invoiced:
167
168 service_item = get_healthcare_service_item('clinical_procedure_consumable_item')
169 if not service_item:
170 msg = _('Please Configure Clinical Procedure Consumable Item in ')
171 msg += '''<b><a href='#Form/Healthcare Settings'>Healthcare Settings</a></b>'''
172 frappe.throw(msg, title=_('Missing Configuration'))
173
174 clinical_procedures_to_invoice.append({
175 'reference_type': 'Clinical Procedure',
176 'reference_name': procedure.name,
177 'service': service_item,
178 'rate': procedure.consumable_total_amount,
179 'description': procedure.consumption_details
180 })
181
Rucha Mahabalced978e2020-04-02 18:45:53 +0530182 procedure_prescriptions = frappe.db.sql(
183 '''
184 SELECT
185 pp.name, pp.procedure
186 FROM
187 `tabPatient Encounter` et, `tabProcedure Prescription` pp
188 WHERE
189 et.patient=%s
190 and pp.parent=et.name
191 and pp.procedure_created=0
192 and pp.invoiced=0
193 and pp.appointment_booked=0
194 ''', (patient.name), as_dict=1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530195
196 for prescription in procedure_prescriptions:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530197 item, is_billable = frappe.get_cached_value('Clinical Procedure Template', prescription.procedure, ['item', 'is_billable'])
198 if is_billable:
Rucha Mahabal197165f2020-03-26 17:29:50 +0530199 clinical_procedures_to_invoice.append({
Rucha Mahabal27512c82020-03-09 17:29:23 +0530200 'reference_type': 'Procedure Prescription',
201 'reference_name': prescription.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530202 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530203 })
204
205 return clinical_procedures_to_invoice
206
207
anoop93d0c782020-04-13 16:42:03 +0530208def get_inpatient_services_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530209 services_to_invoice = []
Rucha Mahabalced978e2020-04-02 18:45:53 +0530210 inpatient_services = frappe.db.sql(
211 '''
212 SELECT
213 io.*
214 FROM
215 `tabInpatient Record` ip, `tabInpatient Occupancy` io
216 WHERE
217 ip.patient=%s
anoop93d0c782020-04-13 16:42:03 +0530218 and ip.company=%s
Rucha Mahabalced978e2020-04-02 18:45:53 +0530219 and io.parent=ip.name
220 and io.left=1
221 and io.invoiced=0
anoop93d0c782020-04-13 16:42:03 +0530222 ''', (patient.name, company), as_dict=1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530223
224 for inpatient_occupancy in inpatient_services:
225 service_unit_type = frappe.db.get_value('Healthcare Service Unit', inpatient_occupancy.service_unit, 'service_unit_type')
Rucha Mahabalced978e2020-04-02 18:45:53 +0530226 service_unit_type = frappe.get_cached_doc('Healthcare Service Unit Type', service_unit_type)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530227 if service_unit_type and service_unit_type.is_billable:
228 hours_occupied = time_diff_in_hours(inpatient_occupancy.check_out, inpatient_occupancy.check_in)
229 qty = 0.5
230 if hours_occupied > 0:
231 actual_qty = hours_occupied / service_unit_type.no_of_hours
232 floor = math.floor(actual_qty)
233 decimal_part = actual_qty - floor
234 if decimal_part > 0.5:
235 qty = rounded(floor + 1, 1)
236 elif decimal_part < 0.5 and decimal_part > 0:
237 qty = rounded(floor + 0.5, 1)
238 if qty <= 0:
239 qty = 0.5
240 services_to_invoice.append({
241 'reference_type': 'Inpatient Occupancy',
242 'reference_name': inpatient_occupancy.name,
243 'service': service_unit_type.item, 'qty': qty
244 })
245
246 return services_to_invoice
247
Jamsheerba119722018-07-06 15:58:13 +0530248
Rucha Mahabald7304512020-04-23 00:52:47 +0530249def get_therapy_sessions_to_invoice(patient, company):
Rucha Mahabaleaa956b2020-04-22 13:07:12 +0530250 therapy_sessions_to_invoice = []
251 therapy_sessions = frappe.get_list(
252 'Therapy Session',
253 fields='*',
Rucha Mahabald7304512020-04-23 00:52:47 +0530254 filters={'patient': patient.name, 'invoiced': 0, 'company': company}
Rucha Mahabaleaa956b2020-04-22 13:07:12 +0530255 )
256 for therapy in therapy_sessions:
257 if not therapy.appointment:
258 if therapy.therapy_type and frappe.db.get_value('Therapy Type', therapy.therapy_type, 'is_billable'):
259 therapy_sessions_to_invoice.append({
260 'reference_type': 'Therapy Session',
261 'reference_name': therapy.name,
262 'service': frappe.db.get_value('Therapy Type', therapy.therapy_type, 'item')
263 })
264
265 return therapy_sessions_to_invoice
266
267
Rucha Mahabal24055e12020-02-24 19:09:50 +0530268def get_service_item_and_practitioner_charge(doc):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530269 is_inpatient = doc.inpatient_record
Rucha Mahabal24055e12020-02-24 19:09:50 +0530270 if is_inpatient:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530271 service_item = get_practitioner_service_item(doc.practitioner, 'inpatient_visit_charge_item')
Jamsheeree5f9c72018-07-30 12:42:06 +0530272 if not service_item:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530273 service_item = get_healthcare_service_item('inpatient_visit_charge_item')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530274 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530275 service_item = get_practitioner_service_item(doc.practitioner, 'op_consulting_charge_item')
Jamsheeree5f9c72018-07-30 12:42:06 +0530276 if not service_item:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530277 service_item = get_healthcare_service_item('op_consulting_charge_item')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530278 if not service_item:
Rucha Mahabal24055e12020-02-24 19:09:50 +0530279 throw_config_service_item(is_inpatient)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530280
Rucha Mahabal24055e12020-02-24 19:09:50 +0530281 practitioner_charge = get_practitioner_charge(doc.practitioner, is_inpatient)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530282 if not practitioner_charge:
Rucha Mahabal24055e12020-02-24 19:09:50 +0530283 throw_config_practitioner_charge(is_inpatient, doc.practitioner)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530284
285 return service_item, practitioner_charge
286
Jamsheer8da6f4e2018-07-26 21:03:17 +0530287
Rucha Mahabal27512c82020-03-09 17:29:23 +0530288def throw_config_service_item(is_inpatient):
Rucha Mahabalced978e2020-04-02 18:45:53 +0530289 service_item_label = _('Out Patient Consulting Charge Item')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530290 if is_inpatient:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530291 service_item_label = _('Inpatient Visit Charge Item')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530292
Rucha Mahabal4f9a1472020-03-23 10:40:39 +0530293 msg = _(('Please Configure {0} in ').format(service_item_label) \
Rucha Mahabal27512c82020-03-09 17:29:23 +0530294 + '''<b><a href='#Form/Healthcare Settings'>Healthcare Settings</a></b>''')
295 frappe.throw(msg, title=_('Missing Configuration'))
296
Jamsheer8da6f4e2018-07-26 21:03:17 +0530297
Rucha Mahabal24055e12020-02-24 19:09:50 +0530298def throw_config_practitioner_charge(is_inpatient, practitioner):
Rucha Mahabalced978e2020-04-02 18:45:53 +0530299 charge_name = _('OP Consulting Charge')
Rucha Mahabal24055e12020-02-24 19:09:50 +0530300 if is_inpatient:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530301 charge_name = _('Inpatient Visit Charge')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530302
Rucha Mahabal27512c82020-03-09 17:29:23 +0530303 msg = _(('Please Configure {0} for Healthcare Practitioner').format(charge_name) \
304 + ''' <b><a href='#Form/Healthcare Practitioner/{0}'>{0}</a></b>'''.format(practitioner))
305 frappe.throw(msg, title=_('Missing Configuration'))
306
Jamsheer8da6f4e2018-07-26 21:03:17 +0530307
Jamsheeree5f9c72018-07-30 12:42:06 +0530308def get_practitioner_service_item(practitioner, service_item_field):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530309 return frappe.db.get_value('Healthcare Practitioner', practitioner, service_item_field)
310
Jamsheeree5f9c72018-07-30 12:42:06 +0530311
Jamsheer8da6f4e2018-07-26 21:03:17 +0530312def get_healthcare_service_item(service_item_field):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530313 return frappe.db.get_single_value('Healthcare Settings', service_item_field)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530314
Jamsheer8da6f4e2018-07-26 21:03:17 +0530315
Rucha Mahabal24055e12020-02-24 19:09:50 +0530316def get_practitioner_charge(practitioner, is_inpatient):
317 if is_inpatient:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530318 practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, 'inpatient_visit_charge')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530319 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530320 practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, 'op_consulting_charge')
Jamsheerba119722018-07-06 15:58:13 +0530321 if practitioner_charge:
322 return practitioner_charge
Jamsheer8da6f4e2018-07-26 21:03:17 +0530323 return False
Jamsheerba119722018-07-06 15:58:13 +0530324
Rucha Mahabal27512c82020-03-09 17:29:23 +0530325
Jamsheerba119722018-07-06 15:58:13 +0530326def manage_invoice_submit_cancel(doc, method):
327 if doc.items:
328 for item in doc.items:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530329 if item.get('reference_dt') and item.get('reference_dn'):
330 if frappe.get_meta(item.reference_dt).has_field('invoiced'):
Jamsheer146683b2018-07-25 11:30:30 +0530331 set_invoiced(item, method, doc.name)
Jamsheerba119722018-07-06 15:58:13 +0530332
Rucha Mahabal27512c82020-03-09 17:29:23 +0530333 if method=='on_submit' and frappe.db.get_single_value('Healthcare Settings', 'create_lab_test_on_si_submit'):
334 create_multiple('Sales Invoice', doc.name)
335
Jamsheer0ae100b2018-08-01 14:29:43 +0530336
Jamsheer146683b2018-07-25 11:30:30 +0530337def set_invoiced(item, method, ref_invoice=None):
Jamsheerba119722018-07-06 15:58:13 +0530338 invoiced = False
Rucha Mahabal27512c82020-03-09 17:29:23 +0530339 if method=='on_submit':
Jamsheerba119722018-07-06 15:58:13 +0530340 validate_invoiced_on_submit(item)
341 invoiced = True
342
Jamsheer8da6f4e2018-07-26 21:03:17 +0530343 if item.reference_dt == 'Clinical Procedure':
344 if get_healthcare_service_item('clinical_procedure_consumable_item') == item.item_code:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530345 frappe.db.set_value(item.reference_dt, item.reference_dn, 'consumption_invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530346 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530347 frappe.db.set_value(item.reference_dt, item.reference_dn, 'invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530348 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530349 frappe.db.set_value(item.reference_dt, item.reference_dn, 'invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530350
Jamsheerba119722018-07-06 15:58:13 +0530351 if item.reference_dt == 'Patient Appointment':
352 if frappe.db.get_value('Patient Appointment', item.reference_dn, 'procedure_template'):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530353 dt_from_appointment = 'Clinical Procedure'
Jamsheerba119722018-07-06 15:58:13 +0530354 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530355 dt_from_appointment = 'Patient Encounter'
Rucha Mahabal06d1b042020-03-12 12:16:23 +0530356 manage_doc_for_appointment(dt_from_appointment, item.reference_dn, invoiced)
Jamsheerba119722018-07-06 15:58:13 +0530357
358 elif item.reference_dt == 'Lab Prescription':
Rucha Mahabal27512c82020-03-09 17:29:23 +0530359 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, 'Lab Test', 'lab_test_created')
Jamsheerba119722018-07-06 15:58:13 +0530360
361 elif item.reference_dt == 'Procedure Prescription':
Rucha Mahabal27512c82020-03-09 17:29:23 +0530362 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, 'Clinical Procedure', 'procedure_created')
363
Jamsheerba119722018-07-06 15:58:13 +0530364
365def validate_invoiced_on_submit(item):
Jamsheer8da6f4e2018-07-26 21:03:17 +0530366 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 +0530367 is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, 'consumption_invoiced')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530368 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530369 is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, 'invoiced')
370 if is_invoiced:
371 frappe.throw(_('The item referenced by {0} - {1} is already invoiced'\
Jamsheerba119722018-07-06 15:58:13 +0530372 ).format(item.reference_dt, item.reference_dn))
373
Rucha Mahabal27512c82020-03-09 17:29:23 +0530374
Jamsheerba119722018-07-06 15:58:13 +0530375def manage_prescriptions(invoiced, ref_dt, ref_dn, dt, created_check_field):
376 created = frappe.db.get_value(ref_dt, ref_dn, created_check_field)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530377 if created:
Jamsheerba119722018-07-06 15:58:13 +0530378 # Fetch the doc created for the prescription
Jamsheereafb0462018-07-25 13:15:12 +0530379 doc_created = frappe.db.get_value(dt, {'prescription': ref_dn})
Jamsheerba119722018-07-06 15:58:13 +0530380 frappe.db.set_value(dt, doc_created, 'invoiced', invoiced)
381
Rucha Mahabal27512c82020-03-09 17:29:23 +0530382
Rucha Mahabalcd319962020-03-13 15:39:31 +0530383def check_fee_validity(appointment):
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530384 if not frappe.db.get_single_value('Healthcare Settings', 'enable_free_follow_ups'):
385 return
386
Rucha Mahabalcd319962020-03-13 15:39:31 +0530387 validity = frappe.db.exists('Fee Validity', {
388 'practitioner': appointment.practitioner,
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530389 'patient': appointment.patient,
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530390 'valid_till': ('>=', appointment.appointment_date)
Rucha Mahabalcd319962020-03-13 15:39:31 +0530391 })
392 if not validity:
393 return
394
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530395 validity = frappe.get_doc('Fee Validity', validity)
396 return validity
397
Rucha Mahabal27512c82020-03-09 17:29:23 +0530398
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530399def manage_fee_validity(appointment):
400 fee_validity = check_fee_validity(appointment)
anoop93d0c782020-04-13 16:42:03 +0530401
Rucha Mahabalcd319962020-03-13 15:39:31 +0530402 if fee_validity:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530403 if appointment.status == 'Cancelled' and fee_validity.visited > 0:
404 fee_validity.visited -= 1
405 frappe.db.delete('Fee Validity Reference', {'appointment': appointment.name})
Rucha Mahabal2cec6bd2020-03-26 14:38:12 +0530406 elif fee_validity.status == 'Completed':
407 return
Rucha Mahabalcd319962020-03-13 15:39:31 +0530408 else:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530409 fee_validity.visited += 1
410 fee_validity.append('ref_appointments', {
411 'appointment': appointment.name
412 })
413 fee_validity.save(ignore_permissions=True)
Jamsheerba119722018-07-06 15:58:13 +0530414 else:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530415 fee_validity = create_fee_validity(appointment)
416 return fee_validity
Rucha Mahabal27512c82020-03-09 17:29:23 +0530417
Jamsheerba119722018-07-06 15:58:13 +0530418
Rucha Mahabal06d1b042020-03-12 12:16:23 +0530419def manage_doc_for_appointment(dt_from_appointment, appointment, invoiced):
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530420 dn_from_appointment = frappe.db.get_value(
421 dt_from_appointment,
Rucha Mahabal27512c82020-03-09 17:29:23 +0530422 filters={'appointment': appointment}
Jamsheerba119722018-07-06 15:58:13 +0530423 )
424 if dn_from_appointment:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530425 frappe.db.set_value(dt_from_appointment, dn_from_appointment, 'invoiced', invoiced)
426
Jamsheere82f27a2018-07-30 11:28:37 +0530427
428@frappe.whitelist()
429def get_drugs_to_invoice(encounter):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530430 encounter = frappe.get_doc('Patient Encounter', encounter)
Jamsheere82f27a2018-07-30 11:28:37 +0530431 if encounter:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530432 patient = frappe.get_doc('Patient', encounter.patient)
433 if patient:
434 if patient.customer:
435 items_to_invoice = []
Jamsheere82f27a2018-07-30 11:28:37 +0530436 for drug_line in encounter.drug_prescription:
437 if drug_line.drug_code:
438 qty = 1
Rucha Mahabal27512c82020-03-09 17:29:23 +0530439 if frappe.db.get_value('Item', drug_line.drug_code, 'stock_uom') == 'Nos':
Jamsheere82f27a2018-07-30 11:28:37 +0530440 qty = drug_line.get_quantity()
Rucha Mahabal27512c82020-03-09 17:29:23 +0530441
442 description = ''
443 if drug_line.dosage and drug_line.period:
444 description = _('{0} for {1}').format(drug_line.dosage, drug_line.period)
445
446 items_to_invoice.append({
447 'drug_code': drug_line.drug_code,
448 'quantity': qty,
449 'description': description
450 })
451 return items_to_invoice
452 else:
453 validate_customer_created(patient)
454
Jamsheer4371c7e2018-08-01 18:40:05 +0530455
456@frappe.whitelist()
457def get_children(doctype, parent, company, is_root=False):
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530458 parent_fieldname = "parent_" + doctype.lower().replace(" ", "_")
Jamsheer4371c7e2018-08-01 18:40:05 +0530459 fields = [
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530460 "name as value",
461 "is_group as expandable",
462 "lft",
463 "rgt"
Jamsheer4371c7e2018-08-01 18:40:05 +0530464 ]
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530465 # fields = [ "name", "is_group", "lft", "rgt" ]
466 filters = [["ifnull(`{0}`,'')".format(parent_fieldname), "=", "" if is_root else parent]]
Jamsheer4371c7e2018-08-01 18:40:05 +0530467
468 if is_root:
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530469 fields += ["service_unit_type"] if doctype == "Healthcare Service Unit" else []
470 filters.append(["company", "=", company])
Jamsheer4371c7e2018-08-01 18:40:05 +0530471
472 else:
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530473 fields += ["service_unit_type", "allow_appointments", "inpatient_occupancy", "occupancy_status"] if doctype == "Healthcare Service Unit" else []
474 fields += [parent_fieldname + " as parent"]
Jamsheer4371c7e2018-08-01 18:40:05 +0530475
476 hc_service_units = frappe.get_list(doctype, fields=fields, filters=filters)
477
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530478 if doctype == "Healthcare Service Unit":
Jamsheer4371c7e2018-08-01 18:40:05 +0530479 for each in hc_service_units:
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530480 occupancy_msg = ""
481 if each["expandable"] == 1:
Jamsheer4371c7e2018-08-01 18:40:05 +0530482 occupied = False
483 vacant = False
Rucha Mahabalced978e2020-04-02 18:45:53 +0530484 child_list = frappe.db.sql(
485 '''
486 SELECT
487 name, occupancy_status
488 FROM
489 `tabHealthcare Service Unit`
490 WHERE
491 inpatient_occupancy = 1
492 and lft > %s and rgt < %s
493 ''', (each['lft'], each['rgt']))
494
Jamsheer4371c7e2018-08-01 18:40:05 +0530495 for child in child_list:
Jamsheer4371c7e2018-08-01 18:40:05 +0530496 if not occupied:
497 occupied = 0
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530498 if child[1] == "Occupied":
Jamsheer4371c7e2018-08-01 18:40:05 +0530499 occupied += 1
500 if not vacant:
501 vacant = 0
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530502 if child[1] == "Vacant":
Jamsheer4371c7e2018-08-01 18:40:05 +0530503 vacant += 1
504 if vacant and occupied:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530505 occupancy_total = vacant + occupied
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530506 occupancy_msg = str(occupied) + " Occupied out of " + str(occupancy_total)
507 each["occupied_out_of_vacant"] = occupancy_msg
Jamsheer4371c7e2018-08-01 18:40:05 +0530508 return hc_service_units
Jamsheer5073ac42019-07-12 12:28:34 +0530509
Rucha Mahabal27512c82020-03-09 17:29:23 +0530510
Jamsheer5073ac42019-07-12 12:28:34 +0530511@frappe.whitelist()
512def get_patient_vitals(patient, from_date=None, to_date=None):
513 if not patient: return
Rucha Mahabal27512c82020-03-09 17:29:23 +0530514
Rucha Mahabal4dd6b992020-05-25 18:42:01 +0530515 vitals = frappe.db.get_all('Vital Signs', filters={
Rucha Mahabal27512c82020-03-09 17:29:23 +0530516 'docstatus': 1,
517 'patient': patient
Rucha Mahabal4dd6b992020-05-25 18:42:01 +0530518 }, order_by='signs_date, signs_time', fields=['*'])
Rucha Mahabal27512c82020-03-09 17:29:23 +0530519
520 if len(vitals):
Jamsheer5073ac42019-07-12 12:28:34 +0530521 return vitals
Rucha Mahabal27512c82020-03-09 17:29:23 +0530522 return False
523
Jamsheer5073ac42019-07-12 12:28:34 +0530524
525@frappe.whitelist()
526def render_docs_as_html(docs):
527 # docs key value pair {doctype: docname}
528 docs_html = "<div class='col-md-12 col-sm-12 text-muted'>"
529 for doc in docs:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530530 docs_html += render_doc_as_html(doc['doctype'], doc['docname'])['html'] + '<br/>'
Jamsheer5073ac42019-07-12 12:28:34 +0530531 return {'html': docs_html}
532
Rucha Mahabal27512c82020-03-09 17:29:23 +0530533
Jamsheer5073ac42019-07-12 12:28:34 +0530534@frappe.whitelist()
535def render_doc_as_html(doctype, docname, exclude_fields = []):
536 #render document as html, three column layout will break
537 doc = frappe.get_doc(doctype, docname)
538 meta = frappe.get_meta(doctype)
539 doc_html = "<div class='col-md-12 col-sm-12'>"
Rucha Mahabal27512c82020-03-09 17:29:23 +0530540 section_html = ''
541 section_label = ''
542 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530543 sec_on = False
544 col_on = 0
545 has_data = False
546 for df in meta.fields:
547 #on section break append append previous section and html to doc html
548 if df.fieldtype == "Section Break":
549 if has_data and col_on and sec_on:
550 doc_html += section_html + html + "</div>"
551 elif has_data and not col_on and sec_on:
552 doc_html += "<div class='col-md-12 col-sm-12'\
553 ><div class='col-md-12 col-sm-12'>" \
554 + section_html + html +"</div></div>"
555 while col_on:
556 doc_html += "</div>"
557 col_on -= 1
558 sec_on = True
559 has_data= False
560 col_on = 0
Rucha Mahabal27512c82020-03-09 17:29:23 +0530561 section_html = ''
562 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530563 if df.label:
564 section_label = df.label
565 continue
566 #on column break append html to section html or doc html
567 if df.fieldtype == "Column Break":
568 if sec_on and has_data:
569 section_html += "<div class='col-md-12 col-sm-12'\
570 ><div class='col-md-6 col\
571 -sm-6'><b>" + section_label + "</b>" + html + "</div><div \
572 class='col-md-6 col-sm-6'>"
573 elif has_data:
574 doc_html += "<div class='col-md-12 col-sm-12'><div class='col-m\
575 d-6 col-sm-6'>" + html + "</div><div class='col-md-6 col-sm-6'>"
576 elif sec_on and not col_on:
577 section_html += "<div class='col-md-6 col-sm-6'>"
Rucha Mahabal27512c82020-03-09 17:29:23 +0530578 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530579 col_on += 1
580 if df.label:
581 html += '<br>' + df.label
582 continue
583 #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 +0530584 if df.fieldtype == 'Table':
Jamsheer5073ac42019-07-12 12:28:34 +0530585 items = doc.get(df.fieldname)
586 if not items: continue
587 child_meta = frappe.get_meta(df.options)
588 if not has_data : has_data = True
Rucha Mahabal27512c82020-03-09 17:29:23 +0530589 table_head = ''
590 table_row = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530591 create_head = True
592 for item in items:
593 table_row += '<tr>'
594 for cdf in child_meta.fields:
595 if cdf.in_list_view:
596 if create_head:
597 table_head += '<th>' + cdf.label + '</th>'
598 if item.get(cdf.fieldname):
599 table_row += '<td>' + str(item.get(cdf.fieldname)) \
600 + '</td>'
601 else:
602 table_row += '<td></td>'
603 create_head = False
604 table_row += '</tr>'
605 if sec_on:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530606 section_html += "<table class='table table-condensed \
607 bordered'>" + table_head + table_row + '</table>'
Jamsheer5073ac42019-07-12 12:28:34 +0530608 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530609 html += "<table class='table table-condensed table-bordered'>" \
610 + table_head + table_row + "</table>"
Jamsheer5073ac42019-07-12 12:28:34 +0530611 continue
612 #on other field types add label and value to html
613 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 +0530614 html += '<br>{0} : {1}'.format(df.label or df.fieldname, \
Jamsheer5073ac42019-07-12 12:28:34 +0530615 doc.get(df.fieldname))
616 if not has_data : has_data = True
617 if sec_on and col_on and has_data:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530618 doc_html += section_html + html + '</div></div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530619 elif sec_on and not col_on and has_data:
620 doc_html += "<div class='col-md-12 col-sm-12'\
621 ><div class='col-md-12 col-sm-12'>" \
Rucha Mahabal27512c82020-03-09 17:29:23 +0530622 + section_html + html +'</div></div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530623 if doc_html:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530624 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 +0530625
626 return {'html': doc_html}