Pricing Rule fixes and reference field in all item table
diff --git a/erpnext/accounts/doctype/pricing_rule/pricing_rule.py b/erpnext/accounts/doctype/pricing_rule/pricing_rule.py
index 6a2a6ef..271dadc 100644
--- a/erpnext/accounts/doctype/pricing_rule/pricing_rule.py
+++ b/erpnext/accounts/doctype/pricing_rule/pricing_rule.py
@@ -23,8 +23,9 @@
 					frappe.MandatoryError)
 		
 	def cleanup_fields_value(self):
-		fields = ["item_code", "item_group", "brand", "customer", "customer_group", "territory", 
-			"supplier", "supplier_type", "campaign", "sales_partner", "price", "discount"]
+		fields = ["item_code", "item_group", "brand", "customer", "customer_group", 
+			"territory", "supplier", "supplier_type", "campaign", "sales_partner", 
+			"price", "discount_percentage"]
 			
 		for field_with_value in ["apply_on", "applicable_for", "price_or_discount"]:
 			val = self.doc.fields.get(field_with_value)
diff --git a/erpnext/accounts/doctype/pricing_rule/pricing_rule.txt b/erpnext/accounts/doctype/pricing_rule/pricing_rule.txt
index bf8e892..126d11c 100644
--- a/erpnext/accounts/doctype/pricing_rule/pricing_rule.txt
+++ b/erpnext/accounts/doctype/pricing_rule/pricing_rule.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2014-02-21 15:02:51", 
   "docstatus": 0, 
