<commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2015, ESS and contributors
# For license information, please see license.txt

from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import getdate, cstr

class LabTest(Document):
	def on_submit(self):
		frappe.db.set_value(self.doctype,self.name,"submitted_date", getdate())
		insert_lab_test_to_medical_record(self)
		frappe.db.set_value("Lab Test", self.name, "status", "Completed")

	def on_cancel(self):
		delete_lab_test_from_medical_record(self)
		frappe.db.set_value("Lab Test", self.name, "status", "Cancelled")
		self.reload()

	def on_update(self):
		if(self.sensitivity_test_items):
			sensitivity = sorted(self.sensitivity_test_items, key=lambda x: x.antibiotic_sensitivity)
			for i, item in enumerate(sensitivity):
				item.idx = i+1
			self.sensitivity_test_items = sensitivity

	def after_insert(self):
		if(self.prescription):
			frappe.db.set_value("Lab Prescription", self.prescription, "test_created", 1)
			if frappe.db.get_value("Lab Prescription", self.prescription, 'invoiced') == 1:
				self.invoiced = True
		if not self.test_name and self.template:
			self.load_test_from_template()
			self.reload()

	def load_test_from_template(self):
		lab_test = self
		create_test_from_template(lab_test)
		self.reload()

def create_test_from_template(lab_test):
	template = frappe.get_doc("Lab Test Template", lab_test.template)
	patient = frappe.get_doc("Patient", lab_test.patient)

	lab_test.test_name = template.test_name
	lab_test.result_date = getdate()
	lab_test.department = template.department
	lab_test.test_group = template.test_group

	lab_test = create_sample_collection(lab_test, template, patient, None)
	lab_test = load_result_format(lab_test, template, None, None)

@frappe.whitelist()
def update_status(status, name):
	frappe.db.sql("""update `tabLab Test` set status=%s, approved_date=%s where name = %s""", (status, getdate(), name))

@frappe.whitelist()
def update_lab_test_print_sms_email_status(print_sms_email, name):
	frappe.db.set_value("Lab Test",name,print_sms_email,1)

@frappe.whitelist()
def create_multiple(doctype, docname):
	lab_test_created = False
	if doctype == "Sales Invoice":
		lab_test_created = create_lab_test_from_invoice(docname)
	elif doctype == "Patient Encounter":
		lab_test_created = create_lab_test_from_encounter(docname)

	if lab_test_created:
		frappe.msgprint(_("Lab Test(s) "+lab_test_created+" created."))
	else:
		frappe.msgprint(_("No Lab Test created"))

def create_lab_test_from_encounter(encounter_id):
	lab_test_created = False
	encounter = frappe.get_doc("Patient Encounter", encounter_id)

	lab_test_ids = frappe.db.sql("""select lp.name, lp.test_code, lp.invoiced
	from `tabPatient Encounter` et, `tabLab Prescription` lp
	where et.patient=%s and lp.parent=%s and
	lp.parent=et.name and lp.test_created=0 and et.docstatus=1""", (encounter.patient, encounter_id))

	if lab_test_ids:
		patient = frappe.get_doc("Patient", encounter.patient)
		for lab_test_id in lab_test_ids:
			template = get_lab_test_template(lab_test_id[1])
			if template:
				lab_test = create_lab_test_doc(lab_test_id[2], encounter.practitioner, patient, template)
				lab_test.save(ignore_permissions = True)
				frappe.db.set_value("Lab Prescription", lab_test_id[0], "test_created", 1)
				if not lab_test_created:
					lab_test_created = lab_test.name
				else:
					lab_test_created += ", "+lab_test.name
	return lab_test_created


def create_lab_test_from_invoice(invoice_name):
	lab_test_created = False
	invoice = frappe.get_doc("Sales Invoice", invoice_name)
	if invoice.patient:
		patient = frappe.get_doc("Patient", invoice.patient)
		for item in invoice.items:
			test_created = 0
			if item.reference_dt == "Lab Prescription":
				test_created = frappe.db.get_value("Lab Prescription", item.reference_dn, "test_created")
			elif item.reference_dt == "Lab Test":
				test_created = 1
			if test_created != 1:
				template = get_lab_test_template(item.item_code)
				if template:
					lab_test = create_lab_test_doc(True, invoice.ref_practitioner, patient, template)
					lab_test.save(ignore_permissions = True)
					frappe.db.set_value("Sales Invoice Item", item.name, "reference_dt", "Lab Test")
					frappe.db.set_value("Sales Invoice Item", item.name, "reference_dn", lab_test.name)
					if not lab_test_created:
						lab_test_created = lab_test.name
					else:
						lab_test_created += ", "+lab_test.name
	return lab_test_created

def get_lab_test_template(item):
	template_id = check_template_exists(item)
	if template_id:
		return frappe.get_doc("Lab Test Template", template_id)
	return False

def check_template_exists(item):
	template_exists = frappe.db.exists(
		"Lab Test Template",
		{
			'item': item
		}
	)
	if template_exists:
		return template_exists
	return False

def create_lab_test_doc(invoiced, practitioner, patient, template):
	lab_test = frappe.new_doc("Lab Test")
	lab_test.invoiced = invoiced
	lab_test.practitioner = practitioner<commit_msg>Fix - Create Multiple Lab Test from Sales Invoice or from Patient Encounter<commit_after># -*- coding: utf-8 -*-
# Copyright (c) 2015, ESS and contributors
# For license information, please see license.txt

from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import getdate, cstr

