Merge branch 'version-12-hotfix' into version-12
diff --git a/.travis.yml b/.travis.yml
index a8a0d82..40afeee 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,51 +1,80 @@
-language: python
 dist: trusty
 
-python:
-  - "2.7"
-  - "3.6"
+language: python
 
-env:
-  - TEST_TYPE="Server Side Test"
-  - TEST_TYPE="Patch Test"
+git:
+  depth: 1
 
-services:
-  - mysql
+cache:
+  - pip
+
+addons:
+  hosts: test_site
+  mariadb: 10.3
+
+jobs:
+  include:
+  - name: "Python 2.7 Server Side Test"
+    python: 2.7
+    script: bench --site test_site run-tests --app erpnext --coverage
+
+  - name: "Python 3.6 Server Side Test"
+    python: 3.6
+    script: bench --site test_site run-tests --app erpnext --coverage
+
+  - name: "Python 2.7 Patch Test"
+    python: 2.7
+    before_script:
+      - wget http://build.erpnext.com/20171108_190013_955977f8_database.sql.gz
+      - bench --site test_site --force restore ~/frappe-bench/20171108_190013_955977f8_database.sql.gz
+    script: bench --site test_site migrate
+
+  - name: "Python 3.6 Patch Test"
+    python: 3.6
+    before_script:
+      - wget http://build.erpnext.com/20171108_190013_955977f8_database.sql.gz
+      - bench --site test_site --force restore ~/frappe-bench/20171108_190013_955977f8_database.sql.gz
+    script: bench --site test_site migrate
 
 install:
-  # fix mongodb travis error
-  - sudo rm /etc/apt/sources.list.d/mongodb*.list
-  - pip install flake8==3.3.0
-  - flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics
-  - sudo rm /etc/apt/sources.list.d/docker.list
-  - sudo apt-get install hhvm && rm -rf /home/travis/.kiex/
-  - sudo apt-get purge -y mysql-common mysql-server mysql-client
+  - cd ~
   - nvm install 10
-  - pip install python-coveralls
-  - wget https://raw.githubusercontent.com/frappe/bench/master/playbooks/install.py
-  - sudo python install.py --develop --user travis --without-bench-setup
-  - sudo pip install -e ~/bench
 
-  - rm $TRAVIS_BUILD_DIR/.git/shallow
-  - bash $TRAVIS_BUILD_DIR/travis/bench_init.sh
-  - cp -r $TRAVIS_BUILD_DIR/test_sites/test_site ~/frappe-bench/sites/
+  - git clone https://github.com/frappe/bench --depth 1
+  - pip install -e ./bench
 
-before_script:
-  - mysql -u root -ptravis -e 'create database test_frappe'
-  - echo "USE mysql;\nCREATE USER 'test_frappe'@'localhost' IDENTIFIED BY 'test_frappe';\nFLUSH PRIVILEGES;\n" | mysql -u root -ptravis
-  - echo "USE mysql;\nGRANT ALL PRIVILEGES ON \`test_frappe\`.* TO 'test_frappe'@'localhost';\n" | mysql -u root -ptravis
+  - git clone https://github.com/frappe/frappe --branch $TRAVIS_BRANCH --depth 1
+  - bench init --skip-assets --frappe-path ~/frappe --python $(which python) frappe-bench
+
+  - mkdir ~/frappe-bench/sites/test_site
+  - cp -r $TRAVIS_BUILD_DIR/.travis/site_config.json ~/frappe-bench/sites/test_site/
+
+  - mysql -u root -e "SET GLOBAL character_set_server = 'utf8mb4'"
+  - mysql -u root -e "SET GLOBAL collation_server = 'utf8mb4_unicode_ci'"
+
+  - mysql -u root -e "CREATE DATABASE test_frappe"
+  - mysql -u root -e "CREATE USER 'test_frappe'@'localhost' IDENTIFIED BY 'test_frappe'"
+  - mysql -u root -e "GRANT ALL PRIVILEGES ON \`test_frappe\`.* TO 'test_frappe'@'localhost'"
+
+  - mysql -u root -e "UPDATE mysql.user SET Password=PASSWORD('travis') WHERE User='root'"
+  - mysql -u root -e "FLUSH PRIVILEGES"
+
+  - wget -O /tmp/wkhtmltox.tar.xz https://github.com/frappe/wkhtmltopdf/raw/master/wkhtmltox-0.12.3_linux-generic-amd64.tar.xz
+  - tar -xf /tmp/wkhtmltox.tar.xz -C /tmp
+  - sudo mv /tmp/wkhtmltox/bin/wkhtmltopdf /usr/local/bin/wkhtmltopdf
+  - sudo chmod o+x /usr/local/bin/wkhtmltopdf
 
   - cd ~/frappe-bench
-  - bench get-app erpnext $TRAVIS_BUILD_DIR
-  - bench use test_site
-  - bench reinstall --mariadb-root-username root --mariadb-root-password travis --yes
-  - bench scheduler disable
-  - sed -i 's/9000/9001/g' sites/common_site_config.json
-  - bench start &
-  - sleep 10
 
-script:
-  - bash $TRAVIS_BUILD_DIR/travis/run-tests.sh
+  - sed -i 's/watch:/# watch:/g' Procfile
+  - sed -i 's/schedule:/# schedule:/g' Procfile
+  - sed -i 's/socketio:/# socketio:/g' Procfile
+  - sed -i 's/redis_socketio:/# redis_socketio:/g' Procfile
+
+  - bench get-app erpnext $TRAVIS_BUILD_DIR
+  - bench start &
+  - bench --site test_site reinstall --yes
 
 after_script:
+  - pip install python-coveralls
   - coveralls -b apps/erpnext -d ../../sites/.coverage
diff --git a/test_sites/test_site/site_config.json b/.travis/site_config.json
similarity index 80%
rename from test_sites/test_site/site_config.json
rename to .travis/site_config.json
index 7a4d106..dae8009 100644
--- a/test_sites/test_site/site_config.json
+++ b/.travis/site_config.json
@@ -6,8 +6,8 @@
  "mail_login": "test@example.com",
  "mail_password": "test",
  "admin_password": "admin",
- "run_selenium_tests": 1,
+ "root_login": "root",
  "root_password": "travis",
- "host_name": "http://localhost:8000",
+ "host_name": "http://test_site:8000",
  "install_apps": ["erpnext"]
 }
\ No newline at end of file
diff --git a/erpnext/__init__.py b/erpnext/__init__.py
index a9348c1..04f741e 100644
--- a/erpnext/__init__.py
+++ b/erpnext/__init__.py
@@ -5,7 +5,7 @@
 from erpnext.hooks import regional_overrides
 from frappe.utils import getdate
 
-__version__ = '12.0.1'
+__version__ = '12.0.2'
 
 def get_default_company(user=None):
 	'''Get default company for user'''
diff --git a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
index b4d584f..6deee38 100644
--- a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
@@ -20,11 +20,13 @@
 test_ignore = ["Serial No"]
 
 class TestPurchaseInvoice(unittest.TestCase):
