blob: 6b495a4eac91d7fb0848e8fcdd97d6eb167f1022 [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 Mahabal5e3c51b2020-11-30 13:35:00 +05309from frappe.utils.formatters import format_value
Rucha Mahabal197165f2020-03-26 17:29:50 +053010from frappe.utils import time_diff_in_hours, rounded
Jamsheerba119722018-07-06 15:58:13 +053011from erpnext.healthcare.doctype.healthcare_settings.healthcare_settings import get_income_account
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +053012from erpnext.healthcare.doctype.fee_validity.fee_validity import create_fee_validity
Jamsheer0ae100b2018-08-01 14:29:43 +053013from erpnext.healthcare.doctype.lab_test.lab_test import create_multiple
Jamsheerba119722018-07-06 15:58:13 +053014
15@frappe.whitelist()
anoop93d0c782020-04-13 16:42:03 +053016def get_healthcare_services_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +053017 patient = frappe.get_doc('Patient', patient)
anoop93d0c782020-04-13 16:42:03 +053018 items_to_invoice = []
Jamsheerba119722018-07-06 15:58:13 +053019 if patient:
Rucha Mahabal27512c82020-03-09 17:29:23 +053020 validate_customer_created(patient)
anoop93d0c782020-04-13 16:42:03 +053021 # Customer validated, build a list of billable services
22 items_to_invoice += get_appointments_to_invoice(patient, company)
23 items_to_invoice += get_encounters_to_invoice(patient, company)
24 items_to_invoice += get_lab_tests_to_invoice(patient, company)
25 items_to_invoice += get_clinical_procedures_to_invoice(patient, company)
26 items_to_invoice += get_inpatient_services_to_invoice(patient, company)
Rucha Mahabal434791e2020-10-24 14:20:38 +053027 items_to_invoice += get_therapy_plans_to_invoice(patient, company)
Rucha Mahabald7304512020-04-23 00:52:47 +053028 items_to_invoice += get_therapy_sessions_to_invoice(patient, company)
Jamsheerba119722018-07-06 15:58:13 +053029
Rucha Mahabal27512c82020-03-09 17:29:23 +053030 return items_to_invoice
Jamsheerba119722018-07-06 15:58:13 +053031
anoop93d0c782020-04-13 16:42:03 +053032
Rucha Mahabal27512c82020-03-09 17:29:23 +053033def validate_customer_created(patient):
34 if not frappe.db.get_value('Patient', patient.name, 'customer'):
35 msg = _("Please set a Customer linked to the Patient")
36 msg += " <b><a href='#Form/Patient/{0}'>{0}</a></b>".format(patient.name)
37 frappe.throw(msg, title=_('Customer Not Found'))
Jamsheer8da6f4e2018-07-26 21:03:17 +053038
Rucha Mahabal434791e2020-10-24 14:20:38 +053039
anoop93d0c782020-04-13 16:42:03 +053040def get_appointments_to_invoice(patient, company):
41 appointments_to_invoice = []
42 patient_appointments = frappe.get_list(
43 'Patient Appointment',
44 fields = '*',
anoop59030022020-07-28 21:15:54 +053045 filters = {'patient': patient.name, 'company': company, 'invoiced': 0, 'status': ['not in', 'Cancelled']},
anoop93d0c782020-04-13 16:42:03 +053046 order_by = 'appointment_date'
47 )
48
Rucha Mahabal27512c82020-03-09 17:29:23 +053049 for appointment in patient_appointments:
anoop93d0c782020-04-13 16:42:03 +053050 # Procedure Appointments
Rucha Mahabal27512c82020-03-09 17:29:23 +053051 if appointment.procedure_template:
52 if frappe.db.get_value('Clinical Procedure Template', appointment.procedure_template, 'is_billable'):
anoop93d0c782020-04-13 16:42:03 +053053 appointments_to_invoice.append({
Rucha Mahabal27512c82020-03-09 17:29:23 +053054 'reference_type': 'Patient Appointment',
55 'reference_name': appointment.name,
56 'service': appointment.procedure_template
57 })
anoop93d0c782020-04-13 16:42:03 +053058 # Consultation Appointments, should check fee validity
Jamsheerba119722018-07-06 15:58:13 +053059 else:
anoop93d0c782020-04-13 16:42:03 +053060 if frappe.db.get_single_value('Healthcare Settings', 'enable_free_follow_ups') and \
61 frappe.db.exists('Fee Validity Reference', {'appointment': appointment.name}):
62 continue # Skip invoicing, fee validty present
63 practitioner_charge = 0
64 income_account = None
65 service_item = None
66 if appointment.practitioner:
67 service_item, practitioner_charge = get_service_item_and_practitioner_charge(appointment)
68 income_account = get_income_account(appointment.practitioner, appointment.company)
69 appointments_to_invoice.append({
70 'reference_type': 'Patient Appointment',
71 'reference_name': appointment.name,
72 'service': service_item,
73 'rate': practitioner_charge,
74 'income_account': income_account
75 })
Rucha Mahabal27512c82020-03-09 17:29:23 +053076
anoop93d0c782020-04-13 16:42:03 +053077 return appointments_to_invoice
Rucha Mahabal27512c82020-03-09 17:29:23 +053078
79
anoop93d0c782020-04-13 16:42:03 +053080def get_encounters_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +053081 encounters_to_invoice = []
82 encounters = frappe.get_list(
83 'Patient Encounter',
84 fields=['*'],
anoop93d0c782020-04-13 16:42:03 +053085 filters={'patient': patient.name, 'company': company, 'invoiced': False, 'docstatus': 1}
Rucha Mahabal27512c82020-03-09 17:29:23 +053086 )
87 if encounters:
88 for encounter in encounters:
89 if not encounter.appointment:
90 practitioner_charge = 0
91 income_account = None
92 service_item = None
93 if encounter.practitioner:
94 service_item, practitioner_charge = get_service_item_and_practitioner_charge(encounter)
95 income_account = get_income_account(encounter.practitioner, encounter.company)
96
97 encounters_to_invoice.append({
98 'reference_type': 'Patient Encounter',
99 'reference_name': encounter.name,
100 'service': service_item,
101 'rate': practitioner_charge,
102 'income_account': income_account
103 })
104
105 return encounters_to_invoice
106
107
anoop93d0c782020-04-13 16:42:03 +0530108def get_lab_tests_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530109 lab_tests_to_invoice = []
110 lab_tests = frappe.get_list(
111 'Lab Test',
112 fields=['name', 'template'],
anoop93d0c782020-04-13 16:42:03 +0530113 filters={'patient': patient.name, 'company': company, 'invoiced': False, 'docstatus': 1}
Rucha Mahabal27512c82020-03-09 17:29:23 +0530114 )
115 for lab_test in lab_tests:
Rucha Mahabal131452c2020-04-27 10:52:38 +0530116 item, is_billable = frappe.get_cached_value('Lab Test Template', lab_test.template, ['item', 'is_billable'])
Rucha Mahabalced978e2020-04-02 18:45:53 +0530117 if is_billable:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530118 lab_tests_to_invoice.append({
119 'reference_type': 'Lab Test',
120 'reference_name': lab_test.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530121 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530122 })
123
Rucha Mahabalced978e2020-04-02 18:45:53 +0530124 lab_prescriptions = frappe.db.sql(
125 '''
126 SELECT
127 lp.name, lp.lab_test_code
128 FROM
129 `tabPatient Encounter` et, `tabLab Prescription` lp
130 WHERE
131 et.patient=%s
132 and lp.parent=et.name
133 and lp.lab_test_created=0
134 and lp.invoiced=0
135 ''', (patient.name), as_dict=1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530136
137 for prescription in lab_prescriptions:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530138 item, is_billable = frappe.get_cached_value('Lab Test Template', prescription.lab_test_code, ['item', 'is_billable'])
139 if prescription.lab_test_code and is_billable:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530140 lab_tests_to_invoice.append({
141 'reference_type': 'Lab Prescription',
142 'reference_name': prescription.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530143 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530144 })
145
146 return lab_tests_to_invoice
147
148
anoop93d0c782020-04-13 16:42:03 +0530149def get_clinical_procedures_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530150 clinical_procedures_to_invoice = []
151 procedures = frappe.get_list(
152 'Clinical Procedure',
153 fields='*',
anoop93d0c782020-04-13 16:42:03 +0530154 filters={'patient': patient.name, 'company': company, 'invoiced': False}
Rucha Mahabal27512c82020-03-09 17:29:23 +0530155 )
156 for procedure in procedures:
157 if not procedure.appointment:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530158 item, is_billable = frappe.get_cached_value('Clinical Procedure Template', procedure.procedure_template, ['item', 'is_billable'])
159 if procedure.procedure_template and is_billable:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530160 clinical_procedures_to_invoice.append({
161 'reference_type': 'Clinical Procedure',
162 'reference_name': procedure.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530163 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530164 })
165
166 # consumables
167 if procedure.invoice_separately_as_consumables and procedure.consume_stock \
168 and procedure.status == 'Completed' and not procedure.consumption_invoiced:
169
170 service_item = get_healthcare_service_item('clinical_procedure_consumable_item')
171 if not service_item:
172 msg = _('Please Configure Clinical Procedure Consumable Item in ')
173 msg += '''<b><a href='#Form/Healthcare Settings'>Healthcare Settings</a></b>'''
174 frappe.throw(msg, title=_('Missing Configuration'))
175
176 clinical_procedures_to_invoice.append({
177 'reference_type': 'Clinical Procedure',
178 'reference_name': procedure.name,
179 'service': service_item,
180 'rate': procedure.consumable_total_amount,
181 'description': procedure.consumption_details
182 })
183
Rucha Mahabalced978e2020-04-02 18:45:53 +0530184 procedure_prescriptions = frappe.db.sql(
185 '''
186 SELECT
187 pp.name, pp.procedure
188 FROM
189 `tabPatient Encounter` et, `tabProcedure Prescription` pp
190 WHERE
191 et.patient=%s
192 and pp.parent=et.name
193 and pp.procedure_created=0
194 and pp.invoiced=0
195 and pp.appointment_booked=0
196 ''', (patient.name), as_dict=1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530197
198 for prescription in procedure_prescriptions:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530199 item, is_billable = frappe.get_cached_value('Clinical Procedure Template', prescription.procedure, ['item', 'is_billable'])
200 if is_billable:
Rucha Mahabal197165f2020-03-26 17:29:50 +0530201 clinical_procedures_to_invoice.append({
Rucha Mahabal27512c82020-03-09 17:29:23 +0530202 'reference_type': 'Procedure Prescription',
203 'reference_name': prescription.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530204 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530205 })
206
207 return clinical_procedures_to_invoice
208
209
anoop93d0c782020-04-13 16:42:03 +0530210def get_inpatient_services_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530211 services_to_invoice = []
Rucha Mahabalced978e2020-04-02 18:45:53 +0530212 inpatient_services = frappe.db.sql(
213 '''
214 SELECT
215 io.*
216 FROM
217 `tabInpatient Record` ip, `tabInpatient Occupancy` io
218 WHERE
219 ip.patient=%s
anoop93d0c782020-04-13 16:42:03 +0530220 and ip.company=%s
Rucha Mahabalced978e2020-04-02 18:45:53 +0530221 and io.parent=ip.name
222 and io.left=1
223 and io.invoiced=0
anoop93d0c782020-04-13 16:42:03 +0530224 ''', (patient.name, company), as_dict=1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530225
226 for inpatient_occupancy in inpatient_services:
227 service_unit_type = frappe.db.get_value('Healthcare Service Unit', inpatient_occupancy.service_unit, 'service_unit_type')
Rucha Mahabalced978e2020-04-02 18:45:53 +0530228 service_unit_type = frappe.get_cached_doc('Healthcare Service Unit Type', service_unit_type)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530229 if service_unit_type and service_unit_type.is_billable:
230 hours_occupied = time_diff_in_hours(inpatient_occupancy.check_out, inpatient_occupancy.check_in)
231 qty = 0.5
232 if hours_occupied > 0:
233 actual_qty = hours_occupied / service_unit_type.no_of_hours
234 floor = math.floor(actual_qty)
235 decimal_part = actual_qty - floor
236 if decimal_part > 0.5:
237 qty = rounded(floor + 1, 1)
238 elif decimal_part < 0.5 and decimal_part > 0:
239 qty = rounded(floor + 0.5, 1)
240 if qty <= 0:
241 qty = 0.5
242 services_to_invoice.append({
243 'reference_type': 'Inpatient Occupancy',
244 'reference_name': inpatient_occupancy.name,
245 'service': service_unit_type.item, 'qty': qty
246 })
247
248 return services_to_invoice
249
Jamsheerba119722018-07-06 15:58:13 +0530250
Rucha Mahabal434791e2020-10-24 14:20:38 +0530251def get_therapy_plans_to_invoice(patient, company):
252 therapy_plans_to_invoice = []
253 therapy_plans = frappe.get_list(
254 'Therapy Plan',
255 fields=['therapy_plan_template', 'name'],
256 filters={
257 'patient': patient.name,
258 'invoiced': 0,
259 'company': company,
260 'therapy_plan_template': ('!=', '')
261 }
262 )
263 for plan in therapy_plans:
264 therapy_plans_to_invoice.append({
265 'reference_type': 'Therapy Plan',
266 'reference_name': plan.name,
267 'service': frappe.db.get_value('Therapy Plan Template', plan.therapy_plan_template, 'linked_item')
268 })
269
270 return therapy_plans_to_invoice
271
272
Rucha Mahabald7304512020-04-23 00:52:47 +0530273def get_therapy_sessions_to_invoice(patient, company):
Rucha Mahabaleaa956b2020-04-22 13:07:12 +0530274 therapy_sessions_to_invoice = []
Rucha Mahabal434791e2020-10-24 14:20:38 +0530275 therapy_plans = frappe.db.get_all('Therapy Plan', {'therapy_plan_template': ('!=', '')})
276 therapy_plans_created_from_template = []
277 for entry in therapy_plans:
278 therapy_plans_created_from_template.append(entry.name)
279
Rucha Mahabaleaa956b2020-04-22 13:07:12 +0530280 therapy_sessions = frappe.get_list(
281 'Therapy Session',
282 fields='*',
Rucha Mahabal434791e2020-10-24 14:20:38 +0530283 filters={
284 'patient': patient.name,
285 'invoiced': 0,
286 'company': company,
287 'therapy_plan': ('not in', therapy_plans_created_from_template)
288 }
Rucha Mahabaleaa956b2020-04-22 13:07:12 +0530289 )
290 for therapy in therapy_sessions:
291 if not therapy.appointment:
292 if therapy.therapy_type and frappe.db.get_value('Therapy Type', therapy.therapy_type, 'is_billable'):
293 therapy_sessions_to_invoice.append({
294 'reference_type': 'Therapy Session',
295 'reference_name': therapy.name,
296 'service': frappe.db.get_value('Therapy Type', therapy.therapy_type, 'item')
297 })
298
299 return therapy_sessions_to_invoice
300
301
Rucha Mahabal24055e12020-02-24 19:09:50 +0530302def get_service_item_and_practitioner_charge(doc):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530303 is_inpatient = doc.inpatient_record
Rucha Mahabal24055e12020-02-24 19:09:50 +0530304 if is_inpatient:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530305 service_item = get_practitioner_service_item(doc.practitioner, 'inpatient_visit_charge_item')
Jamsheeree5f9c72018-07-30 12:42:06 +0530306 if not service_item:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530307 service_item = get_healthcare_service_item('inpatient_visit_charge_item')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530308 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530309 service_item = get_practitioner_service_item(doc.practitioner, 'op_consulting_charge_item')
Jamsheeree5f9c72018-07-30 12:42:06 +0530310 if not service_item:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530311 service_item = get_healthcare_service_item('op_consulting_charge_item')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530312 if not service_item:
Rucha Mahabal24055e12020-02-24 19:09:50 +0530313 throw_config_service_item(is_inpatient)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530314
Rucha Mahabal24055e12020-02-24 19:09:50 +0530315 practitioner_charge = get_practitioner_charge(doc.practitioner, is_inpatient)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530316 if not practitioner_charge:
Rucha Mahabal24055e12020-02-24 19:09:50 +0530317 throw_config_practitioner_charge(is_inpatient, doc.practitioner)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530318
319 return service_item, practitioner_charge
320
Jamsheer8da6f4e2018-07-26 21:03:17 +0530321
Rucha Mahabal27512c82020-03-09 17:29:23 +0530322def throw_config_service_item(is_inpatient):
Rucha Mahabalced978e2020-04-02 18:45:53 +0530323 service_item_label = _('Out Patient Consulting Charge Item')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530324 if is_inpatient:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530325 service_item_label = _('Inpatient Visit Charge Item')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530326
Rucha Mahabal4f9a1472020-03-23 10:40:39 +0530327 msg = _(('Please Configure {0} in ').format(service_item_label) \
Rucha Mahabal27512c82020-03-09 17:29:23 +0530328 + '''<b><a href='#Form/Healthcare Settings'>Healthcare Settings</a></b>''')
329 frappe.throw(msg, title=_('Missing Configuration'))
330
Jamsheer8da6f4e2018-07-26 21:03:17 +0530331
Rucha Mahabal24055e12020-02-24 19:09:50 +0530332def throw_config_practitioner_charge(is_inpatient, practitioner):
Rucha Mahabalced978e2020-04-02 18:45:53 +0530333 charge_name = _('OP Consulting Charge')
Rucha Mahabal24055e12020-02-24 19:09:50 +0530334 if is_inpatient:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530335 charge_name = _('Inpatient Visit Charge')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530336
Rucha Mahabal27512c82020-03-09 17:29:23 +0530337 msg = _(('Please Configure {0} for Healthcare Practitioner').format(charge_name) \
338 + ''' <b><a href='#Form/Healthcare Practitioner/{0}'>{0}</a></b>'''.format(practitioner))
339 frappe.throw(msg, title=_('Missing Configuration'))
340
Jamsheer8da6f4e2018-07-26 21:03:17 +0530341
Jamsheeree5f9c72018-07-30 12:42:06 +0530342def get_practitioner_service_item(practitioner, service_item_field):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530343 return frappe.db.get_value('Healthcare Practitioner', practitioner, service_item_field)
344
Jamsheeree5f9c72018-07-30 12:42:06 +0530345
Jamsheer8da6f4e2018-07-26 21:03:17 +0530346def get_healthcare_service_item(service_item_field):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530347 return frappe.db.get_single_value('Healthcare Settings', service_item_field)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530348
Jamsheer8da6f4e2018-07-26 21:03:17 +0530349
Rucha Mahabal24055e12020-02-24 19:09:50 +0530350def get_practitioner_charge(practitioner, is_inpatient):
351 if is_inpatient:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530352 practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, 'inpatient_visit_charge')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530353 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530354 practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, 'op_consulting_charge')
Jamsheerba119722018-07-06 15:58:13 +0530355 if practitioner_charge:
356 return practitioner_charge
Jamsheer8da6f4e2018-07-26 21:03:17 +0530357 return False
Jamsheerba119722018-07-06 15:58:13 +0530358
Rucha Mahabal27512c82020-03-09 17:29:23 +0530359
Jamsheerba119722018-07-06 15:58:13 +0530360def manage_invoice_submit_cancel(doc, method):
361 if doc.items:
362 for item in doc.items:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530363 if item.get('reference_dt') and item.get('reference_dn'):
364 if frappe.get_meta(item.reference_dt).has_field('invoiced'):
Jamsheer146683b2018-07-25 11:30:30 +0530365 set_invoiced(item, method, doc.name)
Jamsheerba119722018-07-06 15:58:13 +0530366
Rucha Mahabal27512c82020-03-09 17:29:23 +0530367 if method=='on_submit' and frappe.db.get_single_value('Healthcare Settings', 'create_lab_test_on_si_submit'):
368 create_multiple('Sales Invoice', doc.name)
369
Jamsheer0ae100b2018-08-01 14:29:43 +0530370
Jamsheer146683b2018-07-25 11:30:30 +0530371def set_invoiced(item, method, ref_invoice=None):
Jamsheerba119722018-07-06 15:58:13 +0530372 invoiced = False
Rucha Mahabal27512c82020-03-09 17:29:23 +0530373 if method=='on_submit':
Jamsheerba119722018-07-06 15:58:13 +0530374 validate_invoiced_on_submit(item)
375 invoiced = True
376
Jamsheer8da6f4e2018-07-26 21:03:17 +0530377 if item.reference_dt == 'Clinical Procedure':
378 if get_healthcare_service_item('clinical_procedure_consumable_item') == item.item_code:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530379 frappe.db.set_value(item.reference_dt, item.reference_dn, 'consumption_invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530380 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530381 frappe.db.set_value(item.reference_dt, item.reference_dn, 'invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530382 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530383 frappe.db.set_value(item.reference_dt, item.reference_dn, 'invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530384
Jamsheerba119722018-07-06 15:58:13 +0530385 if item.reference_dt == 'Patient Appointment':
386 if frappe.db.get_value('Patient Appointment', item.reference_dn, 'procedure_template'):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530387 dt_from_appointment = 'Clinical Procedure'
Jamsheerba119722018-07-06 15:58:13 +0530388 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530389 dt_from_appointment = 'Patient Encounter'
Rucha Mahabal06d1b042020-03-12 12:16:23 +0530390 manage_doc_for_appointment(dt_from_appointment, item.reference_dn, invoiced)
Jamsheerba119722018-07-06 15:58:13 +0530391
392 elif item.reference_dt == 'Lab Prescription':
Rucha Mahabal27512c82020-03-09 17:29:23 +0530393 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, 'Lab Test', 'lab_test_created')
Jamsheerba119722018-07-06 15:58:13 +0530394
395 elif item.reference_dt == 'Procedure Prescription':
Rucha Mahabal27512c82020-03-09 17:29:23 +0530396 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, 'Clinical Procedure', 'procedure_created')
397
Jamsheerba119722018-07-06 15:58:13 +0530398
399def validate_invoiced_on_submit(item):
Jamsheer8da6f4e2018-07-26 21:03:17 +0530400 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 +0530401 is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, 'consumption_invoiced')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530402 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530403 is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, 'invoiced')
404 if is_invoiced:
Rucha Mahabal434791e2020-10-24 14:20:38 +0530405 frappe.throw(_('The item referenced by {0} - {1} is already invoiced').format(
406 item.reference_dt, item.reference_dn))
Jamsheerba119722018-07-06 15:58:13 +0530407
Rucha Mahabal27512c82020-03-09 17:29:23 +0530408
Jamsheerba119722018-07-06 15:58:13 +0530409def manage_prescriptions(invoiced, ref_dt, ref_dn, dt, created_check_field):
410 created = frappe.db.get_value(ref_dt, ref_dn, created_check_field)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530411 if created:
Jamsheerba119722018-07-06 15:58:13 +0530412 # Fetch the doc created for the prescription
Jamsheereafb0462018-07-25 13:15:12 +0530413 doc_created = frappe.db.get_value(dt, {'prescription': ref_dn})
Jamsheerba119722018-07-06 15:58:13 +0530414 frappe.db.set_value(dt, doc_created, 'invoiced', invoiced)
415
Rucha Mahabal27512c82020-03-09 17:29:23 +0530416
Rucha Mahabalcd319962020-03-13 15:39:31 +0530417def check_fee_validity(appointment):
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530418 if not frappe.db.get_single_value('Healthcare Settings', 'enable_free_follow_ups'):
419 return
420
Rucha Mahabalcd319962020-03-13 15:39:31 +0530421 validity = frappe.db.exists('Fee Validity', {
422 'practitioner': appointment.practitioner,
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530423 'patient': appointment.patient,
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530424 'valid_till': ('>=', appointment.appointment_date)
Rucha Mahabalcd319962020-03-13 15:39:31 +0530425 })
426 if not validity:
427 return
428
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530429 validity = frappe.get_doc('Fee Validity', validity)
430 return validity
431
Rucha Mahabal27512c82020-03-09 17:29:23 +0530432
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530433def manage_fee_validity(appointment):
434 fee_validity = check_fee_validity(appointment)
anoop93d0c782020-04-13 16:42:03 +0530435
Rucha Mahabalcd319962020-03-13 15:39:31 +0530436 if fee_validity:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530437 if appointment.status == 'Cancelled' and fee_validity.visited > 0:
438 fee_validity.visited -= 1
439 frappe.db.delete('Fee Validity Reference', {'appointment': appointment.name})
Rucha Mahabal2cec6bd2020-03-26 14:38:12 +0530440 elif fee_validity.status == 'Completed':
441 return
Rucha Mahabalcd319962020-03-13 15:39:31 +0530442 else:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530443 fee_validity.visited += 1
444 fee_validity.append('ref_appointments', {
445 'appointment': appointment.name
446 })
447 fee_validity.save(ignore_permissions=True)
Jamsheerba119722018-07-06 15:58:13 +0530448 else:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530449 fee_validity = create_fee_validity(appointment)
450 return fee_validity
Rucha Mahabal27512c82020-03-09 17:29:23 +0530451
Jamsheerba119722018-07-06 15:58:13 +0530452
Rucha Mahabal06d1b042020-03-12 12:16:23 +0530453def manage_doc_for_appointment(dt_from_appointment, appointment, invoiced):
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530454 dn_from_appointment = frappe.db.get_value(
455 dt_from_appointment,
Rucha Mahabal27512c82020-03-09 17:29:23 +0530456 filters={'appointment': appointment}
Jamsheerba119722018-07-06 15:58:13 +0530457 )
458 if dn_from_appointment:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530459 frappe.db.set_value(dt_from_appointment, dn_from_appointment, 'invoiced', invoiced)
460
Jamsheere82f27a2018-07-30 11:28:37 +0530461
462@frappe.whitelist()
463def get_drugs_to_invoice(encounter):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530464 encounter = frappe.get_doc('Patient Encounter', encounter)
Jamsheere82f27a2018-07-30 11:28:37 +0530465 if encounter:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530466 patient = frappe.get_doc('Patient', encounter.patient)
467 if patient:
468 if patient.customer:
469 items_to_invoice = []
Jamsheere82f27a2018-07-30 11:28:37 +0530470 for drug_line in encounter.drug_prescription:
471 if drug_line.drug_code:
472 qty = 1
Rucha Mahabal27512c82020-03-09 17:29:23 +0530473 if frappe.db.get_value('Item', drug_line.drug_code, 'stock_uom') == 'Nos':
Jamsheere82f27a2018-07-30 11:28:37 +0530474 qty = drug_line.get_quantity()
Rucha Mahabal27512c82020-03-09 17:29:23 +0530475
476 description = ''
477 if drug_line.dosage and drug_line.period:
478 description = _('{0} for {1}').format(drug_line.dosage, drug_line.period)
479
480 items_to_invoice.append({
481 'drug_code': drug_line.drug_code,
482 'quantity': qty,
483 'description': description
484 })
485 return items_to_invoice
486 else:
487 validate_customer_created(patient)
488
Jamsheer4371c7e2018-08-01 18:40:05 +0530489
490@frappe.whitelist()
491def get_children(doctype, parent, company, is_root=False):
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530492 parent_fieldname = "parent_" + doctype.lower().replace(" ", "_")
Jamsheer4371c7e2018-08-01 18:40:05 +0530493 fields = [
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530494 "name as value",
495 "is_group as expandable",
496 "lft",
497 "rgt"
Jamsheer4371c7e2018-08-01 18:40:05 +0530498 ]
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530499 # fields = [ "name", "is_group", "lft", "rgt" ]
500 filters = [["ifnull(`{0}`,'')".format(parent_fieldname), "=", "" if is_root else parent]]
Jamsheer4371c7e2018-08-01 18:40:05 +0530501
502 if is_root:
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530503 fields += ["service_unit_type"] if doctype == "Healthcare Service Unit" else []
504 filters.append(["company", "=", company])
Jamsheer4371c7e2018-08-01 18:40:05 +0530505
506 else:
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530507 fields += ["service_unit_type", "allow_appointments", "inpatient_occupancy", "occupancy_status"] if doctype == "Healthcare Service Unit" else []
508 fields += [parent_fieldname + " as parent"]
Jamsheer4371c7e2018-08-01 18:40:05 +0530509
510 hc_service_units = frappe.get_list(doctype, fields=fields, filters=filters)
511
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530512 if doctype == "Healthcare Service Unit":
Jamsheer4371c7e2018-08-01 18:40:05 +0530513 for each in hc_service_units:
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530514 occupancy_msg = ""
515 if each["expandable"] == 1:
Jamsheer4371c7e2018-08-01 18:40:05 +0530516 occupied = False
517 vacant = False
Rucha Mahabalced978e2020-04-02 18:45:53 +0530518 child_list = frappe.db.sql(
519 '''
520 SELECT
521 name, occupancy_status
522 FROM
523 `tabHealthcare Service Unit`
524 WHERE
525 inpatient_occupancy = 1
526 and lft > %s and rgt < %s
527 ''', (each['lft'], each['rgt']))
528
Jamsheer4371c7e2018-08-01 18:40:05 +0530529 for child in child_list:
Jamsheer4371c7e2018-08-01 18:40:05 +0530530 if not occupied:
531 occupied = 0
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530532 if child[1] == "Occupied":
Jamsheer4371c7e2018-08-01 18:40:05 +0530533 occupied += 1
534 if not vacant:
535 vacant = 0
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530536 if child[1] == "Vacant":
Jamsheer4371c7e2018-08-01 18:40:05 +0530537 vacant += 1
538 if vacant and occupied:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530539 occupancy_total = vacant + occupied
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530540 occupancy_msg = str(occupied) + " Occupied out of " + str(occupancy_total)
541 each["occupied_out_of_vacant"] = occupancy_msg
Jamsheer4371c7e2018-08-01 18:40:05 +0530542 return hc_service_units
Jamsheer5073ac42019-07-12 12:28:34 +0530543
Rucha Mahabal27512c82020-03-09 17:29:23 +0530544
Jamsheer5073ac42019-07-12 12:28:34 +0530545@frappe.whitelist()
546def get_patient_vitals(patient, from_date=None, to_date=None):
547 if not patient: return
Rucha Mahabal27512c82020-03-09 17:29:23 +0530548
Rucha Mahabal4dd6b992020-05-25 18:42:01 +0530549 vitals = frappe.db.get_all('Vital Signs', filters={
Rucha Mahabal27512c82020-03-09 17:29:23 +0530550 'docstatus': 1,
551 'patient': patient
Rucha Mahabal4dd6b992020-05-25 18:42:01 +0530552 }, order_by='signs_date, signs_time', fields=['*'])
Rucha Mahabal27512c82020-03-09 17:29:23 +0530553
554 if len(vitals):
Jamsheer5073ac42019-07-12 12:28:34 +0530555 return vitals
Rucha Mahabal27512c82020-03-09 17:29:23 +0530556 return False
557
Jamsheer5073ac42019-07-12 12:28:34 +0530558
559@frappe.whitelist()
560def render_docs_as_html(docs):
561 # docs key value pair {doctype: docname}
562 docs_html = "<div class='col-md-12 col-sm-12 text-muted'>"
563 for doc in docs:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530564 docs_html += render_doc_as_html(doc['doctype'], doc['docname'])['html'] + '<br/>'
Jamsheer5073ac42019-07-12 12:28:34 +0530565 return {'html': docs_html}
566
Rucha Mahabal27512c82020-03-09 17:29:23 +0530567
Jamsheer5073ac42019-07-12 12:28:34 +0530568@frappe.whitelist()
569def render_doc_as_html(doctype, docname, exclude_fields = []):
570 #render document as html, three column layout will break
571 doc = frappe.get_doc(doctype, docname)
572 meta = frappe.get_meta(doctype)
573 doc_html = "<div class='col-md-12 col-sm-12'>"
Rucha Mahabal27512c82020-03-09 17:29:23 +0530574 section_html = ''
575 section_label = ''
576 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530577 sec_on = False
578 col_on = 0
579 has_data = False
580 for df in meta.fields:
581 #on section break append append previous section and html to doc html
582 if df.fieldtype == "Section Break":
583 if has_data and col_on and sec_on:
584 doc_html += section_html + html + "</div>"
585 elif has_data and not col_on and sec_on:
586 doc_html += "<div class='col-md-12 col-sm-12'\
587 ><div class='col-md-12 col-sm-12'>" \
588 + section_html + html +"</div></div>"
589 while col_on:
590 doc_html += "</div>"
591 col_on -= 1
592 sec_on = True
593 has_data= False
594 col_on = 0
Rucha Mahabal27512c82020-03-09 17:29:23 +0530595 section_html = ''
596 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530597 if df.label:
598 section_label = df.label
599 continue
600 #on column break append html to section html or doc html
601 if df.fieldtype == "Column Break":
602 if sec_on and has_data:
603 section_html += "<div class='col-md-12 col-sm-12'\
604 ><div class='col-md-6 col\
605 -sm-6'><b>" + section_label + "</b>" + html + "</div><div \
606 class='col-md-6 col-sm-6'>"
607 elif has_data:
608 doc_html += "<div class='col-md-12 col-sm-12'><div class='col-m\
609 d-6 col-sm-6'>" + html + "</div><div class='col-md-6 col-sm-6'>"
610 elif sec_on and not col_on:
611 section_html += "<div class='col-md-6 col-sm-6'>"
Rucha Mahabal27512c82020-03-09 17:29:23 +0530612 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530613 col_on += 1
614 if df.label:
615 html += '<br>' + df.label
616 continue
617 #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 +0530618 if df.fieldtype == 'Table':
Jamsheer5073ac42019-07-12 12:28:34 +0530619 items = doc.get(df.fieldname)
620 if not items: continue
621 child_meta = frappe.get_meta(df.options)
622 if not has_data : has_data = True
Rucha Mahabal27512c82020-03-09 17:29:23 +0530623 table_head = ''
624 table_row = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530625 create_head = True
626 for item in items:
627 table_row += '<tr>'
628 for cdf in child_meta.fields:
629 if cdf.in_list_view:
630 if create_head:
631 table_head += '<th>' + cdf.label + '</th>'
632 if item.get(cdf.fieldname):
633 table_row += '<td>' + str(item.get(cdf.fieldname)) \
634 + '</td>'
635 else:
636 table_row += '<td></td>'
637 create_head = False
638 table_row += '</tr>'
639 if sec_on:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530640 section_html += "<table class='table table-condensed \
641 bordered'>" + table_head + table_row + '</table>'
Jamsheer5073ac42019-07-12 12:28:34 +0530642 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530643 html += "<table class='table table-condensed table-bordered'>" \
644 + table_head + table_row + "</table>"
Jamsheer5073ac42019-07-12 12:28:34 +0530645 continue
Rucha Mahabal5e3c51b2020-11-30 13:35:00 +0530646
Jamsheer5073ac42019-07-12 12:28:34 +0530647 #on other field types add label and value to html
648 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 +0530649 if doc.get(df.fieldname):
650 formatted_value = format_value(doc.get(df.fieldname), meta.get_field(df.fieldname), doc)
651 html += '<br>{0} : {1}'.format(df.label or df.fieldname, formatted_value)
652
Jamsheer5073ac42019-07-12 12:28:34 +0530653 if not has_data : has_data = True
Rucha Mahabal5e3c51b2020-11-30 13:35:00 +0530654
Jamsheer5073ac42019-07-12 12:28:34 +0530655 if sec_on and col_on and has_data:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530656 doc_html += section_html + html + '</div></div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530657 elif sec_on and not col_on and has_data:
658 doc_html += "<div class='col-md-12 col-sm-12'\
659 ><div class='col-md-12 col-sm-12'>" \
Rucha Mahabal27512c82020-03-09 17:29:23 +0530660 + section_html + html +'</div></div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530661 if doc_html:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530662 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 +0530663
664 return {'html': doc_html}