blob: 40f7f9cabd2b0533c4dcb6741b354484f0493f1b [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 Mahabal0f059252021-01-13 09:46:33 +053081 if not isinstance(patient, str):
82 patient = patient.name
Rucha Mahabal27512c82020-03-09 17:29:23 +053083 encounters_to_invoice = []
84 encounters = frappe.get_list(
85 'Patient Encounter',
86 fields=['*'],
Rucha Mahabal0f059252021-01-13 09:46:33 +053087 filters={'patient': patient, 'company': company, 'invoiced': False, 'docstatus': 1}
Rucha Mahabal27512c82020-03-09 17:29:23 +053088 )
89 if encounters:
90 for encounter in encounters:
91 if not encounter.appointment:
92 practitioner_charge = 0
93 income_account = None
94 service_item = None
95 if encounter.practitioner:
Rucha Mahabal13541972021-01-13 09:12:50 +053096 if encounter.inpatient_record and \
97 frappe.db.get_single_value('Healthcare Settings', 'do_not_bill_inpatient_encounters'):
98 continue
99
Rucha Mahabal27512c82020-03-09 17:29:23 +0530100 service_item, practitioner_charge = get_service_item_and_practitioner_charge(encounter)
101 income_account = get_income_account(encounter.practitioner, encounter.company)
102
103 encounters_to_invoice.append({
104 'reference_type': 'Patient Encounter',
105 'reference_name': encounter.name,
106 'service': service_item,
107 'rate': practitioner_charge,
108 'income_account': income_account
109 })
110
111 return encounters_to_invoice
112
113
anoop93d0c782020-04-13 16:42:03 +0530114def get_lab_tests_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530115 lab_tests_to_invoice = []
116 lab_tests = frappe.get_list(
117 'Lab Test',
118 fields=['name', 'template'],
anoop93d0c782020-04-13 16:42:03 +0530119 filters={'patient': patient.name, 'company': company, 'invoiced': False, 'docstatus': 1}
Rucha Mahabal27512c82020-03-09 17:29:23 +0530120 )
121 for lab_test in lab_tests:
Rucha Mahabal131452c2020-04-27 10:52:38 +0530122 item, is_billable = frappe.get_cached_value('Lab Test Template', lab_test.template, ['item', 'is_billable'])
Rucha Mahabalced978e2020-04-02 18:45:53 +0530123 if is_billable:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530124 lab_tests_to_invoice.append({
125 'reference_type': 'Lab Test',
126 'reference_name': lab_test.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530127 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530128 })
129
Rucha Mahabalced978e2020-04-02 18:45:53 +0530130 lab_prescriptions = frappe.db.sql(
131 '''
132 SELECT
133 lp.name, lp.lab_test_code
134 FROM
135 `tabPatient Encounter` et, `tabLab Prescription` lp
136 WHERE
137 et.patient=%s
138 and lp.parent=et.name
139 and lp.lab_test_created=0
140 and lp.invoiced=0
141 ''', (patient.name), as_dict=1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530142
143 for prescription in lab_prescriptions:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530144 item, is_billable = frappe.get_cached_value('Lab Test Template', prescription.lab_test_code, ['item', 'is_billable'])
145 if prescription.lab_test_code and is_billable:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530146 lab_tests_to_invoice.append({
147 'reference_type': 'Lab Prescription',
148 'reference_name': prescription.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530149 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530150 })
151
152 return lab_tests_to_invoice
153
154
anoop93d0c782020-04-13 16:42:03 +0530155def get_clinical_procedures_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530156 clinical_procedures_to_invoice = []
157 procedures = frappe.get_list(
158 'Clinical Procedure',
159 fields='*',
anoop93d0c782020-04-13 16:42:03 +0530160 filters={'patient': patient.name, 'company': company, 'invoiced': False}
Rucha Mahabal27512c82020-03-09 17:29:23 +0530161 )
162 for procedure in procedures:
163 if not procedure.appointment:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530164 item, is_billable = frappe.get_cached_value('Clinical Procedure Template', procedure.procedure_template, ['item', 'is_billable'])
165 if procedure.procedure_template and is_billable:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530166 clinical_procedures_to_invoice.append({
167 'reference_type': 'Clinical Procedure',
168 'reference_name': procedure.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530169 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530170 })
171
172 # consumables
173 if procedure.invoice_separately_as_consumables and procedure.consume_stock \
174 and procedure.status == 'Completed' and not procedure.consumption_invoiced:
175
176 service_item = get_healthcare_service_item('clinical_procedure_consumable_item')
177 if not service_item:
178 msg = _('Please Configure Clinical Procedure Consumable Item in ')
179 msg += '''<b><a href='#Form/Healthcare Settings'>Healthcare Settings</a></b>'''
180 frappe.throw(msg, title=_('Missing Configuration'))
181
182 clinical_procedures_to_invoice.append({
183 'reference_type': 'Clinical Procedure',
184 'reference_name': procedure.name,
185 'service': service_item,
186 'rate': procedure.consumable_total_amount,
187 'description': procedure.consumption_details
188 })
189
Rucha Mahabalced978e2020-04-02 18:45:53 +0530190 procedure_prescriptions = frappe.db.sql(
191 '''
192 SELECT
193 pp.name, pp.procedure
194 FROM
195 `tabPatient Encounter` et, `tabProcedure Prescription` pp
196 WHERE
197 et.patient=%s
198 and pp.parent=et.name
199 and pp.procedure_created=0
200 and pp.invoiced=0
201 and pp.appointment_booked=0
202 ''', (patient.name), as_dict=1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530203
204 for prescription in procedure_prescriptions:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530205 item, is_billable = frappe.get_cached_value('Clinical Procedure Template', prescription.procedure, ['item', 'is_billable'])
206 if is_billable:
Rucha Mahabal197165f2020-03-26 17:29:50 +0530207 clinical_procedures_to_invoice.append({
Rucha Mahabal27512c82020-03-09 17:29:23 +0530208 'reference_type': 'Procedure Prescription',
209 'reference_name': prescription.name,
Rucha Mahabalced978e2020-04-02 18:45:53 +0530210 'service': item
Rucha Mahabal27512c82020-03-09 17:29:23 +0530211 })
212
213 return clinical_procedures_to_invoice
214
215
anoop93d0c782020-04-13 16:42:03 +0530216def get_inpatient_services_to_invoice(patient, company):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530217 services_to_invoice = []
Rucha Mahabalced978e2020-04-02 18:45:53 +0530218 inpatient_services = frappe.db.sql(
219 '''
220 SELECT
221 io.*
222 FROM
223 `tabInpatient Record` ip, `tabInpatient Occupancy` io
224 WHERE
225 ip.patient=%s
anoop93d0c782020-04-13 16:42:03 +0530226 and ip.company=%s
Rucha Mahabalced978e2020-04-02 18:45:53 +0530227 and io.parent=ip.name
228 and io.left=1
229 and io.invoiced=0
anoop93d0c782020-04-13 16:42:03 +0530230 ''', (patient.name, company), as_dict=1)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530231
232 for inpatient_occupancy in inpatient_services:
233 service_unit_type = frappe.db.get_value('Healthcare Service Unit', inpatient_occupancy.service_unit, 'service_unit_type')
Rucha Mahabalced978e2020-04-02 18:45:53 +0530234 service_unit_type = frappe.get_cached_doc('Healthcare Service Unit Type', service_unit_type)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530235 if service_unit_type and service_unit_type.is_billable:
236 hours_occupied = time_diff_in_hours(inpatient_occupancy.check_out, inpatient_occupancy.check_in)
237 qty = 0.5
238 if hours_occupied > 0:
239 actual_qty = hours_occupied / service_unit_type.no_of_hours
240 floor = math.floor(actual_qty)
241 decimal_part = actual_qty - floor
242 if decimal_part > 0.5:
243 qty = rounded(floor + 1, 1)
244 elif decimal_part < 0.5 and decimal_part > 0:
245 qty = rounded(floor + 0.5, 1)
246 if qty <= 0:
247 qty = 0.5
248 services_to_invoice.append({
249 'reference_type': 'Inpatient Occupancy',
250 'reference_name': inpatient_occupancy.name,
251 'service': service_unit_type.item, 'qty': qty
252 })
253
254 return services_to_invoice
255
Jamsheerba119722018-07-06 15:58:13 +0530256
Rucha Mahabal434791e2020-10-24 14:20:38 +0530257def get_therapy_plans_to_invoice(patient, company):
258 therapy_plans_to_invoice = []
259 therapy_plans = frappe.get_list(
260 'Therapy Plan',
261 fields=['therapy_plan_template', 'name'],
262 filters={
263 'patient': patient.name,
264 'invoiced': 0,
265 'company': company,
266 'therapy_plan_template': ('!=', '')
267 }
268 )
269 for plan in therapy_plans:
270 therapy_plans_to_invoice.append({
271 'reference_type': 'Therapy Plan',
272 'reference_name': plan.name,
273 'service': frappe.db.get_value('Therapy Plan Template', plan.therapy_plan_template, 'linked_item')
274 })
275
276 return therapy_plans_to_invoice
277
278
Rucha Mahabald7304512020-04-23 00:52:47 +0530279def get_therapy_sessions_to_invoice(patient, company):
Rucha Mahabaleaa956b2020-04-22 13:07:12 +0530280 therapy_sessions_to_invoice = []
Rucha Mahabal434791e2020-10-24 14:20:38 +0530281 therapy_plans = frappe.db.get_all('Therapy Plan', {'therapy_plan_template': ('!=', '')})
282 therapy_plans_created_from_template = []
283 for entry in therapy_plans:
284 therapy_plans_created_from_template.append(entry.name)
285
Rucha Mahabaleaa956b2020-04-22 13:07:12 +0530286 therapy_sessions = frappe.get_list(
287 'Therapy Session',
288 fields='*',
Rucha Mahabal434791e2020-10-24 14:20:38 +0530289 filters={
290 'patient': patient.name,
291 'invoiced': 0,
292 'company': company,
293 'therapy_plan': ('not in', therapy_plans_created_from_template)
294 }
Rucha Mahabaleaa956b2020-04-22 13:07:12 +0530295 )
296 for therapy in therapy_sessions:
297 if not therapy.appointment:
298 if therapy.therapy_type and frappe.db.get_value('Therapy Type', therapy.therapy_type, 'is_billable'):
299 therapy_sessions_to_invoice.append({
300 'reference_type': 'Therapy Session',
301 'reference_name': therapy.name,
302 'service': frappe.db.get_value('Therapy Type', therapy.therapy_type, 'item')
303 })
304
305 return therapy_sessions_to_invoice
306
307
Rucha Mahabal24055e12020-02-24 19:09:50 +0530308def get_service_item_and_practitioner_charge(doc):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530309 is_inpatient = doc.inpatient_record
Rucha Mahabal24055e12020-02-24 19:09:50 +0530310 if is_inpatient:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530311 service_item = get_practitioner_service_item(doc.practitioner, 'inpatient_visit_charge_item')
Jamsheeree5f9c72018-07-30 12:42:06 +0530312 if not service_item:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530313 service_item = get_healthcare_service_item('inpatient_visit_charge_item')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530314 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530315 service_item = get_practitioner_service_item(doc.practitioner, 'op_consulting_charge_item')
Jamsheeree5f9c72018-07-30 12:42:06 +0530316 if not service_item:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530317 service_item = get_healthcare_service_item('op_consulting_charge_item')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530318 if not service_item:
Rucha Mahabal24055e12020-02-24 19:09:50 +0530319 throw_config_service_item(is_inpatient)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530320
Rucha Mahabal24055e12020-02-24 19:09:50 +0530321 practitioner_charge = get_practitioner_charge(doc.practitioner, is_inpatient)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530322 if not practitioner_charge:
Rucha Mahabal24055e12020-02-24 19:09:50 +0530323 throw_config_practitioner_charge(is_inpatient, doc.practitioner)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530324
325 return service_item, practitioner_charge
326
Jamsheer8da6f4e2018-07-26 21:03:17 +0530327
Rucha Mahabal27512c82020-03-09 17:29:23 +0530328def throw_config_service_item(is_inpatient):
Rucha Mahabalced978e2020-04-02 18:45:53 +0530329 service_item_label = _('Out Patient Consulting Charge Item')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530330 if is_inpatient:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530331 service_item_label = _('Inpatient Visit Charge Item')
Rucha Mahabal27512c82020-03-09 17:29:23 +0530332
Rucha Mahabal4f9a1472020-03-23 10:40:39 +0530333 msg = _(('Please Configure {0} in ').format(service_item_label) \
Rucha Mahabal27512c82020-03-09 17:29:23 +0530334 + '''<b><a href='#Form/Healthcare Settings'>Healthcare Settings</a></b>''')
335 frappe.throw(msg, title=_('Missing Configuration'))
336
Jamsheer8da6f4e2018-07-26 21:03:17 +0530337
Rucha Mahabal24055e12020-02-24 19:09:50 +0530338def throw_config_practitioner_charge(is_inpatient, practitioner):
Rucha Mahabalced978e2020-04-02 18:45:53 +0530339 charge_name = _('OP Consulting Charge')
Rucha Mahabal24055e12020-02-24 19:09:50 +0530340 if is_inpatient:
Rucha Mahabalced978e2020-04-02 18:45:53 +0530341 charge_name = _('Inpatient Visit Charge')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530342
Rucha Mahabal27512c82020-03-09 17:29:23 +0530343 msg = _(('Please Configure {0} for Healthcare Practitioner').format(charge_name) \
344 + ''' <b><a href='#Form/Healthcare Practitioner/{0}'>{0}</a></b>'''.format(practitioner))
345 frappe.throw(msg, title=_('Missing Configuration'))
346
Jamsheer8da6f4e2018-07-26 21:03:17 +0530347
Jamsheeree5f9c72018-07-30 12:42:06 +0530348def get_practitioner_service_item(practitioner, service_item_field):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530349 return frappe.db.get_value('Healthcare Practitioner', practitioner, service_item_field)
350
Jamsheeree5f9c72018-07-30 12:42:06 +0530351
Jamsheer8da6f4e2018-07-26 21:03:17 +0530352def get_healthcare_service_item(service_item_field):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530353 return frappe.db.get_single_value('Healthcare Settings', service_item_field)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530354
Jamsheer8da6f4e2018-07-26 21:03:17 +0530355
Rucha Mahabal24055e12020-02-24 19:09:50 +0530356def get_practitioner_charge(practitioner, is_inpatient):
357 if is_inpatient:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530358 practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, 'inpatient_visit_charge')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530359 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530360 practitioner_charge = frappe.db.get_value('Healthcare Practitioner', practitioner, 'op_consulting_charge')
Jamsheerba119722018-07-06 15:58:13 +0530361 if practitioner_charge:
362 return practitioner_charge
Jamsheer8da6f4e2018-07-26 21:03:17 +0530363 return False
Jamsheerba119722018-07-06 15:58:13 +0530364
Rucha Mahabal27512c82020-03-09 17:29:23 +0530365
Jamsheerba119722018-07-06 15:58:13 +0530366def manage_invoice_submit_cancel(doc, method):
367 if doc.items:
368 for item in doc.items:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530369 if item.get('reference_dt') and item.get('reference_dn'):
370 if frappe.get_meta(item.reference_dt).has_field('invoiced'):
Jamsheer146683b2018-07-25 11:30:30 +0530371 set_invoiced(item, method, doc.name)
Jamsheerba119722018-07-06 15:58:13 +0530372
Rucha Mahabal27512c82020-03-09 17:29:23 +0530373 if method=='on_submit' and frappe.db.get_single_value('Healthcare Settings', 'create_lab_test_on_si_submit'):
374 create_multiple('Sales Invoice', doc.name)
375
Jamsheer0ae100b2018-08-01 14:29:43 +0530376
Jamsheer146683b2018-07-25 11:30:30 +0530377def set_invoiced(item, method, ref_invoice=None):
Jamsheerba119722018-07-06 15:58:13 +0530378 invoiced = False
Rucha Mahabal27512c82020-03-09 17:29:23 +0530379 if method=='on_submit':
Jamsheerba119722018-07-06 15:58:13 +0530380 validate_invoiced_on_submit(item)
381 invoiced = True
382
Jamsheer8da6f4e2018-07-26 21:03:17 +0530383 if item.reference_dt == 'Clinical Procedure':
384 if get_healthcare_service_item('clinical_procedure_consumable_item') == item.item_code:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530385 frappe.db.set_value(item.reference_dt, item.reference_dn, 'consumption_invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530386 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530387 frappe.db.set_value(item.reference_dt, item.reference_dn, 'invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530388 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530389 frappe.db.set_value(item.reference_dt, item.reference_dn, 'invoiced', invoiced)
Jamsheer8da6f4e2018-07-26 21:03:17 +0530390
Jamsheerba119722018-07-06 15:58:13 +0530391 if item.reference_dt == 'Patient Appointment':
392 if frappe.db.get_value('Patient Appointment', item.reference_dn, 'procedure_template'):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530393 dt_from_appointment = 'Clinical Procedure'
Jamsheerba119722018-07-06 15:58:13 +0530394 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530395 dt_from_appointment = 'Patient Encounter'
Rucha Mahabal06d1b042020-03-12 12:16:23 +0530396 manage_doc_for_appointment(dt_from_appointment, item.reference_dn, invoiced)
Jamsheerba119722018-07-06 15:58:13 +0530397
398 elif item.reference_dt == 'Lab Prescription':
Rucha Mahabal27512c82020-03-09 17:29:23 +0530399 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, 'Lab Test', 'lab_test_created')
Jamsheerba119722018-07-06 15:58:13 +0530400
401 elif item.reference_dt == 'Procedure Prescription':
Rucha Mahabal27512c82020-03-09 17:29:23 +0530402 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, 'Clinical Procedure', 'procedure_created')
403
Jamsheerba119722018-07-06 15:58:13 +0530404
405def validate_invoiced_on_submit(item):
Jamsheer8da6f4e2018-07-26 21:03:17 +0530406 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 +0530407 is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, 'consumption_invoiced')
Jamsheer8da6f4e2018-07-26 21:03:17 +0530408 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530409 is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, 'invoiced')
410 if is_invoiced:
Rucha Mahabal434791e2020-10-24 14:20:38 +0530411 frappe.throw(_('The item referenced by {0} - {1} is already invoiced').format(
412 item.reference_dt, item.reference_dn))
Jamsheerba119722018-07-06 15:58:13 +0530413
Rucha Mahabal27512c82020-03-09 17:29:23 +0530414
Jamsheerba119722018-07-06 15:58:13 +0530415def manage_prescriptions(invoiced, ref_dt, ref_dn, dt, created_check_field):
416 created = frappe.db.get_value(ref_dt, ref_dn, created_check_field)
Rucha Mahabal27512c82020-03-09 17:29:23 +0530417 if created:
Jamsheerba119722018-07-06 15:58:13 +0530418 # Fetch the doc created for the prescription
Jamsheereafb0462018-07-25 13:15:12 +0530419 doc_created = frappe.db.get_value(dt, {'prescription': ref_dn})
Jamsheerba119722018-07-06 15:58:13 +0530420 frappe.db.set_value(dt, doc_created, 'invoiced', invoiced)
421
Rucha Mahabal27512c82020-03-09 17:29:23 +0530422
Rucha Mahabalcd319962020-03-13 15:39:31 +0530423def check_fee_validity(appointment):
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530424 if not frappe.db.get_single_value('Healthcare Settings', 'enable_free_follow_ups'):
425 return
426
Rucha Mahabalcd319962020-03-13 15:39:31 +0530427 validity = frappe.db.exists('Fee Validity', {
428 'practitioner': appointment.practitioner,
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530429 'patient': appointment.patient,
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530430 'valid_till': ('>=', appointment.appointment_date)
Rucha Mahabalcd319962020-03-13 15:39:31 +0530431 })
432 if not validity:
433 return
434
Rucha Mahabalf2574dd2020-03-17 19:28:18 +0530435 validity = frappe.get_doc('Fee Validity', validity)
436 return validity
437
Rucha Mahabal27512c82020-03-09 17:29:23 +0530438
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530439def manage_fee_validity(appointment):
440 fee_validity = check_fee_validity(appointment)
anoop93d0c782020-04-13 16:42:03 +0530441
Rucha Mahabalcd319962020-03-13 15:39:31 +0530442 if fee_validity:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530443 if appointment.status == 'Cancelled' and fee_validity.visited > 0:
444 fee_validity.visited -= 1
445 frappe.db.delete('Fee Validity Reference', {'appointment': appointment.name})
Rucha Mahabal2cec6bd2020-03-26 14:38:12 +0530446 elif fee_validity.status == 'Completed':
447 return
Rucha Mahabalcd319962020-03-13 15:39:31 +0530448 else:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530449 fee_validity.visited += 1
450 fee_validity.append('ref_appointments', {
451 'appointment': appointment.name
452 })
453 fee_validity.save(ignore_permissions=True)
Jamsheerba119722018-07-06 15:58:13 +0530454 else:
Rucha Mahabal2f2c09b2020-03-17 18:10:39 +0530455 fee_validity = create_fee_validity(appointment)
456 return fee_validity
Rucha Mahabal27512c82020-03-09 17:29:23 +0530457
Jamsheerba119722018-07-06 15:58:13 +0530458
Rucha Mahabal06d1b042020-03-12 12:16:23 +0530459def manage_doc_for_appointment(dt_from_appointment, appointment, invoiced):
Rucha Mahabalc4b2dce2020-03-09 23:57:00 +0530460 dn_from_appointment = frappe.db.get_value(
461 dt_from_appointment,
Rucha Mahabal27512c82020-03-09 17:29:23 +0530462 filters={'appointment': appointment}
Jamsheerba119722018-07-06 15:58:13 +0530463 )
464 if dn_from_appointment:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530465 frappe.db.set_value(dt_from_appointment, dn_from_appointment, 'invoiced', invoiced)
466
Jamsheere82f27a2018-07-30 11:28:37 +0530467
468@frappe.whitelist()
469def get_drugs_to_invoice(encounter):
Rucha Mahabal27512c82020-03-09 17:29:23 +0530470 encounter = frappe.get_doc('Patient Encounter', encounter)
Jamsheere82f27a2018-07-30 11:28:37 +0530471 if encounter:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530472 patient = frappe.get_doc('Patient', encounter.patient)
473 if patient:
474 if patient.customer:
475 items_to_invoice = []
Jamsheere82f27a2018-07-30 11:28:37 +0530476 for drug_line in encounter.drug_prescription:
477 if drug_line.drug_code:
478 qty = 1
Rucha Mahabal27512c82020-03-09 17:29:23 +0530479 if frappe.db.get_value('Item', drug_line.drug_code, 'stock_uom') == 'Nos':
Jamsheere82f27a2018-07-30 11:28:37 +0530480 qty = drug_line.get_quantity()
Rucha Mahabal27512c82020-03-09 17:29:23 +0530481
482 description = ''
483 if drug_line.dosage and drug_line.period:
484 description = _('{0} for {1}').format(drug_line.dosage, drug_line.period)
485
486 items_to_invoice.append({
487 'drug_code': drug_line.drug_code,
488 'quantity': qty,
489 'description': description
490 })
491 return items_to_invoice
492 else:
493 validate_customer_created(patient)
494
Jamsheer4371c7e2018-08-01 18:40:05 +0530495
496@frappe.whitelist()
497def get_children(doctype, parent, company, is_root=False):
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530498 parent_fieldname = "parent_" + doctype.lower().replace(" ", "_")
Jamsheer4371c7e2018-08-01 18:40:05 +0530499 fields = [
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530500 "name as value",
501 "is_group as expandable",
502 "lft",
503 "rgt"
Jamsheer4371c7e2018-08-01 18:40:05 +0530504 ]
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530505 # fields = [ "name", "is_group", "lft", "rgt" ]
506 filters = [["ifnull(`{0}`,'')".format(parent_fieldname), "=", "" if is_root else parent]]
Jamsheer4371c7e2018-08-01 18:40:05 +0530507
508 if is_root:
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530509 fields += ["service_unit_type"] if doctype == "Healthcare Service Unit" else []
510 filters.append(["company", "=", company])
Jamsheer4371c7e2018-08-01 18:40:05 +0530511
512 else:
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530513 fields += ["service_unit_type", "allow_appointments", "inpatient_occupancy", "occupancy_status"] if doctype == "Healthcare Service Unit" else []
514 fields += [parent_fieldname + " as parent"]
Jamsheer4371c7e2018-08-01 18:40:05 +0530515
516 hc_service_units = frappe.get_list(doctype, fields=fields, filters=filters)
517
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530518 if doctype == "Healthcare Service Unit":
Jamsheer4371c7e2018-08-01 18:40:05 +0530519 for each in hc_service_units:
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530520 occupancy_msg = ""
521 if each["expandable"] == 1:
Jamsheer4371c7e2018-08-01 18:40:05 +0530522 occupied = False
523 vacant = False
Rucha Mahabalced978e2020-04-02 18:45:53 +0530524 child_list = frappe.db.sql(
525 '''
526 SELECT
527 name, occupancy_status
528 FROM
529 `tabHealthcare Service Unit`
530 WHERE
531 inpatient_occupancy = 1
532 and lft > %s and rgt < %s
533 ''', (each['lft'], each['rgt']))
534
Jamsheer4371c7e2018-08-01 18:40:05 +0530535 for child in child_list:
Jamsheer4371c7e2018-08-01 18:40:05 +0530536 if not occupied:
537 occupied = 0
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530538 if child[1] == "Occupied":
Jamsheer4371c7e2018-08-01 18:40:05 +0530539 occupied += 1
540 if not vacant:
541 vacant = 0
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530542 if child[1] == "Vacant":
Jamsheer4371c7e2018-08-01 18:40:05 +0530543 vacant += 1
544 if vacant and occupied:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530545 occupancy_total = vacant + occupied
Rucha Mahabal05853ef2020-03-12 17:44:46 +0530546 occupancy_msg = str(occupied) + " Occupied out of " + str(occupancy_total)
547 each["occupied_out_of_vacant"] = occupancy_msg
Jamsheer4371c7e2018-08-01 18:40:05 +0530548 return hc_service_units
Jamsheer5073ac42019-07-12 12:28:34 +0530549
Rucha Mahabal27512c82020-03-09 17:29:23 +0530550
Jamsheer5073ac42019-07-12 12:28:34 +0530551@frappe.whitelist()
552def get_patient_vitals(patient, from_date=None, to_date=None):
553 if not patient: return
Rucha Mahabal27512c82020-03-09 17:29:23 +0530554
Rucha Mahabal4dd6b992020-05-25 18:42:01 +0530555 vitals = frappe.db.get_all('Vital Signs', filters={
Rucha Mahabal27512c82020-03-09 17:29:23 +0530556 'docstatus': 1,
557 'patient': patient
Rucha Mahabal4dd6b992020-05-25 18:42:01 +0530558 }, order_by='signs_date, signs_time', fields=['*'])
Rucha Mahabal27512c82020-03-09 17:29:23 +0530559
560 if len(vitals):
Jamsheer5073ac42019-07-12 12:28:34 +0530561 return vitals
Rucha Mahabal27512c82020-03-09 17:29:23 +0530562 return False
563
Jamsheer5073ac42019-07-12 12:28:34 +0530564
565@frappe.whitelist()
566def render_docs_as_html(docs):
567 # docs key value pair {doctype: docname}
568 docs_html = "<div class='col-md-12 col-sm-12 text-muted'>"
569 for doc in docs:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530570 docs_html += render_doc_as_html(doc['doctype'], doc['docname'])['html'] + '<br/>'
Jamsheer5073ac42019-07-12 12:28:34 +0530571 return {'html': docs_html}
572
Rucha Mahabal27512c82020-03-09 17:29:23 +0530573
Jamsheer5073ac42019-07-12 12:28:34 +0530574@frappe.whitelist()
575def render_doc_as_html(doctype, docname, exclude_fields = []):
576 #render document as html, three column layout will break
577 doc = frappe.get_doc(doctype, docname)
578 meta = frappe.get_meta(doctype)
579 doc_html = "<div class='col-md-12 col-sm-12'>"
Rucha Mahabal27512c82020-03-09 17:29:23 +0530580 section_html = ''
581 section_label = ''
582 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530583 sec_on = False
584 col_on = 0
585 has_data = False
586 for df in meta.fields:
587 #on section break append append previous section and html to doc html
588 if df.fieldtype == "Section Break":
589 if has_data and col_on and sec_on:
590 doc_html += section_html + html + "</div>"
591 elif has_data and not col_on and sec_on:
592 doc_html += "<div class='col-md-12 col-sm-12'\
593 ><div class='col-md-12 col-sm-12'>" \
594 + section_html + html +"</div></div>"
595 while col_on:
596 doc_html += "</div>"
597 col_on -= 1
598 sec_on = True
599 has_data= False
600 col_on = 0
Rucha Mahabal27512c82020-03-09 17:29:23 +0530601 section_html = ''
602 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530603 if df.label:
604 section_label = df.label
605 continue
606 #on column break append html to section html or doc html
607 if df.fieldtype == "Column Break":
608 if sec_on and has_data:
609 section_html += "<div class='col-md-12 col-sm-12'\
610 ><div class='col-md-6 col\
611 -sm-6'><b>" + section_label + "</b>" + html + "</div><div \
612 class='col-md-6 col-sm-6'>"
613 elif has_data:
614 doc_html += "<div class='col-md-12 col-sm-12'><div class='col-m\
615 d-6 col-sm-6'>" + html + "</div><div class='col-md-6 col-sm-6'>"
616 elif sec_on and not col_on:
617 section_html += "<div class='col-md-6 col-sm-6'>"
Rucha Mahabal27512c82020-03-09 17:29:23 +0530618 html = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530619 col_on += 1
620 if df.label:
621 html += '<br>' + df.label
622 continue
623 #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 +0530624 if df.fieldtype == 'Table':
Jamsheer5073ac42019-07-12 12:28:34 +0530625 items = doc.get(df.fieldname)
626 if not items: continue
627 child_meta = frappe.get_meta(df.options)
628 if not has_data : has_data = True
Rucha Mahabal27512c82020-03-09 17:29:23 +0530629 table_head = ''
630 table_row = ''
Jamsheer5073ac42019-07-12 12:28:34 +0530631 create_head = True
632 for item in items:
633 table_row += '<tr>'
634 for cdf in child_meta.fields:
635 if cdf.in_list_view:
636 if create_head:
637 table_head += '<th>' + cdf.label + '</th>'
638 if item.get(cdf.fieldname):
639 table_row += '<td>' + str(item.get(cdf.fieldname)) \
640 + '</td>'
641 else:
642 table_row += '<td></td>'
643 create_head = False
644 table_row += '</tr>'
645 if sec_on:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530646 section_html += "<table class='table table-condensed \
647 bordered'>" + table_head + table_row + '</table>'
Jamsheer5073ac42019-07-12 12:28:34 +0530648 else:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530649 html += "<table class='table table-condensed table-bordered'>" \
650 + table_head + table_row + "</table>"
Jamsheer5073ac42019-07-12 12:28:34 +0530651 continue
Rucha Mahabal5e3c51b2020-11-30 13:35:00 +0530652
Jamsheer5073ac42019-07-12 12:28:34 +0530653 #on other field types add label and value to html
654 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 +0530655 if doc.get(df.fieldname):
656 formatted_value = format_value(doc.get(df.fieldname), meta.get_field(df.fieldname), doc)
657 html += '<br>{0} : {1}'.format(df.label or df.fieldname, formatted_value)
658
Jamsheer5073ac42019-07-12 12:28:34 +0530659 if not has_data : has_data = True
Rucha Mahabal5e3c51b2020-11-30 13:35:00 +0530660
Jamsheer5073ac42019-07-12 12:28:34 +0530661 if sec_on and col_on and has_data:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530662 doc_html += section_html + html + '</div></div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530663 elif sec_on and not col_on and has_data:
664 doc_html += "<div class='col-md-12 col-sm-12'\
665 ><div class='col-md-12 col-sm-12'>" \
Rucha Mahabal27512c82020-03-09 17:29:23 +0530666 + section_html + html +'</div></div>'
Jamsheer5073ac42019-07-12 12:28:34 +0530667 if doc_html:
Rucha Mahabal27512c82020-03-09 17:29:23 +0530668 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 +0530669
670 return {'html': doc_html}