Merge pull request #17035 from gaurav-naik/issue-17033

fix(regional,italy): autoset tax id, cf from customer before validating
diff --git a/erpnext/accounts/doctype/journal_entry/journal_entry.py b/erpnext/accounts/doctype/journal_entry/journal_entry.py
index 7c48b5c..92342f4 100644
--- a/erpnext/accounts/doctype/journal_entry/journal_entry.py
+++ b/erpnext/accounts/doctype/journal_entry/journal_entry.py
@@ -52,11 +52,6 @@
 		self.update_loan()
 		self.update_inter_company_jv()
 
-	def before_print(self):
-		self.gl_entries = frappe.get_list("GL Entry",filters={"voucher_type": "Journal Entry",
-			"voucher_no": self.name} ,
-			fields=["account", "party_type", "party", "debit", "credit", "remarks"]
-		)
 
 	def get_title(self):
 		return self.pay_to_recd_from or self.accounts[0].account
diff --git a/erpnext/accounts/doctype/payment_entry/payment_entry.py b/erpnext/accounts/doctype/payment_entry/payment_entry.py
index f356ef8..9100410 100644
--- a/erpnext/accounts/doctype/payment_entry/payment_entry.py
+++ b/erpnext/accounts/doctype/payment_entry/payment_entry.py
@@ -70,11 +70,6 @@
 		self.update_advance_paid()
 		self.update_expense_claim()
 
-	def before_print(self):
-		self.gl_entries = frappe.get_list("GL Entry",filters={"voucher_type": "Payment Entry",
-			"voucher_no": self.name} ,
-			fields=["account", "party_type", "party", "debit", "credit", "remarks"]
-		)
 
 	def on_cancel(self):
 		self.setup_party_account_field()
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index 53eb731..450f2d0 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -55,11 +55,6 @@
 		if not self.on_hold:
 			self.release_date = ''
 
-	def before_print(self):
-		self.gl_entries = frappe.get_list("GL Entry",filters={"voucher_type": "Purchase Invoice",
-			"voucher_no": self.name} ,
-			fields=["account", "party_type", "party", "debit", "credit"]
-		)
 
 	def invoice_is_blocked(self):
 		return self.on_hold and (not self.release_date or self.release_date > getdate(nowdate()))
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index 61e1224..489343c 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -205,11 +205,6 @@
 	def before_cancel(self):
 		self.update_time_sheet(None)
 
-	def before_print(self):
-		self.gl_entries = frappe.get_list("GL Entry",filters={"voucher_type": "Sales Invoice",
-			"voucher_no": self.name} ,
-			fields=["account", "party_type", "party", "debit", "credit"]
-		)
 
 	def on_cancel(self):
 		self.check_close_sales_order("sales_order")
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 34bbe7b..86b1ab6 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -116,6 +116,12 @@
 			self.validate_non_invoice_documents_schedule()
 
 	def before_print(self):
+		if self.doctype in ['Journal Entry', 'Payment Entry', 'Sales Invoice', 'Purchase Invoice']:
+			self.gl_entries = frappe.get_list("GL Entry", filters={
+				"voucher_type": self.doctype,
+				"voucher_no": self.name
+			}, fields=["account", "party_type", "party", "debit", "credit", "remarks"])
+
 		if self.doctype in ['Purchase Order', 'Sales Order', 'Sales Invoice', 'Purchase Invoice',
 							'Supplier Quotation', 'Purchase Receipt', 'Delivery Note', 'Quotation']:
 			if self.get("group_same_items"):
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index 7d49ad5..9d1e7b1 100755
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -587,5 +587,5 @@
 execute:frappe.delete_doc('DocType', 'Notification Control')
 erpnext.patches.v11_0.remove_barcodes_field_from_copy_fields_to_variants
 erpnext.patches.v10_0.item_barcode_childtable_migrate # 16-02-2019
-erpnext.patches.v11_0.make_italian_localization_fields # 01-03-2019
-erpnext.patches.v11_1.make_job_card_time_logs
\ No newline at end of file
+erpnext.patches.v11_0.make_italian_localization_fields # 26-03-2019
+erpnext.patches.v11_1.make_job_card_time_logs
diff --git a/erpnext/patches/v11_0/make_italian_localization_fields.py b/erpnext/patches/v11_0/make_italian_localization_fields.py
index 44a281f..79958b9 100644
--- a/erpnext/patches/v11_0/make_italian_localization_fields.py
+++ b/erpnext/patches/v11_0/make_italian_localization_fields.py
@@ -6,7 +6,6 @@
 from erpnext.regional.italy import state_codes
 import frappe
 
-
 def execute():
 	company = frappe.get_all('Company', filters = {'country': 'Italy'})
 	if not company:
@@ -27,4 +26,12 @@
 	frappe.db.sql("""
 		UPDATE tabAddress set {condition} country_code = UPPER(ifnull((select code
 			from `tabCountry` where name = `tabAddress`.country), ''))
+			where country_code is null and state_code is null
 	""".format(condition=condition))
