From e1dc6980d09266b3db115546403d8bbdc0946b1e Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Mon, 5 Jul 2021 14:58:32 +0530
Subject: [PATCH 01/49] feat(Accounts Settings): Add 'Enable Discount
 Accounting' checkbox

---
 .../doctype/accounts_settings/accounts_settings.json     | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/erpnext/accounts/doctype/accounts_settings/accounts_settings.json b/erpnext/accounts/doctype/accounts_settings/accounts_settings.json
index 703e93c075..676c6a8b47 100644
--- a/erpnext/accounts/doctype/accounts_settings/accounts_settings.json
+++ b/erpnext/accounts/doctype/accounts_settings/accounts_settings.json
@@ -12,6 +12,7 @@
   "role_allowed_to_over_bill",
   "make_payment_via_journal_entry",
   "column_break_11",
+  "enable_discount_accounting",
   "check_supplier_invoice_uniqueness",
   "unlink_payment_on_cancellation_of_invoice",
   "automatically_fetch_payment_terms",
@@ -261,6 +262,12 @@
    "fieldname": "post_change_gl_entries",
    "fieldtype": "Check",
    "label": "Create Ledger Entries for Change Amount"
+  },
+  {
+   "default": "0",
+   "fieldname": "enable_discount_accounting",
+   "fieldtype": "Check",
+   "label": "Enable Discount Accounting"
   }
  ],
  "icon": "icon-cog",
@@ -268,7 +275,7 @@
  "index_web_pages_for_search": 1,
  "issingle": 1,
  "links": [],
- "modified": "2021-06-17 20:26:03.721202",
+ "modified": "2021-07-05 14:56:19.820731",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Accounts Settings",

From a6690a8a3df1e467850f98c7a561d2b5b0b295eb Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Mon, 5 Jul 2021 15:09:05 +0530
Subject: [PATCH 02/49] feat(Sales Invoice): Add 'Discount Account' field in
 Items table

---
 .../doctype/sales_invoice_item/sales_invoice_item.json   | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.json b/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.json
index 8e6952a93c..b65903bf5e 100644
--- a/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.json
+++ b/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.json
@@ -63,6 +63,7 @@
   "finance_book",
   "col_break4",
   "expense_account",
+  "discount_account",
   "deferred_revenue",
   "deferred_revenue_account",
   "service_stop_date",
@@ -821,12 +822,18 @@
    "no_copy": 1,
    "options": "currency",
    "read_only": 1
+  },
+  {
+   "fieldname": "discount_account",
+   "fieldtype": "Link",
+   "label": "Discount Account",
+   "options": "Account"
   }
  ],
  "idx": 1,
  "istable": 1,
  "links": [],
- "modified": "2021-02-23 01:05:22.123527",
+ "modified": "2021-07-05 15:07:22.857128",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Sales Invoice Item",

From f6a9374356658f6375b50312838620ae6e14de5a Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 6 Jul 2021 00:36:06 +0530
Subject: [PATCH 03/49] feat: Create GL Entries for discount accounting

---
 .../doctype/sales_invoice/sales_invoice.py    | 35 +++++++++++++++++++
 1 file changed, 35 insertions(+)

diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index 6d1f6249c1..04c789d30a 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -846,6 +846,7 @@ class SalesInvoice(SellingController):
 		self.allocate_advance_taxes(gl_entries)
 
 		self.make_item_gl_entries(gl_entries)
+		self.make_discount_gl_entries(gl_entries)
 
 		# merge gl entries before adding pos entries
 		gl_entries = merge_similar_entries(gl_entries)
@@ -959,6 +960,40 @@ class SalesInvoice(SellingController):
 			erpnext.is_perpetual_inventory_enabled(self.company):
 			gl_entries += super(SalesInvoice, self).get_gl_entries()
 
+	def make_discount_gl_entries(self, gl_entries):
+		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
+
+		if enable_discount_accounting:
+			for item in self.get("items"):
+				if item.get('discount_amount') and item.get('discount_account'):
+					account_currency = get_account_currency(item.discount_account)
+					gl_entries.append(
+						self.get_gl_dict({
+							"account": item.discount_account,
+							"against": self.customer,
+							"debit": flt(item.discount_amount),
+							"debit_in_account_currency": flt(item.discount_amount),
+							"cost_center": self.cost_center,
+							"project": self.project
+						}, account_currency, item=self)
+					)
+
+					income_account = (item.income_account
+						if (not item.enable_deferred_revenue or self.is_return) 
+						else item.deferred_revenue_account)
+
+					account_currency = get_account_currency(income_account)
+					gl_entries.append(
+						self.get_gl_dict({
+							"account": income_account,
+							"against": self.customer,
+							"credit": flt(item.discount_amount),
+							"credit_in_account_currency": flt(item.discount_amount),
+							"cost_center": item.cost_center,
+							"project": item.project or self.project
+						}, account_currency, item=item)
+					)
+
 	def make_loyalty_point_redemption_gle(self, gl_entries):
 		if cint(self.redeem_loyalty_points):
 			gl_entries.append(

From c4e54295601b4dd6da940212ed561cb5f3abb20c Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 6 Jul 2021 16:28:19 +0530
Subject: [PATCH 04/49] feat: Filter list for Discount Account field in Items
 table

---
 erpnext/accounts/doctype/sales_invoice/sales_invoice.js | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
index f813425e6b..dc0d9da97b 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
@@ -510,6 +510,14 @@ cur_frm.set_query("income_account", "items", function(doc) {
 	}
 });
 
+// Discount Account in Details Table
+// --------------------------------
+cur_frm.set_query("discount_account", "items", function(doc) {
+	return{
+		query: "erpnext.controllers.queries.get_income_account",
+		filters: {'company': doc.company}
+	}
+});
 
 // Cost Center in Details Table
 // -----------------------------

From acb9e207ec96f642d5ce935157af4315717c0f57 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 6 Jul 2021 16:29:19 +0530
Subject: [PATCH 05/49] feat: Add Default Discount Account field

---
 erpnext/stock/doctype/item/item.json | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)

diff --git a/erpnext/stock/doctype/item/item.json b/erpnext/stock/doctype/item/item.json
index 6fed9efa63..f1c413e00a 100644
--- a/erpnext/stock/doctype/item/item.json
+++ b/erpnext/stock/doctype/item/item.json
@@ -91,6 +91,7 @@
   "is_sales_item",
   "column_break3",
   "max_discount",
+  "default_discount_account",
   "deferred_revenue",
   "deferred_revenue_account",
   "enable_deferred_revenue",
@@ -1058,6 +1059,12 @@
    "fieldname": "website_image_alt",
    "fieldtype": "Data",
    "label": "Image Description"
+  },
+  {
+   "fieldname": "default_discount_account",
+   "fieldtype": "Link",
+   "label": "Default Discount Account",
+   "options": "Account"
   }
  ],
  "has_web_view": 1,
@@ -1067,7 +1074,7 @@
  "index_web_pages_for_search": 1,
  "links": [],
  "max_attachments": 1,
- "modified": "2021-03-18 14:04:38.575519",
+ "modified": "2021-07-06 00:46:15.878648",
  "modified_by": "Administrator",
  "module": "Stock",
  "name": "Item",
@@ -1138,4 +1145,4 @@
  "sort_order": "DESC",
  "title_field": "item_name",
  "track_changes": 1
-}
+}
\ No newline at end of file

From cdfefa261e021dcba4d1f09b064f2b7baf6d72f1 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 6 Jul 2021 16:51:12 +0530
Subject: [PATCH 06/49] feat: Assign Item's Default Discount Account if present

---
 erpnext/stock/get_item_details.py | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/erpnext/stock/get_item_details.py b/erpnext/stock/get_item_details.py
index cf52803fca..bf082f89be 100644
--- a/erpnext/stock/get_item_details.py
+++ b/erpnext/stock/get_item_details.py
@@ -287,6 +287,7 @@ def get_basic_details(args, item, overwrite_warehouse=True):
 		"warehouse": warehouse,
 		"income_account": get_default_income_account(args, item_defaults, item_group_defaults, brand_defaults),
 		"expense_account": expense_account or get_default_expense_account(args, item_defaults, item_group_defaults, brand_defaults) ,
+		"discount_account": None or get_default_discount_account(args, item_defaults),
 		"cost_center": get_default_cost_center(args, item_defaults, item_group_defaults, brand_defaults),
 		'has_serial_no': item.has_serial_no,
 		'has_batch_no': item.has_batch_no,
@@ -589,6 +590,10 @@ def get_default_expense_account(args, item, item_group, brand):
 		or brand.get("expense_account")
 		or args.expense_account)
 
