Merge pull request #17006 from deepeshgarg007/account-fix

fix: Ignore root company validation setting in company master
diff --git a/erpnext/accounts/doctype/bank_reconciliation/bank_reconciliation.py b/erpnext/accounts/doctype/bank_reconciliation/bank_reconciliation.py
index 9172762..dafa330 100644
--- a/erpnext/accounts/doctype/bank_reconciliation/bank_reconciliation.py
+++ b/erpnext/accounts/doctype/bank_reconciliation/bank_reconciliation.py
@@ -79,8 +79,12 @@
 
 		for d in entries:
 			row = self.append('payment_entries', {})
-			amount = d.debit if d.debit else d.credit
-			d.amount = fmt_money(amount, 2, d.account_currency) + " " + (_("Dr") if d.debit else _("Cr"))
+
+			amount = d.get('debit', 0) - d.get('credit', 0)
+
+			formatted_amount = fmt_money(abs(amount), 2, d.account_currency)
+			d.amount = formatted_amount + " " + (_("Dr") if amount > 0 else _("Cr"))
+
 			d.pop("credit")
 			d.pop("debit")
 			d.pop("account_currency")
diff --git a/erpnext/accounts/party.py b/erpnext/accounts/party.py
index 70e4800..67bd0bd 100644
--- a/erpnext/accounts/party.py
+++ b/erpnext/accounts/party.py
@@ -573,13 +573,17 @@
 	else:
 		return ''
 