+
+	frappe.db.sql("""
+		UPDATE `tabSales Invoice Item` si, `tabSales Order` so
+			set si.customer_po_no = so.po_no, si.customer_po_date = so.po_date
+		WHERE
+			si.sales_order = so.name and so.po_no is not null
+	""")
diff --git a/erpnext/regional/italy/e-invoice.xml b/erpnext/regional/italy/e-invoice.xml
index 912b789..935077b 100644
--- a/erpnext/regional/italy/e-invoice.xml
+++ b/erpnext/regional/italy/e-invoice.xml
@@ -127,22 +127,42 @@
           <ImportoBollo>{{ format_float(doc.stamp_duty) }}</ImportoBollo>
         </DatiBollo>
         {%- endif %}
-        <ImportoTotaleDocumento>{{ format_float(doc.grand_total) }}</ImportoTotaleDocumento>
+        {%- if doc.discount_amount %}
+          <ScontoMaggiorazione>
+            {%- if doc.discount_amount > 0.0 %}
+              <Tipo>SC</Tipo>
+            {%- else %}
+              <Tipo>MG</Tipo>
+            {%- endif %}
+            {%- if doc.additional_discount_percentage > 0.0 %}
+              <Percentuale>{{ format_float(doc.additional_discount_percentage) }}</Percentuale>
+            {%- endif %}
+            <Importo>{{ format_float(doc.discount_amount) }}</Importo>
+          </ScontoMaggiorazione>
+        {%- endif %}
+        <ImportoTotaleDocumento>{{ format_float(doc.rounded_total or doc.grand_total) }}</ImportoTotaleDocumento>
         <Causale>VENDITA</Causale>
       </DatiGeneraliDocumento>
-      {%- if doc.po_no %}
-      <DatiOrdineAcquisto>
-        <IdDocumento>{{ doc.po_no }}</IdDocumento>
-        {%- if doc.po_date %}
-        <Data>{{ doc.po_date }}</Data>
-        {%- endif %}
-      </DatiOrdineAcquisto>
-      {%- endif %}
+      {%- for po_no, po_date in doc.customer_po_data.items() %}
+        <DatiOrdineAcquisto>
+            <IdDocumento>{{ po_no }}</IdDocumento>
+            <Data>{{ po_date }}</Data>
+        </DatiOrdineAcquisto>
+      {%- endfor %}
       {%- if doc.is_return and doc.return_against_unamended %}
       <DatiFattureCollegate>
         <IdDocumento>{{ doc.return_against_unamended }}</IdDocumento>
       </DatiFattureCollegate>
       {%- endif %}
+      {%- for row in doc.e_invoice_items %}
+        {%- if row.delivery_note %}
+          <DatiDDT>
+              <NumeroDDT>{{ row.delivery_note }}</NumeroDDT>
+              <DataDDT>{{ frappe.db.get_value('Delivery Note', row.delivery_note, 'posting_date') }}</DataDDT>
+              <RiferimentoNumeroLinea>{{ row.idx }}</RiferimentoNumeroLinea>
+          </DatiDDT>
+        {%- endif %}
+      {%- endfor %}
       {%- if doc.shipping_address_data %}
       <DatiTrasporto>
       <IndirizzoResa>
@@ -164,7 +184,11 @@
         <UnitaMisura>{{ item.stock_uom }}</UnitaMisura>
         <PrezzoUnitario>{{ format_float(item.price_list_rate or item.rate) }}</PrezzoUnitario>
         {{ render_discount_or_margin(item) }}
-        <PrezzoTotale>{{ format_float(item.amount) }}</PrezzoTotale>
+        {%- if (item.discount_amount or item.rate_with_margin) %}
+          <PrezzoTotale>{{ format_float(item.net_amount) }}</PrezzoTotale>
+        {%- else %}
+          <PrezzoTotale>{{ format_float(item.amount) }}</PrezzoTotale>
+        {%- endif %}
         <AliquotaIVA>{{ format_float(item.tax_rate) }}</AliquotaIVA>
         {%- if item.tax_exemption_reason %}
         <Natura>{{ item.tax_exemption_reason.split("-")[0] }}</Natura>
@@ -198,7 +222,9 @@
         <ModalitaPagamento>{{ payment_term.mode_of_payment_code.split("-")[0] }}</ModalitaPagamento>
         <DataScadenzaPagamento>{{ payment_term.due_date }}</DataScadenzaPagamento>
         <ImportoPagamento>{{ format_float(payment_term.payment_amount) }}</ImportoPagamento>
-        <IstitutoFinanziario>{{ payment_term.bank_account_name }}</IstitutoFinanziario>
+        {%- if payment_term.bank_account_name %}
+          <IstitutoFinanziario>{{ payment_term.bank_account_name }}</IstitutoFinanziario>
+        {%- endif %}
         {%- if payment_term.bank_account_iban %}
           <IBAN>{{ payment_term.bank_account_iban }}</IBAN>
           <ABI>{{ payment_term.bank_account_iban[5:10] }}</ABI>
