Merge pull request #5109 from agusputra/patch-27

Update managing-batch-wise-inventory.md
diff --git a/erpnext/accounts/doctype/fiscal_year/fiscal_year.py b/erpnext/accounts/doctype/fiscal_year/fiscal_year.py
index 9456924..ce76354 100644
--- a/erpnext/accounts/doctype/fiscal_year/fiscal_year.py
+++ b/erpnext/accounts/doctype/fiscal_year/fiscal_year.py
@@ -21,6 +21,7 @@
 
 	def validate(self):
 		self.validate_dates()
+		self.validate_overlap()
 
 		if not self.is_new():
 			year_start_end_dates = frappe.db.sql("""select year_start_date, year_end_date
@@ -40,6 +41,37 @@
 
 	def on_update(self):
 		check_duplicate_fiscal_year(self)
+		
+	def validate_overlap(self):
+		existing_fiscal_years = frappe.db.sql("""select name from `tabFiscal Year`
+			where (
+				(%(year_start_date)s between year_start_date and year_end_date)
+				or (%(year_end_date)s between year_start_date and year_end_date)
+				or (year_start_date between %(year_start_date)s and %(year_end_date)s)
+				or (year_end_date between %(year_start_date)s and %(year_end_date)s)
+			) and name!=%(name)s""",
+			{
+				"year_start_date": self.year_start_date,
+				"year_end_date": self.year_end_date,
+				"name": self.name or "No Name"
+			}, as_dict=True)
+
+		if existing_fiscal_years:
+			for existing in existing_fiscal_years:
+				company_for_existing = frappe.db.sql_list("""select company from `tabFiscal Year Company`
+					where parent=%s""", existing.name)
+				
+				overlap = False
+				if not self.get("companies") or not company_for_existing:
+					overlap = True
+			
+				for d in self.get("companies"):
+					if d.company in company_for_existing:
+						overlap = True
+					
+				if overlap:
+					frappe.throw(_("Year start date or end date is overlapping with {0}. To avoid please set company")
+						.format(existing.name))
 
 @frappe.whitelist()
 def check_duplicate_fiscal_year(doc):
diff --git a/erpnext/accounts/party.py b/erpnext/accounts/party.py
index 9e3319c..e4cba75 100644
--- a/erpnext/accounts/party.py
+++ b/erpnext/accounts/party.py
@@ -227,10 +227,16 @@
 
 		party_account_currency = frappe.db.get_value("Account", account.account, "account_currency")
 		existing_gle_currency = get_party_gle_currency(doc.doctype, doc.name, account.company)
+		company_default_currency = frappe.db.get_value("Company",
+			frappe.db.get_default("Company"), "default_currency", cache=True)
 
 		if existing_gle_currency and party_account_currency != existing_gle_currency:
 			frappe.throw(_("Accounting entries have already been made in currency {0} for company {1}. Please select a receivable or payable account with currency {0}.").format(existing_gle_currency, account.company))
 
+		if doc.default_currency and party_account_currency and company_default_currency:
+			if doc.default_currency != party_account_currency and doc.default_currency != company_default_currency:
+				frappe.throw(_("Billing currency must be equal to either default comapany's currency or party's payble account currency"))
+
 @frappe.whitelist()
 def get_due_date(posting_date, party_type, party, company):
 	"""Set Due Date = Posting Date + Credit Days"""
diff --git a/erpnext/buying/doctype/request_for_quotation/request_for_quotation.js b/erpnext/buying/doctype/request_for_quotation/request_for_quotation.js
index 40e62f1..a072bd7 100644
--- a/erpnext/buying/doctype/request_for_quotation/request_for_quotation.js
+++ b/erpnext/buying/doctype/request_for_quotation/request_for_quotation.js
@@ -32,6 +32,7 @@
 			frm.add_custom_button(__("Send Supplier Emails"), function() {
 				frappe.call({
 					method: 'erpnext.buying.doctype.request_for_quotation.request_for_quotation.send_supplier_emails',
+					freeze: true,
 					args: {
 						rfq_name: frm.doc.name
 					}
@@ -78,6 +79,14 @@
 	}
 })
 
+frappe.ui.form.on("Request for Quotation Supplier",{
+	supplier: function(frm, cdt, cdn){
+		var d = locals[cdt][cdn]
+		frappe.model.set_value(cdt, cdn, 'contact', '')
+		frappe.model.set_value(cdt, cdn, 'email_id', '')
+	}
+})
+
 erpnext.buying.RequestforQuotationController = erpnext.buying.BuyingController.extend({
 	refresh: function() {
 		this._super();
diff --git a/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py b/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py
index 8c23f96..211fdcf 100644
--- a/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py
+++ b/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py
@@ -5,9 +5,10 @@
 from __future__ import unicode_literals
 import frappe, json
 from frappe import _
+from frappe.model.mapper import get_mapped_doc
 from frappe.utils import get_url, random_string
 from frappe.utils.user import get_user_fullname
-from frappe.model.mapper import get_mapped_doc
+from erpnext.accounts.party import get_party_account_currency, get_party_details
 from erpnext.stock.doctype.material_request.material_request import set_missing_values
 from erpnext.controllers.buying_controller import BuyingController
 
@@ -98,7 +99,6 @@
 		frappe.sendmail(recipients=data.email_id, sender=sender, subject=subject,
 			message=frappe.get_template(template).render(args),
 			attachments = [frappe.attach_print('Request for Quotation', self.name)],as_bulk=True)
-
 		frappe.msgprint(_("Email sent to supplier {0}").format(data.supplier))
 
 @frappe.whitelist()
@@ -119,6 +119,9 @@
 def make_supplier_quotation(source_name, for_supplier, target_doc=None):
 	def postprocess(source, target_doc):
 		target_doc.supplier = for_supplier
+		args = get_party_details(for_supplier, party_type="Supplier", ignore_permissions=True)
+		target_doc.currency = args.currency
+		target_doc.buying_price_list = args.buying_price_list or frappe.db.get_value('Buying Settings', None, 'buying_price_list')
 		set_missing_values(source, target_doc)
 
 	doclist = get_mapped_doc("Request for Quotation", source_name, {
@@ -146,18 +149,16 @@
 	if isinstance(doc, basestring):
 		doc = json.loads(doc)
 
-	supplier = frappe.get_doc('Supplier', doc.get('supplier'))
-
 	try:
 		sq_doc = frappe.get_doc({
 			"doctype": "Supplier Quotation",
-			"supplier": supplier.name,
+			"supplier": doc.get('supplier'),
 			"terms": doc.get("terms"),
 			"company": doc.get("company"),
-			"currency": supplier.default_currency,
-			"buying_price_list": supplier.default_price_list or frappe.db.get_value('Buying Settings', None, 'buying_price_list')
+			"currency": doc.get('currency') or get_party_account_currency('Supplier', doc.get('supplier'), doc.get('company')),
+			"buying_price_list": doc.get('buying_price_list') or frappe.db.get_value('Buying Settings', None, 'buying_price_list')
 		})
-		add_items(sq_doc, supplier, doc.get('items'))
+		add_items(sq_doc, doc.get('supplier'), doc.get('items'))
 		sq_doc.flags.ignore_permissions = True
 		sq_doc.run_method("set_missing_values")
 		sq_doc.save()
diff --git a/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py b/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py
index ea6e88d..4f205c5 100644
--- a/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py
+++ b/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py
@@ -50,8 +50,7 @@
 	rfq.transaction_date = nowdate()
 	rfq.status = 'Draft'
 	rfq.company = '_Test Company'
-	rfq.response = 'Test Data'
-	rfq.message_for_supplier = "Please supply the specified items at the best possible rates"
+	rfq.message_for_supplier = 'Please supply the specified items at the best possible rates.'
 	
 	for data in supplier_data:
 		rfq.append('suppliers', data)
@@ -77,4 +76,4 @@
 	{
 		"supplier": "_Test Supplier 1",
 		"supplier_name": "_Test Supplier 1"
-	}]
\ No newline at end of file
+	}]
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 83155f1..50d4d8a 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -4,9 +4,9 @@
 from __future__ import unicode_literals
 import frappe
 from frappe import _, throw
-from frappe.utils import today, flt, cint, fmt_money
+from frappe.utils import today, flt, cint, fmt_money, formatdate
 from erpnext.setup.utils import get_company_currency, get_exchange_rate
-from erpnext.accounts.utils import get_fiscal_year, validate_fiscal_year, get_account_currency
+from erpnext.accounts.utils import get_fiscal_years, validate_fiscal_year, get_account_currency
 from erpnext.utilities.transaction_base import TransactionBase
 from erpnext.controllers.recurring_document import convert_to_recurring, validate_recurring_document
 from erpnext.controllers.sales_and_purchase_return import validate_return
@@ -64,8 +64,6 @@
 		for fieldname in ["posting_date", "transaction_date"]:
 			if not self.get(fieldname) and self.meta.get_field(fieldname):
 				self.set(fieldname, today())
-				if self.meta.get_field("fiscal_year") and not self.fiscal_year:
-					self.fiscal_year = get_fiscal_year(self.get(fieldname))[0]
 				break
 
 	def calculate_taxes_and_totals(self):
@@ -222,10 +220,17 @@
 
 	def get_gl_dict(self, args, account_currency=None):
 		"""this method populates the common properties of a gl entry record"""
+		
+		fiscal_years = get_fiscal_years(self.posting_date, company=self.company)
+		if len(fiscal_years) > 1:
+			frappe.throw(_("Multiple fiscal years exist for the date {0}. Please set company in Fiscal Year").format(formatdate(self.posting_date)))
+		else:
+			fiscal_year = fiscal_years[0][0]
+						
 		gl_dict = frappe._dict({
 			'company': self.company,
 			'posting_date': self.posting_date,
-			'fiscal_year': get_fiscal_year(self.posting_date, company=self.company)[0],
+			'fiscal_year': fiscal_year,
 			'voucher_type': self.doctype,
 			'voucher_no': self.name,
 			'remarks': self.get("remarks"),
diff --git a/erpnext/controllers/queries.py b/erpnext/controllers/queries.py
index eb16ac5..b94b3eb 100644
--- a/erpnext/controllers/queries.py
+++ b/erpnext/controllers/queries.py
@@ -362,6 +362,6 @@
 			{condition} {match_condition}"""
 		.format(condition=condition, key=frappe.db.escape(searchfield), 
 			match_condition=get_match_cond(doctype)), {
-			'company': filters['company'], 
+			'company': filters.get("company", ""),
 			'txt': "%%%s%%" % frappe.db.escape(txt)
 		})