-  "modified": "2014-02-25 13:59:13", 
+  "modified": "2014-02-27 18:08:42", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -44,6 +44,85 @@
   "label": "Basic Section"
  }, 
  {
+  "default": "Today", 
+  "doctype": "DocField", 
+  "fieldname": "valid_from", 
+  "fieldtype": "Date", 
+  "label": "Valid From"
+ }, 
+ {
+  "doctype": "DocField", 
+  "fieldname": "valid_upto", 
+  "fieldtype": "Date", 
+  "label": "Valid Upto"
+ }, 
+ {
+  "doctype": "DocField", 
+  "fieldname": "col_break1", 
+  "fieldtype": "Column Break"
+ }, 
+ {
+  "doctype": "DocField", 
+  "fieldname": "priority", 
+  "fieldtype": "Select", 
+  "label": "Priority", 
+  "options": "\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20"
+ }, 
+ {
+  "doctype": "DocField", 
+  "fieldname": "disable", 
+  "fieldtype": "Check", 
+  "label": "Disable"
+ }, 
+ {
+  "doctype": "DocField", 
+  "fieldname": "price_discount_section", 
+  "fieldtype": "Section Break", 
+  "label": "Price / Discount"
+ }, 
+ {
+  "default": "Discount Percentage", 
+  "doctype": "DocField", 
+  "fieldname": "price_or_discount", 
+  "fieldtype": "Select", 
+  "label": "Price or Discount", 
+  "options": "\nPrice\nDiscount Percentage", 
+  "reqd": 1
+ }, 
+ {
+  "doctype": "DocField", 
+  "fieldname": "col_break2", 
+  "fieldtype": "Column Break"
+ }, 
+ {
+  "depends_on": "eval:doc.price_or_discount==\"Price\"", 
+  "doctype": "DocField", 
+  "fieldname": "price", 
+  "fieldtype": "Float", 
+  "label": "Price"
+ }, 
+ {
+  "depends_on": "eval:doc.price_or_discount==\"Discount Percentage\"", 
+  "doctype": "DocField", 
+  "fieldname": "discount_percentage", 
+  "fieldtype": "Float", 
+  "label": "Discount Percentage"
+ }, 
+ {
+  "depends_on": "eval:doc.price_or_discount==\"Discount Percentage\"", 
+  "doctype": "DocField", 
+  "fieldname": "for_price_list", 
+  "fieldtype": "Link", 
+  "label": "For Price List", 
+  "options": "Price List"
+ }, 
+ {
+  "doctype": "DocField", 
+  "fieldname": "applicability_section", 
+  "fieldtype": "Section Break", 
+  "label": "Applicability"
+ }, 
+ {
   "default": "Item Code", 
   "doctype": "DocField", 
   "fieldname": "apply_on", 
@@ -79,94 +158,15 @@
  }, 
  {
   "doctype": "DocField", 
-  "fieldname": "priority", 
-  "fieldtype": "Select", 
-  "label": "Priority", 
-  "options": "\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20"
- }, 
- {
-  "doctype": "DocField", 
-  "fieldname": "col_break1", 
+  "fieldname": "col_break3", 
   "fieldtype": "Column Break"
  }, 
  {
-  "default": "Today", 
-  "doctype": "DocField", 
-  "fieldname": "valid_from", 
-  "fieldtype": "Date", 
-  "label": "Valid From"
- }, 
- {
-  "doctype": "DocField", 
-  "fieldname": "valid_upto", 
-  "fieldtype": "Date", 
-  "label": "Valid Upto"
- }, 
- {
-  "doctype": "DocField", 
-  "fieldname": "disable", 
-  "fieldtype": "Check", 
-  "label": "Disable"
- }, 
- {
-  "doctype": "DocField", 
-  "fieldname": "price_discount_section", 
-  "fieldtype": "Section Break", 
-  "label": "Price / Discount"
- }, 
- {
-  "default": "Discount", 
-  "doctype": "DocField", 
-  "fieldname": "price_or_discount", 
-  "fieldtype": "Select", 
-  "label": "Price or Discount", 
-  "options": "\nPrice\nDiscount", 
-  "reqd": 1
- }, 
- {
-  "doctype": "DocField", 
-  "fieldname": "col_break2", 
-  "fieldtype": "Column Break"
- }, 
- {
-  "depends_on": "eval:doc.price_or_discount==\"Price\"", 
-  "doctype": "DocField", 
-  "fieldname": "price", 
-  "fieldtype": "Float", 
-  "label": "Price"
- }, 
- {
-  "depends_on": "eval:doc.price_or_discount==\"Discount\"", 
-  "doctype": "DocField", 
-  "fieldname": "discount", 
-  "fieldtype": "Float", 
-  "label": "Discount"
- }, 
- {
-  "depends_on": "eval:doc.price_or_discount==\"Discount\"", 
-  "doctype": "DocField", 
-  "fieldname": "for_price_list", 
-  "fieldtype": "Link", 
-  "label": "For Price List", 
-  "options": "Price List"
- }, 
- {
-  "doctype": "DocField", 
-  "fieldname": "applicability_section", 
-  "fieldtype": "Section Break", 
-  "label": "Applicability"
- }, 
- {
   "doctype": "DocField", 
   "fieldname": "applicable_for", 
   "fieldtype": "Select", 
   "label": "Applicable For", 
-  "options": "\nCustomer\nCustomer Group\nTerritory\nSales Person\nSales Partner\nCampaign\nSupplier\nSupplier Type"
- }, 
- {
-  "doctype": "DocField", 
-  "fieldname": "col_break3", 
-  "fieldtype": "Column Break"
+  "options": "\nCustomer\nCustomer Group\nTerritory\nSales Partner\nCampaign\nSupplier\nSupplier Type"
  }, 
  {
   "depends_on": "eval:doc.applicable_for==\"Customer\"", 
@@ -226,23 +226,12 @@
  }, 
  {
   "doctype": "DocField", 
-  "fieldname": "qty_section", 
-  "fieldtype": "Section Break", 
-  "label": "Based on Qty"
- }, 
- {
-  "doctype": "DocField", 
   "fieldname": "min_qty", 
   "fieldtype": "Float", 
   "label": "Min Qty"
  }, 
  {
   "doctype": "DocField", 
-  "fieldname": "col_break4", 
-  "fieldtype": "Column Break"
- }, 
- {
-  "doctype": "DocField", 
   "fieldname": "max_qty", 
   "fieldtype": "Float", 
   "label": "Max Qty"
diff --git a/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py b/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py
index 0f18eaf..f71ea13 100644
--- a/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py
+++ b/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py
@@ -29,39 +29,45 @@
 		self.assertEquals(details.get("discount_percentage"), 10)
 		
 		prule = frappe.bean(copy=test_records[0])
-		prule.doc.apply_on = "Item Group"
-		prule.doc.item_group = "_Test Item Group"
-		prule.doc.discount = 15
-		prule.insert()
-		
-		details = get_item_details(args)
-		self.assertEquals(details.get("discount_percentage"), 10)
-		
-		prule = frappe.bean(copy=test_records[0])
 		prule.doc.applicable_for = "Customer"
 		self.assertRaises(MandatoryError, prule.insert)
 		prule.doc.customer = "_Test Customer"
-		prule.doc.discount = 20
+		prule.doc.discount_percentage = 20
 		prule.insert()
 		details = get_item_details(args)
 		self.assertEquals(details.get("discount_percentage"), 20)
 		
 		prule = frappe.bean(copy=test_records[0])
+		prule.doc.apply_on = "Item Group"
+		prule.doc.item_group = "_Test Item Group"
+		prule.doc.discount_percentage = 15
+		prule.insert()
+		
+		args.customer = None
+		details = get_item_details(args)
+		self.assertEquals(details.get("discount_percentage"), 10)
+		
+
+		
+		prule = frappe.bean(copy=test_records[0])
 		prule.doc.applicable_for = "Campaign"
 		prule.doc.campaign = "_Test Campaign"
-		prule.doc.discount = 30
+		prule.doc.discount_percentage = 5
+		prule.doc.priority = 8
 		prule.insert()
+		
 		args.campaign = "_Test Campaign"
 		details = get_item_details(args)
-		self.assertEquals(details.get("discount_percentage"), 30)
+		self.assertEquals(details.get("discount_percentage"), 5)
+		
+		frappe.db.sql("update `tabPricing Rule` set priority=NULL where campaign='_Test Campaign'")
+		details = get_item_details(args)
+		self.assertEquals(details.get("discount_percentage"), 15)
 		
 		args.item_code = "_Test Item 2"
 		details = get_item_details(args)
 		self.assertEquals(details.get("discount_percentage"), 15)
-		
-		args.customer = None
-		details = get_item_details(args)
-		self.assertEquals(details.get("discount_percentage"), 15)
+
 		
 		
 		
@@ -71,9 +77,8 @@
 		"doctype": "Pricing Rule", 
 		"apply_on": "Item Code", 
 		"item_code": "_Test Item", 
-		"price_or_discount": "Discount", 
+		"price_or_discount": "Discount Percentage", 
 		"price": 0, 
-		"discount": 10, 
+		"discount_percentage": 10, 
 	}],