+def get_default_discount_account(args, item_defaults):
+	return (item_defaults.default_discount_account
+		or args.discount_account)
+
 def get_default_deferred_account(args, item, fieldname=None):
 	if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
 		return (item.get(fieldname)

From f48fa2e7f3893020b9ccbd546ff83e53a2c1c581 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 6 Jul 2021 20:22:13 +0530
Subject: [PATCH 07/49] feat: Toggle display for discount accounting fields
 according to enable_discount_accounting

---
 .../doctype/accounts_settings/accounts_settings.py         | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/erpnext/accounts/doctype/accounts_settings/accounts_settings.py b/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
index ac4a2d6f16..9e33eb395b 100644
--- a/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
+++ b/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
@@ -21,6 +21,7 @@ class AccountsSettings(Document):
 
 		self.validate_stale_days()
 		self.enable_payment_schedule_in_print()
+		self.toggle_discount_accounting_fields()
 
 	def validate_stale_days(self):
 		if not self.allow_stale and cint(self.stale_days) <= 0:
@@ -33,3 +34,9 @@ class AccountsSettings(Document):
 		for doctype in ("Sales Order", "Sales Invoice", "Purchase Order", "Purchase Invoice"):
 			make_property_setter(doctype, "due_date", "print_hide", show_in_print, "Check", validate_fields_for_doctype=False)
 			make_property_setter(doctype, "payment_schedule", "print_hide",  0 if show_in_print else 1, "Check", validate_fields_for_doctype=False)
+
+	def toggle_discount_accounting_fields(self):
+		enable_discount_accounting = cint(self.enable_discount_accounting)
+		
+		make_property_setter("Sales Invoice Item", "discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
+		make_property_setter("Item", "default_discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
\ No newline at end of file

From d24b5f707a870e1e1c44ce0caadff9005c79f633 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Mon, 12 Jul 2021 18:56:06 +0530
Subject: [PATCH 08/49] fix: Add description for Enable Discount Accounting
 checkbox

---
 .../doctype/accounts_settings/accounts_settings.json         | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/erpnext/accounts/doctype/accounts_settings/accounts_settings.json b/erpnext/accounts/doctype/accounts_settings/accounts_settings.json
index 676c6a8b47..49a2afee85 100644
--- a/erpnext/accounts/doctype/accounts_settings/accounts_settings.json
+++ b/erpnext/accounts/doctype/accounts_settings/accounts_settings.json
@@ -12,7 +12,6 @@
   "role_allowed_to_over_bill",
   "make_payment_via_journal_entry",
   "column_break_11",
-  "enable_discount_accounting",
   "check_supplier_invoice_uniqueness",
   "unlink_payment_on_cancellation_of_invoice",
   "automatically_fetch_payment_terms",
@@ -20,6 +19,7 @@
   "book_asset_depreciation_entry_automatically",
   "unlink_advance_payment_on_cancelation_of_order",
   "post_change_gl_entries",
+  "enable_discount_accounting",
   "tax_settings_section",
   "determine_address_tax_category_from",
   "column_break_19",
@@ -265,6 +265,7 @@
   },
   {
    "default": "0",
+   "description": "If enabled, additional ledger entries will be made for discounts in a separate Discount Account",
    "fieldname": "enable_discount_accounting",
    "fieldtype": "Check",
    "label": "Enable Discount Accounting"
@@ -275,7 +276,7 @@
  "index_web_pages_for_search": 1,
  "issingle": 1,
  "links": [],
- "modified": "2021-07-05 14:56:19.820731",
+ "modified": "2021-07-12 18:54:29.084958",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Accounts Settings",

From cfb94175a2458b47ec54fb0ccabcb0a682004504 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Mon, 12 Jul 2021 19:07:54 +0530
Subject: [PATCH 09/49] fix: Filter Discount Account list

---
 .../doctype/sales_invoice/sales_invoice.js    | 22 +++++++++++--------
 1 file changed, 13 insertions(+), 9 deletions(-)

diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
index dc0d9da97b..17228a3c28 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
@@ -510,15 +510,6 @@ cur_frm.set_query("income_account", "items", function(doc) {
 	}
 });
 
-// Discount Account in Details Table
-// --------------------------------
-cur_frm.set_query("discount_account", "items", function(doc) {
-	return{
-		query: "erpnext.controllers.queries.get_income_account",
-		filters: {'company': doc.company}
-	}
-});
-
 // Cost Center in Details Table
 // -----------------------------
 cur_frm.fields_dict["items"].grid.get_field("cost_center").get_query = function(doc) {
@@ -626,6 +617,19 @@ frappe.ui.form.on('Sales Invoice', {
 			}
 		}
 
+		// discount account
+		frm.fields_dict['items'].grid.get_field('discount_account').get_query = function(doc) {
+			if (erpnext.is_perpetual_inventory_enabled(doc.company)) {
+				return {
+					filters: {
+						'report_type': 'Profit and Loss',
+						'company': doc.company,
+						"is_group": 0
+					}
+				}
+			}
+		}
+
 		frm.fields_dict['items'].grid.get_field('deferred_revenue_account').get_query = function(doc) {
 			return {
 				filters: {

From 613d08faad544cd0c6855e30bf082538c2c992cf Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Mon, 12 Jul 2021 22:32:38 +0530
Subject: [PATCH 10/49] fix: Copy discount account from first row to all Items

---
 erpnext/accounts/doctype/sales_invoice/sales_invoice.js | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
index 17228a3c28..2b48d66dca 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
@@ -347,8 +347,8 @@ erpnext.accounts.SalesInvoiceController = erpnext.selling.SellingController.exte
 
 	items_add: function(doc, cdt, cdn) {
 		var row = frappe.get_doc(cdt, cdn);
-		this.frm.script_manager.copy_from_first_row("items", row, ["income_account", "cost_center"]);
-	},
+		this.frm.script_manager.copy_from_first_row("items", row, ["income_account", "discount_account", "cost_center"]);
+	}
 
 	set_dynamic_labels: function() {
 		this._super();

From 546c8d125c6563ffa57f31b08a79948c7ce0d8ba Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 13 Jul 2021 01:37:30 +0530
Subject: [PATCH 11/49] fix: Move Default Discount Account field to Item
 Defaults

---
 erpnext/stock/doctype/item/item.json          |   9 +-
 .../doctype/item_default/item_default.json    | 548 ++++--------------
 erpnext/stock/get_item_details.py             |   4 +-
 3 files changed, 104 insertions(+), 457 deletions(-)

diff --git a/erpnext/stock/doctype/item/item.json b/erpnext/stock/doctype/item/item.json
index f1c413e00a..f662bbd1c7 100644
--- a/erpnext/stock/doctype/item/item.json
+++ b/erpnext/stock/doctype/item/item.json
@@ -91,7 +91,6 @@
   "is_sales_item",
   "column_break3",
   "max_discount",
-  "default_discount_account",
   "deferred_revenue",
   "deferred_revenue_account",
   "enable_deferred_revenue",
@@ -1059,12 +1058,6 @@
    "fieldname": "website_image_alt",
    "fieldtype": "Data",
    "label": "Image Description"
-  },
-  {
-   "fieldname": "default_discount_account",
-   "fieldtype": "Link",
-   "label": "Default Discount Account",
-   "options": "Account"
   }
  ],
  "has_web_view": 1,
@@ -1074,7 +1067,7 @@
  "index_web_pages_for_search": 1,
  "links": [],
  "max_attachments": 1,
- "modified": "2021-07-06 00:46:15.878648",
+ "modified": "2021-07-13 01:29:06.071827",
  "modified_by": "Administrator",
  "module": "Stock",
  "name": "Item",
diff --git a/erpnext/stock/doctype/item_default/item_default.json b/erpnext/stock/doctype/item_default/item_default.json
index 96b5dfdc8f..bc171604f4 100644
--- a/erpnext/stock/doctype/item_default/item_default.json
+++ b/erpnext/stock/doctype/item_default/item_default.json
@@ -1,464 +1,118 @@
 {
- "allow_copy": 0, 
- "allow_events_in_timeline": 0, 
- "allow_guest_to_view": 0, 
- "allow_import": 0, 
- "allow_rename": 0, 
- "beta": 0, 
- "creation": "2018-05-03 02:29:24.444341", 
- "custom": 0, 
- "docstatus": 0, 
- "doctype": "DocType", 
- "document_type": "", 
- "editable_grid": 1, 
- "engine": "InnoDB", 
+ "actions": [],
+ "creation": "2018-05-03 02:29:24.444341",
+ "doctype": "DocType",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+  "company",
+  "default_warehouse",
+  "column_break_3",
+  "default_price_list",
+  "default_discount_account",
+  "purchase_defaults",
+  "buying_cost_center",
+  "default_supplier",
+  "column_break_8",
+  "expense_account",
+  "selling_defaults",
+  "selling_cost_center",
+  "column_break_12",
+  "income_account"
+ ],
  "fields": [
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "company", 
-   "fieldtype": "Link", 
-   "hidden": 0, 
-   "ignore_user_permissions": 1, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 1, 
-   "in_standard_filter": 0, 
-   "label": "Company", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "Company", 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 1, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
+   "fieldname": "company",
+   "fieldtype": "Link",
+   "ignore_user_permissions": 1,
+   "in_list_view": 1,
+   "label": "Company",
+   "options": "Company",
+   "reqd": 1
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "default_warehouse", 
-   "fieldtype": "Link", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 1, 
-   "in_standard_filter": 0, 
-   "label": "Default Warehouse", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "Warehouse", 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
+   "fieldname": "default_warehouse",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "Default Warehouse",
+   "options": "Warehouse"
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "column_break_3", 
-   "fieldtype": "Column Break", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "length": 0, 
-   "no_copy": 0, 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
+   "fieldname": "column_break_3",
+   "fieldtype": "Column Break"
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "default_price_list", 
-   "fieldtype": "Link", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 1, 
-   "in_standard_filter": 0, 
-   "label": "Default Price List", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "Price List", 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
+   "fieldname": "default_price_list",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "Default Price List",
+   "options": "Price List"
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "purchase_defaults", 
-   "fieldtype": "Section Break", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "label": "Purchase Defaults", 
-   "length": 0, 
-   "no_copy": 0, 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
+   "fieldname": "purchase_defaults",
+   "fieldtype": "Section Break",
+   "label": "Purchase Defaults"
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "buying_cost_center", 
-   "fieldtype": "Link", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "label": "Default Buying Cost Center", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "Cost Center", 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
+   "fieldname": "buying_cost_center",
+   "fieldtype": "Link",
+   "label": "Default Buying Cost Center",
+   "options": "Cost Center"
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "default_supplier", 
-   "fieldtype": "Link", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "label": "Default Supplier", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "Supplier", 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
+   "fieldname": "default_supplier",
+   "fieldtype": "Link",
+   "label": "Default Supplier",
+   "options": "Supplier"
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "column_break_8", 
-   "fieldtype": "Column Break", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "length": 0, 
-   "no_copy": 0, 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
+   "fieldname": "column_break_8",
+   "fieldtype": "Column Break"
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "expense_account", 
-   "fieldtype": "Link", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "label": "Default Expense Account", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "Account", 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
+   "fieldname": "expense_account",
+   "fieldtype": "Link",
+   "label": "Default Expense Account",
+   "options": "Account"
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "selling_defaults", 
-   "fieldtype": "Section Break", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "label": "Sales Defaults", 
-   "length": 0, 
-   "no_copy": 0, 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
+   "fieldname": "selling_defaults",
+   "fieldtype": "Section Break",
+   "label": "Sales Defaults"
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "selling_cost_center", 
-   "fieldtype": "Link", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "label": "Default Selling Cost Center", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "Cost Center", 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
+   "fieldname": "selling_cost_center",
+   "fieldtype": "Link",
+   "label": "Default Selling Cost Center",
+   "options": "Cost Center"
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "column_break_12", 
-   "fieldtype": "Column Break", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "length": 0, 
-   "no_copy": 0, 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
+   "fieldname": "column_break_12",
+   "fieldtype": "Column Break"
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "income_account", 
-   "fieldtype": "Link", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "label": "Default Income Account", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "Account", 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
+   "fieldname": "income_account",
+   "fieldtype": "Link",
+   "label": "Default Income Account",
+   "options": "Account"
+  },
+  {
+   "fieldname": "default_discount_account",
+   "fieldtype": "Link",
+   "label": "Default Discount Account",
+   "options": "Account"
   }
- ], 
- "has_web_view": 0, 
- "hide_heading": 0, 
- "hide_toolbar": 0, 
- "idx": 0, 
- "image_view": 0, 
- "in_create": 0, 
- "is_submittable": 0, 
- "issingle": 0, 
- "istable": 1, 
- "max_attachments": 0, 
- "modified": "2018-12-07 11:48:07.638935", 
- "modified_by": "Administrator", 
- "module": "Stock", 
- "name": "Item Default", 
- "name_case": "", 
- "owner": "Administrator", 
- "permissions": [], 
- "quick_entry": 1, 
- "read_only": 0, 
- "read_only_onload": 0, 
- "show_name_in_global_search": 0, 
- "sort_field": "modified", 
- "sort_order": "DESC", 
- "track_changes": 1, 
- "track_seen": 0, 
- "track_views": 0
+ ],
+ "istable": 1,
+ "links": [],
+ "modified": "2021-07-13 01:26:03.860065",
+ "modified_by": "Administrator",
+ "module": "Stock",
+ "name": "Item Default",
+ "owner": "Administrator",
+ "permissions": [],
+ "quick_entry": 1,
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "track_changes": 1
 }
\ No newline at end of file
diff --git a/erpnext/stock/get_item_details.py b/erpnext/stock/get_item_details.py
index bf082f89be..cadb4aa97b 100644
--- a/erpnext/stock/get_item_details.py
+++ b/erpnext/stock/get_item_details.py
@@ -590,8 +590,8 @@ def get_default_expense_account(args, item, item_group, brand):
 		or brand.get("expense_account")
 		or args.expense_account)
 