\ No newline at end of file
diff --git a/erpnext/controllers/website_list_for_contact.py b/erpnext/controllers/website_list_for_contact.py
index 4bf8da0..e411cdf 100644
--- a/erpnext/controllers/website_list_for_contact.py
+++ b/erpnext/controllers/website_list_for_contact.py
@@ -93,6 +93,7 @@
 	return result
 
 def get_customers_suppliers(doctype, user):
+	from erpnext.shopping_cart.cart import get_customer
 	meta = frappe.get_meta(doctype)
 	contacts = frappe.get_all("Contact", fields=["customer", "supplier", "email_id"],
 		filters={"email_id": user})
@@ -100,6 +101,9 @@
 	customers = [c.customer for c in contacts if c.customer] if meta.get_field("customer") else None
 	suppliers = [c.supplier for c in contacts if c.supplier] if meta.get_field("supplier") else None
 
+	if not customers and not suppliers:
+		return [get_customer().name], None
+
 	return customers, suppliers
 
 def has_website_permission(doc, ptype, user, verbose=False):
diff --git a/erpnext/docs/user/manual/en/stock/articles/managing-assets.md b/erpnext/docs/user/manual/en/stock/articles/managing-assets.md
index 0be7860..1e1fcf4 100644
--- a/erpnext/docs/user/manual/en/stock/articles/managing-assets.md
+++ b/erpnext/docs/user/manual/en/stock/articles/managing-assets.md
@@ -18,6 +18,6 @@
 
 Separate Warehouse should be created for the fixed asset items. All the sales, purchase and stock transactions for asset items should be done for fixed asset warehouse only.
 