-
 ]
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/purchase_invoice_item/purchase_invoice_item.txt b/erpnext/accounts/doctype/purchase_invoice_item/purchase_invoice_item.txt
index 5bb3f5a..b3562b3 100755
--- a/erpnext/accounts/doctype/purchase_invoice_item/purchase_invoice_item.txt
+++ b/erpnext/accounts/doctype/purchase_invoice_item/purchase_invoice_item.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-05-22 12:43:10", 
   "docstatus": 0, 
-  "modified": "2014-02-10 17:29:13", 
+  "modified": "2014-02-28 11:27:53", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -215,6 +215,22 @@
  }, 
  {
   "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_price", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Price", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_discount", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Discount", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
   "fieldname": "accounting", 
   "fieldtype": "Section Break", 
   "in_list_view": 0, 
diff --git a/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.txt b/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.txt
index a6b6c6e..224f7b7 100644
--- a/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.txt
+++ b/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-06-04 11:02:19", 
   "docstatus": 0, 
-  "modified": "2014-02-10 17:28:47", 
+  "modified": "2014-02-28 11:04:19", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -223,6 +223,22 @@
  }, 
  {
   "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_price", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Price", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_discount", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Discount", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
   "fieldname": "accounting", 
   "fieldtype": "Section Break", 
   "in_list_view": 0, 
diff --git a/erpnext/buying/doctype/purchase_order_item/purchase_order_item.txt b/erpnext/buying/doctype/purchase_order_item/purchase_order_item.txt
index 334c74b..192b206 100755
--- a/erpnext/buying/doctype/purchase_order_item/purchase_order_item.txt
+++ b/erpnext/buying/doctype/purchase_order_item/purchase_order_item.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-05-24 19:29:06", 
   "docstatus": 0, 
-  "modified": "2014-02-10 17:29:01", 
+  "modified": "2014-02-28 11:26:25", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -274,6 +274,22 @@
  }, 
  {
   "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_price", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Price", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_discount", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Discount", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
   "fieldname": "warehouse_and_reference", 
   "fieldtype": "Section Break", 
   "in_list_view": 0, 
diff --git a/erpnext/buying/doctype/supplier_quotation_item/supplier_quotation_item.txt b/erpnext/buying/doctype/supplier_quotation_item/supplier_quotation_item.txt
index 30666bb..18b9216 100644
--- a/erpnext/buying/doctype/supplier_quotation_item/supplier_quotation_item.txt
+++ b/erpnext/buying/doctype/supplier_quotation_item/supplier_quotation_item.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-05-22 12:43:10", 
   "docstatus": 0, 
-  "modified": "2014-02-10 17:28:54", 
+  "modified": "2014-02-28 11:25:38", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -217,6 +217,22 @@
  }, 
  {
   "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_price", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Price", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_discount", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Discount", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
   "fieldname": "warehouse_and_reference", 
   "fieldtype": "Section Break", 
   "in_list_view": 0, 
diff --git a/erpnext/selling/doctype/quotation_item/quotation_item.txt b/erpnext/selling/doctype/quotation_item/quotation_item.txt
index 735e539..bbf953a 100644
--- a/erpnext/selling/doctype/quotation_item/quotation_item.txt
+++ b/erpnext/selling/doctype/quotation_item/quotation_item.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-03-07 11:42:57", 
   "docstatus": 0, 
-  "modified": "2014-02-10 17:28:02", 
+  "modified": "2014-02-28 11:20:34", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -253,6 +253,22 @@
  }, 
  {
   "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_price", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Price", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_discount", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Discount", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
   "fieldname": "reference", 
   "fieldtype": "Section Break", 
   "in_list_view": 0, 
diff --git a/erpnext/selling/doctype/sales_order_item/sales_order_item.txt b/erpnext/selling/doctype/sales_order_item/sales_order_item.txt
index b57ba99..7e471e4 100644
--- a/erpnext/selling/doctype/sales_order_item/sales_order_item.txt
+++ b/erpnext/selling/doctype/sales_order_item/sales_order_item.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-03-07 11:42:58", 
   "docstatus": 0, 
-  "modified": "2014-02-10 17:28:08", 
+  "modified": "2014-02-28 11:20:05", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -239,6 +239,22 @@
  }, 
  {
   "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_price", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Price", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_discount", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Discount", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
   "fieldname": "warehouse_and_reference", 
   "fieldtype": "Section Break", 
   "in_list_view": 0, 
diff --git a/erpnext/stock/doctype/delivery_note_item/delivery_note_item.txt b/erpnext/stock/doctype/delivery_note_item/delivery_note_item.txt
index 5d04992..f5f7712 100644
--- a/erpnext/stock/doctype/delivery_note_item/delivery_note_item.txt
+++ b/erpnext/stock/doctype/delivery_note_item/delivery_note_item.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-04-22 13:15:44", 
   "docstatus": 0, 
-  "modified": "2014-02-10 17:28:16", 
+  "modified": "2014-02-28 11:20:58", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -247,6 +247,22 @@
  }, 
  {
   "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_price", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Price", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_discount", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Discount", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
   "fieldname": "warehouse_and_reference", 
   "fieldtype": "Section Break", 
   "in_list_view": 0, 
diff --git a/erpnext/stock/doctype/purchase_receipt_item/purchase_receipt_item.txt b/erpnext/stock/doctype/purchase_receipt_item/purchase_receipt_item.txt
index efc5a17..cde7911 100755
--- a/erpnext/stock/doctype/purchase_receipt_item/purchase_receipt_item.txt
+++ b/erpnext/stock/doctype/purchase_receipt_item/purchase_receipt_item.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-05-24 19:29:10", 
   "docstatus": 0, 
-  "modified": "2014-02-10 17:29:07", 
+  "modified": "2014-02-28 11:27:09", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -278,6 +278,22 @@
  }, 
  {
   "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_price", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Price", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
+  "fieldname": "pricing_rule_for_discount", 
+  "fieldtype": "Link", 
+  "label": "Pricing Rule For Discount", 
+  "options": "Pricing Rule", 
+  "read_only": 1
+ }, 
+ {
+  "doctype": "DocField", 
   "fieldname": "warehouse_and_reference", 
   "fieldtype": "Section Break", 
   "in_list_view": 0, 
diff --git a/erpnext/stock/get_item_details.py b/erpnext/stock/get_item_details.py
index 411435e..c5bce47 100644
--- a/erpnext/stock/get_item_details.py
+++ b/erpnext/stock/get_item_details.py
@@ -100,16 +100,16 @@
 		if args.get("order_type") == "Maintenance":
 			if item.is_service_item != "Yes":
 				throw(_("Item") + (" %s: " % item.name) + 
-					_("not a service item.") +
+					_("is not a service item.") +
 					_("Please select a service item or change the order type to Sales."))
 		
 		elif item.is_sales_item != "Yes":
-			throw(_("Item") + (" %s: " % item.name) + _("not a sales item"))
+			throw(_("Item") + (" %s: " % item.name) + _("is not a sales item"))
 
 	elif args.transaction_type == "buying":
 		# validate if purchase item or subcontracted item
 		if item.is_purchase_item != "Yes":
-			throw(_("Item") + (" %s: " % item.name) + _("not a purchase item"))
+			throw(_("Item") + (" %s: " % item.name) + _("is not a purchase item"))
 	
 		if args.get("is_subcontracted") == "Yes" and item.is_sub_contracted_item != "Yes":
 			throw(_("Item") + (" %s: " % item.name) + 
@@ -265,57 +265,21 @@
 def apply_pricing_rule(out, args):
 	args_dict = frappe._dict().update(args)
 	args_dict.update(out)
-	pricing_rules = get_pricing_rules(args_dict)
-	for rule_for in ["price", "discount"]:
-		pricing_rules = filter(lambda x: x[rule_for] > 0, pricing_rules)
-		pricing_rules = filter_pricing_rules(args_dict, pricing_rules)
-		
-		if len(pricing_rules) > 1:
-			pricing_rules = sorted(pricing_rules, key=lambda x: x[rule_for])
+	all_pricing_rules = get_pricing_rules(args_dict)
+
+	for rule_for in ["price", "discount_percentage"]:
+		pricing_rules = filter(lambda x: x[rule_for] > 0.0, all_pricing_rules)
+		pricing_rules = filter_pricing_rules(args_dict, pricing_rules, rule_for)
+
 		if pricing_rules:
-			if rule_for == "discount":
-				out["discount_percentage"] = pricing_rules[-1]["discount"]
+			if rule_for == "discount_percentage":
+				out["discount_percentage"] = pricing_rules[-1]["discount_percentage"]
+				out["pricing_rule_for_discount"] = pricing_rules[-1]["name"]
 			else:
 				out["base_price_list_rate"] = pricing_rules[0]["price"]
 				out["price_list_rate"] = pricing_rules[0]["price"] * \
 					flt(args_dict.plc_conversion_rate) / flt(args_dict.conversion_rate)
-	
-	
-def filter_pricing_rules(args_dict, pricing_rules):	
-	def _filter_pricing_rules(pricing_rules, field_set):
-		p_rules = []
-		for field in field_set:
-			if not p_rules:
-				for p_rule in pricing_rules:
-					if p_rule[field] == args_dict.get(field):
-						p_rules.append(p_rule)
-			else:
-				break
-		
-		return p_rules or pricing_rules
-
-	for field_set in [["item_code", "item_group", "brand"], ["customer", "customer_group", 
-		"territory", "supplier", "supplier_type", "campaign", "sales_partner"]]:
-			if pricing_rules:
-				pricing_rules = _filter_pricing_rules(pricing_rules, field_set)
-
-	# filter for price list
-	if pricing_rules:
-		pricing_rules = filter(lambda x: (not x.for_price_list or 
-			x.for_price_list==args_dict.price_list), pricing_rules)
-			
-	# filter for qty
-	if pricing_rules and args_dict.get("qty"):
-		pricing_rules = filter(lambda x: (args_dict.qty>=flt(x.min_qty) 
-			and (args_dict.qty<=x.max_qty if x.max_qty else True)), pricing_rules)
-			
-	# find pricing rule with highest priority
-	if pricing_rules:
-		max_priority = min([cint(p.priority) for p in pricing_rules])
-		if max_priority:
-			pricing_rules = filter(lambda x: x.priority==max_priority, pricing_rules)
-
-	return pricing_rules
+				out["pricing_rule_for_price"] = pricing_rules[-1]["name"]
 	
 def get_pricing_rules(args_dict):	
 	conditions = ""
@@ -323,17 +287,68 @@
 		"campaign", "sales_partner"]:
 			if args_dict.get(field):
 				conditions += " and ifnull("+field+", '') in (%("+field+")s, '')"
-				
+			else:
+				conditions += " and ifnull("+field+", '') = ''"
+	
+	conditions += " and ifnull(for_price_list, '') in (%(price_list)s, '')"
+	
 	if args_dict.get("transaction_date"):
 		conditions += """ and %(transaction_date)s between ifnull(valid_from, '2000-01-01') 
 			and ifnull(valid_upto, '2500-12-31')"""
 	
-	return frappe.conn.sql("""select * from `tabPricing Rule` 
+	return frappe.db.sql("""select * from `tabPricing Rule` 
 		where (item_code=%(item_code)s or item_group=%(item_group)s or brand=%(brand)s) 
 			and docstatus < 2 and ifnull(disable, 0) = 0 {0}
 		order by priority desc, name desc""".format(conditions), args_dict, as_dict=1)
-		
+
+def filter_pricing_rules(args_dict, pricing_rules, price_or_discount):
+	# filter for qty
+	if pricing_rules and args_dict.get("qty"):
+		pricing_rules = filter(lambda x: (args_dict.qty>=flt(x.min_qty) 
+			and (args_dict.qty<=x.max_qty if x.max_qty else True)), pricing_rules)
+ 
+	# find pricing rule with highest priority
+	if pricing_rules:
+		max_priority = max([cint(p.priority) for p in pricing_rules])
+		if max_priority:
+			pricing_rules = filter(lambda x: cint(x.priority)==max_priority, pricing_rules)
+			
+	# apply internal priority
+	all_fields = ["item_code", "item_group", "brand", "customer", "customer_group", "territory", 
+		"supplier", "supplier_type", "campaign", "for_price_list", "sales_partner"]
 	
+	if len(pricing_rules) > 1:
+		for field_set in [["item_code", "item_group", "brand"], 
+			["customer", "customer_group", "territory"], ["supplier", "supplier_type"]]:
+				remaining_fields = list(set(all_fields) - set(field_set))
+				if if_all_rules_same(pricing_rules, remaining_fields):
+					pricing_rules = apply_internal_priority(pricing_rules, field_set, args_dict)
+					break
+
+		if len(pricing_rules) > 1:
+			pricing_rules = sorted(pricing_rules, key=lambda x: x[price_or_discount])
+	
+	return pricing_rules
+
+def if_all_rules_same(pricing_rules, fields):
+	all_rules_same = True
+	val = [pricing_rules[0][k] for k in fields]
+	for p in pricing_rules[1:]:
+		if val != [p[k] for k in fields]:
+			all_rules_same = False
+			break
+	
+	return all_rules_same
+
+def apply_internal_priority(pricing_rules, field_set, args_dict):
+	filtered_rules = []
+	for field in field_set:
+		if args_dict.get(field):
+			filtered_rules = filter(lambda x: x[field]==args_dict[field], pricing_rules)
+			if filtered_rules: break
+
+	return filtered_rules or pricing_rules
+
 def get_serial_nos_by_fifo(args, item_bean):
 	return "\n".join(frappe.db.sql_list("""select name from `tabSerial No` 
 		where item_code=%(item_code)s and warehouse=%(warehouse)s and status='Available' 
@@ -342,17 +357,17 @@
 			"warehouse": args.warehouse,
 			"qty": cint(args.qty)
 		}))
-		
+
 @frappe.whitelist()
 def get_conversion_factor(item_code, uom):
 	return {"conversion_factor": frappe.db.get_value("UOM Conversion Detail",
 		{"parent": item_code, "uom": uom}, "conversion_factor")}
-		
+
 @frappe.whitelist()
 def get_projected_qty(item_code, warehouse):
 	return {"projected_qty": frappe.db.get_value("Bin", 
 		{"item_code": item_code, "warehouse": warehouse}, "projected_qty")}
-		
+
 @frappe.whitelist()
 def get_available_qty(item_code, warehouse):
 	return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},