-def get_default_discount_account(args, item_defaults):
-	return (item_defaults.default_discount_account
+def get_default_discount_account(args, item):
+	return (item.get("default_discount_account")
 		or args.discount_account)
 
 def get_default_deferred_account(args, item, fieldname=None):

From ee025b501fbb15ab21ceaf8f3bf36f892279c4ed Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 13 Jul 2021 01:43:41 +0530
Subject: [PATCH 12/49] fix: Filter options for Default Discount Account

---
 erpnext/stock/doctype/item/item.js | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/erpnext/stock/doctype/item/item.js b/erpnext/stock/doctype/item/item.js
index 264baeaa47..2fee57f2d1 100644
--- a/erpnext/stock/doctype/item/item.js
+++ b/erpnext/stock/doctype/item/item.js
@@ -274,6 +274,17 @@ $.extend(erpnext.item, {
 			}
 		}
 
+		frm.fields_dict["item_defaults"].grid.get_field("default_discount_account").get_query = function(doc, cdt, cdn) {
+			const row = locals[cdt][cdn];
+			return {
+				filters: {
+					'report_type': 'Profit and Loss',
+					'company': row.company,
+					"is_group": 0
+				}
+			}
+		}
+
 		frm.fields_dict["item_defaults"].grid.get_field("buying_cost_center").get_query = function(doc, cdt, cdn) {
 			const row = locals[cdt][cdn];
 			return {

From bde5c619db8e80796a923cc57af1d97cc235f125 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 13 Jul 2021 02:06:03 +0530
Subject: [PATCH 13/49] fix: Add Discount Account field

---
 .../purchase_invoice_item/purchase_invoice_item.json     | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/erpnext/accounts/doctype/purchase_invoice_item/purchase_invoice_item.json b/erpnext/accounts/doctype/purchase_invoice_item/purchase_invoice_item.json
index 8a55ff87e3..922b567d15 100644
--- a/erpnext/accounts/doctype/purchase_invoice_item/purchase_invoice_item.json
+++ b/erpnext/accounts/doctype/purchase_invoice_item/purchase_invoice_item.json
@@ -73,6 +73,7 @@
   "manufacturer_part_no",
   "accounting",
   "expense_account",
+  "discount_account",
   "col_break5",
   "is_fixed_asset",
   "asset_location",
@@ -849,12 +850,18 @@
    "options": "Company:company:default_currency",
    "print_hide": 1,
    "read_only": 1
+  },
+  {
+   "fieldname": "discount_account",
+   "fieldtype": "Link",
+   "label": "Discount Account",
+   "options": "Account"
   }
  ],
  "idx": 1,
  "istable": 1,
  "links": [],
- "modified": "2021-06-16 19:57:03.101571",
+ "modified": "2021-07-13 02:04:37.787882",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Purchase Invoice Item",

From e2c83c3bafe00951a66bb9405bd6da911539a875 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 13 Jul 2021 02:07:46 +0530
Subject: [PATCH 14/49] fix: Display Discount Account only if Enable Discount
 Accounting is checked

---
 .../accounts/doctype/accounts_settings/accounts_settings.py   | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/erpnext/accounts/doctype/accounts_settings/accounts_settings.py b/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
index 9e33eb395b..d1abdba379 100644
--- a/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
+++ b/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
@@ -38,5 +38,7 @@ class AccountsSettings(Document):
 	def toggle_discount_accounting_fields(self):
 		enable_discount_accounting = cint(self.enable_discount_accounting)
 		
-		make_property_setter("Sales Invoice Item", "discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
+		for doctype in ["Sales Invoice Item", "Purchase Invoice Item"]:
+			make_property_setter(doctype, "discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
+
 		make_property_setter("Item", "default_discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
\ No newline at end of file

From 377775ad8ead56e000717ce769e4da06fb5e7855 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 13 Jul 2021 02:09:40 +0530
Subject: [PATCH 15/49] fix: Copy Discount Account from first row

---
 erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
index dc9094c3e9..81e3aaa8a5 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
@@ -365,7 +365,7 @@ erpnext.accounts.PurchaseInvoice = erpnext.buying.BuyingController.extend({
 	items_add: function(doc, cdt, cdn) {
 		var row = frappe.get_doc(cdt, cdn);
 		this.frm.script_manager.copy_from_first_row("items", row,
-			["expense_account", "cost_center", "project"]);
+			["expense_account", "discount_account", "cost_center", "project"]);
 	},
 
 	on_submit: function() {

From e06eb8e6a9fe6f6c36bf83f49bb5f72f1203b794 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 13 Jul 2021 02:14:18 +0530
Subject: [PATCH 16/49] fix: Filter options for Discount Account

---
 .../doctype/purchase_invoice/purchase_invoice.js       | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
index 81e3aaa8a5..a1ee5d0076 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
@@ -508,6 +508,16 @@ frappe.ui.form.on("Purchase Invoice", {
 				}
 			}
 		}
+
+		frm.fields_dict['items'].grid.get_field('discount_account').get_query = function(doc) {
+			return {
+				filters: {
+					'report_type': 'Profit and Loss',
+					'company': doc.company,
+					"is_group": 0
+				}
+			}
+		}
 	},
 
 	refresh: function(frm) {

From fd2852e87e3b03c019cff84669f908fdc70f3704 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 13 Jul 2021 03:01:02 +0530
Subject: [PATCH 17/49] fix: Create common function for discount accounting

---
 .../purchase_invoice/purchase_invoice.py      |  1 +
 .../doctype/sales_invoice/sales_invoice.py    | 34 --------------
 erpnext/controllers/accounts_controller.py    | 45 +++++++++++++++++++
 3 files changed, 46 insertions(+), 34 deletions(-)

diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index f7992797ed..78d1ee972f 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -446,6 +446,7 @@ class PurchaseInvoice(BuyingController):
 
 		self.make_supplier_gl_entry(gl_entries)
 		self.make_item_gl_entries(gl_entries)
+		self.make_discount_gl_entries(gl_entries)
 
 		if self.check_asset_cwip_enabled():
 			self.get_asset_gl_entry(gl_entries)
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index 04c789d30a..15fae84b79 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -960,40 +960,6 @@ class SalesInvoice(SellingController):
 			erpnext.is_perpetual_inventory_enabled(self.company):
 			gl_entries += super(SalesInvoice, self).get_gl_entries()
 
-	def make_discount_gl_entries(self, gl_entries):
-		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
-
-		if enable_discount_accounting:
-			for item in self.get("items"):
-				if item.get('discount_amount') and item.get('discount_account'):
-					account_currency = get_account_currency(item.discount_account)
-					gl_entries.append(
-						self.get_gl_dict({
-							"account": item.discount_account,
-							"against": self.customer,
-							"debit": flt(item.discount_amount),
-							"debit_in_account_currency": flt(item.discount_amount),
-							"cost_center": self.cost_center,
-							"project": self.project
-						}, account_currency, item=self)
-					)
-
-					income_account = (item.income_account
-						if (not item.enable_deferred_revenue or self.is_return) 
-						else item.deferred_revenue_account)
-
-					account_currency = get_account_currency(income_account)
-					gl_entries.append(
-						self.get_gl_dict({
-							"account": income_account,
-							"against": self.customer,
-							"credit": flt(item.discount_amount),
-							"credit_in_account_currency": flt(item.discount_amount),
-							"cost_center": item.cost_center,
-							"project": item.project or self.project
-						}, account_currency, item=item)
-					)
-
 	def make_loyalty_point_redemption_gle(self, gl_entries):
 		if cint(self.redeem_loyalty_points):
 			gl_entries.append(
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 4c313c43a7..0a11582508 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -808,6 +808,51 @@ class AccountsController(TransactionBase):
 							tax_map[tax.account_head] -= allocated_amount
 							allocated_tax_map[tax.account_head] -= allocated_amount
 
+	def make_discount_gl_entries(self, gl_entries):
+		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
+
+		if enable_discount_accounting:
+			for item in self.get("items"):
+				if item.get('discount_amount') and item.get('discount_account'):
+					if self.doctype == "Purchase Invoice":
+						dr_or_cr = "credit"
+						rev_dr_cr = "debit"
+						supplier_or_customer = self.supplier
+						income_or_expense_account = (item.expense_account
+							if (not item.enable_deferred_expense or self.is_return) 
+							else item.deferred_expense_account)
+					else:
+						dr_or_cr = "debit"
+						rev_dr_cr = "credit"
+						supplier_or_customer = self.customer
+						income_or_expense_account = (item.income_account
+							if (not item.enable_deferred_revenue or self.is_return) 
+							else item.deferred_revenue_account)
+
+					account_currency = get_account_currency(item.discount_account)
+					gl_entries.append(
+						self.get_gl_dict({
+							"account": item.discount_account,
+							"against": supplier_or_customer,
+							dr_or_cr: flt(item.discount_amount),
+							dr_or_cr + "_in_account_currency": flt(item.discount_amount),
+							"cost_center": self.cost_center,
+							"project": self.project
+						}, account_currency, item=self)
+					)
+
+					account_currency = get_account_currency(income_or_expense_account)
+					gl_entries.append(
+						self.get_gl_dict({
+							"account": income_or_expense_account,
+							"against": supplier_or_customer,
+							rev_dr_cr: flt(item.discount_amount),
+							rev_dr_cr + "_in_account_currency": flt(item.discount_amount),
+							"cost_center": item.cost_center,
+							"project": item.project or self.project
+						}, account_currency, item=item)
+					)
+
 	def allocate_advance_taxes(self, gl_entries):
 		tax_map = self.get_tax_map()
 		for pe in self.get("advances"):

From 38e87fce099100d1db3386730140212bc8a42d51 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 13 Jul 2021 17:41:29 +0530
Subject: [PATCH 18/49] fix: Add tests for discount accounting

---
 .../purchase_invoice/test_purchase_invoice.py | 20 ++++++++++++++++++-
 .../sales_invoice/test_sales_invoice.py       | 15 ++++++++++++++
 2 files changed, 34 insertions(+), 1 deletion(-)

diff --git a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
index ca4d009956..bd7ded269c 100644
--- a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
@@ -230,6 +230,16 @@ class TestPurchaseInvoice(unittest.TestCase):
 			self.assertEqual(expected_values[gle.account][1], gle.debit)
 			self.assertEqual(expected_values[gle.account][2], gle.credit)
 
+	def test_purchase_invoice_with_discount_accounting_enabled(self):
+		enable_discount_accounting()
+
+		discount_account = create_account(account_name="Discount Account",
+			parent_account="Indirect Expenses - _TC", company="_Test Company")
+		pi = make_purchase_invoice(discount_account=discount_account, discount_amount=100)
+
+		discount_amount = frappe.db.get_value('GL Entry', {'account': discount_account, 'voucher_no': pi.name}, 'credit')
+		self.assertEqual(discount_amount, 100)
+
 	def test_purchase_invoice_change_naming_series(self):
 		pi = frappe.copy_doc(test_records[1])
 		pi.insert()
@@ -1170,6 +1180,11 @@ def unlink_payment_on_cancel_of_invoice(enable=1):
 	accounts_settings.unlink_payment_on_cancellation_of_invoice = enable
 	accounts_settings.save()
 
+def enable_discount_accounting(enable=1):
+	accounts_settings = frappe.get_doc("Accounts Settings")
+	accounts_settings.enable_discount_accounting = enable
+	accounts_settings.save()
+
 def make_purchase_invoice(**args):
 	pi = frappe.new_doc("Purchase Invoice")
 	args = frappe._dict(args)
@@ -1192,6 +1207,7 @@ def make_purchase_invoice(**args):
 	pi.return_against = args.return_against
 	pi.is_subcontracted = args.is_subcontracted or "No"
 	pi.supplier_warehouse = args.supplier_warehouse or "_Test Warehouse 1 - _TC"
+	pi.cost_center = args.cost_center or "_Test Cost Center - _TC"
 
 	pi.append("items", {
 		"item_code": args.item or args.item_code or "_Test Item",
@@ -1200,7 +1216,9 @@ def make_purchase_invoice(**args):
 		"received_qty": args.received_qty or 0,
 		"rejected_qty": args.rejected_qty or 0,
 		"rate": args.rate or 50,
-		'expense_account': args.expense_account or '_Test Account Cost for Goods Sold - _TC',
+		"expense_account": args.expense_account or '_Test Account Cost for Goods Sold - _TC',
+		"discount_account": args.discount_account or None,
+		"discount_amount": args.discount_amount or 0,
 		"conversion_factor": 1.0,
 		"serial_no": args.serial_no,
 		"stock_uom": args.uom or "_Test UOM",
diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index dbc7f8632f..d03a874c28 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -1984,6 +1984,18 @@ class TestSalesInvoice(unittest.TestCase):
 		sales_invoice.save()
 		self.assertEqual(sales_invoice.items[0].item_tax_template, "_Test Account Excise Duty @ 10 - _TC")
 
+	def test_sales_invoice_with_discount_accounting_enabled(self):
+		from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import enable_discount_accounting
+
+		enable_discount_accounting()
+
+		discount_account = create_account(account_name="Discount Account",
+			parent_account="Indirect Expenses - _TC", company="_Test Company")
+		si = create_sales_invoice(discount_account=discount_account, discount_amount=100)
+
+		discount_amount = frappe.db.get_value('GL Entry', {'account': discount_account, 'voucher_no': si.name}, 'debit')
+		self.assertEqual(discount_amount, 100)
+
 def get_sales_invoice_for_e_invoice():
 	si = make_sales_invoice_for_ewaybill()
 	si.naming_series = 'INV-2020-.#####'
@@ -2152,6 +2164,7 @@ def create_sales_invoice(**args):
 	si.currency=args.currency or "INR"
 	si.conversion_rate = args.conversion_rate or 1
 	si.naming_series = args.naming_series or "T-SINV-"
+	si.cost_center = args.cost_center or "_Test Cost Center - _TC"
 
 	si.append("items", {
 		"item_code": args.item or args.item_code or "_Test Item",
@@ -2165,6 +2178,8 @@ def create_sales_invoice(**args):
 		"rate": args.rate if args.get("rate") is not None else 100,
 		"income_account": args.income_account or "Sales - _TC",
 		"expense_account": args.expense_account or "Cost of Goods Sold - _TC",
+		"discount_account": args.discount_account or None,
+		"discount_amount": args.discount_amount or 0,
 		"cost_center": args.cost_center or "_Test Cost Center - _TC",
 		"serial_no": args.serial_no,
 		"conversion_factor": 1

From 9e788cfdcd866780b16195fff411a4dc4bfd822d Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Thu, 15 Jul 2021 22:01:02 +0530
Subject: [PATCH 19/49] fix: Add Additional Discount Account field

---
 .../accounts/doctype/sales_invoice/sales_invoice.json    | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
index e7dd6b8a60..5c09b71cf3 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
@@ -104,6 +104,7 @@
   "section_break_49",
   "apply_discount_on",
   "base_discount_amount",
+  "additional_discount_account",
   "column_break_51",
   "additional_discount_percentage",
   "discount_amount",
@@ -1966,6 +1967,12 @@
    "fieldname": "disable_rounded_total",
    "fieldtype": "Check",
    "label": "Disable Rounded Total"
+  },
+  {
+   "fieldname": "additional_discount_account",
+   "fieldtype": "Link",
+   "label": "Additional Discount Account",
+   "options": "Account"
   }
  ],
  "icon": "fa fa-file-text",
@@ -1978,7 +1985,7 @@
    "link_fieldname": "consolidated_invoice"
   }
  ],
- "modified": "2021-05-20 22:48:33.988881",
+ "modified": "2021-07-15 21:57:17.544279",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Sales Invoice",

From c1d65cfa8d987c734b412026a7fbc5aec427359a Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Thu, 15 Jul 2021 22:01:38 +0530
Subject: [PATCH 20/49] fix: Filter options for Additional Discount Account

---
 .../accounts/doctype/sales_invoice/sales_invoice.js    | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
index 2b48d66dca..fab0e11324 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
@@ -591,6 +591,16 @@ frappe.ui.form.on('Sales Invoice', {
 			};
 		});
 
+		frm.set_query("additional_discount_account", function() {
+			return {
+				filters: {
+					company: frm.doc.company,
+					is_group: 0,
+					root_type: "Profit and Loss",
+				}
+			};
+		});
+
 		frm.custom_make_buttons = {
 			'Delivery Note': 'Delivery',
 			'Sales Invoice': 'Return / Credit Note',

From b64787ee9ca81aa18904419e072296c1932ed15a Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Thu, 15 Jul 2021 22:02:43 +0530
Subject: [PATCH 21/49] fix: Only display Additional Discount Account if Enable
 Discount Accounting is checked

---
 .../accounts/doctype/accounts_settings/accounts_settings.py    | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/erpnext/accounts/doctype/accounts_settings/accounts_settings.py b/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
index d1abdba379..053f061acc 100644
--- a/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
+++ b/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
@@ -41,4 +41,5 @@ class AccountsSettings(Document):
 		for doctype in ["Sales Invoice Item", "Purchase Invoice Item"]:
 			make_property_setter(doctype, "discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
 
-		make_property_setter("Item", "default_discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
\ No newline at end of file
+		make_property_setter("Item", "default_discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
+		make_property_setter("Sales Invoice", "additional_discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
\ No newline at end of file

From 38327fc17764516a5844af6ee4fcf36986e715b6 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Thu, 15 Jul 2021 22:03:46 +0530
Subject: [PATCH 22/49] fix: Make additional GL Entries for discount applied on
 taxes

---
 erpnext/controllers/accounts_controller.py | 36 ++++++++++++++++++++++
 1 file changed, 36 insertions(+)

diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 0a11582508..8fc4023f2e 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -852,6 +852,42 @@ class AccountsController(TransactionBase):
 							"project": item.project or self.project
 						}, account_currency, item=item)
 					)
+			
+			if self.get('discount_amount') and self.get('additional_discount_account'):
+				self.make_gle_for_additional_discount_applied_on_taxes(gl_entries)
+
+	def make_gle_for_additional_discount_applied_on_taxes(self, gl_entries):
+		for tax in self.get("taxes"):
+			if flt(tax.base_tax_amount_after_discount_amount) and flt(tax.base_tax_amount):
+				account_currency = get_account_currency(tax.account_head)
+				additional_discount_applied_on_taxes = flt(tax.base_tax_amount) - flt(tax.base_tax_amount_after_discount_amount)
+
+				gl_entries.append(
+					self.get_gl_dict({
+						"account": tax.account_head,
+						"against": self.customer,
+						"credit": flt(additional_discount_applied_on_taxes,
+							tax.precision("tax_amount_after_discount_amount")),
+						"credit_in_account_currency": (flt(additional_discount_applied_on_taxes,
+							tax.precision("base_tax_amount_after_discount_amount")) if account_currency==self.company_currency else
+							flt(additional_discount_applied_on_taxes, tax.precision("tax_amount_after_discount_amount"))),
+						"cost_center": tax.cost_center
+					}, account_currency, item=tax)
+				)
+
+				gl_entries.append(
+					self.get_gl_dict({
+						"account": self.additional_discount_account,
+						"against": self.customer,
+						"debit": flt(additional_discount_applied_on_taxes,
+							tax.precision("tax_amount_after_discount_amount")),
+						"debit_in_account_currency": (flt(additional_discount_applied_on_taxes,
+							tax.precision("base_tax_amount_after_discount_amount")) if account_currency==self.company_currency else
+							flt(additional_discount_applied_on_taxes, tax.precision("tax_amount_after_discount_amount"))),
+						"cost_center": tax.cost_center
+					}, account_currency, item=tax)
+				)
+				
 
 	def allocate_advance_taxes(self, gl_entries):
 		tax_map = self.get_tax_map()

From d6f409addcedaff16339000374b74a5d93be31db Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Fri, 16 Jul 2021 02:18:45 +0530
Subject: [PATCH 23/49] fix: Sider issues

---
 erpnext/stock/doctype/item/item.js | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/erpnext/stock/doctype/item/item.js b/erpnext/stock/doctype/item/item.js
index 2fee57f2d1..4566618385 100644
--- a/erpnext/stock/doctype/item/item.js
+++ b/erpnext/stock/doctype/item/item.js
@@ -282,8 +282,8 @@ $.extend(erpnext.item, {
 					'company': row.company,
 					"is_group": 0
 				}
-			}
-		}
+			};
+		};
 
 		frm.fields_dict["item_defaults"].grid.get_field("buying_cost_center").get_query = function(doc, cdt, cdn) {
 			const row = locals[cdt][cdn];

From d0d9e83ad202f22d1cc3c6c21f20f9b934ad3700 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Sat, 17 Jul 2021 17:34:50 +0530
Subject: [PATCH 24/49] fix: Check all expected GL Entries

---
 .../doctype/purchase_invoice/test_purchase_invoice.py | 11 +++++++++--
 .../doctype/sales_invoice/test_sales_invoice.py       |  9 +++++++--
 2 files changed, 16 insertions(+), 4 deletions(-)

diff --git a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
index bd7ded269c..36fbc7e351 100644
--- a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
@@ -231,14 +231,21 @@ class TestPurchaseInvoice(unittest.TestCase):
 			self.assertEqual(expected_values[gle.account][2], gle.credit)
 
 	def test_purchase_invoice_with_discount_accounting_enabled(self):
+		from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import check_gl_entries
+
 		enable_discount_accounting()
 
 		discount_account = create_account(account_name="Discount Account",
 			parent_account="Indirect Expenses - _TC", company="_Test Company")
 		pi = make_purchase_invoice(discount_account=discount_account, discount_amount=100)
 
-		discount_amount = frappe.db.get_value('GL Entry', {'account': discount_account, 'voucher_no': pi.name}, 'credit')
-		self.assertEqual(discount_amount, 100)
+		expected_gle = [
+			["Discount Account - _TC", 0.0, 100.0, nowdate()],
+			["_Test Account Cost for Goods Sold - _TC", 350.0, 0.0, nowdate()],
+			["Creditors - _TC", 0.0, 250.0, nowdate()]
+		]
+
+		check_gl_entries(self, pi.name, expected_gle, nowdate())
 
 	def test_purchase_invoice_change_naming_series(self):
 		pi = frappe.copy_doc(test_records[1])
diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index d03a874c28..2ddfad9c31 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -1992,9 +1992,14 @@ class TestSalesInvoice(unittest.TestCase):
 		discount_account = create_account(account_name="Discount Account",
 			parent_account="Indirect Expenses - _TC", company="_Test Company")
 		si = create_sales_invoice(discount_account=discount_account, discount_amount=100)
+		
+		expected_gle = [
+			["Discount Account - _TC", 100.0, 0.0, nowdate()],
+			["Sales - _TC", 0.0, 200.0, nowdate()],
+			["Debtors - _TC", 100.0, 0.0, nowdate()]
+		]
 
-		discount_amount = frappe.db.get_value('GL Entry', {'account': discount_account, 'voucher_no': si.name}, 'debit')
-		self.assertEqual(discount_amount, 100)
+		check_gl_entries(self, si.name, expected_gle, nowdate())
 
 def get_sales_invoice_for_e_invoice():
 	si = make_sales_invoice_for_ewaybill()

From 03f270697194c81f50a66d3318cbf2928ddfb9e8 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Sat, 17 Jul 2021 17:40:43 +0530
Subject: [PATCH 25/49] fix: Add Additional Discount Account field

---
 .../doctype/purchase_invoice/purchase_invoice.json       | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
index 00ef7d5c18..96ae828f46 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
@@ -96,6 +96,7 @@
   "section_break_44",
   "apply_discount_on",
   "base_discount_amount",
+  "additional_discount_account",
   "column_break_46",
   "additional_discount_percentage",
   "discount_amount",
@@ -1377,13 +1378,19 @@
    "no_copy": 1,
    "print_hide": 1,
    "read_only": 1
+  },
+  {
+   "fieldname": "additional_discount_account",
+   "fieldtype": "Link",
+   "label": "Additional Discount Account",
+   "options": "Account"
   }
  ],
  "icon": "fa fa-file-text",
  "idx": 204,
  "is_submittable": 1,
  "links": [],
- "modified": "2021-06-15 18:20:56.806195",
+ "modified": "2021-07-17 17:37:50.570595",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Purchase Invoice",

From ff25683378769b5869f19dc49f8165d18938a8fd Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Sat, 17 Jul 2021 17:41:06 +0530
Subject: [PATCH 26/49] fix: Filter options for Additional Discount Account

---
 .../doctype/purchase_invoice/purchase_invoice.js       | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
index a1ee5d0076..4ed31cc227 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
@@ -499,6 +499,16 @@ frappe.ui.form.on("Purchase Invoice", {
 			'Payment Entry': 'Payment'
 		}
 
+		frm.set_query("additional_discount_account", function() {
+			return {
+				filters: {
+					company: frm.doc.company,
+					is_group: 0,
+					root_type: "Profit and Loss",
+				}
+			};
+		});
+
 		frm.fields_dict['items'].grid.get_field('deferred_expense_account').get_query = function(doc) {
 			return {
 				filters: {

From 9dd2a9e8973fe4e5c70dc4aa65683870281e4091 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Sat, 17 Jul 2021 17:42:36 +0530
Subject: [PATCH 27/49] fix: Create ledger entries for discount applied on
 taxes in make_tax_gl_entries

---
 .../accounts/doctype/purchase_invoice/purchase_invoice.py    | 5 +++++
 erpnext/accounts/doctype/sales_invoice/sales_invoice.py      | 5 +++++
 erpnext/controllers/accounts_controller.py                   | 3 ---
 3 files changed, 10 insertions(+), 3 deletions(-)

diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index 78d1ee972f..006f5bb0e8 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -888,6 +888,11 @@ class PurchaseInvoice(BuyingController):
 							"remarks": self.remarks or "Accounting Entry for Stock"
 						}, item=tax))
 
+		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
+
+		if enable_discount_accounting and self.get('discount_amount') and self.get('additional_discount_account'):
+			self.make_gle_for_additional_discount_applied_on_taxes(gl_entries)
+
 	def make_internal_transfer_gl_entries(self, gl_entries):
 		if self.is_internal_transfer() and flt(self.base_total_taxes_and_charges):
 			account_currency = get_account_currency(self.unrealized_profit_loss_account)
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index 15fae84b79..ee9b59e769 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -902,6 +902,11 @@ class SalesInvoice(SellingController):
 					}, account_currency, item=tax)
 				)
 
+		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
+
+		if enable_discount_accounting and self.get('discount_amount') and self.get('additional_discount_account'):
+			self.make_gle_for_additional_discount_applied_on_taxes(gl_entries)
+
 	def make_internal_transfer_gl_entries(self, gl_entries):
 		if self.is_internal_transfer() and flt(self.base_total_taxes_and_charges):
 			account_currency = get_account_currency(self.unrealized_profit_loss_account)
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 8fc4023f2e..f4593c2a76 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -852,9 +852,6 @@ class AccountsController(TransactionBase):
 							"project": item.project or self.project
 						}, account_currency, item=item)
 					)