-	def setUp(self):
+	@classmethod
+	def setUpClass(self):
 		unlink_payment_on_cancel_of_invoice()
 		frappe.db.set_value("Buying Settings", None, "allow_multiple_items", 1)
 
-	def tearDown(self):
+	@classmethod
+	def tearDownClass(self):
 		unlink_payment_on_cancel_of_invoice(0)
 
 	def test_gl_entries_without_perpetual_inventory(self):
@@ -91,6 +93,7 @@
 		pi_doc = frappe.get_doc('Purchase Invoice', pi_doc.name)
 
 		self.assertRaises(frappe.LinkExistsError, pi_doc.cancel)
+		unlink_payment_on_cancel_of_invoice()
 
 	def test_purchase_invoice_for_blocked_supplier(self):
 		supplier = frappe.get_doc('Supplier', '_Test Supplier')
diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index 52470fd..dff5594 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -29,10 +29,12 @@
 		w.submit()
 		return w
 
-	def setUp(self):
+	@classmethod
+	def setUpClass(self):
 		unlink_payment_on_cancel_of_invoice()
 
-	def tearDown(self):
+	@classmethod
+	def tearDownClass(self):
 		unlink_payment_on_cancel_of_invoice(0)
 
 	def test_timestamp_change(self):
@@ -135,6 +137,7 @@
 		unlink_payment_on_cancel_of_invoice(0)
 		si = frappe.get_doc('Sales Invoice', si.name)
 		self.assertRaises(frappe.LinkExistsError, si.cancel)
+		unlink_payment_on_cancel_of_invoice()
 
 	def test_sales_invoice_calculation_export_currency(self):
 		si = frappe.copy_doc(test_records[2])