-def get_partywise_advanced_payment_amount(party_type="Customer"):
+def get_partywise_advanced_payment_amount(party_type, posting_date = None):
+	cond = "1=1"
+	if posting_date:
+		cond = "posting_date <= '{0}'".format(posting_date)
+
 	data = frappe.db.sql(""" SELECT party, sum({0}) as amount
 		FROM `tabGL Entry`
 		WHERE
 			party_type = %s and against_voucher is null
-			GROUP BY party"""
-		.format(("credit") if party_type == "Customer" else "debit") , party_type)
+			and {1} GROUP BY party"""
+		.format(("credit") if party_type == "Customer" else "debit", cond) , party_type)
 
 	if data:
 		return frappe._dict(data)
\ No newline at end of file
diff --git a/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py b/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py
index 8cb5ac1..ffd1994 100644
--- a/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py
+++ b/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py
@@ -136,7 +136,8 @@
 
 		partywise_total = self.get_partywise_total(party_naming_by, args)
 
-		partywise_advance_amount = get_partywise_advanced_payment_amount(args.get("party_type")) or {}
+		partywise_advance_amount = get_partywise_advanced_payment_amount(args.get("party_type"),
+			self.filters.get("report_date")) or {}
 		for party, party_dict in iteritems(partywise_total):
 			row = [party]
 
@@ -144,7 +145,9 @@
 				row += [self.get_party_name(args.get("party_type"), party)]
 
 			row += [partywise_advance_amount.get(party, 0)]
-			paid_amt = flt(party_dict.paid_amt - partywise_advance_amount.get(party, 0))
+
+			if party_dict.paid_amt > 0:
+				paid_amt = flt(party_dict.paid_amt - partywise_advance_amount.get(party, 0))
 
 			row += [
 				party_dict.invoiced_amt, paid_amt, party_dict.credit_amt, party_dict.outstanding_amt,
diff --git a/erpnext/accounts/report/profitability_analysis/profitability_analysis.py b/erpnext/accounts/report/profitability_analysis/profitability_analysis.py
index 39706ac..a0d8c5f 100644
--- a/erpnext/accounts/report/profitability_analysis/profitability_analysis.py
+++ b/erpnext/accounts/report/profitability_analysis/profitability_analysis.py
@@ -134,6 +134,13 @@
 			"width": 300
 		},
 		{
+			"fieldname": "currency",
+			"label": _("Currency"),
+			"fieldtype": "Link",
+			"options": "Currency",
+			"hidden": 1
+		},
+		{
 			"fieldname": "income",
 			"label": _("Income"),
 			"fieldtype": "Currency",
@@ -153,13 +160,6 @@
 			"fieldtype": "Currency",
 			"options": "currency",
 			"width": 120
-		},
-		{
-			"fieldname": "currency",
-			"label": _("Currency"),
-			"fieldtype": "Link",
-			"options": "Currency",
-			"hidden": 1
 		}
 	]
 
@@ -191,4 +191,4 @@
 	for entry in gl_entries:
 		gl_entries_by_account.setdefault(entry.based_on, []).append(entry)
 
-	return gl_entries_by_account
\ No newline at end of file
+	return gl_entries_by_account
diff --git a/erpnext/projects/doctype/timesheet/timesheet.js b/erpnext/projects/doctype/timesheet/timesheet.js
index 8811ab9..8ffc10e 100644
--- a/erpnext/projects/doctype/timesheet/timesheet.js
+++ b/erpnext/projects/doctype/timesheet/timesheet.js
@@ -10,8 +10,8 @@
 				filters:{
 					'status': 'Active'
 				}
-			}
-		}
+			};
+		};
 
 		frm.fields_dict['time_logs'].grid.get_field('task').get_query = function(frm, cdt, cdn) {
 			var child = locals[cdt][cdn];
@@ -20,33 +20,37 @@
 					'project': child.project,
 					'status': ["!=", "Cancelled"]
 				}
-			}
-		}
+			};
+		};
 
 		frm.fields_dict['time_logs'].grid.get_field('project').get_query = function() {
 			return{
 				filters: {
 					'company': frm.doc.company
 				}
-			}
-		}
+			};
+		};
 	},
 
 	onload: function(frm){
 		if (frm.doc.__islocal && frm.doc.time_logs) {
 			calculate_time_and_amount(frm);
 		}
+
+		if (frm.is_new()) {
+			set_employee_and_company(frm);
+		}
 	},
 
 	refresh: function(frm) {
 		if(frm.doc.docstatus==1) {
 			if(frm.doc.per_billed < 100 && frm.doc.total_billable_hours && frm.doc.total_billable_hours > frm.doc.total_billed_hours){
-				frm.add_custom_button(__("Make Sales Invoice"), function() { frm.trigger("make_invoice") },
+				frm.add_custom_button(__("Make Sales Invoice"), function() { frm.trigger("make_invoice"); },
 					"fa fa-file-alt");
 			}
 
 			if(!frm.doc.salary_slip && frm.doc.employee){
-				frm.add_custom_button(__("Make Salary Slip"), function() { frm.trigger("make_salary_slip") },
+				frm.add_custom_button(__("Make Salary Slip"), function() { frm.trigger("make_salary_slip"); },
 					"fa fa-file-alt");
 			}
 		}
@@ -58,7 +62,7 @@
 				if ((row.from_time <= frappe.datetime.now_datetime()) && !row.completed) {
 					button = 'Resume Timer';
 				}
-			})
+			});
 
 			frm.add_custom_button(__(button), function() {
 				var flag = true;
@@ -77,7 +81,7 @@
 						erpnext.timesheet.timer(frm, row, timestamp);
 						flag = false;
 					}
-				})
+				});
 				// If no activities found to start a timer, create new
 				if (flag) {
 					erpnext.timesheet.timer(frm);
@@ -94,7 +98,7 @@
 		frappe.db.get_value('Company', { 'company_name' : frm.doc.company }, 'standard_working_hours')
 			.then(({ message }) => {
 				(frappe.working_hours = message.standard_working_hours || 0);
-		});
+			});
 	},
 
 	make_invoice: function(frm) {
@@ -125,8 +129,8 @@
 						frappe.set_route("Form", r.message.doctype, r.message.name);
 					}
 				}
-			})
-		})
+			});
+		});
 		dialog.show();
 	},
 
@@ -136,7 +140,7 @@
 			frm: frm
 		});
 	},
-})
+});
 
 frappe.ui.form.on("Timesheet Detail", {
 	time_logs_remove: function(frm) {
@@ -171,22 +175,22 @@
 				.find('[data-fieldname="timer"]')
 				.append(frappe.render_template("timesheet"));
 			frm.trigger("control_timer");
-		})
+		});
 	},
 	hours: function(frm, cdt, cdn) {
-		calculate_end_time(frm, cdt, cdn)
+		calculate_end_time(frm, cdt, cdn);
 	},
 
 	billing_hours: function(frm, cdt, cdn) {
-		calculate_billing_costing_amount(frm, cdt, cdn)
+		calculate_billing_costing_amount(frm, cdt, cdn);
 	},
 
 	billing_rate: function(frm, cdt, cdn) {
-		calculate_billing_costing_amount(frm, cdt, cdn)
+		calculate_billing_costing_amount(frm, cdt, cdn);
 	},
 
 	costing_rate: function(frm, cdt, cdn) {
-		calculate_billing_costing_amount(frm, cdt, cdn)
+		calculate_billing_costing_amount(frm, cdt, cdn);
 	},
 
 	billable: function(frm, cdt, cdn) {
@@ -212,7 +216,7 @@
 					calculate_billing_costing_amount(frm, cdt, cdn);
 				}
 			}
-		})
+		});
 	}
 });
 
@@ -240,23 +244,23 @@
 			frm._setting_hours = true;
 			frappe.model.set_value(cdt, cdn, "to_time",
 				d.format(frappe.defaultDatetimeFormat)).then(() => {
-					frm._setting_hours = false;
-				});
+				frm._setting_hours = false;
+			});
 		}
 	}
-}
+};
 
 var update_billing_hours = function(frm, cdt, cdn){
 	var child = locals[cdt][cdn];
 	if(!child.billable) frappe.model.set_value(cdt, cdn, 'billing_hours', 0.0);
-}
+};
 
 var update_time_rates = function(frm, cdt, cdn){
 	var child = locals[cdt][cdn];
 	if(!child.billable){
 		frappe.model.set_value(cdt, cdn, 'billing_rate', 0.0);
 	}
-}
+};
 
 var calculate_billing_costing_amount = function(frm, cdt, cdn){
 	var child = locals[cdt][cdn];
@@ -270,7 +274,7 @@
 	frappe.model.set_value(cdt, cdn, 'billing_amount', billing_amount);
 	frappe.model.set_value(cdt, cdn, 'costing_amount', costing_amount);
 	calculate_time_and_amount(frm);
-}
+};
 
 var calculate_time_and_amount = function(frm) {
 	var tl = frm.doc.time_logs || [];
@@ -294,4 +298,17 @@
 	frm.set_value("total_hours", total_working_hr);
 	frm.set_value("total_billable_amount", total_billable_amount);
 	frm.set_value("total_costing_amount", total_costing_amount);
-}
\ No newline at end of file
+};
+
+// set employee (and company) to the one that's currently logged in
+const set_employee_and_company = function(frm) {
+	const options = { user_id: frappe.session.user };
+	const fields = ['name', 'company'];
+	frappe.db.get_value('Employee', options, fields).then(({ message }) => {
+		if (message) {
+			// there is an employee with the currently logged in user_id
+			frm.set_value("employee", message.name);
+			frm.set_value("company", message.company);
+		}
+	});
+};
diff --git a/erpnext/regional/italy/e-invoice.xml b/erpnext/regional/italy/e-invoice.xml
index c886ee9..912b789 100644
--- a/erpnext/regional/italy/e-invoice.xml
+++ b/erpnext/regional/italy/e-invoice.xml
@@ -95,13 +95,12 @@
             <Cognome>{{ doc.customer_data.last_name }}</Cognome>
           </Anagrafica>
         {%- else %}
-          {%- if doc.customer_data.is_public_administration %}
-          <CodiceFiscale>{{ doc.customer_data.fiscal_code }}</CodiceFiscale>
-          {%- else %}
           <IdFiscaleIVA>
             <IdPaese>{{ doc.customer_address_data.country_code }}</IdPaese>
             <IdCodice>{{ doc.tax_id | replace("IT","") }}</IdCodice>
           </IdFiscaleIVA>
+          {%- if doc.customer_data.fiscal_code %}
+          <CodiceFiscale>{{ doc.customer_data.fiscal_code }}</CodiceFiscale>
           {%- endif %}
           <Anagrafica>
             <Denominazione>{{ doc.customer_name }}</Denominazione>