-			
-			if self.get('discount_amount') and self.get('additional_discount_account'):
-				self.make_gle_for_additional_discount_applied_on_taxes(gl_entries)
 
 	def make_gle_for_additional_discount_applied_on_taxes(self, gl_entries):
 		for tax in self.get("taxes"):

From 4da7c5882ba8a05c42a013c3b0690b1701da14f9 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Sat, 17 Jul 2021 17:45:35 +0530
Subject: [PATCH 28/49] fix: Only display Additional Discount Account if Enable
 Discount Accounting is checked

---
 .../accounts/doctype/accounts_settings/accounts_settings.py | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/erpnext/accounts/doctype/accounts_settings/accounts_settings.py b/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
index 053f061acc..24b0ec4d4a 100644
--- a/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
+++ b/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
@@ -41,5 +41,7 @@ class AccountsSettings(Document):
 		for doctype in ["Sales Invoice Item", "Purchase Invoice Item"]:
 			make_property_setter(doctype, "discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
 
-		make_property_setter("Item", "default_discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
-		make_property_setter("Sales Invoice", "additional_discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
\ No newline at end of file
+		for doctype in ["Sales Invoice", "Purchase Invoice"]:
+			make_property_setter(doctype, "additional_discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
+
+		make_property_setter("Item", "default_discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
\ No newline at end of file

From d62af77ca8e88b83a921e892fffd583ffd21f6c6 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Sat, 17 Jul 2021 17:47:20 +0530
Subject: [PATCH 29/49] fix: Remove unnecessary condition

---
 .../accounts/doctype/sales_invoice/sales_invoice.js  | 12 +++++-------
 1 file changed, 5 insertions(+), 7 deletions(-)

diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
index fab0e11324..a5341df2e3 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
@@ -629,13 +629,11 @@ frappe.ui.form.on('Sales Invoice', {
 
 		// discount account
 		frm.fields_dict['items'].grid.get_field('discount_account').get_query = function(doc) {
-			if (erpnext.is_perpetual_inventory_enabled(doc.company)) {
-				return {
-					filters: {
-						'report_type': 'Profit and Loss',
-						'company': doc.company,
-						"is_group": 0
-					}
+			return {
+				filters: {
+					'report_type': 'Profit and Loss',
+					'company': doc.company,
+					"is_group": 0
 				}
 			}
 		}

From 99652876d090781916ce8af600e619ea63be0d86 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Sat, 17 Jul 2021 18:45:21 +0530
Subject: [PATCH 30/49] fix: Add test for additional discount applied on taxes

---
 .../sales_invoice/test_sales_invoice.py       | 29 +++++++++++++++++++
 1 file changed, 29 insertions(+)

diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index 2ddfad9c31..1e2e92f609 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -2001,6 +2001,35 @@ class TestSalesInvoice(unittest.TestCase):
 
 		check_gl_entries(self, si.name, expected_gle, nowdate())
 
+	def test_additional_discount_for_sales_invoice_with_discount_accounting_enabled(self):
+		from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import enable_discount_accounting
+
+		enable_discount_accounting()
+		additional_discount_account = create_account(account_name="Discount Account",
+			parent_account="Indirect Expenses - _TC", company="_Test Company")
+		
+		si = create_sales_invoice(rate=75000, do_not_save=1)
+		si.apply_discount_on = "Grand Total"
+		si.additional_discount_account = additional_discount_account
+		si.additional_discount_percentage = 10
+		si.append("taxes", {
+			"charge_type": "On Net Total",
+			"account_head": "CGST - _TC",
+			"cost_center": "Main - _TC",
+			"description": "CGST @ 9.0",
+			"rate": 9
+		})
+		si.submit()
+
+		expected_gle = [
+			["Sales - _TC", 0.0,  67500.0, nowdate()],
+			["Discount Account - _TC", 675.0, 0.0, nowdate()],
+			["CGST - _TC", 0.0, 6750.0, nowdate()],
+			["Debtors - _TC", 73575.0, 0.0, nowdate()]
+		]
+
+		check_gl_entries(self, si.name, expected_gle, nowdate())
+
 def get_sales_invoice_for_e_invoice():
 	si = make_sales_invoice_for_ewaybill()
 	si.naming_series = 'INV-2020-.#####'

From 99cb89f449b6013457f538cd027b72556e18ebf8 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Sat, 17 Jul 2021 19:49:16 +0530
Subject: [PATCH 31/49] fix: Switch debit and credit for ledger entries for
 discount applied on taxes for Purchase Invoice

---
 erpnext/controllers/accounts_controller.py | 21 ++++++++++++++-------
 1 file changed, 14 insertions(+), 7 deletions(-)

diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index f4593c2a76..aa2fe29bc6 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -858,14 +858,22 @@ class AccountsController(TransactionBase):
 			if flt(tax.base_tax_amount_after_discount_amount) and flt(tax.base_tax_amount):
 				account_currency = get_account_currency(tax.account_head)
 				additional_discount_applied_on_taxes = flt(tax.base_tax_amount) - flt(tax.base_tax_amount_after_discount_amount)
+				if self.doctype == 'Purchase Invoice':
+					against = self.supplier
+					dr_or_cr = "debit"
+					rev_dr_cr = "credit"
+				else:
+					against = self.customer
+					dr_or_cr = "credit"
+					rev_dr_cr = "debit"
 
 				gl_entries.append(
 					self.get_gl_dict({
 						"account": tax.account_head,
-						"against": self.customer,
-						"credit": flt(additional_discount_applied_on_taxes,
+						"against": against,
+						dr_or_cr: flt(additional_discount_applied_on_taxes,
 							tax.precision("tax_amount_after_discount_amount")),
-						"credit_in_account_currency": (flt(additional_discount_applied_on_taxes,
+						dr_or_cr + "_in_account_currency": (flt(additional_discount_applied_on_taxes,
 							tax.precision("base_tax_amount_after_discount_amount")) if account_currency==self.company_currency else
 							flt(additional_discount_applied_on_taxes, tax.precision("tax_amount_after_discount_amount"))),
 						"cost_center": tax.cost_center
@@ -875,17 +883,16 @@ class AccountsController(TransactionBase):
 				gl_entries.append(
 					self.get_gl_dict({
 						"account": self.additional_discount_account,
-						"against": self.customer,
-						"debit": flt(additional_discount_applied_on_taxes,
+						"against": against,
+						rev_dr_cr: flt(additional_discount_applied_on_taxes,
 							tax.precision("tax_amount_after_discount_amount")),
-						"debit_in_account_currency": (flt(additional_discount_applied_on_taxes,
+						rev_dr_cr + "_in_account_currency": (flt(additional_discount_applied_on_taxes,
 							tax.precision("base_tax_amount_after_discount_amount")) if account_currency==self.company_currency else
 							flt(additional_discount_applied_on_taxes, tax.precision("tax_amount_after_discount_amount"))),
 						"cost_center": tax.cost_center
 					}, account_currency, item=tax)
 				)
 				
-
 	def allocate_advance_taxes(self, gl_entries):
 		tax_map = self.get_tax_map()
 		for pe in self.get("advances"):

From 251f2296018a996737da6eadddcb650994b3f728 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Sat, 17 Jul 2021 19:49:42 +0530
Subject: [PATCH 32/49] fix: Add test for additional discount applied on taxes

---
 .../purchase_invoice/test_purchase_invoice.py | 29 +++++++++++++++++++
 1 file changed, 29 insertions(+)

diff --git a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
index 36fbc7e351..4eb71f8e70 100644
--- a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
@@ -247,6 +247,35 @@ class TestPurchaseInvoice(unittest.TestCase):
 
 		check_gl_entries(self, pi.name, expected_gle, nowdate())
 
+	def test_additional_discount_for_purchase_invoice_with_discount_accounting_enabled(self):
+		from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import check_gl_entries
+
+		enable_discount_accounting()
+		additional_discount_account = create_account(account_name="Discount Account",
+			parent_account="Indirect Expenses - _TC", company="_Test Company")
+		
+		pi = make_purchase_invoice(qty=1, rate=75000, do_not_save=1)
+		pi.apply_discount_on = "Grand Total"
+		pi.additional_discount_account = additional_discount_account
+		pi.additional_discount_percentage = 10
+		pi.append("taxes", {
+			"charge_type": "On Net Total",
+			"account_head": "CGST - _TC",
+			"cost_center": "Main - _TC",
+			"description": "CGST @ 9.0",
+			"rate": 9
+		})
+		pi.submit()
+
+		expected_gle = [
+			["Discount Account - _TC", 0.0, 675.0, nowdate()],
+			["CGST - _TC", 6750.0, 0.0, nowdate()],
+			["_Test Account Cost for Goods Sold - _TC", 67500.0, 0.0, nowdate()],
+			["Creditors - _TC", 0.0, 73575.0, nowdate()]
+		]
+
+		check_gl_entries(self, pi.name, expected_gle, nowdate())
+
 	def test_purchase_invoice_change_naming_series(self):
 		pi = frappe.copy_doc(test_records[1])
 		pi.insert()

From b4a8bc8e4cbacb80e077b450195c1be346524387 Mon Sep 17 00:00:00 2001
From: Ganga Manoj <ganga.manoj98@gmail.com>
Date: Mon, 19 Jul 2021 23:43:36 +0530
Subject: [PATCH 33/49] fix: Use the item's cost centre instead of the
 Invoice's

Co-authored-by: Deepesh Garg <42651287+deepeshgarg007@users.noreply.github.com>
---
 erpnext/controllers/accounts_controller.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index aa2fe29bc6..65dbe17ec1 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -836,7 +836,7 @@ class AccountsController(TransactionBase):
 							"against": supplier_or_customer,
 							dr_or_cr: flt(item.discount_amount),
 							dr_or_cr + "_in_account_currency": flt(item.discount_amount),
-							"cost_center": self.cost_center,
+							"cost_center": item.cost_center,
 							"project": self.project
 						}, account_currency, item=self)
 					)

From e7e9bda1235f2b9d35b1f8a9d3b525a026bf4dd5 Mon Sep 17 00:00:00 2001
From: Ganga Manoj <ganga.manoj98@gmail.com>
Date: Mon, 19 Jul 2021 23:44:21 +0530
Subject: [PATCH 34/49] fix: Use the item's project instead of the invoice's

Co-authored-by: Deepesh Garg <42651287+deepeshgarg007@users.noreply.github.com>
---
 erpnext/controllers/accounts_controller.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 65dbe17ec1..2aac4968a2 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -837,7 +837,7 @@ class AccountsController(TransactionBase):
 							dr_or_cr: flt(item.discount_amount),
 							dr_or_cr + "_in_account_currency": flt(item.discount_amount),
 							"cost_center": item.cost_center,
-							"project": self.project
+							"project": item.project
 						}, account_currency, item=self)
 					)
 

From f421dc7ca74f97794c8eca5bf52fcfabef178cfe Mon Sep 17 00:00:00 2001
From: Ganga Manoj <ganga.manoj98@gmail.com>
Date: Mon, 19 Jul 2021 23:44:55 +0530
Subject: [PATCH 35/49] fix: GL Entry creation

Co-authored-by: Deepesh Garg <42651287+deepeshgarg007@users.noreply.github.com>
---
 erpnext/controllers/accounts_controller.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 2aac4968a2..9b3336cde5 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -838,7 +838,7 @@ class AccountsController(TransactionBase):
 							dr_or_cr + "_in_account_currency": flt(item.discount_amount),
 							"cost_center": item.cost_center,
 							"project": item.project
-						}, account_currency, item=self)
+						}, account_currency, item=item)
 					)
 
 					account_currency = get_account_currency(income_or_expense_account)

From 821b75f1b119b5ef9be2278889882db3b73af33c Mon Sep 17 00:00:00 2001
From: Ganga Manoj <ganga.manoj98@gmail.com>
Date: Mon, 19 Jul 2021 23:46:38 +0530
Subject: [PATCH 36/49] fix: Filter for additional_discount_account

Co-authored-by: Deepesh Garg <42651287+deepeshgarg007@users.noreply.github.com>
---
 erpnext/accounts/doctype/sales_invoice/sales_invoice.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
index a5341df2e3..0256227886 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
@@ -596,7 +596,7 @@ frappe.ui.form.on('Sales Invoice', {
 				filters: {
 					company: frm.doc.company,
 					is_group: 0,
-					root_type: "Profit and Loss",
+					report_type: "Profit and Loss",
 				}
 			};
 		});

From ed6ebdf5ed297352ac7120bb910662d8c4a41183 Mon Sep 17 00:00:00 2001
From: Ganga Manoj <ganga.manoj98@gmail.com>
Date: Mon, 19 Jul 2021 23:47:58 +0530
Subject: [PATCH 37/49] fix: Filter for additional_discount_account

Co-authored-by: Deepesh Garg <42651287+deepeshgarg007@users.noreply.github.com>
---
 erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
index 4ed31cc227..bf78c028c8 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
@@ -504,7 +504,7 @@ frappe.ui.form.on("Purchase Invoice", {
 				filters: {
 					company: frm.doc.company,
 					is_group: 0,
-					root_type: "Profit and Loss",
+					report_type: "Profit and Loss",
 				}
 			};
 		});

From 566e8f849903644cad157fb8ae9a790d304e84e4 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 20 Jul 2021 03:46:02 +0530
Subject: [PATCH 38/49] fix: Create GL Entries for Additional Discount Account

---
 .../purchase_invoice/purchase_invoice.py      | 11 ++--
 .../doctype/sales_invoice/sales_invoice.py    | 31 +++++++---
 erpnext/controllers/accounts_controller.py    | 60 ++++++-------------
 3 files changed, 45 insertions(+), 57 deletions(-)

diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index 006f5bb0e8..feae213d92 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -609,7 +609,11 @@ class PurchaseInvoice(BuyingController):
 						if (not item.enable_deferred_expense or self.is_return) else item.deferred_expense_account)
 
 					if not item.is_fixed_asset:
-						amount = flt(item.base_net_amount, item.precision("base_net_amount"))
+						if frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'):
+							amount = flt(item.base_amount, item.precision("base_amount"))
+						else:
+							amount = flt(item.base_net_amount, item.precision("base_net_amount"))
+
 					else:
 						amount = flt(item.base_net_amount + item.item_tax_amount, item.precision("base_net_amount"))
 
@@ -888,11 +892,6 @@ class PurchaseInvoice(BuyingController):
 							"remarks": self.remarks or "Accounting Entry for Stock"
 						}, item=tax))
 
-		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
-
-		if enable_discount_accounting and self.get('discount_amount') and self.get('additional_discount_account'):
-			self.make_gle_for_additional_discount_applied_on_taxes(gl_entries)
-
 	def make_internal_transfer_gl_entries(self, gl_entries):
 		if self.is_internal_transfer() and flt(self.base_total_taxes_and_charges):
 			account_currency = get_account_currency(self.unrealized_profit_loss_account)
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index ee9b59e769..52c2a9c42c 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -902,11 +902,6 @@ class SalesInvoice(SellingController):
 					}, account_currency, item=tax)
 				)
 