diff --git a/erpnext/regional/italy/sales_invoice.js b/erpnext/regional/italy/sales_invoice.js
index 3457f71..586a529 100644
--- a/erpnext/regional/italy/sales_invoice.js
+++ b/erpnext/regional/italy/sales_invoice.js
@@ -3,15 +3,26 @@
 		refresh: (frm) => {
 			if(frm.doc.docstatus == 1) {
 				frm.add_custom_button('Generate E-Invoice', () => {
-					var w = window.open(
-						frappe.urllib.get_full_url(
-							"/api/method/erpnext.regional.italy.utils.generate_single_invoice?"
-							+ "docname=" + frm.doc.name
-						)
-					)
-					if (!w) {
-						frappe.msgprint(__("Please enable pop-ups")); return;
-					}
+					frm.call({
+						method: "erpnext.regional.italy.utils.generate_single_invoice",
+						args: {
+							docname: frm.doc.name
+						},
+						callback: function(r) {
+							frm.reload_doc();
+							if(r.message) {
+								var w = window.open(
+									frappe.urllib.get_full_url(
+										"/api/method/erpnext.regional.italy.utils.download_e_invoice_file?"
+										+ "file_name=" + r.message
+									)
+								)
+								if (!w) {
+									frappe.msgprint(__("Please enable pop-ups")); return;
+								}
+							}
+						}
+					});
 				});
 			}
 		}
diff --git a/erpnext/regional/italy/setup.py b/erpnext/regional/italy/setup.py
index 2b6e3af..1526d6f 100644
--- a/erpnext/regional/italy/setup.py
+++ b/erpnext/regional/italy/setup.py
@@ -26,6 +26,22 @@
 			print_hide=1, hidden=1, read_only=1, options="currency")
 	]
 
+	customer_po_fields = [
+		dict(fieldname='customer_po_details', label='Customer PO',
+			fieldtype='Section Break', insert_after='image'),
+		dict(fieldname='customer_po_no', label='Customer PO No',
+			fieldtype='Data', insert_after='customer_po_details',
+			fetch_from = 'sales_order.po_no',
+			print_hide=1, allow_on_submit=1, fetch_if_empty= 1, read_only=1, no_copy=1),
+		dict(fieldname='customer_po_clm_brk', label='',
+			fieldtype='Column Break', insert_after='customer_po_no',
+			print_hide=1, read_only=1),
+		dict(fieldname='customer_po_date', label='Customer PO Date',
+			fieldtype='Date', insert_after='customer_po_clm_brk',
+			fetch_from = 'sales_order.po_date',
+			print_hide=1, allow_on_submit=1, fetch_if_empty= 1, read_only=1, no_copy=1)
+	]
+
 	custom_fields = {
 		'Company': [
 			dict(fieldname='sb_e_invoicing', label='E-Invoicing',
@@ -128,7 +144,7 @@
 		'Purchase Invoice Item': invoice_item_fields,
 		'Sales Order Item': invoice_item_fields,
 		'Delivery Note Item': invoice_item_fields,
-		'Sales Invoice Item': invoice_item_fields,
+		'Sales Invoice Item': invoice_item_fields + customer_po_fields,
 		'Quotation Item': invoice_item_fields,
 		'Purchase Order Item': invoice_item_fields,
 		'Purchase Receipt Item': invoice_item_fields,
diff --git a/erpnext/regional/italy/utils.py b/erpnext/regional/italy/utils.py
index 89a603f..435faea 100644
--- a/erpnext/regional/italy/utils.py
+++ b/erpnext/regional/italy/utils.py
@@ -82,6 +82,14 @@
 		if item.tax_rate == 0.0 and item.tax_amount == 0.0:
 			item.tax_exemption_reason = tax_data["0.0"]["tax_exemption_reason"]
 
+	customer_po_data = {}
+	for d in invoice.e_invoice_items:
+		if (d.customer_po_no and d.customer_po_date
+			and d.customer_po_no not in customer_po_data):
+			customer_po_data[d.customer_po_no] = d.customer_po_date
+
+	invoice.customer_po_data = customer_po_data
+
 	return invoice
 
 def get_conditions(filters):
@@ -273,13 +281,18 @@
 def generate_single_invoice(docname):
 	doc = frappe.get_doc("Sales Invoice", docname)
 
+
 	e_invoice = prepare_and_attach_invoice(doc, True)
 
+	return e_invoice.file_name
+
+@frappe.whitelist()
+def download_e_invoice_file(file_name):
 	content = None
-	with open(frappe.get_site_path('private', 'files', e_invoice.file_name), "r") as f:
+	with open(frappe.get_site_path('private', 'files', file_name), "r") as f:
 		content = f.read()
 
-	frappe.local.response.filename = e_invoice.file_name
+	frappe.local.response.filename = file_name
 	frappe.local.response.filecontent = content
 	frappe.local.response.type = "download"