-As per the perpetual inventory valuation system, accounting ledger is auto-created for a warehouse. You can move the accounting ledger of fixed asset asset from Stock Asset (default group) to Fixed Asset's group account.
+As per the perpetual inventory valuation system, accounting ledger is auto-created for a warehouse. You can move the accounting ledger of fixed asset from Stock Asset (default group) to Fixed Asset's group account.
 
-<!-- markdown -->
\ No newline at end of file
+<!-- markdown -->
diff --git a/erpnext/shopping_cart/cart.py b/erpnext/shopping_cart/cart.py
index 7d5e250..c353b8d 100644
--- a/erpnext/shopping_cart/cart.py
+++ b/erpnext/shopping_cart/cart.py
@@ -351,7 +351,7 @@
 
 def get_address_docs(doctype=None, txt=None, filters=None, limit_start=0, limit_page_length=20, party=None):
 	if not party:
-		party = get_customer()
+		return
 
 	address_docs = frappe.db.sql("""select * from `tabAddress`
 		where `{0}`=%s order by name limit {1}, {2}""".format(party.doctype.lower(),
diff --git a/erpnext/support/doctype/warranty_claim/warranty_claim.py b/erpnext/support/doctype/warranty_claim/warranty_claim.py
index 93f5245..b4427be 100644
--- a/erpnext/support/doctype/warranty_claim/warranty_claim.py
+++ b/erpnext/support/doctype/warranty_claim/warranty_claim.py
@@ -5,7 +5,7 @@
 from __future__ import unicode_literals
 import frappe
 from frappe import session, _
-from frappe.utils import today
+from frappe.utils import today, now_datetime
 
 
 
@@ -21,7 +21,7 @@
 
 		if self.status=="Closed" and \
 			frappe.db.get_value("Warranty Claim", self.name, "status")!="Closed":
-			self.resolution_date = today()
+			self.resolution_date = now_datetime()
 
 	def on_cancel(self):
 		lst = frappe.db.sql("""select t1.name
diff --git a/erpnext/templates/includes/rfq.js b/erpnext/templates/includes/rfq.js
index 3623d77..ea003d8 100644
--- a/erpnext/templates/includes/rfq.js
+++ b/erpnext/templates/includes/rfq.js
@@ -6,6 +6,9 @@
 $(document).ready(function() {
 	new rfq();
 	doc.supplier = "{{ doc.supplier }}"
+	doc.currency = "{{ doc.currency }}"
+	doc.number_format = "{{ doc.number_format }}"
+	doc.buying_price_list = "{{ doc.buying_price_list }}"
 });
 
 rfq = Class.extend({
@@ -57,11 +60,11 @@
 				data.qty = me.qty;
 				data.rate = me.rate;
 				data.amount = (me.rate * me.qty) || 0.0;
-				$(repl('.rfq-amount[data-idx=%(idx)s]',{'idx': me.idx})).text(data.amount.toFixed(2));
+				$(repl('.rfq-amount[data-idx=%(idx)s]',{'idx': me.idx})).text(format_number(data.amount, doc.number_format, 2));
 			}
 
 			doc.grand_total += flt(data.amount);
-			$('.tax-grand-total').text(doc.grand_total.toFixed(2));
+			$('.tax-grand-total').text(format_number(doc.grand_total, doc.number_format, 2));
 		})
 	},
 
diff --git a/erpnext/templates/includes/rfq/rfq_items.html b/erpnext/templates/includes/rfq/rfq_items.html
index f03fb8f..1e99a76 100644
--- a/erpnext/templates/includes/rfq/rfq_items.html
+++ b/erpnext/templates/includes/rfq/rfq_items.html
@@ -18,12 +18,12 @@
 				</p>
 		</div>
 		<div class="col-sm-2 col-xs-2 text-right">
-				<input type="number" class="form-control text-right rfq-rate"
+			{{doc.currency_symbol}}	<input type="number" class="form-control text-right rfq-rate"
 				style="margin-top: 5px; max-width: 70px;display: inline-block" value="0.00"
 				data-idx="{{ d.idx }}">
 		</div>
         <div class="col-sm-2 col-xs-2 text-right" style="padding-top: 9px;">
-            <span class="rfq-amount" data-idx="{{ d.idx }}">0.00</span>
+           {{doc.currency_symbol}} <span class="rfq-amount" data-idx="{{ d.idx }}">0.00</span>
         </div>
 		</div>
 	</div>
diff --git a/erpnext/templates/pages/rfq.html b/erpnext/templates/pages/rfq.html
index 8009819..dfbbbc9 100644
--- a/erpnext/templates/pages/rfq.html
+++ b/erpnext/templates/pages/rfq.html
@@ -64,7 +64,7 @@
 		<div class="row grand-total-row">
 			<div class="col-xs-10 text-right">{{ _("Grand Total") }}</div>
 			<div class="col-xs-2 text-right">
-				<span class="tax-grand-total">0.0</span>
+			{{doc.currency_symbol}}	<span class="tax-grand-total">0.0</span>
 			</div>
 		</div>
         {% endif %}
diff --git a/erpnext/templates/pages/rfq.py b/erpnext/templates/pages/rfq.py
index aefa315..181cf73 100644
--- a/erpnext/templates/pages/rfq.py
+++ b/erpnext/templates/pages/rfq.py
@@ -4,24 +4,24 @@
 from __future__ import unicode_literals
 import frappe
 from frappe import _
+from erpnext.controllers.website_list_for_contact import get_customers_suppliers, \
+					get_party_details
 
 def get_context(context):
 	context.no_cache = 1
 	context.doc = frappe.get_doc(frappe.form_dict.doctype, frappe.form_dict.name)
 	context.parents = frappe.form_dict.parents
 	context.doc.supplier = get_supplier()
-	unauthrized_user(context.doc.supplier)
+	update_supplier_details(context)
+	unauthorized_user(context.doc.supplier)
 	context["title"] = frappe.form_dict.name
 
-def unauthrized_user(supplier):
-	status = check_supplier_has_docname_access(supplier)
-	if status == False:
-		frappe.throw(_("Not Permitted"), frappe.PermissionError)
-
 def get_supplier():
-	from erpnext.shopping_cart.utils import check_customer_or_supplier
-	key, parties = check_customer_or_supplier()
-	return parties[0] if key == 'Supplier' else ''
+	doctype = frappe.form_dict.doctype
+	parties_doctype = 'Request for Quotation Supplier' if doctype == 'Request for Quotation' else doctype
+	customers, suppliers = get_customers_suppliers(parties_doctype, frappe.session.user)
+	key, parties = get_party_details(customers, suppliers)
+	return parties[0] if key == 'supplier' else ''
 
 def check_supplier_has_docname_access(supplier):
 	status = True
@@ -29,3 +29,15 @@
 		where supplier = '{supplier}'""".format(supplier=supplier)):
 		status = False
 	return status
+
+def unauthorized_user(supplier):
+	status = check_supplier_has_docname_access(supplier)
+	if status == False:
+		frappe.throw(_("Not Permitted"), frappe.PermissionError)
+
+def update_supplier_details(context):
+	supplier_doc = frappe.get_doc("Supplier", context.doc.supplier)
+	context.doc.currency = supplier_doc.default_currency
+	context.doc.currency_symbol = frappe.db.get_value("Currency", context.doc.currency, "symbol")
+	context.doc.number_format = frappe.db.get_value("Currency", context.doc.currency, "number_format")
+	context.doc.buying_price_list = supplier_doc.default_price_list
\ No newline at end of file