-		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
-
-		if enable_discount_accounting and self.get('discount_amount') and self.get('additional_discount_account'):
-			self.make_gle_for_additional_discount_applied_on_taxes(gl_entries)
-
 	def make_internal_transfer_gl_entries(self, gl_entries):
 		if self.is_internal_transfer() and flt(self.base_total_taxes_and_charges):
 			account_currency = get_account_currency(self.unrealized_profit_loss_account)
@@ -946,15 +941,17 @@ class SalesInvoice(SellingController):
 						income_account = (item.income_account
 							if (not item.enable_deferred_revenue or self.is_return) else item.deferred_revenue_account)
 
+						amount, base_amount = self.get_amount_and_base_amount(item)
+
 						account_currency = get_account_currency(income_account)
 						gl_entries.append(
 							self.get_gl_dict({
 								"account": income_account,
 								"against": self.customer,
-								"credit": flt(item.base_net_amount, item.precision("base_net_amount")),
-								"credit_in_account_currency": (flt(item.base_net_amount, item.precision("base_net_amount"))
+								"credit": flt(base_amount, item.precision("base_net_amount")),
+								"credit_in_account_currency": (flt(base_amount, item.precision("base_net_amount"))
 									if account_currency==self.company_currency
-									else flt(item.net_amount, item.precision("net_amount"))),
+									else flt(amount, item.precision("net_amount"))),
 								"cost_center": item.cost_center,
 								"project": item.project or self.project
 							}, account_currency, item=item)
@@ -965,6 +962,24 @@ class SalesInvoice(SellingController):
 			erpnext.is_perpetual_inventory_enabled(self.company):
 			gl_entries += super(SalesInvoice, self).get_gl_entries()
 
+	def get_amount_and_base_amount(self, item):
+		amount = item.net_amount
+		base_amount = item.base_net_amount
+
+		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
+
+		if enable_discount_accounting and self.get('discount_amount') and self.get('additional_discount_account'):
+			amount = item.amount
+			base_amount = item.base_amount
+
+		return amount, base_amount
+
+	def set_asset_status(self, asset):
+		if self.is_return:
+			asset.set_status()
+		else: 	
+			asset.set_status("Sold" if self.docstatus==1 else None)
+
 	def make_loyalty_point_redemption_gle(self, gl_entries):
 		if cint(self.redeem_loyalty_points):
 			gl_entries.append(
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 9b3336cde5..59879e0df5 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -812,19 +812,23 @@ class AccountsController(TransactionBase):
 		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
 
 		if enable_discount_accounting:
+			if self.doctype == "Purchase Invoice":
+				dr_or_cr = "credit"
+				rev_dr_cr = "debit"
+				supplier_or_customer = self.supplier
+	
+			else:
+				dr_or_cr = "debit"
+				rev_dr_cr = "credit"
+				supplier_or_customer = self.customer
+
 			for item in self.get("items"):
 				if item.get('discount_amount') and item.get('discount_account'):
 					if self.doctype == "Purchase Invoice":
-						dr_or_cr = "credit"
-						rev_dr_cr = "debit"
-						supplier_or_customer = self.supplier
 						income_or_expense_account = (item.expense_account
 							if (not item.enable_deferred_expense or self.is_return) 
 							else item.deferred_expense_account)
 					else:
-						dr_or_cr = "debit"
-						rev_dr_cr = "credit"
-						supplier_or_customer = self.customer
 						income_or_expense_account = (item.income_account
 							if (not item.enable_deferred_revenue or self.is_return) 
 							else item.deferred_revenue_account)
@@ -853,46 +857,16 @@ class AccountsController(TransactionBase):
 						}, account_currency, item=item)
 					)
 