diff --git a/erpnext/assets/doctype/asset/asset.js b/erpnext/assets/doctype/asset/asset.js
index 2d78d26..c5cad73 100644
--- a/erpnext/assets/doctype/asset/asset.js
+++ b/erpnext/assets/doctype/asset/asset.js
@@ -303,14 +303,17 @@
 	},
 
 	set_depreciation_rate: function(frm, row) {
-		if (row.total_number_of_depreciations && row.frequency_of_depreciation) {
+		if (row.total_number_of_depreciations && row.frequency_of_depreciation
+			&& row.expected_value_after_useful_life) {
 			frappe.call({
 				method: "get_depreciation_rate",
 				doc: frm.doc,
 				args: row,
 				callback: function(r) {
 					if (r.message) {
-						frappe.model.set_value(row.doctype, row.name, "rate_of_depreciation", r.message);
+						frappe.flags.dont_change_rate = true;
+						frappe.model.set_value(row.doctype, row.name,
+							"rate_of_depreciation", flt(r.message, precision("rate_of_depreciation", row)));
 					}
 				}
 			});
@@ -338,6 +341,14 @@
 	total_number_of_depreciations: function(frm, cdt, cdn) {
 		const row = locals[cdt][cdn];
 		frm.events.set_depreciation_rate(frm, row);
+	},
+
+	rate_of_depreciation: function(frm, cdt, cdn) {
+		if(!frappe.flags.dont_change_rate) {
+			frappe.model.set_value(cdt, cdn, "expected_value_after_useful_life", 0);
+		}
+
+		frappe.flags.dont_change_rate = false;
 	}
 });
 
diff --git a/erpnext/assets/doctype/asset/asset.py b/erpnext/assets/doctype/asset/asset.py
index c398a73..45d2ec2 100644
--- a/erpnext/assets/doctype/asset/asset.py
+++ b/erpnext/assets/doctype/asset/asset.py
@@ -6,7 +6,7 @@
 import frappe, erpnext, math, json
 from frappe import _
 from six import string_types
-from frappe.utils import flt, add_months, cint, nowdate, getdate, today, date_diff
+from frappe.utils import flt, add_months, cint, nowdate, getdate, today, date_diff, add_days
 from frappe.model.document import Document
 from erpnext.assets.doctype.asset_category.asset_category import get_asset_category_account
 from erpnext.assets.doctype.asset.depreciation \
@@ -101,97 +101,88 @@
 
 	def set_depreciation_rate(self):
 		for d in self.get("finance_books"):
-			d.rate_of_depreciation = self.get_depreciation_rate(d, on_validate=True)
+			d.rate_of_depreciation = flt(self.get_depreciation_rate(d, on_validate=True),
+				d.precision("rate_of_depreciation"))
 
 	def make_depreciation_schedule(self):
-		depreciation_method = [d.depreciation_method for d in self.finance_books]
-
-		if 'Manual' not in depreciation_method:
+		if 'Manual' not in [d.depreciation_method for d in self.finance_books]:
 			self.schedules = []
 
-		if not self.get("schedules") and self.available_for_use_date:
-			total_depreciations = sum([d.total_number_of_depreciations for d in self.get('finance_books')])
+		if self.get("schedules") or not self.available_for_use_date:
+			return
 
-			for d in self.get('finance_books'):
-				self.validate_asset_finance_books(d)
+		for d in self.get('finance_books'):
+			self.validate_asset_finance_books(d)
 
-				value_after_depreciation = (flt(self.gross_purchase_amount) -
-					flt(self.opening_accumulated_depreciation))
+			value_after_depreciation = (flt(self.gross_purchase_amount) -
+				flt(self.opening_accumulated_depreciation))
 
-				d.value_after_depreciation = value_after_depreciation
+			d.value_after_depreciation = value_after_depreciation
 
-				no_of_depreciations = cint(d.total_number_of_depreciations - 1) - cint(self.number_of_depreciations_booked)
-				end_date = add_months(d.depreciation_start_date,
-					no_of_depreciations * cint(d.frequency_of_depreciation))
+			number_of_pending_depreciations = cint(d.total_number_of_depreciations) - \
+				cint(self.number_of_depreciations_booked)
 
-				total_days = date_diff(end_date, self.available_for_use_date)
-				rate_per_day = (value_after_depreciation - d.get("expected_value_after_useful_life")) / total_days
+			has_pro_rata = self.check_is_pro_rata(d)
 
-				number_of_pending_depreciations = cint(d.total_number_of_depreciations) - \
-					cint(self.number_of_depreciations_booked)
+			if has_pro_rata:
+				number_of_pending_depreciations += 1
 
-				from_date = self.available_for_use_date
-				if number_of_pending_depreciations:
-					next_depr_date = getdate(add_months(self.available_for_use_date,
-						number_of_pending_depreciations * 12))
-					if  (cint(frappe.db.get_value("Asset Settings", None, "schedule_based_on_fiscal_year")) == 1
-						and getdate(d.depreciation_start_date) < next_depr_date):
+			skip_row = False
+			for n in range(number_of_pending_depreciations):
+				# If depreciation is already completed (for double declining balance)
+				if skip_row: continue
 
-						number_of_pending_depreciations += 1
-						for n in range(number_of_pending_depreciations):
-							if n == list(range(number_of_pending_depreciations))[-1]:
-								schedule_date = add_months(self.available_for_use_date, n * 12)
-								previous_scheduled_date = add_months(d.depreciation_start_date, (n-1) * 12)
-								depreciation_amount = \
-									self.get_depreciation_amount_prorata_temporis(value_after_depreciation,
-										d, previous_scheduled_date, schedule_date)
+				depreciation_amount = self.get_depreciation_amount(value_after_depreciation,
+					d.total_number_of_depreciations, d)
 
-							elif n == list(range(number_of_pending_depreciations))[0]:
-								schedule_date = d.depreciation_start_date
-								depreciation_amount = \
-									self.get_depreciation_amount_prorata_temporis(value_after_depreciation,
-										d, self.available_for_use_date, schedule_date)
+				if not has_pro_rata or n < cint(number_of_pending_depreciations) - 1:
+					schedule_date = add_months(d.depreciation_start_date,
+						n * cint(d.frequency_of_depreciation))
 
-							else:
-								schedule_date = add_months(d.depreciation_start_date, n * 12)
-								depreciation_amount = \
-									 self.get_depreciation_amount_prorata_temporis(value_after_depreciation, d)
+				# For first row
+				if has_pro_rata and n==0:
+					depreciation_amount, days = get_pro_rata_amt(d, depreciation_amount,
+						self.available_for_use_date, d.depreciation_start_date)
+				# For last row
+				elif has_pro_rata and n == cint(number_of_pending_depreciations) - 1:
+					to_date = add_months(self.available_for_use_date,
+						n * cint(d.frequency_of_depreciation))
 
-							if value_after_depreciation != 0:
-								value_after_depreciation -= flt(depreciation_amount)
+					depreciation_amount, days = get_pro_rata_amt(d,
+						depreciation_amount, schedule_date, to_date)
 
-								self.append("schedules", {
-									"schedule_date": schedule_date,
-									"depreciation_amount": depreciation_amount,
-									"depreciation_method": d.depreciation_method,
-									"finance_book": d.finance_book,
-									"finance_book_id": d.idx
-								})
-					else:
-						for n in range(number_of_pending_depreciations):
-							schedule_date = add_months(d.depreciation_start_date,
-								n * cint(d.frequency_of_depreciation))
+					schedule_date = add_days(schedule_date, days)
 
-							if d.depreciation_method in ("Straight Line", "Manual"):
-								days = date_diff(schedule_date, from_date)
-								if n == 0: days += 1
+				if not depreciation_amount: continue
+				value_after_depreciation -= flt(depreciation_amount,
+					self.precision("gross_purchase_amount"))
 
-								depreciation_amount = days * rate_per_day
-								from_date = schedule_date
-							else:
-								depreciation_amount = self.get_depreciation_amount(value_after_depreciation,
-									d.total_number_of_depreciations, d)
+				# Adjust depreciation amount in the last period based on the expected value after useful life
+				if d.expected_value_after_useful_life and ((n == cint(number_of_pending_depreciations) - 1
+					and value_after_depreciation != d.expected_value_after_useful_life)
+					or value_after_depreciation < d.expected_value_after_useful_life):
+					depreciation_amount += (value_after_depreciation - d.expected_value_after_useful_life)
+					skip_row = True
 
-							if depreciation_amount:
-								value_after_depreciation -= flt(depreciation_amount)
+				if depreciation_amount > 0:
+					self.append("schedules", {
+						"schedule_date": schedule_date,
+						"depreciation_amount": depreciation_amount,
+						"depreciation_method": d.depreciation_method,
+						"finance_book": d.finance_book,
+						"finance_book_id": d.idx
+					})
 
-								self.append("schedules", {
-									"schedule_date": schedule_date,
-									"depreciation_amount": depreciation_amount,
-									"depreciation_method": d.depreciation_method,
-									"finance_book": d.finance_book,
-									"finance_book_id": d.idx
-								})
+	def check_is_pro_rata(self, row):
+		has_pro_rata = False
+
+		days = date_diff(row.depreciation_start_date, self.available_for_use_date) + 1
+		total_days = get_total_days(row.depreciation_start_date, row.frequency_of_depreciation)
+
+		if days < total_days:
+			has_pro_rata = True
+
+		return has_pro_rata
 
 	def validate_asset_finance_books(self, row):
 		if flt(row.expected_value_after_useful_life) >= flt(self.gross_purchase_amount):
@@ -261,31 +252,14 @@
 		return flt(self.get('finance_books')[cint(idx)-1].value_after_depreciation)
 
 	def get_depreciation_amount(self, depreciable_value, total_number_of_depreciations, row):
-		if row.depreciation_method in ["Straight Line", "Manual"]:
-			amt = (flt(self.gross_purchase_amount) - flt(row.expected_value_after_useful_life) -
-				flt(self.opening_accumulated_depreciation))
-
-			depreciation_amount = amt * row.rate_of_depreciation
-		else:
-			depreciation_amount = flt(depreciable_value) * (flt(row.rate_of_depreciation) / 100)
-			value_after_depreciation = flt(depreciable_value) - depreciation_amount
-			if value_after_depreciation < flt(row.expected_value_after_useful_life):
-				depreciation_amount = flt(depreciable_value) - flt(row.expected_value_after_useful_life)
-
-		return depreciation_amount
-
-	def get_depreciation_amount_prorata_temporis(self, depreciable_value, row, start_date=None, end_date=None):
-		if start_date and end_date:
-			prorata_temporis =  min(abs(flt(date_diff(str(end_date), str(start_date)))) / flt(frappe.db.get_value("Asset Settings", None, "number_of_days_in_fiscal_year")), 1)
-		else:
-			prorata_temporis = 1
+		precision = self.precision("gross_purchase_amount")
 
 		if row.depreciation_method in ("Straight Line", "Manual"):
 			depreciation_amount = (flt(row.value_after_depreciation) -
 				flt(row.expected_value_after_useful_life)) / (cint(row.total_number_of_depreciations) -
-				cint(self.number_of_depreciations_booked)) * prorata_temporis
+				cint(self.number_of_depreciations_booked))
 		else:
-			depreciation_amount = self.get_depreciation_amount(depreciable_value, row.total_number_of_depreciations, row)
+			depreciation_amount = flt(depreciable_value * (flt(row.rate_of_depreciation) / 100), precision)
 
 		return depreciation_amount
 
@@ -301,9 +275,12 @@
 					flt(accumulated_depreciation_after_full_schedule),
 					self.precision('gross_purchase_amount'))
 
-				if row.expected_value_after_useful_life < asset_value_after_full_schedule:
+				if (row.expected_value_after_useful_life and 
+					row.expected_value_after_useful_life < asset_value_after_full_schedule):
 					frappe.throw(_("Depreciation Row {0}: Expected value after useful life must be greater than or equal to {1}")
 						.format(row.idx, asset_value_after_full_schedule))
+				elif not row.expected_value_after_useful_life:
+					row.expected_value_after_useful_life = asset_value_after_full_schedule
 
 	def validate_cancellation(self):
 		if self.status not in ("Submitted", "Partially Depreciated", "Fully Depreciated"):
@@ -412,15 +389,7 @@
 		if isinstance(args, string_types):
 			args = json.loads(args)
 
