From e9377e25131891a79f959a9dc90299fa4a4a2799 Mon Sep 17 00:00:00 2001
From: "hello@openetech.com" <pawan@erpnext.com>
Date: Mon, 11 Nov 2019 16:14:28 +0530
Subject: [PATCH] review changes

---
 .../import_supplier_invoice.py                | 101 ++++++++++--------
 1 file changed, 54 insertions(+), 47 deletions(-)

diff --git a/erpnext/regional/doctype/import_supplier_invoice/import_supplier_invoice.py b/erpnext/regional/doctype/import_supplier_invoice/import_supplier_invoice.py
index e28d305e86..f65c7f169a 100644
--- a/erpnext/regional/doctype/import_supplier_invoice/import_supplier_invoice.py
+++ b/erpnext/regional/doctype/import_supplier_invoice/import_supplier_invoice.py
@@ -33,6 +33,11 @@ class ImportSupplierInvoice(Document):
 		mop_str = re.sub('\n', ',', mop_options)
 		mop_dict = dict(item.split("-") for item in mop_str.split(","))
 
+		default_uom = frappe.db.get_value("Stock Settings", fieldname="stock_uom")
+
+		if not default_uom:
+			frappe.throw(_("Please set default UOM in Stock Settings"))
+
 		with zipfile.ZipFile(get_full_path(self.zip_file)) as zf:
 			file_count = 0
 			for file_name in zf.namelist():
@@ -54,6 +59,7 @@ class ImportSupplierInvoice(Document):
 				for line in file_content.find_all("DatiTrasmissione"):
 					destination_code = line.CodiceDestinatario.text
 
+				#read address information from file
 				for line in file_content.find_all("DatiGeneraliDocumento"):
 					document_type = line.TipoDocumento.text
 					bill_date = dateutil.parser.parse(line.Data.text).strftime("%Y-%m-%d")
@@ -84,26 +90,27 @@ class ImportSupplierInvoice(Document):
 
 						total_discount = 0
 
+						#read item information from file
 						for line in file_content.find_all("DettaglioLinee"):
 							if line.find("PrezzoUnitario") and line.find("PrezzoTotale"):
-								unit_rate = float(line.PrezzoUnitario.text) or float(0)
-								line_total = float(line.PrezzoTotale.text) or float(0)
+								unit_rate = flt(line.PrezzoUnitario.text) or 0
+								line_total = flt(line.PrezzoTotale.text) or 0
 
 								if (unit_rate == 0.0):
-									qty = float(1)
-									uom = "nos"
+									qty = 1.0
+									uom = default_uom
 									rate = tax_rate = 0
 								else:
 									if (line_total / unit_rate) == 1.0:
-										qty = float(1)
-										uom = "nos"
+										qty = 1.0
+										uom = default_uom
 									else:
 										if line.find("Quantita"):
-											qty = float(line.Quantita.text) or float(0)
+											qty = flt(line.Quantita.text) or 0
 											if line.find("UnitaMisura"):
 												uom = create_uom(line.UnitaMisura.text)
 											else:
-												uom = "nos"
+												uom = default_uom
 
 									if (unit_rate < 0 and line_total < 0):
 										qty *= -1
@@ -113,7 +120,7 @@ class ImportSupplierInvoice(Document):
 
 									rate = unit_rate
 									if line.find("AliquotaIVA"):
-										tax_rate = float(line.AliquotaIVA.text)
+										tax_rate = flt(line.AliquotaIVA.text)
 
 								line_str = re.sub('[^A-Za-z0-9]+', '-', line.Descrizione.text)
 								item_name = line_str[0:140]
@@ -121,18 +128,19 @@ class ImportSupplierInvoice(Document):
 												"item_code": self.item_code,
 												"item_name": item_name,
 												"description": line_str,
-												"qty": float(qty),
+												"qty": qty,
 												"uom": uom,
 												"rate": rate,
-												"conversion_factor": float(1),
+												"conversion_factor": 1.0,
 												"tax_rate": tax_rate
 											})
 
 								for disc_line in line.find_all("ScontoMaggiorazione"):
 									if disc_line.find("Percentuale"):
-										discount = float(disc_line.Percentuale.text) or float(0)
-										total_discount += float((discount / 100) * (rate * qty))
+										discount = flt(disc_line.Percentuale.text) or 0
+										total_discount += flt((discount / 100) * (rate * qty))
 
+						#read taxes from file
 						for line in file_content.find_all("DatiRiepilogo"):
 							if line.find("AliquotaIVA"):
 								if line.find("EsigibilitaIVA"):
@@ -142,11 +150,12 @@ class ImportSupplierInvoice(Document):
 								taxes.append({
 									"charge_type": "Actual",
 									"account_head": self.tax_account,
-									"tax_rate": float(line.AliquotaIVA.text) or float(0),
+									"tax_rate": flt(line.AliquotaIVA.text) or 0,
 									"description": descr,
-									"tax_amount": float(line.Imposta.text) if len(line.find("Imposta"))!=0 else float(0)
+									"tax_amount": flt(line.Imposta.text) if len(line.find("Imposta"))!=0 else 0
 								})
