Merge pull request #14024 from ESS-LLP/jam_additional_sal_comp

Additional Salary Component
diff --git a/erpnext/accounts/doctype/cost_center/cost_center.js b/erpnext/accounts/doctype/cost_center/cost_center.js
index cbc37ff..a5bcaf4 100644
--- a/erpnext/accounts/doctype/cost_center/cost_center.js
+++ b/erpnext/accounts/doctype/cost_center/cost_center.js
@@ -15,8 +15,57 @@
 				}
 			}
 		})
+	},
+	refresh: function(frm) {
+		if (!frm.is_new()) {
+			frm.add_custom_button(__('Update Cost Center Number'), function () {
+				frm.trigger("update_cost_center_number");
+			});
+		}
+	},
+	update_cost_center_number: function(frm) {
+		var d = new frappe.ui.Dialog({
+			title: __('Update Cost Center Number'),
+			fields: [
+				{
+					"label": 'Cost Center Number',
+					"fieldname": "cost_center_number",
+					"fieldtype": "Data",
+					"reqd": 1
+				}
+			],
+			primary_action: function() {
+				var data = d.get_values();
+				if(data.cost_center_number === frm.doc.cost_center_number) {
+					d.hide();
+					return;
+				}
+				frappe.call({
+					method: "erpnext.accounts.doctype.cost_center.cost_center.update_number_field",
+					args: {
+						doctype_name: frm.doc.doctype,
+						name: frm.doc.name,
+						field_name: d.fields[0].fieldname,
+						field_value: data.cost_center_number,
+						company: frm.doc.company
+					},
+					callback: function(r) {
+						if(!r.exc) {
+							if(r.message) {
+								frappe.set_route("Form", "Cost Center", r.message);
+							} else {
+								me.set_value("cost_center_number", data.cost_center_number);
+							}
+							d.hide();
+						}
+					}
+				});
+			},
+			primary_action_label: __('Update')
+		});
+		d.show();
 	}