-		number_of_depreciations_booked = 0
-		if self.is_existing_asset:
-			number_of_depreciations_booked = self.number_of_depreciations_booked
-
 		float_precision = cint(frappe.db.get_default("float_precision")) or 2
-		tot_no_of_depreciation = flt(args.get("total_number_of_depreciations")) - flt(number_of_depreciations_booked)
-
-		if args.get("depreciation_method") in ["Straight Line", "Manual"]:
-			return 1.0 / tot_no_of_depreciation
 
 		if args.get("depreciation_method") == 'Double Declining Balance':
 			return 200.0 / args.get("total_number_of_depreciations")
@@ -600,3 +569,15 @@
 
 def is_cwip_accounting_disabled():
 	return cint(frappe.db.get_single_value("Asset Settings", "disable_cwip_accounting"))
+
+def get_pro_rata_amt(row, depreciation_amount, from_date, to_date):
+	days = date_diff(to_date, from_date)
+	total_days = get_total_days(to_date, row.frequency_of_depreciation)
+
+	return (depreciation_amount * flt(days)) / flt(total_days), days
+
+def get_total_days(date, frequency):
+	period_start_date = add_months(date,
+		cint(frequency) * -1)
+
+	return date_diff(date, period_start_date)
\ No newline at end of file
diff --git a/erpnext/assets/doctype/asset/test_asset.py b/erpnext/assets/doctype/asset/test_asset.py
index fceccfb..481ee7d 100644
--- a/erpnext/assets/doctype/asset/test_asset.py
+++ b/erpnext/assets/doctype/asset/test_asset.py
@@ -88,23 +88,23 @@
 		asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, 'name')
 		asset = frappe.get_doc('Asset', asset_name)
 		asset.calculate_depreciation = 1
-		asset.available_for_use_date = '2020-06-06'
-		asset.purchase_date = '2020-06-06'
+		asset.available_for_use_date = '2030-01-01'
+		asset.purchase_date = '2030-01-01'
 
 		asset.append("finance_books", {
 			"expected_value_after_useful_life": 10000,
-			"next_depreciation_date": "2020-12-31",
 			"depreciation_method": "Straight Line",
 			"total_number_of_depreciations": 3,
-			"frequency_of_depreciation": 10,
-			"depreciation_start_date": "2020-06-06"
+			"frequency_of_depreciation": 12,
+			"depreciation_start_date": "2030-12-31"
 		})
 		asset.save()
+
 		self.assertEqual(asset.status, "Draft")
 		expected_schedules = [
-			["2020-06-06", 147.54, 147.54],
-			["2021-04-06", 44852.46, 45000.0],
-			["2022-02-06", 45000.0, 90000.00]
+			["2030-12-31", 30000.00, 30000.00],
+			["2031-12-31", 30000.00, 60000.00],
+			["2032-12-31", 30000.00, 90000.00]
 		]
 
 		schedules = [[cstr(d.schedule_date), d.depreciation_amount, d.accumulated_depreciation_amount]
@@ -118,20 +118,21 @@
 		asset.calculate_depreciation = 1
 		asset.number_of_depreciations_booked = 1
 		asset.opening_accumulated_depreciation = 40000
+		asset.available_for_use_date = "2030-06-06"
 		asset.append("finance_books", {
 			"expected_value_after_useful_life": 10000,
-			"next_depreciation_date": "2020-12-31",
 			"depreciation_method": "Straight Line",
 			"total_number_of_depreciations": 3,
-			"frequency_of_depreciation": 10,
-			"depreciation_start_date": "2020-06-06"
+			"frequency_of_depreciation": 12,
+			"depreciation_start_date": "2030-12-31"
 		})
 		asset.insert()
 		self.assertEqual(asset.status, "Draft")
 		asset.save()
 		expected_schedules = [
-			["2020-06-06", 164.47, 40164.47],
-			["2021-04-06", 49835.53, 90000.00]
+			["2030-12-31", 14246.58, 54246.58],
+			["2031-12-31", 25000.00, 79246.58],
+			["2032-06-06", 10753.42, 90000.00]
 		]
 		schedules = [[cstr(d.schedule_date), flt(d.depreciation_amount, 2), d.accumulated_depreciation_amount]
 			for d in asset.get("schedules")]
@@ -145,24 +146,23 @@
 		asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, 'name')
 		asset = frappe.get_doc('Asset', asset_name)
 		asset.calculate_depreciation = 1