class LabTest(Document):
	def on_submit(self):
		frappe.db.set_value(self.doctype,self.name,"submitted_date", getdate())
		insert_lab_test_to_medical_record(self)
		frappe.db.set_value("Lab Test", self.name, "status", "Completed")

	def on_cancel(self):
		delete_lab_test_from_medical_record(self)
		frappe.db.set_value("Lab Test", self.name, "status", "Cancelled")
		self.reload()

	def on_update(self):
		if(self.sensitivity_test_items):
			sensitivity = sorted(self.sensitivity_test_items, key=lambda x: x.antibiotic_sensitivity)
			for i, item in enumerate(sensitivity):
				item.idx = i+1
			self.sensitivity_test_items = sensitivity

	def after_insert(self):
		if(self.prescription):
			frappe.db.set_value("Lab Prescription", self.prescription, "test_created", 1)
			if frappe.db.get_value("Lab Prescription", self.prescription, 'invoiced') == 1:
				self.invoiced = True
		if not self.test_name and self.template:
			self.load_test_from_template()
			self.reload()

	def load_test_from_template(self):
		lab_test = self
		create_test_from_template(lab_test)
		self.reload()

def create_test_from_template(lab_test):
	template = frappe.get_doc("Lab Test Template", lab_test.template)
	patient = frappe.get_doc("Patient", lab_test.patient)

	lab_test.test_name = template.test_name
	lab_test.result_date = getdate()
	lab_test.department = template.department
	lab_test.test_group = template.test_group

	lab_test = create_sample_collection(lab_test, template, patient, None)
	lab_test = load_result_format(lab_test, template, None, None)

@frappe.whitelist()
def update_status(status, name):
	frappe.db.sql("""update `tabLab Test` set status=%s, approved_date=%s where name = %s""", (status, getdate(), name))

@frappe.whitelist()
def update_lab_test_print_sms_email_status(print_sms_email, name):
	frappe.db.set_value("Lab Test",name,print_sms_email,1)

@frappe.whitelist()
def create_multiple(doctype, docname):
	lab_test_created = False
	if doctype == "Sales Invoice":
		lab_test_created = create_lab_test_from_invoice(docname)
	elif doctype == "Patient Encounter":
		lab_test_created = create_lab_test_from_encounter(docname)

	if lab_test_created:
		frappe.msgprint(_("Lab Test(s) "+lab_test_created+" created."))
	else:
		frappe.msgprint(_("No Lab Test created"))

def create_lab_test_from_encounter(encounter_id):
	lab_test_created = False
	encounter = frappe.get_doc("Patient Encounter", encounter_id)

	lab_test_ids = frappe.db.sql("""select lp.name, lp.test_code, lp.invoiced
	from `tabPatient Encounter` et, `tabLab Prescription` lp
	where et.patient=%s and lp.parent=%s and
	lp.parent=et.name and lp.test_created=0 and et.docstatus=1""", (encounter.patient, encounter_id))

	if lab_test_ids:
		patient = frappe.get_doc("Patient", encounter.patient)
		for lab_test_id in lab_test_ids:
			template = get_lab_test_template(lab_test_id[1])
			if template:
				lab_test = create_lab_test_doc(lab_test_id[2], encounter.practitioner, patient, template)
				lab_test.save(ignore_permissions = True)
				frappe.db.set_value("Lab Prescription", lab_test_id[0], "test_created", 1)
				if not lab_test_created:
					lab_test_created = lab_test.name
				else:
					lab_test_created += ", "+lab_test.name
	return lab_test_created


def create_lab_test_from_invoice(invoice_name):
	lab_test_created = False
	invoice = frappe.get_doc("Sales Invoice", invoice_name)
	if invoice.patient:
		patient = frappe.get_doc("Patient", invoice.patient)
		for item in invoice.items:
			test_created = 0
			if item.reference_dt == "Lab Prescription":
				test_created = frappe.db.get_value("Lab Prescription", item.reference_dn, "test_created")
			elif item.reference_dt == "Lab Test":
				test_created = 1
			if test_created != 1:
				template = get_lab_test_template(item.item_code)
				if template:
					lab_test = create_lab_test_doc(True, invoice.ref_practitioner, patient, template)
					if item.reference_dt == "Lab Prescription":
						lab_test.prescription = item.reference_dn
					lab_test.save(ignore_permissions = True)
					if item.reference_dt != "Lab Prescription":
						frappe.db.set_value("Sales Invoice Item", item.name, "reference_dt", "Lab Test")
						frappe.db.set_value("Sales Invoice Item", item.name, "reference_dn", lab_test.name)
					if not lab_test_created:
						lab_test_created = lab_test.name
					else:
						lab_test_created += ", "+lab_test.name
	return lab_test_created

def get_lab_test_template(item):
	template_id = check_template_exists(item)
	if template_id:
		return frappe.get_doc("Lab Test Template", template_id)
	return False

def check_template_exists(item):
	template_exists = frappe.db.exists(
		"Lab Test Template",
		{
			'item': item
		}
	)
	if template_exists:
		return template_exists
	return False

def create_lab_test_doc(invoiced, practitioner, patient, template):
	lab_test = frappe.new_doc("Lab Test")
	lab_test.invoiced = invoiced
	lab_test.practitioner = practitioner
{'fraction_non_alphanumeric': 0.10872923908845114, 'fraction_numerical': 0.0034762456546929316, 'mean_word_length': 5.493416927899687, 'pattern_counts': {'":': 10, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5757994', 'n_tokens_mistral': 3976, 'n_tokens_neox': 3605, 'n_words': 734}