-})
+});
 
 cur_frm.cscript.refresh = function(doc, cdt, cdn) {
 	var intro_txt = '';
diff --git a/erpnext/accounts/doctype/cost_center/cost_center.json b/erpnext/accounts/doctype/cost_center/cost_center.json
index 9eddeec..4da21f1 100644
--- a/erpnext/accounts/doctype/cost_center/cost_center.json
+++ b/erpnext/accounts/doctype/cost_center/cost_center.json
@@ -1,5 +1,6 @@
 {
  "allow_copy": 1, 
+ "allow_guest_to_view": 0, 
  "allow_import": 1, 
  "allow_rename": 1, 
  "autoname": "field:cost_center_name", 
@@ -13,6 +14,7 @@
  "editable_grid": 0, 
  "fields": [
   {
+   "allow_bulk_edit": 0, 
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
@@ -38,9 +40,11 @@
    "reqd": 0, 
    "search_index": 0, 
    "set_only_once": 0, 
+   "translatable": 0, 
    "unique": 0
   }, 
   {
+   "allow_bulk_edit": 0, 
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
@@ -68,9 +72,42 @@
    "reqd": 1, 
    "search_index": 0, 
    "set_only_once": 0, 
+   "translatable": 0, 
    "unique": 0
   }, 
   {
+   "allow_bulk_edit": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
+   "fieldname": "cost_center_number", 
+   "fieldtype": "Data", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_global_search": 0, 
+   "in_list_view": 1, 
+   "in_standard_filter": 1, 
+   "label": "Cost Center Number", 
+   "length": 0, 
+   "no_copy": 0, 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 1, 
+   "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_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
@@ -99,9 +136,11 @@
    "reqd": 1, 
    "search_index": 0, 
    "set_only_once": 0, 
+   "translatable": 0, 
    "unique": 0
   }, 
   {
+   "allow_bulk_edit": 0, 
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
@@ -130,9 +169,11 @@
    "reqd": 1, 
    "search_index": 0, 
    "set_only_once": 0, 
+   "translatable": 0, 
    "unique": 0
   }, 
   {
+   "allow_bulk_edit": 0, 
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
@@ -157,10 +198,12 @@
    "reqd": 0, 
    "search_index": 0, 
    "set_only_once": 0, 
+   "translatable": 0, 
    "unique": 0, 
    "width": "50%"
   }, 
   {
+   "allow_bulk_edit": 0, 
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
@@ -188,9 +231,11 @@
    "reqd": 0, 
    "search_index": 0, 
    "set_only_once": 0, 
+   "translatable": 0, 
    "unique": 0
   }, 
   {
+   "allow_bulk_edit": 0, 
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
@@ -218,9 +263,11 @@
    "reqd": 0, 
    "search_index": 1, 
    "set_only_once": 0, 
+   "translatable": 0, 
    "unique": 0
   }, 
   {
+   "allow_bulk_edit": 0, 
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
@@ -248,9 +295,11 @@
    "reqd": 0, 
    "search_index": 1, 
    "set_only_once": 0, 
+   "translatable": 0, 
    "unique": 0
   }, 
   {
+   "allow_bulk_edit": 0, 
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
@@ -279,22 +328,23 @@
    "reqd": 0, 
    "search_index": 0, 
    "set_only_once": 0, 
+   "translatable": 0, 
    "unique": 0
   }
  ], 
+ "has_web_view": 0, 
  "hide_heading": 0, 
  "hide_toolbar": 0, 
  "icon": "fa fa-money", 
  "idx": 1, 
  "image_view": 0, 
  "in_create": 0, 
- "in_dialog": 0, 
  "is_submittable": 0, 
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
  "menu_index": 0, 
- "modified": "2017-02-17 16:22:27.129572", 
+ "modified": "2018-04-26 15:26:25.325778", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "Cost Center", 
@@ -302,7 +352,6 @@
  "permissions": [
   {
    "amend": 0, 
-   "apply_user_permissions": 0, 
    "cancel": 0, 
    "create": 1, 
    "delete": 1, 
@@ -322,7 +371,6 @@
   }, 
   {
    "amend": 0, 
-   "apply_user_permissions": 0, 
    "cancel": 0, 
    "create": 0, 
    "delete": 0, 
@@ -342,7 +390,6 @@
   }, 
   {
    "amend": 0, 
-   "apply_user_permissions": 0, 
    "cancel": 0, 
    "create": 0, 
    "delete": 0, 
@@ -362,7 +409,6 @@
   }, 
   {
    "amend": 0, 
-   "apply_user_permissions": 0, 
    "cancel": 0, 
    "create": 0, 
    "delete": 0, 
@@ -382,7 +428,6 @@
   }, 
   {
    "amend": 0, 
-   "apply_user_permissions": 0, 
    "cancel": 0, 
    "create": 0, 
    "delete": 0, 
diff --git a/erpnext/accounts/doctype/cost_center/cost_center.py b/erpnext/accounts/doctype/cost_center/cost_center.py
index fe1e907..24af0ce 100644
--- a/erpnext/accounts/doctype/cost_center/cost_center.py
+++ b/erpnext/accounts/doctype/cost_center/cost_center.py
@@ -4,6 +4,7 @@
 from __future__ import unicode_literals
 import frappe
 from frappe import _
+from frappe.utils import cint, cstr
 from frappe.utils.nestedset import NestedSet
 
 class CostCenter(NestedSet):
@@ -62,8 +63,68 @@
 		super(CostCenter, self).after_rename(olddn, newdn, merge)
 
 		if not merge:
-			frappe.db.set_value("Cost Center", newdn, "cost_center_name",
-				" - ".join(newdn.split(" - ")[:-1]))
+			new_cost_center = frappe.db.get_value("Cost Center", newdn, ["cost_center_name", "cost_center_number"], as_dict=1)
+
+			# exclude company abbr
+			new_parts = newdn.split(" - ")[:-1]
+			# update cost center number and remove from parts
+			if new_parts[0][0].isdigit():
+				if len(new_parts) == 1:
+					new_parts = newdn.split(" ")
+				if new_cost_center.cost_center_number != new_parts[0]:
+					validate_field_number("Cost Center", self.name, new_parts[0], self.company, "cost_center_number")
+					self.cost_center_number = new_parts[0]
+					self.db_set("cost_center_number", new_parts[0])
+				new_parts = new_parts[1:]
+
+			# update cost center name
+			cost_center_name = " - ".join(new_parts)
+			if new_cost_center.cost_center_name != cost_center_name:
+				self.cost_center_name = cost_center_name
+				self.db_set("cost_center_name", cost_center_name)
 
 def on_doctype_update():
-	frappe.db.add_index("Cost Center", ["lft", "rgt"])
\ No newline at end of file
+	frappe.db.add_index("Cost Center", ["lft", "rgt"])
+
+def get_doc_name_autoname(field_value, doc_title, name, company):
+	if company:
+		name_split=name.split("-")
+		parts = [doc_title.strip(), name_split[len(name_split)-1].strip()]
+	else:
+		parts = [doc_title.strip()]
+	if cstr(field_value).strip():
+		parts.insert(0, cstr(field_value).strip())
+	return ' - '.join(parts)
+
+def validate_field_number(doctype_name, name, field_value, company, field_name):
+	if field_value:
+		if company:
+			doctype_with_same_number = frappe.db.get_value(doctype_name,
+				{field_name: field_value, "company": company, "name": ["!=", name]})
+		else:
+			doctype_with_same_number = frappe.db.get_value(doctype_name,
+				{field_name: field_value, "name": ["!=", name]})
+		if doctype_with_same_number:
+			frappe.throw(_("{0} Number {1} already used in account {2}")
+				.format(doctype_name, field_value, doctype_with_same_number))
+
+@frappe.whitelist()
+def update_number_field(doctype_name, name, field_name, field_value, company):
+
+	doc_title = frappe.db.get_value(doctype_name, name, frappe.scrub(doctype_name)+"_name")
+
+	validate_field_number(doctype_name, name, field_value, company, field_name)
+
+	frappe.db.set_value(doctype_name, name, field_name, field_value)
+
+	if doc_title[0].isdigit():
+		separator = " - " if " - " in doc_title else " "
+		doc_title = doc_title.split(separator, 1)[1]
+
+	frappe.db.set_value(doctype_name, name, frappe.scrub(doctype_name)+"_name", doc_title)
+
+	new_name = get_doc_name_autoname(field_value, doc_title, name, company)
+
+	if name != new_name:
+		frappe.rename_doc(doctype_name, name, new_name)
+		return new_name		
\ No newline at end of file
diff --git a/erpnext/assets/doctype/asset/asset.js b/erpnext/assets/doctype/asset/asset.js
index 236c4f9..f4a01ae 100644
--- a/erpnext/assets/doctype/asset/asset.js
+++ b/erpnext/assets/doctype/asset/asset.js
@@ -23,6 +23,14 @@
 				}
 			};
 		});
