blob: b038d8f0a589b18539b6b64ed77217f720773423 [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
6import frappe
7import datetime
8from frappe import _
Jamsheer54ae74e2018-07-13 21:10:14 +05309from frappe.utils import date_diff, getdate
Jamsheerba119722018-07-06 15:58:13 +053010from erpnext.healthcare.doctype.healthcare_settings.healthcare_settings import get_income_account
11from erpnext.healthcare.doctype.patient_appointment.patient_appointment import validity_exists
12from erpnext.healthcare.doctype.fee_validity.fee_validity import create_fee_validity, update_fee_validity
13
14@frappe.whitelist()
15def get_healthcare_services_to_invoice(patient):
16 patient = frappe.get_doc("Patient", patient)
17 if patient:
18 if patient.customer:
19 item_to_invoice = []
20 patient_appointments = frappe.get_list("Patient Appointment",{'patient': patient.name, 'invoiced': False},
21 order_by="appointment_date")
22 if patient_appointments:
23 fee_validity_details = []
24 valid_days = frappe.db.get_value("Healthcare Settings", None, "valid_days")
25 max_visit = frappe.db.get_value("Healthcare Settings", None, "max_visit")
26 for patient_appointment in patient_appointments:
27 patient_appointment_obj = frappe.get_doc("Patient Appointment", patient_appointment['name'])
28
29 if patient_appointment_obj.procedure_template:
30 if frappe.db.get_value("Clinical Procedure Template", patient_appointment_obj.procedure_template, "is_billable") == 1:
31 item_to_invoice.append({'reference_type': 'Patient Appointment', 'reference_name': patient_appointment_obj.name, 'service': patient_appointment_obj.procedure_template})
32 else:
33 practitioner_exist_in_list = False
34 skip_invoice = False
35 if fee_validity_details:
36 for validity in fee_validity_details:
37 if validity['practitioner'] == patient_appointment_obj.practitioner:
38 practitioner_exist_in_list = True
39 if validity['valid_till'] >= patient_appointment_obj.appointment_date:
40 validity['visits'] = validity['visits']+1
41 if int(max_visit) > validity['visits']:
42 skip_invoice = True
43 if not skip_invoice:
44 validity['visits'] = 1
45 validity['valid_till'] = patient_appointment_obj.appointment_date + datetime.timedelta(days=int(valid_days))
46 if not practitioner_exist_in_list:
47 valid_till = patient_appointment_obj.appointment_date + datetime.timedelta(days=int(valid_days))
48 visits = 0
49 validity_exist = validity_exists(patient_appointment_obj.practitioner, patient_appointment_obj.patient)
50 if validity_exist:
51 fee_validity = frappe.get_doc("Fee Validity", validity_exist[0][0])
52 valid_till = fee_validity.valid_till
53 visits = fee_validity.visited
54 fee_validity_details.append({'practitioner': patient_appointment_obj.practitioner,
55 'valid_till': valid_till, 'visits': visits})
56
57 if not skip_invoice:
58 practitioner_charge = 0
59 income_account = None
60 if patient_appointment_obj.practitioner:
61 practitioner_charge = get_practitioner_charge(patient_appointment_obj.practitioner)
62 income_account = get_income_account(patient_appointment_obj.practitioner, patient_appointment_obj.company)
63 item_to_invoice.append({'reference_type': 'Patient Appointment', 'reference_name': patient_appointment_obj.name,
64 'service': 'Consulting Charges', 'rate': practitioner_charge,
65 'income_account': income_account})
66
67 encounters = frappe.get_list("Patient Encounter", {'patient': patient.name, 'invoiced': False, 'docstatus': 1})
68 if encounters:
69 for encounter in encounters:
70 encounter_obj = frappe.get_doc("Patient Encounter", encounter['name'])
71 if not encounter_obj.appointment:
72 practitioner_charge = 0
73 income_account = None
74 if encounter_obj.practitioner:
75 practitioner_charge = get_practitioner_charge(encounter_obj.practitioner)
76 income_account = get_income_account(encounter_obj.practitioner, encounter_obj.company)
77 item_to_invoice.append({'reference_type': 'Patient Encounter', 'reference_name': encounter_obj.name,
78 'service': 'Consulting Charges', 'rate': practitioner_charge,
79 'income_account': income_account})
80
81 lab_tests = frappe.get_list("Lab Test", {'patient': patient.name, 'invoiced': False})
82 if lab_tests:
83 for lab_test in lab_tests:
84 lab_test_obj = frappe.get_doc("Lab Test", lab_test['name'])
85 if frappe.db.get_value("Lab Test Template", lab_test_obj.template, "is_billable") == 1:
86 item_to_invoice.append({'reference_type': 'Lab Test', 'reference_name': lab_test_obj.name, 'service': lab_test_obj.template})
87
88 lab_rxs = frappe.db.sql("""select lp.name from `tabPatient Encounter` et,
89 `tabLab Prescription` lp where et.patient=%s and lp.parent=et.name and lp.test_created=0 and lp.invoiced=0""", (patient.name))
90 if lab_rxs:
91 for lab_rx in lab_rxs:
92 rx_obj = frappe.get_doc("Lab Prescription", lab_rx[0])
93 if rx_obj.test_code and (frappe.db.get_value("Lab Test Template", rx_obj.test_code, "is_billable") == 1):
94 item_to_invoice.append({'reference_type': 'Lab Prescription', 'reference_name': rx_obj.name, 'service': rx_obj.test_code})
95
96 procedures = frappe.get_list("Clinical Procedure", {'patient': patient.name, 'invoiced': False})
97 if procedures:
98 for procedure in procedures:
99 procedure_obj = frappe.get_doc("Clinical Procedure", procedure['name'])
100 if not procedure_obj.appointment:
101 if procedure_obj.procedure_template and (frappe.db.get_value("Clinical Procedure Template", procedure_obj.procedure_template, "is_billable") == 1):
102 item_to_invoice.append({'reference_type': 'Clinical Procedure', 'reference_name': procedure_obj.name, 'service': procedure_obj.procedure_template})
103
104 procedure_rxs = frappe.db.sql("""select pp.name from `tabPatient Encounter` et,
105 `tabProcedure Prescription` pp where et.patient=%s and pp.parent=et.name and
106 pp.procedure_created=0 and pp.invoiced=0 and pp.appointment_booked=0""", (patient.name))
107 if procedure_rxs:
108 for procedure_rx in procedure_rxs:
109 rx_obj = frappe.get_doc("Procedure Prescription", procedure_rx[0])
110 if frappe.db.get_value("Clinical Procedure Template", rx_obj.procedure, "is_billable") == 1:
111 item_to_invoice.append({'reference_type': 'Procedure Prescription', 'reference_name': rx_obj.name, 'service': rx_obj.procedure})
112
113 procedure_consumables = frappe.db.sql("""select pc.name from `tabClinical Procedure` cp,
114 `tabClinical Procedure Item` pc where cp.patient=%s and pc.parent=cp.name and
115 pc.invoice_separately_as_consumables=1 and pc.invoiced=0""", (patient.name))
116 if procedure_consumables:
117 for procedure_consumable in procedure_consumables:
118 procedure_consumable_obj = frappe.get_doc("Clinical Procedure Item", procedure_consumable[0])
119 item_to_invoice.append({'reference_type': 'Clinical Procedure Item', 'reference_name': procedure_consumable_obj.name,
120 'service': procedure_consumable_obj.item_code, 'qty': procedure_consumable_obj.qty})
121
Jamsheer54ae74e2018-07-13 21:10:14 +0530122 inpatient_services = frappe.db.sql("""select io.name, io.parent from `tabInpatient Record` ip,
123 `tabInpatient Occupancy` io where ip.patient=%s and io.parent=ip.name and
124 io.left=1 and io.invoiced=0""", (patient.name))
125 if inpatient_services:
126 for inpatient_service in inpatient_services:
127 inpatient_occupancy = frappe.get_doc("Inpatient Occupancy", inpatient_service[0])
128 service_unit_type = frappe.get_doc("Healthcare Service Unit Type", frappe.db.get_value("Healthcare Service Unit", inpatient_occupancy.service_unit, "service_unit_type"))
129 if service_unit_type and service_unit_type.is_billable == 1:
130 qty = date_diff(getdate(inpatient_occupancy.check_out), getdate(inpatient_occupancy.check_in))
131 if qty < 1:
132 qty = 1
133 item_to_invoice.append({'reference_type': 'Inpatient Occupancy', 'reference_name': inpatient_occupancy.name,
134 'service': service_unit_type.item, 'qty': qty})
135
Jamsheerba119722018-07-06 15:58:13 +0530136 return item_to_invoice
137 else:
138 frappe.throw(_("The Patient {0} do not have customer refrence to invoice").format(patient.name))
139
140def get_practitioner_charge(practitioner):
141 practitioner_charge = frappe.db.get_value("Healthcare Practitioner", practitioner, "op_consulting_charge")
142 if practitioner_charge:
143 return practitioner_charge
144
145def manage_invoice_submit_cancel(doc, method):
146 if doc.items:
147 for item in doc.items:
148 if item.reference_dt and item.reference_dn:
149 if frappe.get_meta(item.reference_dt).has_field("invoiced"):
Jamsheer146683b2018-07-25 11:30:30 +0530150 set_invoiced(item, method, doc.name)
Jamsheerba119722018-07-06 15:58:13 +0530151
Jamsheer146683b2018-07-25 11:30:30 +0530152def set_invoiced(item, method, ref_invoice=None):
Jamsheerba119722018-07-06 15:58:13 +0530153 invoiced = False
154 if(method=="on_submit"):
155 validate_invoiced_on_submit(item)
156 invoiced = True
157
158 frappe.db.set_value(item.reference_dt, item.reference_dn, "invoiced", invoiced)
159 if item.reference_dt == 'Patient Appointment':
160 if frappe.db.get_value('Patient Appointment', item.reference_dn, 'procedure_template'):
161 dt_from_appointment = "Clinical Procedure"
162 else:
Jamsheer146683b2018-07-25 11:30:30 +0530163 manage_fee_validity(item.reference_dn, method, ref_invoice)
Jamsheerba119722018-07-06 15:58:13 +0530164 dt_from_appointment = "Patient Encounter"
165 manage_doc_for_appoitnment(dt_from_appointment, item.reference_dn, invoiced)
166
167 elif item.reference_dt == 'Lab Prescription':
168 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, "Lab Test", "test_created")
169
170 elif item.reference_dt == 'Procedure Prescription':
171 manage_prescriptions(invoiced, item.reference_dt, item.reference_dn, "Clinical Procedure", "procedure_created")
172
173def validate_invoiced_on_submit(item):
174 is_invoiced = frappe.db.get_value(item.reference_dt, item.reference_dn, "invoiced")
175 if is_invoiced == 1:
176 frappe.throw(_("The item referenced by {0} - {1} is already invoiced"\
177 ).format(item.reference_dt, item.reference_dn))
178
179def manage_prescriptions(invoiced, ref_dt, ref_dn, dt, created_check_field):
180 created = frappe.db.get_value(ref_dt, ref_dn, created_check_field)
181 if created == 1:
182 # Fetch the doc created for the prescription
183 doc_created = frappe.db.get_value(dt, {'prescription': item.reference_dn})
184 frappe.db.set_value(dt, doc_created, 'invoiced', invoiced)
185
Jamsheer146683b2018-07-25 11:30:30 +0530186def manage_fee_validity(appointment_name, method, ref_invoice=None):
Jamsheerba119722018-07-06 15:58:13 +0530187 appointment_doc = frappe.get_doc("Patient Appointment", appointment_name)
188 validity_exist = validity_exists(appointment_doc.practitioner, appointment_doc.patient)
189 do_not_update = False
190 visited = 0
191 if validity_exist:
192 fee_validity = frappe.get_doc("Fee Validity", validity_exist[0][0])
193 # Check if the validity is valid
194 if (fee_validity.valid_till >= appointment_doc.appointment_date):
195 if (method == "on_cancel" and appointment_doc.status != "Closed"):
196 visited = fee_validity.visited - 1
197 if visited < 0:
198 visited = 0
199 frappe.db.set_value("Fee Validity", fee_validity.name, "visited", visited)
200 do_not_update = True
201 elif (fee_validity.visited < fee_validity.max_visit):
202 visited = fee_validity.visited + 1
203 frappe.db.set_value("Fee Validity", fee_validity.name, "visited", visited)
204 do_not_update = True
205 else:
206 do_not_update = False
207
208 if not do_not_update:
Jamsheer146683b2018-07-25 11:30:30 +0530209 fee_validity = update_fee_validity(fee_validity, appointment_doc.appointment_date, ref_invoice)
Jamsheerba119722018-07-06 15:58:13 +0530210 visited = fee_validity.visited
211 else:
Jamsheer146683b2018-07-25 11:30:30 +0530212 fee_validity = create_fee_validity(appointment_doc.practitioner, appointment_doc.patient, appointment_doc.appointment_date, ref_invoice)
Jamsheerba119722018-07-06 15:58:13 +0530213 visited = fee_validity.visited
214
215 # Mark All Patient Appointment invoiced = True in the validity range do not cross the max visit
216 if (method == "on_cancel"):
217 invoiced = True
218 else:
219 invoiced = False
220 patient_appointments = frappe.get_list("Patient Appointment",{'patient': fee_validity.patient, 'invoiced': invoiced,
221 'appointment_date':("<=", fee_validity.valid_till), 'practitioner': fee_validity.practitioner}, order_by="appointment_date")
222 if patient_appointments and fee_validity:
223 visit = visited
224 for appointment in patient_appointments:
225 if (method == "on_cancel" and appointment.status != "Closed"):
226 visited = visited - 1
227 if visited < 0:
228 visited = 0
229 frappe.db.set_value("Fee Validity", fee_validity.name, "visited", visited)
230 frappe.db.set_value("Patient Appointment", appointment.name, "invoiced", False)
231 manage_doc_for_appoitnment("Patient Encounter", appointment.name, False)
232 elif int(fee_validity.max_visit) > visit:
233 visited = visited + 1
234 frappe.db.set_value("Fee Validity", fee_validity.name, "visited", visited)
235 frappe.db.set_value("Patient Appointment", appointment.name, "invoiced", True)
236 manage_doc_for_appoitnment("Patient Encounter", appointment.name, True)
237 visit = visit + 1
238
239def manage_doc_for_appoitnment(dt_from_appointment, appointment, invoiced):
240 dn_from_appointment = frappe.db.exists(
241 dt_from_appointment,
242 {
243 "appointment": appointment
244 }
245 )
246 if dn_from_appointment:
247 frappe.db.set_value(dt_from_appointment, dn_from_appointment, "invoiced", invoiced)