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