-		asset.available_for_use_date = '2020-06-06'
-		asset.purchase_date = '2020-06-06'
+		asset.available_for_use_date = '2030-01-01'
+		asset.purchase_date = '2030-01-01'
 		asset.append("finance_books", {
 			"expected_value_after_useful_life": 10000,
-			"next_depreciation_date": "2020-12-31",
 			"depreciation_method": "Double Declining Balance",
 			"total_number_of_depreciations": 3,
-			"frequency_of_depreciation": 10,
-			"depreciation_start_date": "2020-06-06"
+			"frequency_of_depreciation": 12,
+			"depreciation_start_date": '2030-12-31'
 		})
 		asset.insert()
 		self.assertEqual(asset.status, "Draft")
 		asset.save()
 
 		expected_schedules = [
-			["2020-06-06", 66666.67, 66666.67],
-			["2021-04-06", 22222.22, 88888.89],
-			["2022-02-06", 1111.11, 90000.0]
+			['2030-12-31', 66667.00, 66667.00],
+			['2031-12-31', 22222.11, 88889.11],
+			['2032-12-31', 1110.89, 90000.0]
 		]
 
 		schedules = [[cstr(d.schedule_date), d.depreciation_amount, d.accumulated_depreciation_amount]
@@ -177,23 +177,21 @@
 		asset.is_existing_asset = 1
 		asset.number_of_depreciations_booked = 1
 		asset.opening_accumulated_depreciation = 50000
+		asset.available_for_use_date = '2030-01-01'
+		asset.purchase_date = '2029-11-30'
 		asset.append("finance_books", {
 			"expected_value_after_useful_life": 10000,
-			"next_depreciation_date": "2020-12-31",
 			"depreciation_method": "Double Declining Balance",
 			"total_number_of_depreciations": 3,
-			"frequency_of_depreciation": 10,
-			"depreciation_start_date": "2020-06-06"
+			"frequency_of_depreciation": 12,
+			"depreciation_start_date": "2030-12-31"
 		})
 		asset.insert()
 		self.assertEqual(asset.status, "Draft")
-		asset.save()
-
-		asset.save()
 
 		expected_schedules = [
-			["2020-06-06", 33333.33, 83333.33],
-			["2021-04-06", 6666.67, 90000.0]
+			["2030-12-31", 33333.50, 83333.50],
+			["2031-12-31", 6666.50, 90000.0]
 		]
 
 		schedules = [[cstr(d.schedule_date), d.depreciation_amount, d.accumulated_depreciation_amount]
@@ -209,25 +207,25 @@
 		asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, 'name')
 		asset = frappe.get_doc('Asset', asset_name)
 		asset.calculate_depreciation = 1
-		asset.purchase_date = '2020-01-30'
+		asset.purchase_date = '2030-01-30'
 		asset.is_existing_asset = 0
-		asset.available_for_use_date = "2020-01-30"
+		asset.available_for_use_date = "2030-01-30"
 		asset.append("finance_books", {
 			"expected_value_after_useful_life": 10000,
 			"depreciation_method": "Straight Line",
 			"total_number_of_depreciations": 3,
-			"frequency_of_depreciation": 10,
-			"depreciation_start_date": "2020-12-31"
+			"frequency_of_depreciation": 12,
+			"depreciation_start_date": "2030-12-31"
 		})
 
 		asset.insert()
 		asset.save()
 
 		expected_schedules = [
-			["2020-12-31", 28000.0, 28000.0],
-			["2021-12-31", 30000.0, 58000.0],
-			["2022-12-31", 30000.0, 88000.0],
-			["2023-01-30", 2000.0, 90000.0]
+			["2030-12-31", 27534.25, 27534.25],
+			["2031-12-31", 30000.0, 57534.25],
+			["2032-12-31", 30000.0, 87534.25],
+			["2033-01-30", 2465.75, 90000.0]
 		]
 
 		schedules = [[cstr(d.schedule_date), flt(d.depreciation_amount, 2), flt(d.accumulated_depreciation_amount, 2)]
@@ -266,8 +264,8 @@
 		self.assertEqual(asset.get("schedules")[0].journal_entry[:4], "DEPR")
 
 		expected_gle = (
-			("_Test Accumulated Depreciations - _TC", 0.0, 32129.24),
-			("_Test Depreciations - _TC", 32129.24, 0.0)
+			("_Test Accumulated Depreciations - _TC", 0.0, 30000.0),
+			("_Test Depreciations - _TC", 30000.0, 0.0)
 		)
 
 		gle = frappe.db.sql("""select account, debit, credit from `tabGL Entry`
@@ -277,15 +275,15 @@
 		self.assertEqual(gle, expected_gle)
 		self.assertEqual(asset.get("value_after_depreciation"), 0)
 
-	def test_depreciation_entry_for_wdv(self):
+	def test_depreciation_entry_for_wdv_without_pro_rata(self):
 		pr = make_purchase_receipt(item_code="Macbook Pro",
 			qty=1, rate=8000.0, location="Test Location")
 
 		asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, 'name')
 		asset = frappe.get_doc('Asset', asset_name)
 		asset.calculate_depreciation = 1
-		asset.available_for_use_date = '2030-06-06'
-		asset.purchase_date = '2030-06-06'
+		asset.available_for_use_date = '2030-01-01'
+		asset.purchase_date = '2030-01-01'
 		asset.append("finance_books", {
 			"expected_value_after_useful_life": 1000,
 			"depreciation_method": "Written Down Value",
@@ -298,9 +296,41 @@
 		self.assertEqual(asset.finance_books[0].rate_of_depreciation, 50.0)
 
 		expected_schedules = [
-			["2030-12-31", 4000.0, 4000.0],
-			["2031-12-31", 2000.0, 6000.0],
-			["2032-12-31", 1000.0, 7000.0],
+			["2030-12-31", 4000.00, 4000.00],
+			["2031-12-31", 2000.00, 6000.00],
+			["2032-12-31", 1000.00, 7000.0],
+		]
+
+		schedules = [[cstr(d.schedule_date), flt(d.depreciation_amount, 2), flt(d.accumulated_depreciation_amount, 2)]
+			for d in asset.get("schedules")]
+
+		self.assertEqual(schedules, expected_schedules)
+
+	def test_pro_rata_depreciation_entry_for_wdv(self):
+		pr = make_purchase_receipt(item_code="Macbook Pro",
+			qty=1, rate=8000.0, location="Test Location")
+
+		asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, 'name')
+		asset = frappe.get_doc('Asset', asset_name)
+		asset.calculate_depreciation = 1
+		asset.available_for_use_date = '2030-06-06'
+		asset.purchase_date = '2030-01-01'
+		asset.append("finance_books", {
+			"expected_value_after_useful_life": 1000,
+			"depreciation_method": "Written Down Value",
+			"total_number_of_depreciations": 3,
+			"frequency_of_depreciation": 12,
+			"depreciation_start_date": "2030-12-31"
+		})
+		asset.save(ignore_permissions=True)
+
+		self.assertEqual(asset.finance_books[0].rate_of_depreciation, 50.0)
+
+		expected_schedules = [
+			["2030-12-31", 2279.45, 2279.45],
+			["2031-12-31", 2860.28, 5139.73],
+			["2032-12-31", 1430.14, 6569.87],
+			["2033-06-06", 430.13, 7000.0],
 		]
 
 		schedules = [[cstr(d.schedule_date), flt(d.depreciation_amount, 2), flt(d.accumulated_depreciation_amount, 2)]
@@ -346,18 +376,19 @@
 		asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, 'name')
 		asset = frappe.get_doc('Asset', asset_name)
 		asset.calculate_depreciation = 1
-		asset.available_for_use_date = '2020-06-06'
-		asset.purchase_date = '2020-06-06'
+		asset.available_for_use_date = nowdate()
+		asset.purchase_date = nowdate()
 		asset.append("finance_books", {
 			"expected_value_after_useful_life": 10000,
 			"depreciation_method": "Straight Line",
 			"total_number_of_depreciations": 3,
 			"frequency_of_depreciation": 10,
-			"depreciation_start_date": "2020-06-06"
+			"depreciation_start_date": nowdate()
 		})
 		asset.insert()
 		asset.submit()
-		post_depreciation_entries(date="2021-01-01")
+
+		post_depreciation_entries(date=add_months(nowdate(), 10))
 
 		scrap_asset(asset.name)
 
@@ -366,9 +397,9 @@
 		self.assertTrue(asset.journal_entry_for_scrap)
 
 		expected_gle = (
-			("_Test Accumulated Depreciations - _TC", 147.54, 0.0),
+			("_Test Accumulated Depreciations - _TC", 30000.0, 0.0),
 			("_Test Fixed Asset - _TC", 0.0, 100000.0),
-			("_Test Gain/Loss on Asset Disposal - _TC", 99852.46, 0.0)
+			("_Test Gain/Loss on Asset Disposal - _TC", 70000.0, 0.0)
 		)
 
 		gle = frappe.db.sql("""select account, debit, credit from `tabGL Entry`
@@ -412,9 +443,9 @@
 		self.assertEqual(frappe.db.get_value("Asset", asset.name, "status"), "Sold")
 
 		expected_gle = (
-			("_Test Accumulated Depreciations - _TC", 23051.47, 0.0),
+			("_Test Accumulated Depreciations - _TC", 20392.16, 0.0),
 			("_Test Fixed Asset - _TC", 0.0, 100000.0),
-			("_Test Gain/Loss on Asset Disposal - _TC", 51948.53, 0.0),
+			("_Test Gain/Loss on Asset Disposal - _TC", 54607.84, 0.0),
 			("Debtors - _TC", 25000.0, 0.0)
 		)
 
diff --git a/erpnext/assets/doctype/asset_settings/asset_settings.json b/erpnext/assets/doctype/asset_settings/asset_settings.json
index a3fee96..edc5ce1 100644
--- a/erpnext/assets/doctype/asset_settings/asset_settings.json
+++ b/erpnext/assets/doctype/asset_settings/asset_settings.json
@@ -54,75 +54,6 @@
    "collapsible": 0, 
    "columns": 0, 
    "fetch_if_empty": 0, 
-   "fieldname": "schedule_based_on_fiscal_year", 
-   "fieldtype": "Check", 
-   "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": "Calculate Prorated Depreciation Schedule Based on Fiscal Year", 
-   "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
-  }, 
-  {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "default": "360", 
-   "depends_on": "eval:doc.schedule_based_on_fiscal_year", 
-   "description": "This value is used for pro-rata temporis calculation", 
-   "fetch_if_empty": 0, 
-   "fieldname": "number_of_days_in_fiscal_year", 
-   "fieldtype": "Data", 
-   "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": "Number of Days in Fiscal Year", 
-   "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
-  }, 
-  {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fetch_if_empty": 0, 
    "fieldname": "disable_cwip_accounting", 
    "fieldtype": "Check", 
    "hidden": 0, 
@@ -159,7 +90,7 @@
  "issingle": 1, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2019-03-08 10:44:41.924547", 
+ "modified": "2019-05-26 18:31:19.930563", 
  "modified_by": "Administrator", 
  "module": "Assets", 
  "name": "Asset Settings", 
diff --git a/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py b/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py
index 4a13f38..bebf0cc 100644
--- a/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py
+++ b/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py
@@ -30,7 +30,7 @@
 				company_name="_Test Procurement Company",
 				abbr="_TPC",
 				default_currency="INR",
-				country="India"
+				country="Pakistan"
 				)).insert()
 		warehouse = create_warehouse("_Test Procurement Warehouse", company="_Test Procurement Company")
 		mr = make_material_request(company="_Test Procurement Company", warehouse=warehouse)
diff --git a/erpnext/config/hr.py b/erpnext/config/hr.py
index 0367755..bb055df 100644
--- a/erpnext/config/hr.py
+++ b/erpnext/config/hr.py
@@ -162,6 +162,10 @@
 				},
 				{
 					"type": "doctype",
+					"name": "Payroll Period",
+				},
+				{
+					"type": "doctype",
 					"name": "Salary Component",
 				},
 				{
diff --git a/erpnext/hr/doctype/payroll_entry/payroll_entry.py b/erpnext/hr/doctype/payroll_entry/payroll_entry.py
index d8dd5c6..38c36d9 100644
--- a/erpnext/hr/doctype/payroll_entry/payroll_entry.py
+++ b/erpnext/hr/doctype/payroll_entry/payroll_entry.py
@@ -12,6 +12,16 @@
 from erpnext.hr.doctype.employee.employee import get_holiday_list_for_employee
 
 class PayrollEntry(Document):
+	def onload(self):
+		if not self.docstatus==1:
+			return
+
+		# check if salary slips were manually submitted
+		entries = frappe.db.count("Salary Slip", {'payroll_entry': self.name, 'docstatus': 1}, ['name'])
+		if cint(entries) == len(self.employees) and not self.salary_slips_submitted:
+			self.db_set("salary_slips_submitted", 1)
+			self.reload()
+
 	def on_submit(self):
 		self.create_salary_slips()
 
diff --git a/erpnext/hr/doctype/staffing_plan/test_staffing_plan.py b/erpnext/hr/doctype/staffing_plan/test_staffing_plan.py
index 4a0ce18..9ba6d5e 100644
--- a/erpnext/hr/doctype/staffing_plan/test_staffing_plan.py
+++ b/erpnext/hr/doctype/staffing_plan/test_staffing_plan.py
@@ -92,5 +92,5 @@
 	company.abbr = "_TC10"
 	company.parent_company = "_Test Company"
 	company.default_currency = "INR"
-	company.country = "India"
+	company.country = "Pakistan"
 	company.insert()
\ No newline at end of file
diff --git a/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py b/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py
index d9e62c7..98a8c59 100644
--- a/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py
+++ b/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py
@@ -327,7 +327,8 @@
 
 		if sl_entries:
 			sl_entries.reverse()
-			self.make_sl_entries(sl_entries)
+			allow_negative_stock = frappe.db.get_value("Stock Settings", None, "allow_negative_stock")
+			self.make_sl_entries(sl_entries, allow_negative_stock=allow_negative_stock)
 
 		# repost future entries for selected item_code, warehouse
 		for entries in existing_entries:
diff --git a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
index f0c71cf..ededc4d 100644
--- a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
+++ b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
@@ -17,10 +17,11 @@
 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
 
 class TestStockReconciliation(unittest.TestCase):
-	def setUp(self):
+	@classmethod
+	def setUpClass(self):
 		create_batch_or_serial_no_items()
 		frappe.db.set_value("Stock Settings", None, "allow_negative_stock", 1)
-		self.insert_existing_sle()
+		insert_existing_sle()
 
 	def test_reco_for_fifo(self):
 		self._test_reco_sle_gle("FIFO")
@@ -97,18 +98,6 @@
 		self.assertEqual(["_Test Stock Reco Item", "_Test Warehouse Ledger 1 - _TC", 100],
 			[items[0]["item_code"], items[0]["warehouse"], items[0]["qty"]])
 
-	def insert_existing_sle(self):
-		from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
-
-		make_stock_entry(posting_date="2012-12-15", posting_time="02:00", item_code="_Test Item",
-			target="_Test Warehouse - _TC", qty=10, basic_rate=700)
-
-		make_stock_entry(posting_date="2012-12-25", posting_time="03:00", item_code="_Test Item",
-			source="_Test Warehouse - _TC", qty=15)
-
-		make_stock_entry(posting_date="2013-01-05", posting_time="07:00", item_code="_Test Item",
-			target="_Test Warehouse - _TC", qty=15, basic_rate=1200)
-
 	def test_stock_reco_for_serialized_item(self):
 		set_perpetual_inventory()
 
@@ -218,6 +207,18 @@
 		for d in to_delete_records:
 			frappe.delete_doc("Stock Reconciliation", d)
 
+def insert_existing_sle():
+	from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
+
+	make_stock_entry(posting_date="2012-12-15", posting_time="02:00", item_code="_Test Item",
+		target="_Test Warehouse - _TC", qty=10, basic_rate=700)
+
+	make_stock_entry(posting_date="2012-12-25", posting_time="03:00", item_code="_Test Item",
+		source="_Test Warehouse - _TC", qty=15)
+
+	make_stock_entry(posting_date="2013-01-05", posting_time="07:00", item_code="_Test Item",
+		target="_Test Warehouse - _TC", qty=15, basic_rate=1200)
+
 def create_batch_or_serial_no_items():
 	create_warehouse("_Test Warehouse for Stock Reco1",
 		{"is_group": 0, "parent_warehouse": "_Test Warehouse Group - _TC"})
diff --git a/erpnext/stock/doctype/stock_settings/test_stock_settings.py b/erpnext/stock/doctype/stock_settings/test_stock_settings.py
index 1e83ec2..42a78f7 100644
--- a/erpnext/stock/doctype/stock_settings/test_stock_settings.py
+++ b/erpnext/stock/doctype/stock_settings/test_stock_settings.py
@@ -8,16 +8,7 @@
 
 class TestStockSettings(unittest.TestCase):
 	def setUp(self):
-		settings = frappe.get_single('Stock Settings')
-		settings.clean_description_html = 0
-		settings.save()
-
-		frappe.delete_doc('Item', 'Item for description test')
-
-	def tearDown(self):
-		settings = frappe.get_single('Stock Settings')
-		settings.clean_description_html = 1
-		settings.save()
+		frappe.db.set_value("Stock Settings", None, "clean_description_html", 0)
 
 	def test_settings(self):
 		item = frappe.get_doc(dict(
diff --git a/erpnext/stock/report/stock_ageing/stock_ageing.js b/erpnext/stock/report/stock_ageing/stock_ageing.js
index aad8df4..ccde61a 100644
--- a/erpnext/stock/report/stock_ageing/stock_ageing.js
+++ b/erpnext/stock/report/stock_ageing/stock_ageing.js
@@ -37,8 +37,8 @@
 			"options": "Brand"
 		},
 		{
-			"fieldname":"show_ageing_warehouse_wise",
-			"label": __("Show Ageing Warehouse-wise"),
+			"fieldname":"show_warehouse_wise_stock",
+			"label": __("Show Warehouse-wise Stock"),
 			"fieldtype": "Check",
 			"default": 0
 		}
diff --git a/erpnext/stock/report/stock_ageing/stock_ageing.py b/erpnext/stock/report/stock_ageing/stock_ageing.py
index 9692845..83a1d7b 100644
--- a/erpnext/stock/report/stock_ageing/stock_ageing.py
+++ b/erpnext/stock/report/stock_ageing/stock_ageing.py
@@ -6,6 +6,7 @@
 from frappe import _
 from frappe.utils import date_diff, flt
 from six import iteritems
+from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
 
 def execute(filters=None):
 
@@ -14,9 +15,9 @@
 	to_date = filters["to_date"]
 	data = []
 	for item, item_dict in iteritems(item_details):
-		fifo_queue = item_dict["fifo_queue"]
+		fifo_queue = sorted(item_dict["fifo_queue"], key=lambda x: x[1])
 		details = item_dict["details"]
-		if not fifo_queue: continue
+		if not fifo_queue or (not item_dict.get("total_qty")): continue
 
 		average_age = get_average_age(fifo_queue, to_date)
 		earliest_age = date_diff(to_date, fifo_queue[0][1])
@@ -25,7 +26,7 @@
 		row = [details.name, details.item_name,
 			details.description, details.item_group, details.brand]
 
-		if filters.get("show_ageing_warehouse_wise"):
+		if filters.get("show_warehouse_wise_stock"):
 			row.append(details.warehouse)
 
 		row.extend([item_dict.get("total_qty"), average_age,
@@ -39,48 +40,150 @@
 	batch_age = age_qty = total_qty = 0.0
 	for batch in fifo_queue:
 		batch_age = date_diff(to_date, batch[1])
-		age_qty += batch_age * batch[0]
-		total_qty += batch[0]
+
+		if type(batch[0]) in ['int', 'float']:
+			age_qty += batch_age * batch[0]
+			total_qty += batch[0]
+		else:
+			age_qty += batch_age * 1
+			total_qty += 1
 
 	return (age_qty / total_qty) if total_qty else 0.0
 
 def get_columns(filters):
-	columns = [_("Item Code") + ":Link/Item:100", _("Item Name") + "::100", _("Description") + "::200",
-		_("Item Group") + ":Link/Item Group:100", _("Brand") + ":Link/Brand:100"]
+	columns = [
+		{
+			"label": _("Item Code"),
+			"fieldname": "item_code",
+			"fieldtype": "Link",
+			"options": "Item",
+			"width": 100
+		},
+		{
+			"label": _("Item Name"),
+			"fieldname": "item_name",
+			"fieldtype": "Data",
+			"width": 100
+		},
+		{
+			"label": _("Description"),
+			"fieldname": "description",
+			"fieldtype": "Data",
+			"width": 200
+		},
+		{
+			"label": _("Item Group"),
+			"fieldname": "item_group",
+			"fieldtype": "Link",
+			"options": "Item Group",
+			"width": 100
+		},
+		{
+			"label": _("Brand"),
+			"fieldname": "brand",
+			"fieldtype": "Link",
+			"options": "Brand",
+			"width": 100
+		}]
 
-	if filters.get("show_ageing_warehouse_wise"):
-		columns.extend([_("Warehouse") + ":Link/Warehouse:100"])
+	if filters.get("show_warehouse_wise_stock"):
+		columns +=[{
+			"label": _("Warehouse"),
+			"fieldname": "warehouse",
+			"fieldtype": "Link",
+			"options": "Warehouse",
+			"width": 100
+		}]
 
-	columns.extend([_("Available Qty") + ":Float:100", _("Average Age") + ":Float:100",
-		_("Earliest") + ":Int:80", _("Latest") + ":Int:80", _("UOM") + ":Link/UOM:100"])
+	columns.extend([
+		{
+			"label": _("Available Qty"),
+			"fieldname": "qty",
+			"fieldtype": "Float",
+			"width": 100
+		},
+		{
+			"label": _("Average Age"),
+			"fieldname": "average_age",
+			"fieldtype": "Float",
+			"width": 100
+		},
+		{
+			"label": _("Earliest"),
+			"fieldname": "earliest",
+			"fieldtype": "Int",
+			"width": 80
+		},
+		{
+			"label": _("Latest"),
+			"fieldname": "latest",
+			"fieldtype": "Int",
+			"width": 80
+		},
+		{
+			"label": _("UOM"),
+			"fieldname": "uom",
+			"fieldtype": "Link",
+			"options": "UOM",
+			"width": 100
+		}
+	])
 
 	return columns
 
 def get_fifo_queue(filters):
 	item_details = {}
-	for d in get_stock_ledger_entries(filters):
-		key = (d.name, d.warehouse) if filters.get('show_ageing_warehouse_wise') else d.name
+	transfered_item_details = {}
+	serial_no_batch_purchase_details = {}
+
+	sle = get_stock_ledger_entries(filters)
+
+	for d in sle:
+		key = (d.name, d.warehouse) if filters.get('show_warehouse_wise_stock') else d.name
 		item_details.setdefault(key, {"details": d, "fifo_queue": []})
 		fifo_queue = item_details[key]["fifo_queue"]
 
+		transfered_item_details.setdefault((d.voucher_no, d.name), [])
+
 		if d.voucher_type == "Stock Reconciliation":
 			d.actual_qty = flt(d.qty_after_transaction) - flt(item_details[key].get("qty_after_transaction", 0))
 
+		serial_no_list = get_serial_nos(d.serial_no) if d.serial_no else []
+
 		if d.actual_qty > 0:
-			fifo_queue.append([d.actual_qty, d.posting_date])
-		else:
-			qty_to_pop = abs(d.actual_qty)
-			while qty_to_pop:
-				batch = fifo_queue[0] if fifo_queue else [0, None]
-				if 0 < batch[0] <= qty_to_pop:
-					# if batch qty > 0
-					# not enough or exactly same qty in current batch, clear batch
-					qty_to_pop -= batch[0]
-					fifo_queue.pop(0)
+			if transfered_item_details.get((d.voucher_no, d.name)):
+				batch = transfered_item_details[(d.voucher_no, d.name)][0]
+				fifo_queue.append(batch)
+				transfered_item_details[((d.voucher_no, d.name))].pop(0)
+			else:
+				if serial_no_list:
+					for serial_no in serial_no_list:
+						if serial_no_batch_purchase_details.get(serial_no):
+							fifo_queue.append([serial_no, serial_no_batch_purchase_details.get(serial_no)])
+						else:
+							serial_no_batch_purchase_details.setdefault(serial_no, d.posting_date)
+							fifo_queue.append([serial_no, d.posting_date])
 				else:
-					# all from current batch
-					batch[0] -= qty_to_pop
-					qty_to_pop = 0
+					fifo_queue.append([d.actual_qty, d.posting_date])
+		else:
+			if serial_no_list:
+				for serial_no in fifo_queue:
+					if serial_no[0] in serial_no_list:
+						fifo_queue.remove(serial_no)
+			else:
+				qty_to_pop = abs(d.actual_qty)
+				while qty_to_pop:
+					batch = fifo_queue[0] if fifo_queue else [0, None]
+					if 0 < batch[0] <= qty_to_pop:
+						# if batch qty > 0
+						# not enough or exactly same qty in current batch, clear batch
+						qty_to_pop -= batch[0]
+						transfered_item_details[(d.voucher_no, d.name)].append(fifo_queue.pop(0))
+					else:
+						# all from current batch
+						batch[0] -= qty_to_pop
+						transfered_item_details[(d.voucher_no, d.name)].append([qty_to_pop, batch[1]])
+						qty_to_pop = 0
 
 		item_details[key]["qty_after_transaction"] = d.qty_after_transaction
 
@@ -94,7 +197,7 @@
 def get_stock_ledger_entries(filters):
 	return frappe.db.sql("""select
 			item.name, item.item_name, item_group, brand, description, item.stock_uom,
-			actual_qty, posting_date, voucher_type, qty_after_transaction, warehouse
+			actual_qty, posting_date, voucher_type, voucher_no, serial_no, batch_no, qty_after_transaction, warehouse
 		from `tabStock Ledger Entry` sle,
 			(select name, item_name, description, stock_uom, brand, item_group
 				from `tabItem` {item_conditions}) item
@@ -102,7 +205,7 @@
 			company = %(company)s and
 			posting_date <= %(to_date)s
 			{sle_conditions}
-			order by posting_date, posting_time, sle.creation"""\
+			order by posting_date, posting_time, sle.creation, actual_qty""" #nosec
 		.format(item_conditions=get_item_conditions(filters),
 			sle_conditions=get_sle_conditions(filters)), filters, as_dict=True)
 
diff --git a/erpnext/tests/test_notifications.py b/erpnext/tests/test_notifications.py
index 596bc80..1fd90be 100644
--- a/erpnext/tests/test_notifications.py
+++ b/erpnext/tests/test_notifications.py
@@ -2,45 +2,31 @@
 # MIT License. See license.txt
 
 from __future__ import unicode_literals
+import frappe
 import unittest
 
 from frappe.desk import notifications
 from frappe.test_runner import make_test_objects
 
 class TestNotifications(unittest.TestCase):
-	def setUp(self):
-		test_records_company = [
-			{
-				"abbr": "_TC6",
-				"company_name": "_Test Company 6",
-				"country": "India",
-				"default_currency": "INR",
-				"doctype": "Company",
-				"domain": "Manufacturing",
-				"monthly_sales_target": 2000,
-				"chart_of_accounts": "Standard"
-			},
-			{
-				"abbr": "_TC7",
-				"company_name": "_Test Company 7",
-				"country": "United States",
-				"default_currency": "USD",
-				"doctype": "Company",
-				"domain": "Retail",
-				"monthly_sales_target": 10000,
-				"total_monthly_sales": 1000,
-				"chart_of_accounts": "Standard"
-			},
-		]
-
-		make_test_objects('Company', test_records=test_records_company, reset=True)
-
 	def test_get_notifications_for_targets(self):
 		'''
 			Test notification config entries for targets as percentages
 		'''
 
+		company = frappe.get_all("Company")[0]
+		frappe.db.set_value("Company", company.name, "monthly_sales_target", 10000)
+		frappe.db.set_value("Company", company.name, "total_monthly_sales", 1000)
+
 		config = notifications.get_notification_config()
 		doc_target_percents = notifications.get_notifications_for_targets(config, {})
-		self.assertEqual(doc_target_percents['Company']['_Test Company 7'], 10)
-		self.assertEqual(doc_target_percents['Company']['_Test Company 6'], 0)
+
+		self.assertEqual(doc_target_percents['Company'][company.name], 10)
+
+		frappe.db.set_value("Company", company.name, "monthly_sales_target", 2000)
+		frappe.db.set_value("Company", company.name, "total_monthly_sales", 0)
+
+		config = notifications.get_notification_config()
+		doc_target_percents = notifications.get_notifications_for_targets(config, {})
+
+		self.assertEqual(doc_target_percents['Company'][company.name], 0)
diff --git a/test_sites/apps.txt b/test_sites/apps.txt
deleted file mode 100644
index ee64549..0000000
--- a/test_sites/apps.txt
+++ /dev/null
@@ -1 +0,0 @@
-erpnext
\ No newline at end of file
diff --git a/travis/bench_init.sh b/travis/bench_init.sh
deleted file mode 100755
index f96269b..0000000
--- a/travis/bench_init.sh
+++ /dev/null
@@ -1,8 +0,0 @@
-#!/bin/bash
-
-cd ~/
-curl -I https://github.com/frappe/frappe/tree/$TRAVIS_BRANCH | head -n 1 | cut -d $' ' -f2 | (
-	read response;
-	[ $response == '200' ] && branch=$TRAVIS_BRANCH || branch='develop';
-	bench init frappe-bench --frappe-path https://github.com/frappe/frappe.git --frappe-branch $branch --python $(which python)
-)
diff --git a/travis/run-tests.sh b/travis/run-tests.sh
deleted file mode 100755
index 7cfd648..0000000
--- a/travis/run-tests.sh
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/bin/bash
-
-set -e
-
-if [[ $TEST_TYPE == 'Server Side Test' ]]; then
-    bench run-tests --app erpnext --coverage
-
-elif [[ $TEST_TYPE == 'Patch Test' ]]; then
-    wget http://build.erpnext.com/20171108_190013_955977f8_database.sql.gz
-    bench --force restore ~/frappe-bench/20171108_190013_955977f8_database.sql.gz --mariadb-root-password travis
-    bench migrate
-fi