+
+		frm.set_query("department", function() {
+			return {
+				"filters": {
+					"company": frm.doc.company,
+				}
+			};
+		});
 	},
 
 	refresh: function(frm) {
diff --git a/erpnext/education/doctype/instructor/instructor.js b/erpnext/education/doctype/instructor/instructor.js
index 62d73b3..f9c7a2a 100644
--- a/erpnext/education/doctype/instructor/instructor.js
+++ b/erpnext/education/doctype/instructor/instructor.js
@@ -1,31 +1,53 @@
 cur_frm.add_fetch("employee", "department", "department");
 cur_frm.add_fetch("employee", "image", "image");
 
-frappe.ui.form.on("Instructor", "refresh", function(frm) {
-	if(!frm.doc.__islocal) {
-		frm.add_custom_button(__("Student Group"), function() {
-			frappe.route_options = {
-				instructor: frm.doc.name
-			}
-			frappe.set_route("List", "Student Group");
+frappe.ui.form.on("Instructor", {
+	employee: function(frm) {
+		if(!frm.doc.employee) return;
+		frappe.db.get_value('Employee', {name: frm.doc.employee}, 'company', (company) => {
+			frm.set_query("department", function() {
+				return {
+					"filters": {
+						"company": company,
+					}
+				};
+			});
+
+			frm.set_query("department", "instructor_log", function() {
+				return {
+					"filters": {
+						"company": company,
+					}
+				};
+			});
 		});
-		frm.add_custom_button(__("Course Schedule"), function() {
-			frappe.route_options = {
-				instructor: frm.doc.name
-			}
-			frappe.set_route("List", "Course Schedule");
-		});
-		frm.add_custom_button(__("As Examiner"), function() {
-			frappe.route_options = {
-				examiner: frm.doc.name
-			}
-			frappe.set_route("List", "Assessment Plan");
-		}, __("Assessment Plan"));
-		frm.add_custom_button(__("As Supervisor"), function() {
-			frappe.route_options = {
-				supervisor: frm.doc.name
-			}
-			frappe.set_route("List", "Assessment Plan");
-		}, __("Assessment Plan"));
+	},
+	refresh: function(frm) {
+		if(!frm.doc.__islocal) {
+			frm.add_custom_button(__("Student Group"), function() {
+				frappe.route_options = {
+					instructor: frm.doc.name
+				}
+				frappe.set_route("List", "Student Group");
+			});
+			frm.add_custom_button(__("Course Schedule"), function() {
+				frappe.route_options = {
+					instructor: frm.doc.name
+				}
+				frappe.set_route("List", "Course Schedule");
+			});
+			frm.add_custom_button(__("As Examiner"), function() {
+				frappe.route_options = {
+					examiner: frm.doc.name
+				}
+				frappe.set_route("List", "Assessment Plan");
+			}, __("Assessment Plan"));
+			frm.add_custom_button(__("As Supervisor"), function() {
+				frappe.route_options = {
+					supervisor: frm.doc.name
+				}
+				frappe.set_route("List", "Assessment Plan");
+			}, __("Assessment Plan"));
+		}
 	}
 });
diff --git a/erpnext/hr/doctype/department/department.json b/erpnext/hr/doctype/department/department.json
index a1c8dc1..664679d 100644
--- a/erpnext/hr/doctype/department/department.json
+++ b/erpnext/hr/doctype/department/department.json
@@ -3,7 +3,7 @@
  "allow_guest_to_view": 0, 
  "allow_import": 1, 
  "allow_rename": 1, 
- "autoname": "field:department_name", 
+ "autoname": "",
  "beta": 0, 
  "creation": "2013-02-05 11:48:26", 
  "custom": 0, 
@@ -434,7 +434,7 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2018-04-18 12:02:42.572599", 
+ "modified": "2018-05-11 12:18:18.839182",
  "modified_by": "Administrator", 
  "module": "HR", 
  "name": "Department", 
diff --git a/erpnext/hr/doctype/department/department.py b/erpnext/hr/doctype/department/department.py
index fda1b69..19994ae 100644
--- a/erpnext/hr/doctype/department/department.py
+++ b/erpnext/hr/doctype/department/department.py
@@ -10,6 +10,10 @@
 class Department(NestedSet):
 	nsm_parent_field = 'parent_department'
 
+	def autoname(self):
+		abbr = frappe.db.get_value('Company', self.company, 'abbr')
+		self.name = '{0} - {1}'.format(self.department_name, abbr)
+
 	def update_nsm_model(self):
 		frappe.utils.nestedset.update_nsm(self)
 
@@ -21,4 +25,23 @@
 		delete_events(self.doctype, self.name)
 
 def on_doctype_update():
-	frappe.db.add_index("Department", ["lft", "rgt"])
\ No newline at end of file
+	frappe.db.add_index("Department", ["lft", "rgt"])
+
+@frappe.whitelist()
+def get_children(doctype, parent=None, company=None, is_root=False):
+	condition = ''
+	if company == parent:
+		condition = 'name="All Departments"'
+	elif company:
+		condition = "parent_department='{0}' and company='{1}'".format(parent, company)
+	else:
+		condition = "parent_department = '{0}'".format(parent)
+
+	return frappe.db.sql("""
+		select
+			name as value,
+			is_group as expandable
+		from `tab{doctype}`
+		where
+			{condition}
+		order by name""".format(doctype=doctype, condition=condition), as_dict=1)
diff --git a/erpnext/hr/doctype/department/department_tree.js b/erpnext/hr/doctype/department/department_tree.js
index 5652ad6..1f891fd 100644
--- a/erpnext/hr/doctype/department/department_tree.js
+++ b/erpnext/hr/doctype/department/department_tree.js
@@ -1,3 +1,27 @@
 frappe.treeview_settings["Department"] = {
-	ignore_fields:["parent_department"]
+	ignore_fields:["parent_department"],
+	get_tree_nodes: 'erpnext.hr.doctype.department.department.get_children',
+	filters: [
+		{
+			fieldname: "company",
+			fieldtype:"Link",
+			options: "Company",
+			label: __("Company"),
+		},
+	],
+	breadcrumb: "HR",
+	root_label: "All Departments",
+	get_tree_root: true,
+	menu_items: [
+		{
+			label: __("New Department"),
+			action: function() {
+				frappe.new_doc("Department", true);
+			},
+			condition: 'frappe.boot.user.can_create.indexOf("Department") !== -1'
+		}
+	],
+	onload: function(treeview) {
+		treeview.make_tree();
+	}
 };
\ No newline at end of file
diff --git a/erpnext/hr/doctype/employee/employee.js b/erpnext/hr/doctype/employee/employee.js
index 240411d..6f6873a 100755
--- a/erpnext/hr/doctype/employee/employee.js
+++ b/erpnext/hr/doctype/employee/employee.js
@@ -37,6 +37,15 @@
 
 });
 frappe.ui.form.on('Employee',{
+	onload:function(frm) {
+		frm.set_query("department", function() {
+			return {
+				"filters": {
+					"company": frm.doc.company,
+				}
+			};
+		});
+	},
 	prefered_contact_email:function(frm){		
 		frm.events.update_contact(frm)		
 	},
diff --git a/erpnext/hr/doctype/job_opening/job_opening.js b/erpnext/hr/doctype/job_opening/job_opening.js
index 960f5b3..7b0e447 100644
--- a/erpnext/hr/doctype/job_opening/job_opening.js
+++ b/erpnext/hr/doctype/job_opening/job_opening.js
@@ -2,6 +2,15 @@
 // For license information, please see license.txt
 
 frappe.ui.form.on('Job Opening', {
+	onload: function(frm) {
+		frm.set_query("department", function() {
+			return {
+				"filters": {
+					"company": frm.doc.company,
+				}
+			};
+		});
+	},
 	designation: function(frm) {
 		if(frm.doc.designation && frm.doc.company){
 			frappe.call({
diff --git a/erpnext/hr/doctype/leave_control_panel/leave_control_panel.js b/erpnext/hr/doctype/leave_control_panel/leave_control_panel.js
index 0eb6414..7aeb8ea 100644
--- a/erpnext/hr/doctype/leave_control_panel/leave_control_panel.js
+++ b/erpnext/hr/doctype/leave_control_panel/leave_control_panel.js
@@ -26,6 +26,19 @@
 	refresh_field('no_of_days');
 }
 
-frappe.ui.form.on("Leave Control Panel", "refresh", function (frm) {
-	frm.disable_save();
+frappe.ui.form.on("Leave Control Panel", {
+	company: function(frm) {
+		if(frm.doc.company) {
+			frm.set_query("department", function() {
+				return {
+					"filters": {
+						"company": frm.doc.company,
+					}
+				};
+			});
+		}
+	},
+	refresh: function(frm) {
+		frm.disable_save();
+	}
 });
\ No newline at end of file
diff --git a/erpnext/hr/doctype/leave_period/leave_period.js b/erpnext/hr/doctype/leave_period/leave_period.js
index 2a6010e..a54147d 100644
--- a/erpnext/hr/doctype/leave_period/leave_period.js
+++ b/erpnext/hr/doctype/leave_period/leave_period.js
@@ -2,7 +2,13 @@
 // For license information, please see license.txt
 
 frappe.ui.form.on('Leave Period', {
-	refresh: function(frm) {
-
+	onload: function(frm) {
+		frm.set_query("department", function() {
+			return {
+				"filters": {
+					"company": frm.doc.company,
+				}
+			};
+		});
 	}
 });
diff --git a/erpnext/hr/doctype/payroll_entry/payroll_entry.js b/erpnext/hr/doctype/payroll_entry/payroll_entry.js
index 1e6dc51..d02e1f1 100644
--- a/erpnext/hr/doctype/payroll_entry/payroll_entry.js
+++ b/erpnext/hr/doctype/payroll_entry/payroll_entry.js
@@ -9,6 +9,14 @@
 			frm.doc.posting_date = frappe.datetime.nowdate();
 		}
 		frm.toggle_reqd(['payroll_frequency'], !frm.doc.salary_slip_based_on_timesheet);
+
+		frm.set_query("department", function() {
+			return {
+				"filters": {
+					"company": frm.doc.company,
+				}
+			};
+		});
 	},
 
 	refresh: function(frm) {
diff --git a/erpnext/hr/doctype/staffing_plan/staffing_plan.js b/erpnext/hr/doctype/staffing_plan/staffing_plan.js
index 1c1a720..ca57d9f 100644
--- a/erpnext/hr/doctype/staffing_plan/staffing_plan.js
+++ b/erpnext/hr/doctype/staffing_plan/staffing_plan.js
@@ -17,6 +17,14 @@
 				]
 			}
 		});
+
+		frm.set_query("department", function() {
+			return {
+				"filters": {
+					"company": frm.doc.company,
+				}
+			};
+		});
 	}
 });
 
diff --git a/erpnext/hr/utils.py b/erpnext/hr/utils.py
index 057f406..686f791 100644
--- a/erpnext/hr/utils.py
+++ b/erpnext/hr/utils.py
@@ -49,3 +49,20 @@
 			new_data = get_datetime(new_data)
 		setattr(employee, item.fieldname, new_data)
 	return employee
+
+def get_leave_period(from_date, to_date, company):
+	leave_period = frappe.db.sql("""
+		select name, from_date, to_date
+		from `tabLeave Period`
+		where company=%(company)s and is_active=1
+			and (from_date between %(from_date)s and %(to_date)s
+				or to_date between %(from_date)s and %(to_date)s
+				or (from_date < %(from_date)s and to_date > %(to_date)s))
+	""", {
+		"from_date": from_date,
+		"to_date": to_date,
+		"company": company
+	}, as_dict=1)
+
+	if leave_period:
+		return leave_period
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index 3fffade..4bbb3e9 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -527,3 +527,4 @@
 erpnext.patches.v11_0.create_salary_structure_assignments
 erpnext.patches.v11_0.rename_health_insurance
 erpnext.patches.v11_0.rebuild_tree_for_company
+erpnext.patches.v11_0.create_department_records_for_each_company
diff --git a/erpnext/patches/v11_0/create_department_records_for_each_company.py b/erpnext/patches/v11_0/create_department_records_for_each_company.py
new file mode 100644
index 0000000..9407185
--- /dev/null
+++ b/erpnext/patches/v11_0/create_department_records_for_each_company.py
@@ -0,0 +1,73 @@
+import frappe
+from frappe.utils.nestedset import rebuild_tree
+
+def execute():
+	frappe.reload_doc("hr", "doctype", "department")
+	companies = frappe.db.get_all("Company", fields=["name", "abbr"])
+	departments = frappe.db.get_all("Department")
+	comp_dict = {}
+
+	# create a blank list for each company
+	for company in companies:
+		comp_dict[company.name] = {}
+
+	for department in departments:
+		# skip root node
+		if department.name == "All Departments":
+			continue
+
+		# for each company, create a copy of the doc
+		department_doc = frappe.get_doc("Department", department)
+		for company in companies:
+			copy_doc = frappe.copy_doc(department_doc)
+			copy_doc.update({"company": company.name})
+			copy_doc.insert()
+
+			# append list of new department for each company
+			comp_dict[company.name][department.name] = copy_doc.name
+
+	rebuild_tree('Department', 'parent_department')
+	doctypes = ["Asset", "Employee", "Leave Period", "Payroll Entry", "Staffing Plan", "Job Opening"]
+
+	for d in doctypes:
+		update_records(d, comp_dict)
+
+	update_instructors(comp_dict)
+
+def update_records(doctype, comp_dict):
+	when_then = []
+	for company in comp_dict:
+		records = comp_dict[company]
+
+		for department in records:
+			when_then.append('''
+				WHEN company = "%s" and department = "%s"
+				THEN "%s"
+			'''%(company, department, records[department]))
+
+	frappe.db.sql("""
+		update
+			`tab%s`
+		set
+			department = CASE %s END
+	"""%(doctype, " ".join(when_then)))
+
+def update_instructors(comp_dict):
+	when_then = []
+	emp_details = frappe.get_all("Employee", fields=["name", "company"])
+
+	for employee in emp_details:
+		records = comp_dict[employee.company]
+
+		for department in records:
+			when_then.append('''
+				WHEN employee = "%s" and department = "%s"
+				THEN "%s"
+			'''%(employee.name, department, records[department]))
+
+	frappe.db.sql("""
+		update
+			`tabInstructor`
+		set
+			department = CASE %s END
+	"""%(" ".join(when_then)))
diff --git a/erpnext/setup/doctype/company/company.json b/erpnext/setup/doctype/company/company.json
index 66b1433..d236dda 100644
--- a/erpnext/setup/doctype/company/company.json
+++ b/erpnext/setup/doctype/company/company.json
@@ -456,7 +456,38 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "fieldname": "default_letter_head", 
+   "fieldname": "default_currency",
+   "fieldtype": "Link", 
+   "hidden": 0, 
+   "ignore_user_permissions": 1,
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_global_search": 0, 
+   "in_list_view": 0, 
+   "in_standard_filter": 0, 
+   "label": "Default Currency",
+   "length": 0, 
+   "no_copy": 0, 
+   "options": "Currency",
+   "permlevel": 0, 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 0, 
+   "remember_last_selected_value": 0, 
+   "report_hide": 0, 
+   "reqd": 1,
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "translatable": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
+   "fieldname": "default_letter_head",
    "fieldtype": "Link", 
    "hidden": 0, 
    "ignore_user_permissions": 0, 
@@ -465,10 +496,10 @@
    "in_global_search": 0, 
    "in_list_view": 0, 
    "in_standard_filter": 0, 
-   "label": "Default Letter Head", 
+   "label": "Default Letter Head",
    "length": 0, 
    "no_copy": 0, 
-   "options": "Letter Head", 
+   "options": "Letter Head",
    "permlevel": 0, 
    "precision": "", 
    "print_hide": 0, 
@@ -488,7 +519,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "fieldname": "default_holiday_list", 
+   "fieldname": "default_holiday_list",
    "fieldtype": "Link", 
    "hidden": 0, 
    "ignore_user_permissions": 0, 
@@ -497,12 +528,12 @@
    "in_global_search": 0, 
    "in_list_view": 0, 
    "in_standard_filter": 0, 
-   "label": "Default Holiday List", 
+   "label": "Default Holiday List",
    "length": 0, 
    "no_copy": 0, 
-   "options": "Holiday List", 
+   "options": "Holiday List",
    "permlevel": 0, 
-   "precision": "", 
+   "precision": "",
    "print_hide": 0, 
    "print_hide_if_no_value": 0, 
    "read_only": 0, 
@@ -520,57 +551,26 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "fieldname": "default_terms", 
+   "fieldname": "default_terms",
    "fieldtype": "Link", 
    "hidden": 0, 
-   "ignore_user_permissions": 0, 
+   "ignore_user_permissions": 0,
    "ignore_xss_filter": 0, 
    "in_filter": 0, 
    "in_global_search": 0, 
    "in_list_view": 0, 
    "in_standard_filter": 0, 
-   "label": "Default Terms", 
+   "label": "Default Terms",
    "length": 0, 
    "no_copy": 0, 
-   "options": "Terms and Conditions", 
+   "options": "Terms and Conditions",
    "permlevel": 0, 
    "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_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "default_currency", 
-   "fieldtype": "Link", 
-   "hidden": 0, 
-   "ignore_user_permissions": 1, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "label": "Default Currency", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "Currency", 
-   "permlevel": 0, 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 1, 
+   "reqd": 0,
    "search_index": 0, 
    "set_only_once": 0, 
    "translatable": 0,