-	def make_gle_for_additional_discount_applied_on_taxes(self, gl_entries):
-		for tax in self.get("taxes"):
-			if flt(tax.base_tax_amount_after_discount_amount) and flt(tax.base_tax_amount):
-				account_currency = get_account_currency(tax.account_head)
-				additional_discount_applied_on_taxes = flt(tax.base_tax_amount) - flt(tax.base_tax_amount_after_discount_amount)
-				if self.doctype == 'Purchase Invoice':
-					against = self.supplier
-					dr_or_cr = "debit"
-					rev_dr_cr = "credit"
-				else:
-					against = self.customer
-					dr_or_cr = "credit"
-					rev_dr_cr = "debit"
-
-				gl_entries.append(
-					self.get_gl_dict({
-						"account": tax.account_head,
-						"against": against,
-						dr_or_cr: flt(additional_discount_applied_on_taxes,
-							tax.precision("tax_amount_after_discount_amount")),
-						dr_or_cr + "_in_account_currency": (flt(additional_discount_applied_on_taxes,
-							tax.precision("base_tax_amount_after_discount_amount")) if account_currency==self.company_currency else
-							flt(additional_discount_applied_on_taxes, tax.precision("tax_amount_after_discount_amount"))),
-						"cost_center": tax.cost_center
-					}, account_currency, item=tax)
-				)
-
+			if self.get('discount_amount') and self.get('additional_discount_account'):
 				gl_entries.append(
 					self.get_gl_dict({
 						"account": self.additional_discount_account,
-						"against": against,
-						rev_dr_cr: flt(additional_discount_applied_on_taxes,
-							tax.precision("tax_amount_after_discount_amount")),
-						rev_dr_cr + "_in_account_currency": (flt(additional_discount_applied_on_taxes,
-							tax.precision("base_tax_amount_after_discount_amount")) if account_currency==self.company_currency else
-							flt(additional_discount_applied_on_taxes, tax.precision("tax_amount_after_discount_amount"))),
-						"cost_center": tax.cost_center
-					}, account_currency, item=tax)
-				)
-				
+						"against": supplier_or_customer,
+						dr_or_cr: self.discount_amount,
+						"cost_center": self.cost_center
+					}, item=self)
+				)		
+										
 	def allocate_advance_taxes(self, gl_entries):
 		tax_map = self.get_tax_map()
 		for pe in self.get("advances"):

From 1f6c05f0139a8ad9f1d22c4c35552e51e767180f Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 20 Jul 2021 03:52:39 +0530
Subject: [PATCH 39/49] fix: Make discount_account mandatory if discount
 accounting is enabled

---
 erpnext/accounts/doctype/accounts_settings/accounts_settings.py | 1 +
 1 file changed, 1 insertion(+)