-				
+
+						#read payment data from file
 						for line in file_content.find_all("DettaglioPagamento"):
 							mop_code = line.ModalitaPagamento.text + '-' + mop_dict.get(line.ModalitaPagamento.text)
 							
@@ -162,19 +171,18 @@ class ImportSupplierInvoice(Document):
 							})
 
 						supplier_name = create_supplier(supplier = supplier, supplier_group = self.supplier_group, 
-														tax_id = tax_id, fiscal_code = fiscal_code,
-														fiscal_regime = fiscal_regime)
+											tax_id = tax_id, fiscal_code = fiscal_code,
+											fiscal_regime = fiscal_regime)
 
 						address = create_address(supplier_name = supplier_name, address_line1 = address_line1, 
-												city = city, province = province, 
-												pin_code = pin_code, country = country)
+									city = city, province = province, 
+									pin_code = pin_code, country = country)
 
 						pi_name = create_purchase_invoice(company = self.company, naming_series = self.invoice_series,
-														supplier_name = supplier_name, bill_no = invoice_no,
-														document_type = document_type, bill_date = bill_date,
-														is_return = return_invoice, destination_code = destination_code,
-														total_discount = total_discount, items = items,
-														taxes = taxes, terms = terms,file_name = file_name)
+									supplier_name = supplier_name, bill_no = invoice_no,document_type = document_type, 
+									bill_date = bill_date,is_return = return_invoice, destination_code = destination_code,
+									total_discount = total_discount, items = items,taxes = taxes, terms = terms,
+									file_name = file_name)
 
 						file_count += 1
 						if pi_name:
@@ -264,36 +272,31 @@ def create_address(**args):
 	existing_address = frappe.get_list("Address", filters)
 
 	if args.address_line1:
-		make_address = frappe.new_doc("Address")
-		make_address.address_line1 = args.address_line1
+		new_address_doc = frappe.new_doc("Address")
+		new_address_doc.address_line1 = args.address_line1
 
 		if args.city:
-			make_address.city = args.city
+			new_address_doc.city = args.city
 		else:
-			make_address.city = "Not Provided"
+			new_address_doc.city = "Not Provided"
 
-		if args.province:
-			make_address.state_code = args.province
-
-		if args.pincode:
-			make_address.pincode = args.pincode
-
-		if args.country:
-			make_address.country = args.country
+		for field in ["province", "pincode", "country"]:
+			if args.get(field):
+				new_address_doc.set(field, args.get(field))
 
 		for address in existing_address:
 			address_doc = frappe.get_doc("Address", address["name"])
-			if (address_doc.address_line1 == make_address.address_line1 and
-				address_doc.pincode == make_address.pincode):
+			if (address_doc.address_line1 == new_address_doc.address_line1 and
+				address_doc.pincode == new_address_doc.pincode):
 				return address
 
-		make_address.append("links", {
+		new_address_doc.append("links", {
 			"link_doctype": "Supplier",
 			"link_name": args.supplier_name
 		})
-		make_address.address_type = "Billing"
-		make_address.insert()
-		return make_address.name
+		new_address_doc.address_type = "Billing"
+		new_address_doc.insert()
+		return new_address_doc.name
 	else:
 		return None
 
@@ -316,28 +319,32 @@ def create_purchase_invoice(**args):
 		})
 
 	try:
+		pi.set_missing_values()
 		pi.insert(ignore_permissions=True)
 
+		#if discount exists in file, apply any discount on grand total
 		if args.total_discount > 0:
 			pi.apply_discount_on = "Grand Total"
 			pi.discount_amount = args.total_discount
 			pi.save()
 
+		#adjust payment amount to match with grand total calculated
 		calc_total = 0
 		adj = 0
 		for term in args.terms:
-			calc_total += float(term["payment_amount"])
-		if float(calc_total - float(pi.grand_total)) != 0:
-			adj = calc_total - float(pi.grand_total)
+			calc_total += flt(term["payment_amount"])
+		if flt(calc_total - flt(pi.grand_total)) != 0:
+			adj = calc_total - flt(pi.grand_total)
 		pi.payment_schedule = []
 		for term in args.terms:
 			pi.append('payment_schedule',{"mode_of_payment_code": term["mode_of_payment_code"],
 			"bank_account_iban": term["bank_account_iban"],
 			"due_date": term["due_date"],
-			"payment_amount": float(term["payment_amount"]) - adj })
+			"payment_amount": flt(term["payment_amount"]) - adj })
 			adj = 0
 		pi.imported_grand_total = calc_total
 		pi.save()
+
 		return pi.name
 	except Exception as e:
 		frappe.log_error(message=e, title="Create Purchase Invoice: " + args.bill_no + "File Name: " + args.file_name)