diff --git a/erpnext/accounts/doctype/accounts_settings/accounts_settings.py b/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
index 24b0ec4d4a..a3a32d5e97 100644
--- a/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
+++ b/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
@@ -40,6 +40,7 @@ class AccountsSettings(Document):
 		
 		for doctype in ["Sales Invoice Item", "Purchase Invoice Item"]:
 			make_property_setter(doctype, "discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
+			make_property_setter(doctype, "discount_account", "mandatory", enable_discount_accounting, "Check", validate_fields_for_doctype=False)
 
 		for doctype in ["Sales Invoice", "Purchase Invoice"]:
 			make_property_setter(doctype, "additional_discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)

From 45327e04db1a35f439e874e2e5175c87683af959 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 20 Jul 2021 05:16:33 +0530
Subject: [PATCH 40/49] fix: Tests

---
 .../purchase_invoice/test_purchase_invoice.py | 43 +++++++++++++------
 .../sales_invoice/test_sales_invoice.py       | 25 +++++------
 2 files changed, 43 insertions(+), 25 deletions(-)

diff --git a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
index 4eb71f8e70..0487ef6444 100644
--- a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
@@ -231,8 +231,6 @@ class TestPurchaseInvoice(unittest.TestCase):
 			self.assertEqual(expected_values[gle.account][2], gle.credit)
 
 	def test_purchase_invoice_with_discount_accounting_enabled(self):
-		from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import check_gl_entries
-
 		enable_discount_accounting()
 
 		discount_account = create_account(account_name="Discount Account",
@@ -240,38 +238,45 @@ class TestPurchaseInvoice(unittest.TestCase):
 		pi = make_purchase_invoice(discount_account=discount_account, discount_amount=100)
 
 		expected_gle = [
-			["Discount Account - _TC", 0.0, 100.0, nowdate()],
 			["_Test Account Cost for Goods Sold - _TC", 350.0, 0.0, nowdate()],
-			["Creditors - _TC", 0.0, 250.0, nowdate()]
+			["Creditors - _TC", 0.0, 250.0, nowdate()],
+			["Discount Account - _TC", 0.0, 100.0, nowdate()]
 		]
 
 		check_gl_entries(self, pi.name, expected_gle, nowdate())
 
 	def test_additional_discount_for_purchase_invoice_with_discount_accounting_enabled(self):
-		from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import check_gl_entries
-
 		enable_discount_accounting()
 		additional_discount_account = create_account(account_name="Discount Account",
 			parent_account="Indirect Expenses - _TC", company="_Test Company")
 		
-		pi = make_purchase_invoice(qty=1, rate=75000, do_not_save=1)
+		pi = make_purchase_invoice(qty=1, rate=100, do_not_save=1)
 		pi.apply_discount_on = "Grand Total"
 		pi.additional_discount_account = additional_discount_account
-		pi.additional_discount_percentage = 10
+		pi.additional_discount_percentage = 20
 		pi.append("taxes", {
 			"charge_type": "On Net Total",
 			"account_head": "CGST - _TC",
 			"cost_center": "Main - _TC",
 			"description": "CGST @ 9.0",
-			"rate": 9
+			"base_tax_amount": 20,
+			"base_tax_amount_after_discount_amount": 20
 		})
 		pi.submit()
 
+		# gle = frappe.get_all(
+		# 	"GL Entry",
+		# 	fields = ['account', 'debit', 'credit', 'posting_date'],
+		# 	filters = {'voucher_no': pi.name}
+		# )
+		# for gl in gle:
+		# 	print(gl, "\n")
+
 		expected_gle = [
-			["Discount Account - _TC", 0.0, 675.0, nowdate()],
-			["CGST - _TC", 6750.0, 0.0, nowdate()],
-			["_Test Account Cost for Goods Sold - _TC", 67500.0, 0.0, nowdate()],
-			["Creditors - _TC", 0.0, 73575.0, nowdate()]
+			["CGST - _TC", 20.0, 0.0, nowdate()],
+			["Creditors - _TC", 0.0, 96.0, nowdate()],
+			["Discount Account - _TC", 0.0, 24.0, nowdate()],
+			["_Test Account Cost for Goods Sold - _TC", 100.0, 0.0, nowdate()]
 		]
 
 		check_gl_entries(self, pi.name, expected_gle, nowdate())
@@ -1186,6 +1191,18 @@ class TestPurchaseInvoice(unittest.TestCase):
 			self.assertEqual(expected_gle[i][0], gle.account)
 			self.assertEqual(expected_gle[i][1], gle.amount)
 
+def check_gl_entries(doc, voucher_no, expected_gle, posting_date):
+	gl_entries = frappe.db.sql("""select account, debit, credit, posting_date
+		from `tabGL Entry`
+		where voucher_type='Purchase Invoice' and voucher_no=%s and posting_date >= %s
+		order by posting_date asc, account asc""", (voucher_no, posting_date), as_dict=1)
+
+	for i, gle in enumerate(gl_entries):
+		doc.assertEqual(expected_gle[i][0], gle.account)
+		doc.assertEqual(expected_gle[i][1], gle.debit)
+		doc.assertEqual(expected_gle[i][2], gle.credit)
+		doc.assertEqual(getdate(expected_gle[i][3]), gle.posting_date)
+
 def update_tax_witholding_category(company, account, date):
 	from erpnext.accounts.utils import get_fiscal_year
 
diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index 1e2e92f609..9f7d18bdb4 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -1994,12 +1994,12 @@ class TestSalesInvoice(unittest.TestCase):
 		si = create_sales_invoice(discount_account=discount_account, discount_amount=100)
 		
 		expected_gle = [
+			["Debtors - _TC", 100.0, 0.0, nowdate()],
 			["Discount Account - _TC", 100.0, 0.0, nowdate()],
-			["Sales - _TC", 0.0, 200.0, nowdate()],
-			["Debtors - _TC", 100.0, 0.0, nowdate()]
+			["Sales - _TC", 0.0, 200.0, nowdate()]
 		]
 
-		check_gl_entries(self, si.name, expected_gle, nowdate())
+		check_gl_entries(self, si.name, expected_gle, add_days(nowdate(), -1))
 
 	def test_additional_discount_for_sales_invoice_with_discount_accounting_enabled(self):
 		from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import enable_discount_accounting
@@ -2008,27 +2008,28 @@ class TestSalesInvoice(unittest.TestCase):
 		additional_discount_account = create_account(account_name="Discount Account",
 			parent_account="Indirect Expenses - _TC", company="_Test Company")
 		
-		si = create_sales_invoice(rate=75000, do_not_save=1)
+		si = create_sales_invoice(rate=100, do_not_save=1)
 		si.apply_discount_on = "Grand Total"
 		si.additional_discount_account = additional_discount_account
-		si.additional_discount_percentage = 10
+		si.additional_discount_percentage = 20
 		si.append("taxes", {
-			"charge_type": "On Net Total",
+			"charge_type": "Actual",
 			"account_head": "CGST - _TC",
 			"cost_center": "Main - _TC",
 			"description": "CGST @ 9.0",
-			"rate": 9
+			"rate": 0,
+			"tax_amount": 20
 		})
 		si.submit()
 
 		expected_gle = [
-			["Sales - _TC", 0.0,  67500.0, nowdate()],
-			["Discount Account - _TC", 675.0, 0.0, nowdate()],
-			["CGST - _TC", 0.0, 6750.0, nowdate()],
-			["Debtors - _TC", 73575.0, 0.0, nowdate()]
+			["CGST - _TC", 0.0, 20.0, nowdate()],
+			["Debtors - _TC", 96.0, 0.0, nowdate()],
+			["Discount Account - _TC", 24.0, 0.0, nowdate()],
+			["Sales - _TC", 0.0, 100.0, nowdate()]
 		]
 
-		check_gl_entries(self, si.name, expected_gle, nowdate())
+		check_gl_entries(self, si.name, expected_gle, add_days(nowdate(), -1))
 
 def get_sales_invoice_for_e_invoice():
 	si = make_sales_invoice_for_ewaybill()

From 4fa409e0194fde280647b31c96a404099cf99eb1 Mon Sep 17 00:00:00 2001
From: GangaManoj <ganga.manoj98@gmail.com>
Date: Tue, 20 Jul 2021 22:03:44 +0530
Subject: [PATCH 41/49] fix: Add mandatory_depends_on property for Discount
 Account

---
 .../doctype/accounts_settings/accounts_settings.py       | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/erpnext/accounts/doctype/accounts_settings/accounts_settings.py b/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
index a3a32d5e97..5544913292 100644
--- a/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
+++ b/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
@@ -40,9 +40,16 @@ class AccountsSettings(Document):
 		
 		for doctype in ["Sales Invoice Item", "Purchase Invoice Item"]:
 			make_property_setter(doctype, "discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
-			make_property_setter(doctype, "discount_account", "mandatory", enable_discount_accounting, "Check", validate_fields_for_doctype=False)
+			if enable_discount_accounting:
+				make_property_setter(doctype, "discount_account", "mandatory_depends_on", "eval: doc.discount_amount", "Code", validate_fields_for_doctype=False)
+			else:
+				make_property_setter(doctype, "discount_account", "mandatory_depends_on", "", "Code", validate_fields_for_doctype=False)
 
 		for doctype in ["Sales Invoice", "Purchase Invoice"]:
 			make_property_setter(doctype, "additional_discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
+			if enable_discount_accounting:
+				make_property_setter(doctype, "additional_discount_account", "mandatory_depends_on", "eval: doc.discount_amount", "Code", validate_fields_for_doctype=False)
+			else:
+				make_property_setter(doctype, "additional_discount_account", "mandatory_depends_on", "", "Code", validate_fields_for_doctype=False)
 
 		make_property_setter("Item", "default_discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False)
\ No newline at end of file

From fc09d845c5b38dd60783dfd287a71f7ab0dcbad9 Mon Sep 17 00:00:00 2001
From: Deepesh Garg <deepeshgarg6@gmail.com>
Date: Wed, 21 Jul 2021 15:25:09 +0530
Subject: [PATCH 42/49] fix: Syntax Error

---
 erpnext/accounts/doctype/sales_invoice/sales_invoice.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
index 0256227886..56f11650ff 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
@@ -348,7 +348,7 @@ erpnext.accounts.SalesInvoiceController = erpnext.selling.SellingController.exte
 	items_add: function(doc, cdt, cdn) {
 		var row = frappe.get_doc(cdt, cdn);
 		this.frm.script_manager.copy_from_first_row("items", row, ["income_account", "discount_account", "cost_center"]);
-	}
+	},
 
 	set_dynamic_labels: function() {
 		this._super();

From 5a06019440f80b2c3719f195cdf5619d3715b759 Mon Sep 17 00:00:00 2001
From: Deepesh Garg <deepeshgarg6@gmail.com>
Date: Wed, 21 Jul 2021 15:25:40 +0530
Subject: [PATCH 43/49] fix: GL For taxes if discount applied on Grand Total

---
 .../doctype/sales_invoice/sales_invoice.py    | 26 +++++++------------
 erpnext/controllers/accounts_controller.py    | 21 +++++++++++++++
 2 files changed, 31 insertions(+), 16 deletions(-)

diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index 52c2a9c42c..2539de7b12 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -886,18 +886,22 @@ class SalesInvoice(SellingController):
 			)
 
 	def make_tax_gl_entries(self, gl_entries):
+		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
+
 		for tax in self.get("taxes"):
+			amount, base_amount = self.get_tax_amounts(tax, enable_discount_accounting)
+
 			if flt(tax.base_tax_amount_after_discount_amount):
 				account_currency = get_account_currency(tax.account_head)
 				gl_entries.append(
 					self.get_gl_dict({
 						"account": tax.account_head,
 						"against": self.customer,
-						"credit": flt(tax.base_tax_amount_after_discount_amount,
+						"credit": flt(base_amount,
 							tax.precision("tax_amount_after_discount_amount")),
-						"credit_in_account_currency": (flt(tax.base_tax_amount_after_discount_amount,
+						"credit_in_account_currency": (flt(base_amount,
 							tax.precision("base_tax_amount_after_discount_amount")) if account_currency==self.company_currency else
-							flt(tax.tax_amount_after_discount_amount, tax.precision("tax_amount_after_discount_amount"))),
+							flt(amount, tax.precision("tax_amount_after_discount_amount"))),
 						"cost_center": tax.cost_center
 					}, account_currency, item=tax)
 				)
@@ -916,6 +920,8 @@ class SalesInvoice(SellingController):
 
 	def make_item_gl_entries(self, gl_entries):
 		# income account gl entries
+		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
+
 		for item in self.get("items"):
 			if flt(item.base_net_amount, item.precision("base_net_amount")):
 				if item.is_fixed_asset:
@@ -941,7 +947,7 @@ class SalesInvoice(SellingController):
 						income_account = (item.income_account
 							if (not item.enable_deferred_revenue or self.is_return) else item.deferred_revenue_account)
 
-						amount, base_amount = self.get_amount_and_base_amount(item)
+						amount, base_amount = self.get_amount_and_base_amount(item, enable_discount_accounting)
 
 						account_currency = get_account_currency(income_account)
 						gl_entries.append(
@@ -962,18 +968,6 @@ class SalesInvoice(SellingController):
 			erpnext.is_perpetual_inventory_enabled(self.company):
 			gl_entries += super(SalesInvoice, self).get_gl_entries()
 
-	def get_amount_and_base_amount(self, item):
-		amount = item.net_amount
-		base_amount = item.base_net_amount
-
-		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
-
-		if enable_discount_accounting and self.get('discount_amount') and self.get('additional_discount_account'):
-			amount = item.amount
-			base_amount = item.base_amount
-
-		return amount, base_amount
-
 	def set_asset_status(self, asset):
 		if self.is_return:
 			asset.set_status()
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 59879e0df5..3d048c3686 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -808,6 +808,27 @@ class AccountsController(TransactionBase):
 							tax_map[tax.account_head] -= allocated_amount
 							allocated_tax_map[tax.account_head] -= allocated_amount
 
+	def get_amount_and_base_amount(self, item, enable_discount_accounting):
+		amount = item.net_amount
+		base_amount = item.base_net_amount
+
+		if enable_discount_accounting and self.get('discount_amount') and self.get('additional_discount_account'):
+			amount = item.amount
+			base_amount = item.base_amount
+
+		return amount, base_amount
+
+	def get_tax_amounts(self, tax, enable_discount_accounting):
+		amount = tax.tax_amount_after_discount_amount
+		base_amount = tax.base_tax_amount_after_discount_amount
+
+		if enable_discount_accounting and self.get('discount_amount') and self.get('additional_discount_account') \
+			and self.get('apply_discount_on') == 'Grand Total':
+			amount = tax.tax_amount
+			base_amount = tax.base_tax_amount
+
+		return amount, base_amount
+
 	def make_discount_gl_entries(self, gl_entries):
 		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
 

From c765073c2a56688835b04d72fc335f654e2ef86a Mon Sep 17 00:00:00 2001
From: Deepesh Garg <deepeshgarg6@gmail.com>
Date: Wed, 21 Jul 2021 22:28:32 +0530
Subject: [PATCH 44/49] fix: Tests

---
 .../purchase_invoice/test_purchase_invoice.py | 20 +++++++++----------
 .../sales_invoice/test_sales_invoice.py       |  9 +++++----
 2 files changed, 15 insertions(+), 14 deletions(-)

diff --git a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
index 0487ef6444..e20e385f63 100644
--- a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
@@ -250,17 +250,16 @@ class TestPurchaseInvoice(unittest.TestCase):
 		additional_discount_account = create_account(account_name="Discount Account",
 			parent_account="Indirect Expenses - _TC", company="_Test Company")
 		
-		pi = make_purchase_invoice(qty=1, rate=100, do_not_save=1)
+		pi = make_purchase_invoice(qty=1, rate=100, do_not_save=1, parent_cost_center="Main - _TC")
 		pi.apply_discount_on = "Grand Total"
 		pi.additional_discount_account = additional_discount_account
 		pi.additional_discount_percentage = 20
 		pi.append("taxes", {
-			"charge_type": "On Net Total",
-			"account_head": "CGST - _TC",
+			"charge_type": "Actual",
+			"account_head": "_Test Account VAT - _TC",
 			"cost_center": "Main - _TC",
-			"description": "CGST @ 9.0",
-			"base_tax_amount": 20,
-			"base_tax_amount_after_discount_amount": 20
+			"description": "Test",
+			"tax_amount": 20
 		})
 		pi.submit()
 
@@ -273,10 +272,10 @@ class TestPurchaseInvoice(unittest.TestCase):
 		# 	print(gl, "\n")
 
 		expected_gle = [
-			["CGST - _TC", 20.0, 0.0, nowdate()],
+			["_Test Account Cost for Goods Sold - _TC", 100.0, 0.0, nowdate()],
+			["_Test Account VAT - _TC", 20.0, 0.0, nowdate()],
 			["Creditors - _TC", 0.0, 96.0, nowdate()],
-			["Discount Account - _TC", 0.0, 24.0, nowdate()],
-			["_Test Account Cost for Goods Sold - _TC", 100.0, 0.0, nowdate()]
+			["Discount Account - _TC", 0.0, 24.0, nowdate()]
 		]
 
 		check_gl_entries(self, pi.name, expected_gle, nowdate())
@@ -1197,6 +1196,7 @@ def check_gl_entries(doc, voucher_no, expected_gle, posting_date):
 		where voucher_type='Purchase Invoice' and voucher_no=%s and posting_date >= %s
 		order by posting_date asc, account asc""", (voucher_no, posting_date), as_dict=1)
 
+	print(gl_entries)
 	for i, gle in enumerate(gl_entries):
 		doc.assertEqual(expected_gle[i][0], gle.account)
 		doc.assertEqual(expected_gle[i][1], gle.debit)
@@ -1260,7 +1260,7 @@ def make_purchase_invoice(**args):
 	pi.return_against = args.return_against
 	pi.is_subcontracted = args.is_subcontracted or "No"
 	pi.supplier_warehouse = args.supplier_warehouse or "_Test Warehouse 1 - _TC"
-	pi.cost_center = args.cost_center or "_Test Cost Center - _TC"
+	pi.cost_center = args.parent_cost_center
 
 	pi.append("items", {
 		"item_code": args.item or args.item_code or "_Test Item",
diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index 9f7d18bdb4..1c0177d3d0 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -2014,16 +2014,17 @@ class TestSalesInvoice(unittest.TestCase):
 		si.additional_discount_percentage = 20
 		si.append("taxes", {
 			"charge_type": "Actual",
-			"account_head": "CGST - _TC",
+			"account_head": "_Test Account VAT - _TC",
 			"cost_center": "Main - _TC",
-			"description": "CGST @ 9.0",
+			"parent_cost_center": "Main - _TC",
+			"description": "Test",
 			"rate": 0,
 			"tax_amount": 20
 		})
 		si.submit()
 
 		expected_gle = [
-			["CGST - _TC", 0.0, 20.0, nowdate()],
+			["_Test Account VAT - _TC", 0.0, 20.0, nowdate()],
 			["Debtors - _TC", 96.0, 0.0, nowdate()],
 			["Discount Account - _TC", 24.0, 0.0, nowdate()],
 			["Sales - _TC", 0.0, 100.0, nowdate()]
@@ -2199,7 +2200,7 @@ def create_sales_invoice(**args):
 	si.currency=args.currency or "INR"
 	si.conversion_rate = args.conversion_rate or 1
 	si.naming_series = args.naming_series or "T-SINV-"
-	si.cost_center = args.cost_center or "_Test Cost Center - _TC"
+	si.cost_center = args.parent_cost_center
 
 	si.append("items", {
 		"item_code": args.item or args.item_code or "_Test Item",

From 2ff0d3e0ebf5424ad8a50f65ad64b531a13f4b40 Mon Sep 17 00:00:00 2001
From: Deepesh Garg <deepeshgarg6@gmail.com>
Date: Thu, 22 Jul 2021 10:43:16 +0530
Subject: [PATCH 45/49] fix: Test Cases

---
 .../doctype/purchase_invoice/test_purchase_invoice.py    | 9 ---------
 .../accounts/doctype/sales_invoice/test_sales_invoice.py | 3 +--
 2 files changed, 1 insertion(+), 11 deletions(-)

diff --git a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
index e20e385f63..9d2acdc977 100644
--- a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
@@ -263,14 +263,6 @@ class TestPurchaseInvoice(unittest.TestCase):
 		})
 		pi.submit()
 
-		# gle = frappe.get_all(
-		# 	"GL Entry",
-		# 	fields = ['account', 'debit', 'credit', 'posting_date'],
-		# 	filters = {'voucher_no': pi.name}
-		# )
-		# for gl in gle:
-		# 	print(gl, "\n")
-
 		expected_gle = [
 			["_Test Account Cost for Goods Sold - _TC", 100.0, 0.0, nowdate()],
 			["_Test Account VAT - _TC", 20.0, 0.0, nowdate()],
@@ -1196,7 +1188,6 @@ def check_gl_entries(doc, voucher_no, expected_gle, posting_date):
 		where voucher_type='Purchase Invoice' and voucher_no=%s and posting_date >= %s
 		order by posting_date asc, account asc""", (voucher_no, posting_date), as_dict=1)
 
-	print(gl_entries)
 	for i, gle in enumerate(gl_entries):
 		doc.assertEqual(expected_gle[i][0], gle.account)
 		doc.assertEqual(expected_gle[i][1], gle.debit)
diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index 1c0177d3d0..a7fbbdd5ca 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -2008,7 +2008,7 @@ class TestSalesInvoice(unittest.TestCase):
 		additional_discount_account = create_account(account_name="Discount Account",
 			parent_account="Indirect Expenses - _TC", company="_Test Company")
 		
-		si = create_sales_invoice(rate=100, do_not_save=1)
+		si = create_sales_invoice(rate=100, parent_cost_center='Main - _TC', do_not_save=1)
 		si.apply_discount_on = "Grand Total"
 		si.additional_discount_account = additional_discount_account
 		si.additional_discount_percentage = 20
@@ -2016,7 +2016,6 @@ class TestSalesInvoice(unittest.TestCase):
 			"charge_type": "Actual",
 			"account_head": "_Test Account VAT - _TC",
 			"cost_center": "Main - _TC",
-			"parent_cost_center": "Main - _TC",
 			"description": "Test",
 			"rate": 0,
 			"tax_amount": 20

From 1c9e516092e415ae27441b26e0a632427cd81f31 Mon Sep 17 00:00:00 2001
From: Deepesh Garg <deepeshgarg6@gmail.com>
Date: Wed, 28 Jul 2021 11:38:44 +0530
Subject: [PATCH 46/49] fix: GL Entries for discount amount with item qty
 greater than 1

---
 erpnext/controllers/accounts_controller.py | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 3d048c3686..8199b1040f 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -845,6 +845,7 @@ class AccountsController(TransactionBase):
 
 			for item in self.get("items"):
 				if item.get('discount_amount') and item.get('discount_account'):
+					discount_amount = item.discount_amount * item.qty
 					if self.doctype == "Purchase Invoice":
 						income_or_expense_account = (item.expense_account
 							if (not item.enable_deferred_expense or self.is_return) 
@@ -859,8 +860,9 @@ class AccountsController(TransactionBase):
 						self.get_gl_dict({
 							"account": item.discount_account,
 							"against": supplier_or_customer,
-							dr_or_cr: flt(item.discount_amount),
-							dr_or_cr + "_in_account_currency": flt(item.discount_amount),
+							dr_or_cr: flt(discount_amount, item.precision('discount_amount')),
+							dr_or_cr + "_in_account_currency": flt(discount_amount * self.get('conversion_rate'), 
+								item.precision('discount_amount')),
 							"cost_center": item.cost_center,
 							"project": item.project
 						}, account_currency, item=item)
@@ -871,8 +873,9 @@ class AccountsController(TransactionBase):
 						self.get_gl_dict({
 							"account": income_or_expense_account,
 							"against": supplier_or_customer,
-							rev_dr_cr: flt(item.discount_amount),
-							rev_dr_cr + "_in_account_currency": flt(item.discount_amount),
+							rev_dr_cr: flt(discount_amount, item.precision('discount_amount')),
+							rev_dr_cr + "_in_account_currency": flt(discount_amount * self.get('conversion_rate'), 
+								item.precision('discount_amount')),
 							"cost_center": item.cost_center,
 							"project": item.project or self.project
 						}, account_currency, item=item)

From b73bb3e5013e08276f7af4f83321cc600b081ad0 Mon Sep 17 00:00:00 2001
From: Deepesh Garg <deepeshgarg6@gmail.com>
Date: Thu, 5 Aug 2021 22:38:00 +0530
Subject: [PATCH 47/49] fix: Add discount account handling in Purchase Invoice

---
 .../purchase_invoice/purchase_invoice.py      | 25 +++++++++++--------
 1 file changed, 14 insertions(+), 11 deletions(-)

diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index feae213d92..d0f4e96541 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -519,6 +519,10 @@ class PurchaseInvoice(BuyingController):
 			if d.category in ('Valuation', 'Total and Valuation')
 			and flt(d.base_tax_amount_after_discount_amount)]
 
+		exchange_rate_map, net_rate_map = get_purchase_document_details(self)
+		
+		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
+
 		for item in self.get("items"):
 			if flt(item.base_net_amount):
 				account_currency = get_account_currency(item.expense_account)
@@ -609,11 +613,7 @@ class PurchaseInvoice(BuyingController):
 						if (not item.enable_deferred_expense or self.is_return) else item.deferred_expense_account)
 
 					if not item.is_fixed_asset:
-						if frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'):
-							amount = flt(item.base_amount, item.precision("base_amount"))
-						else:
-							amount = flt(item.base_net_amount, item.precision("base_net_amount"))
-
+						dummy, amount = self.get_amount_and_base_amount(item, enable_discount_accounting)
 					else:
 						amount = flt(item.base_net_amount + item.item_tax_amount, item.precision("base_net_amount"))
 
@@ -827,8 +827,11 @@ class PurchaseInvoice(BuyingController):
 	def make_tax_gl_entries(self, gl_entries):
 		# tax table gl entries
 		valuation_tax = {}
+		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
+
 		for tax in self.get("taxes"):
-			if tax.category in ("Total", "Valuation and Total") and flt(tax.base_tax_amount_after_discount_amount):
+			amount, base_amount = self.get_tax_amounts(tax, enable_discount_accounting)
+			if tax.category in ("Total", "Valuation and Total") and flt(base_amount):
 				account_currency = get_account_currency(tax.account_head)
 
 				dr_or_cr = "debit" if tax.add_deduct_tax == "Add" else "credit"
@@ -837,21 +840,21 @@ class PurchaseInvoice(BuyingController):
 					self.get_gl_dict({
 						"account": tax.account_head,
 						"against": self.supplier,
-						dr_or_cr: tax.base_tax_amount_after_discount_amount,
-						dr_or_cr + "_in_account_currency": tax.base_tax_amount_after_discount_amount \
+						dr_or_cr: base_amount,
+						dr_or_cr + "_in_account_currency": base_amount \
 							if account_currency==self.company_currency \
-							else tax.tax_amount_after_discount_amount,
+							else amount,
 						"cost_center": tax.cost_center
 					}, account_currency, item=tax)
 				)
 			# accumulate valuation tax
-			if self.is_opening == "No" and tax.category in ("Valuation", "Valuation and Total") and flt(tax.base_tax_amount_after_discount_amount) \
+			if self.is_opening == "No" and tax.category in ("Valuation", "Valuation and Total") and flt(base_amount) \
 				and not self.is_internal_transfer():
 				if self.auto_accounting_for_stock and not tax.cost_center:
 					frappe.throw(_("Cost Center is required in row {0} in Taxes table for type {1}").format(tax.idx, _(tax.category)))
 				valuation_tax.setdefault(tax.name, 0)
 				valuation_tax[tax.name] += \
-					(tax.add_deduct_tax == "Add" and 1 or -1) * flt(tax.base_tax_amount_after_discount_amount)
+					(tax.add_deduct_tax == "Add" and 1 or -1) * flt(base_amount)
 
 		if self.is_opening == "No" and self.negative_expense_to_be_booked and valuation_tax:
 			# credit valuation tax amount in "Expenses Included In Valuation"

From 428ccebad95a82ca0a38c35924fe5756ac35311b Mon Sep 17 00:00:00 2001
From: Deepesh Garg <deepeshgarg6@gmail.com>
Date: Thu, 5 Aug 2021 22:38:24 +0530
Subject: [PATCH 48/49] test: Update test cases for discount accounting

---
 .../purchase_invoice/test_purchase_invoice.py | 27 ++++++++++---------
 .../sales_invoice/test_sales_invoice.py       | 24 +++++++++--------
 2 files changed, 28 insertions(+), 23 deletions(-)

diff --git a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
index d60f0a40b1..f0f5a58d15 100644
--- a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
@@ -235,39 +235,41 @@ class TestPurchaseInvoice(unittest.TestCase):
 
 		discount_account = create_account(account_name="Discount Account",
 			parent_account="Indirect Expenses - _TC", company="_Test Company")
-		pi = make_purchase_invoice(discount_account=discount_account, discount_amount=100)
+		pi = make_purchase_invoice(discount_account=discount_account, rate=45)
 
 		expected_gle = [
-			["_Test Account Cost for Goods Sold - _TC", 350.0, 0.0, nowdate()],
-			["Creditors - _TC", 0.0, 250.0, nowdate()],
-			["Discount Account - _TC", 0.0, 100.0, nowdate()]
+			["_Test Account Cost for Goods Sold - _TC", 250.0, 0.0, nowdate()],
+			["Creditors - _TC", 0.0, 225.0, nowdate()],
+			["Discount Account - _TC", 0.0, 25.0, nowdate()]
 		]
 
 		check_gl_entries(self, pi.name, expected_gle, nowdate())
+		enable_discount_accounting(enable=0)
 
 	def test_additional_discount_for_purchase_invoice_with_discount_accounting_enabled(self):
 		enable_discount_accounting()
 		additional_discount_account = create_account(account_name="Discount Account",
 			parent_account="Indirect Expenses - _TC", company="_Test Company")
 		
-		pi = make_purchase_invoice(qty=1, rate=100, do_not_save=1, parent_cost_center="Main - _TC")
+		pi = make_purchase_invoice(do_not_save=1, parent_cost_center="Main - _TC")
 		pi.apply_discount_on = "Grand Total"
 		pi.additional_discount_account = additional_discount_account
-		pi.additional_discount_percentage = 20
+		pi.additional_discount_percentage = 10
+		pi.disable_rounded_total = 1
 		pi.append("taxes", {
-			"charge_type": "Actual",
+			"charge_type": "On Net Total",
 			"account_head": "_Test Account VAT - _TC",
 			"cost_center": "Main - _TC",
 			"description": "Test",
-			"tax_amount": 20
+			"rate": 10
 		})
 		pi.submit()
 
 		expected_gle = [
-			["_Test Account Cost for Goods Sold - _TC", 100.0, 0.0, nowdate()],
-			["_Test Account VAT - _TC", 20.0, 0.0, nowdate()],
-			["Creditors - _TC", 0.0, 96.0, nowdate()],
-			["Discount Account - _TC", 0.0, 24.0, nowdate()]
+			["_Test Account Cost for Goods Sold - _TC", 250.0, 0.0, nowdate()],
+			["_Test Account VAT - _TC", 25.0, 0.0, nowdate()],
+			["Creditors - _TC", 0.0, 247.5, nowdate()],
+			["Discount Account - _TC", 0.0, 27.5, nowdate()]
 		]
 
 		check_gl_entries(self, pi.name, expected_gle, nowdate())
@@ -1260,6 +1262,7 @@ def make_purchase_invoice(**args):
 		"received_qty": args.received_qty or 0,
 		"rejected_qty": args.rejected_qty or 0,
 		"rate": args.rate or 50,
+		"price_list_rate": args.price_list_rate or 50,
 		"expense_account": args.expense_account or '_Test Account Cost for Goods Sold - _TC',
 		"discount_account": args.discount_account or None,
 		"discount_amount": args.discount_amount or 0,
diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index af317db712..12f03be288 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -1993,15 +1993,16 @@ class TestSalesInvoice(unittest.TestCase):
 
 		discount_account = create_account(account_name="Discount Account",
 			parent_account="Indirect Expenses - _TC", company="_Test Company")
-		si = create_sales_invoice(discount_account=discount_account, discount_amount=100)
+		si = create_sales_invoice(discount_account=discount_account, discount_percentage=10, rate=90)
 		
 		expected_gle = [
-			["Debtors - _TC", 100.0, 0.0, nowdate()],
-			["Discount Account - _TC", 100.0, 0.0, nowdate()],
-			["Sales - _TC", 0.0, 200.0, nowdate()]
+			["Debtors - _TC", 90.0, 0.0, nowdate()],
+			["Discount Account - _TC", 10.0, 0.0, nowdate()],
+			["Sales - _TC", 0.0, 100.0, nowdate()]
 		]
 
 		check_gl_entries(self, si.name, expected_gle, add_days(nowdate(), -1))
+		enable_discount_accounting(enable=0)
 
 	def test_additional_discount_for_sales_invoice_with_discount_accounting_enabled(self):
 		from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import enable_discount_accounting
@@ -2010,28 +2011,28 @@ class TestSalesInvoice(unittest.TestCase):
 		additional_discount_account = create_account(account_name="Discount Account",
 			parent_account="Indirect Expenses - _TC", company="_Test Company")
 		
-		si = create_sales_invoice(rate=100, parent_cost_center='Main - _TC', do_not_save=1)
+		si = create_sales_invoice(parent_cost_center='Main - _TC', do_not_save=1)
 		si.apply_discount_on = "Grand Total"
 		si.additional_discount_account = additional_discount_account
 		si.additional_discount_percentage = 20
 		si.append("taxes", {
-			"charge_type": "Actual",
+			"charge_type": "On Net Total",
 			"account_head": "_Test Account VAT - _TC",
 			"cost_center": "Main - _TC",
 			"description": "Test",
-			"rate": 0,
-			"tax_amount": 20
+			"rate": 10
 		})
 		si.submit()
 
 		expected_gle = [
-			["_Test Account VAT - _TC", 0.0, 20.0, nowdate()],
-			["Debtors - _TC", 96.0, 0.0, nowdate()],
-			["Discount Account - _TC", 24.0, 0.0, nowdate()],
+			["_Test Account VAT - _TC", 0.0, 10.0, nowdate()],
+			["Debtors - _TC", 88, 0.0, nowdate()],
+			["Discount Account - _TC", 22.0, 0.0, nowdate()],
 			["Sales - _TC", 0.0, 100.0, nowdate()]
 		]
 
 		check_gl_entries(self, si.name, expected_gle, add_days(nowdate(), -1))
+		enable_discount_accounting(enable=0)
 
 def get_sales_invoice_for_e_invoice():
 	si = make_sales_invoice_for_ewaybill()
@@ -2238,6 +2239,7 @@ def create_sales_invoice(**args):
 		"uom": args.uom or "Nos",
 		"stock_uom": args.uom or "Nos",
 		"rate": args.rate if args.get("rate") is not None else 100,
+		"price_list_rate": args.price_list_rate if args.get("price_list_rate") is not None else 100,
 		"income_account": args.income_account or "Sales - _TC",
 		"expense_account": args.expense_account or "Cost of Goods Sold - _TC",
 		"discount_account": args.discount_account or None,

From 797170e9138310da53ef33ecb2f8397f8b292882 Mon Sep 17 00:00:00 2001
From: Deepesh Garg <deepeshgarg6@gmail.com>
Date: Tue, 10 Aug 2021 11:02:21 +0530
Subject: [PATCH 49/49] fix: Linting issues

---
 .../accounts/doctype/purchase_invoice/purchase_invoice.py   | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index d0f4e96541..d7d9a3886a 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -519,8 +519,6 @@ class PurchaseInvoice(BuyingController):
 			if d.category in ('Valuation', 'Total and Valuation')
 			and flt(d.base_tax_amount_after_discount_amount)]
 
-		exchange_rate_map, net_rate_map = get_purchase_document_details(self)
-		
 		enable_discount_accounting = cint(frappe.db.get_single_value('Accounts Settings', 'enable_discount_accounting'))
 
 		for item in self.get("items"):
@@ -841,8 +839,8 @@ class PurchaseInvoice(BuyingController):
 						"account": tax.account_head,
 						"against": self.supplier,
 						dr_or_cr: base_amount,
-						dr_or_cr + "_in_account_currency": base_amount \
-							if account_currency==self.company_currency \
+						dr_or_cr + "_in_account_currency": base_amount
+							if account_currency==self.company_currency
 							else amount,
 						"cost_center": tax.cost_center
 					}, account_currency, item=tax)