Merge pull request #5752 from KanchanChauhan/employee-holiday-attendance-report-renamed

Employee Attendance report renamed to Employees working on a holiday
diff --git a/erpnext/controllers/item_variant.py b/erpnext/controllers/item_variant.py
index 3ff3d88..8294b64 100644
--- a/erpnext/controllers/item_variant.py
+++ b/erpnext/controllers/item_variant.py
@@ -24,22 +24,23 @@
 	if not args:
 		frappe.throw(_("Please specify at least one attribute in the Attributes table"))
 
-	validate_item_variant_attributes(template, args)
-
 	return find_variant(template, args, variant)
 
 def validate_item_variant_attributes(item, args=None):
+	if isinstance(item, basestring):
+		item = frappe.get_doc('Item', item)
+
 	if not args:
 		args = {d.attribute.lower():d.attribute_value for d in item.attributes}
 
-	attribute_values = get_attribute_values()
-
-	numeric_attributes = frappe._dict({d.attribute.lower(): d for d
-		in item.attributes if d.numeric_values==1})
+	attribute_values, numeric_values = get_attribute_values()
 
 	for attribute, value in args.items():
-		if attribute.lower() in numeric_attributes:
-			numeric_attribute = numeric_attributes[attribute.lower()]
+		if not value:
+			continue
+
+		if attribute.lower() in numeric_values:
+			numeric_attribute = numeric_values[attribute.lower()]
 
 			from_range = numeric_attribute.from_range
 			to_range = numeric_attribute.to_range
@@ -57,22 +58,28 @@
 			is_incremental = remainder==0 or remainder==increment
 
 			if not (is_in_range and is_incremental):
-				frappe.throw(_("Value for Attribute {0} must be within the range of {1} to {2} in the increments of {3}")\
-					.format(attribute, from_range, to_range, increment), InvalidItemAttributeValueError)
+				frappe.throw(_("Value for Attribute {0} must be within the range of {1} to {2} in the increments of {3} for Item {2}")\
+					.format(attribute, from_range, to_range, increment, item.name), InvalidItemAttributeValueError)
 
 		elif value not in attribute_values.get(attribute.lower(), []):
-			frappe.throw(_("Value {0} for Attribute {1} does not exist in the list of valid Item Attribute Values").format(
-				value, attribute), InvalidItemAttributeValueError)
+			frappe.throw(_("Value {0} for Attribute {1} does not exist in the list of valid Item Attribute Values for Item {2}").format(
+				value, attribute, item.name), InvalidItemAttributeValueError)
 
 def get_attribute_values():
 	if not frappe.flags.attribute_values:
 		attribute_values = {}
+		numeric_values = {}
 		for t in frappe.get_all("Item Attribute Value", fields=["parent", "attribute_value"]):
-			(attribute_values.setdefault(t.parent.lower(), [])).append(t.attribute_value)
+			attribute_values.setdefault(t.parent.lower(), []).append(t.attribute_value)
+
+		for t in frappe.get_all('Item Attribute',
+			fields=["name", "from_range", "to_range", "increment"], filters={'numeric_values': 1}):
+			numeric_values[t.name.lower()] = t
 
 		frappe.flags.attribute_values = attribute_values
+		frappe.flags.numeric_values = numeric_values
 
-	return frappe.flags.attribute_values
+	return frappe.flags.attribute_values, frappe.flags.numeric_values
 
 def find_variant(template, args, variant_item_code=None):
 	conditions = ["""(iv_attribute.attribute="{0}" and iv_attribute.attribute_value="{1}")"""\
@@ -126,7 +133,7 @@
 
 	variant.set("attributes", variant_attributes)
 	copy_attributes_to_variant(template, variant)
-	make_variant_item_code(template, variant)
+	make_variant_item_code(template.item_code, variant)
 
 	return variant
 
@@ -144,7 +151,7 @@
 		for d in variant.attributes:
 			variant.description += "<p>" + d.attribute + ": " + cstr(d.attribute_value) + "</p>"
 
-def make_variant_item_code(template, variant):
+def make_variant_item_code(template_item_code, variant):
 	"""Uses template's item code and abbreviations to make variant's item code"""
 	if variant.item_code:
 		return
@@ -160,8 +167,10 @@
 			}, as_dict=True)
 
 		if not item_attribute:
-			# somehow an invalid item attribute got used
 			return
+			# frappe.throw(_('Invalid attribute {0} {1}').format(frappe.bold(attr.attribute),
+			# 	frappe.bold(attr.attribute_value)), title=_('Invalid Attribute'),
+			# 	exc=InvalidItemAttributeValueError)
 
 		if item_attribute[0].numeric_values:
 			# don't generate item code if one of the attributes is numeric
@@ -170,7 +179,7 @@
 		abbreviations.append(item_attribute[0].abbr)
 
 	if abbreviations:
-		variant.item_code = "{0}-{1}".format(template.item_code, "-".join(abbreviations))
+		variant.item_code = "{0}-{1}".format(template_item_code, "-".join(abbreviations))
 
 	if variant.item_code:
 		variant.item_name = variant.item_code
diff --git a/erpnext/crm/doctype/opportunity/opportunity.py b/erpnext/crm/doctype/opportunity/opportunity.py
index 69a04c6..1e57878 100644
--- a/erpnext/crm/doctype/opportunity/opportunity.py
+++ b/erpnext/crm/doctype/opportunity/opportunity.py
@@ -54,6 +54,7 @@
 					email_name = self.contact_email[0:self.contact_email.index('@')]
 
 					email_split = email_name.split('.')
+					sender_name = ''
 					for s in email_split:
 						sender_name += s.capitalize() + ' '
 
@@ -189,11 +190,11 @@
 def make_quotation(source_name, target_doc=None):
 	def set_missing_values(source, target):
 		quotation = frappe.get_doc(target)
-		
+
 		company_currency = frappe.db.get_value("Company", quotation.company, "default_currency")
-		party_account_currency = get_party_account_currency("Customer", quotation.customer, 
+		party_account_currency = get_party_account_currency("Customer", quotation.customer,
 			quotation.company) if quotation.customer else company_currency
-		
+
 		quotation.currency = party_account_currency or company_currency
 
 		if company_currency == quotation.currency:
diff --git a/erpnext/demo/data/bom.json b/erpnext/demo/data/bom.json
index 1c3f7a9..3085435 100644
--- a/erpnext/demo/data/bom.json
+++ b/erpnext/demo/data/bom.json
@@ -100,7 +100,7 @@
   ]
  },
  {
-  "item": "Wind Turbine",
+  "item": "Wind Turbine-S",
   "with_operations": 1,
   "operations": [
    {
diff --git a/erpnext/demo/demo.py b/erpnext/demo/demo.py
index 6642e7b..4188432 100644
--- a/erpnext/demo/demo.py
+++ b/erpnext/demo/demo.py
@@ -4,7 +4,7 @@
 import erpnext
 import frappe.utils
 from erpnext.demo.setup_data import setup_data
-from erpnext.demo.user import hr, sales, purchase, manufacturing, stock, accounts
+from erpnext.demo.user import hr, sales, purchase, manufacturing, stock, accounts, projects
 
 """
 Make a demo
@@ -69,6 +69,9 @@
 		manufacturing.work()
 		stock.work()
 		accounts.work()
+		projects.run_projects(current_date)
+		# run_stock()
+		# run_accounts()
 		# run_projects()
 		# run_messages()
 
diff --git a/erpnext/demo/setup_data.py b/erpnext/demo/setup_data.py
index 6f1fb0a..5245063 100644
--- a/erpnext/demo/setup_data.py
+++ b/erpnext/demo/setup_data.py
@@ -3,7 +3,7 @@
 import random, json
 from erpnext.demo.domains import data
 import frappe, erpnext
-import frappe.utils
+from frappe.utils import cint, flt
 
 def setup_data():
 	domain = frappe.flags.domain
@@ -27,6 +27,7 @@
 	setup_user()
 	setup_employee()
 	setup_salary_structure()
+	setup_salary_structure_for_timesheet()
 	setup_user_roles()
 	frappe.db.commit()
 	frappe.clear_cache()
@@ -286,6 +287,14 @@
 		})
 
 		ss.insert()
+		
+def setup_salary_structure_for_timesheet():
+	for e in frappe.get_all('Salary Structure', fields=['name'], filters={'is_active': 'Yes'}, limit=2):
+		ss_doc = frappe.get_doc("Salary Structure", e.name)
+		ss_doc.salary_slip_based_on_timesheet = 1
+		ss_doc.salary_component = 'Basic'
+		ss_doc.hour_rate = flt(random.random() * 10, 2)
+		ss_doc.save(ignore_permissions=True)
 
 def setup_account():
 	frappe.flags.in_import = True
@@ -332,4 +341,9 @@
 		user = frappe.get_doc('User', 'LeonAbdulov@example.com')
 		user.add_roles('Accounts User', 'Accounts Manager', 'Sales User', 'Purchase User')
 		frappe.db.set_global('demo_accounts_user', user.name)
+		
+	if not frappe.db.get_global('demo_projects_user'):
+		user = frappe.get_doc('User', 'panca@example.com')
+		user.add_roles('HR User', 'Projects User')
+		frappe.db.set_global('demo_projects_user', user.name)
 
diff --git a/erpnext/demo/user/hr.py b/erpnext/demo/user/hr.py
index 8196701..86fb526 100644
--- a/erpnext/demo/user/hr.py
+++ b/erpnext/demo/user/hr.py
@@ -1,10 +1,13 @@
 from __future__ import unicode_literals
 import frappe
+import random
 from frappe.utils import random_string
+from erpnext.projects.doctype.timesheet.test_timesheet import make_timesheet
+from erpnext.projects.doctype.timesheet.timesheet import make_salary_slip, make_sales_invoice
+from frappe.utils.make_random import how_many, get_random
 
 def work():
 	frappe.set_user(frappe.db.get_global('demo_hr_user'))
-
 	year, month = frappe.flags.current_date.strftime("%Y-%m").split("-")
 
 	# process payroll
@@ -24,3 +27,45 @@
 		journal_entry.posting_date = frappe.flags.current_date
 		journal_entry.insert()
 		journal_entry.submit()
+	
+	if frappe.db.get_global('demo_hr_user'):
+		make_timesheet_records()
+
+def get_timesheet_based_salary_slip_employee():
+	return frappe.get_all('Salary Structure', fields = ["distinct employee as name"],
+		filters = {'salary_slip_based_on_timesheet': 1})
+	
+def make_timesheet_records():
+	employees = get_timesheet_based_salary_slip_employee()
+	for employee in employees:
+		ts = make_timesheet(employee.name, simulate = True, billable = 1, activity_type=get_random("Activity Type"))
+
+		rand = random.random()
+		if rand >= 0.3:
+			make_salary_slip_for_timesheet(ts.name)
+
+		rand = random.random()
+		if rand >= 0.2:
+			make_sales_invoice_for_timesheet(ts.name)
+
+def make_salary_slip_for_timesheet(name):
+	salary_slip = make_salary_slip(name)
+	salary_slip.insert()
+	salary_slip.submit()
+
+def make_sales_invoice_for_timesheet(name):
+	sales_invoice = make_sales_invoice(name)
+	sales_invoice.customer = get_random("Customer")
+	sales_invoice.append('items', {
+		'item_code': get_random_item(),
+		'qty': 1,
+		'rate': 1000
+	})
+	sales_invoice.set_missing_values()
+	sales_invoice.calculate_taxes_and_totals()
+	sales_invoice.insert()
+	sales_invoice.submit()
+
+def get_random_item():
+	return frappe.db.sql_list(""" select name from `tabItem` where
+		has_variants = 0 order by rand() limit 1""")[0]
diff --git a/erpnext/demo/user/manufacturing.py b/erpnext/demo/user/manufacturing.py
index c91570c..80d140a 100644
--- a/erpnext/demo/user/manufacturing.py
+++ b/erpnext/demo/user/manufacturing.py
@@ -6,6 +6,8 @@
 import frappe, random, erpnext
 from frappe.utils.make_random import how_many
 from frappe.desk import query_report
+from erpnext.manufacturing.doctype.workstation.workstation import WorkstationHolidayError
+from erpnext.manufacturing.doctype.production_order.test_production_order import make_prod_order_test_record
 
 def work():
 	frappe.set_user(frappe.db.get_global('demo_manufacturing_user'))
@@ -46,6 +48,13 @@
 		for pro in query_report.run("Production Orders in Progress")["result"][:how_many("Stock Entry for FG")]:
 			make_stock_entry_from_pro(pro[0], "Manufacture")
 
+	for bom in frappe.get_all('BOM', fields=['item'], filters = {'with_operations': 1}):
+		pro_order = make_prod_order_test_record(item=bom.item, qty=2,
+			source_warehouse="Stores - WPL", wip_warehouse = "Work in Progress - WPL",
+			fg_warehouse = "Stores - WPL", company = erpnext.get_default_company(),
+			stock_uom = frappe.db.get_value('Item', bom.item, 'stock_uom'),
+			planned_start_date = frappe.flags.current_date)
+
 	# submit time logs
 	for timesheet in frappe.get_all("Timesheet", ["name"], {"docstatus": 0,
 		"production_order": ("!=", ""), "to_time": ("<", frappe.flags.current_date)}):
@@ -55,6 +64,8 @@
 			frappe.db.commit()
 		except OverlapError:
 			pass
+		except WorkstationHolidayError:
+			pass
 
 def make_stock_entry_from_pro(pro_id, purpose):
 	from erpnext.manufacturing.doctype.production_order.production_order import make_stock_entry
diff --git a/erpnext/demo/user/projects.py b/erpnext/demo/user/projects.py
new file mode 100644
index 0000000..12fad29
--- /dev/null
+++ b/erpnext/demo/user/projects.py
@@ -0,0 +1,95 @@
+# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
+# License: GNU General Public License v3. See license.txt
+
+from __future__ import unicode_literals
+
+import frappe
+from frappe.utils.make_random import can_make
+from frappe.utils.make_random import how_many, get_random
+from erpnext.projects.doctype.timesheet.test_timesheet import make_timesheet
+
+def run_projects(current_date):
+	frappe.set_user(frappe.db.get_global('demo_projects_user'))
+	if frappe.db.get_global('demo_projects_user'):
+		make_project(current_date)
+		make_timesheet_for_projects(current_date)
+		close_tasks(current_date)
+
+def make_timesheet_for_projects(current_date	):
+	for data in frappe.get_all("Task", ["name", "project"], {"status": "Open", "exp_end_date": ("<", current_date)}):
+		employee = get_random("Employee")
+		if frappe.db.get_value('Salary Structure', {'employee': employee}, 'salary_slip_based_on_timesheet'):
+			make_timesheet(employee, simulate = True, billable = 1, 
+				activity_type=get_random("Activity Type"), project=data.project, task =data.name)
+
+def close_tasks(current_date):
+	for task in frappe.get_all("Task", ["name"], {"status": "Open", "exp_end_date": ("<", current_date)}):
+		task = frappe.get_doc("Task", task.name)
+		task.status = "Closed"
+		task.save()
+
+def make_project(current_date):
+	if not frappe.db.exists('Project', 
+		"New Product Development " + current_date.strftime("%Y-%m-%d")):
+		project = frappe.get_doc({
+			"doctype": "Project",
+			"project_name": "New Product Development " + current_date.strftime("%Y-%m-%d"),
+		})
+		project.set("tasks", [
+				{
+					"title": "Review Requirements",
+					"start_date": frappe.utils.add_days(current_date, 10),
+					"end_date": frappe.utils.add_days(current_date, 11)
+				},
+				{
+					"title": "Design Options",
+					"start_date": frappe.utils.add_days(current_date, 11),
+					"end_date": frappe.utils.add_days(current_date, 20)
+				},
+				{
+					"title": "Make Prototypes",
+					"start_date": frappe.utils.add_days(current_date, 20),
+					"end_date": frappe.utils.add_days(current_date, 30)
+				},
+				{
+					"title": "Customer Feedback on Prototypes",
+					"start_date": frappe.utils.add_days(current_date, 30),
+					"end_date": frappe.utils.add_days(current_date, 40)
+				},
+				{
+					"title": "Freeze Feature Set",
+					"start_date": frappe.utils.add_days(current_date, 40),
+					"end_date": frappe.utils.add_days(current_date, 45)
+				},
+				{
+					"title": "Testing",
+					"start_date": frappe.utils.add_days(current_date, 45),
+					"end_date": frappe.utils.add_days(current_date, 60)
+				},
+				{
+					"title": "Product Engineering",
+					"start_date": frappe.utils.add_days(current_date, 45),
+					"end_date": frappe.utils.add_days(current_date, 55)
+				},
+				{
+					"title": "Supplier Contracts",
+					"start_date": frappe.utils.add_days(current_date, 55),
+					"end_date": frappe.utils.add_days(current_date, 70)
+				},
+				{
+					"title": "Design and Build Fixtures",
+					"start_date": frappe.utils.add_days(current_date, 45),
+					"end_date": frappe.utils.add_days(current_date, 65)
+				},
+				{
+					"title": "Test Run",
+					"start_date": frappe.utils.add_days(current_date, 70),
+					"end_date": frappe.utils.add_days(current_date, 80)
+				},
+				{
+					"title": "Launch",
+					"start_date": frappe.utils.add_days(current_date, 80),
+					"end_date": frappe.utils.add_days(current_date, 90)
+				},
+			])
+		project.insert()
diff --git a/erpnext/hr/doctype/job_applicant/job_applicant.json b/erpnext/hr/doctype/job_applicant/job_applicant.json
index 6bb9ea7..4af03b6 100644
--- a/erpnext/hr/doctype/job_applicant/job_applicant.json
+++ b/erpnext/hr/doctype/job_applicant/job_applicant.json
@@ -3,16 +3,18 @@
  "allow_import": 0, 
  "allow_rename": 0, 
  "autoname": "JA-.######", 
+ "beta": 0, 
  "creation": "2013-01-29 19:25:37", 
  "custom": 0, 
  "description": "Applicant for a Job", 
  "docstatus": 0, 
  "doctype": "DocType", 
  "document_type": "Document", 
+ "editable_grid": 0, 
  "fields": [
   {
    "allow_on_submit": 0, 
-   "bold": 0, 
+   "bold": 1, 
    "collapsible": 0, 
    "fieldname": "applicant_name", 
    "fieldtype": "Data", 
@@ -29,14 +31,14 @@
    "print_hide_if_no_value": 0, 
    "read_only": 0, 
    "report_hide": 0, 
-   "reqd": 1, 
+   "reqd": 0, 
    "search_index": 0, 
    "set_only_once": 0, 
    "unique": 0
   }, 
   {
    "allow_on_submit": 0, 
-   "bold": 0, 
+   "bold": 1, 
    "collapsible": 0, 
    "fieldname": "email_id", 
    "fieldtype": "Data", 
@@ -54,7 +56,7 @@
    "print_hide_if_no_value": 0, 
    "read_only": 0, 
    "report_hide": 0, 
-   "reqd": 1, 
+   "reqd": 0, 
    "search_index": 0, 
    "set_only_once": 0, 
    "unique": 0
@@ -212,13 +214,14 @@
  "hide_toolbar": 0, 
  "icon": "icon-user", 
  "idx": 1, 
+ "image_view": 0, 
  "in_create": 0, 
  "in_dialog": 0, 
  "is_submittable": 0, 
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2016-03-02 02:22:31.941850", 
+ "modified": "2016-07-15 07:10:58.195489", 
  "modified_by": "Administrator", 
  "module": "HR", 
  "name": "Job Applicant", 
@@ -245,9 +248,11 @@
    "write": 1
   }
  ], 
+ "quick_entry": 0, 
  "read_only": 0, 
  "read_only_onload": 0, 
  "search_fields": "applicant_name", 
  "sort_order": "ASC", 
- "title_field": "applicant_name"
+ "title_field": "applicant_name", 
+ "track_seen": 0
 }
\ No newline at end of file
diff --git a/erpnext/hr/doctype/job_applicant/job_applicant.py b/erpnext/hr/doctype/job_applicant/job_applicant.py
index 56c31cd..365386c 100644
--- a/erpnext/hr/doctype/job_applicant/job_applicant.py
+++ b/erpnext/hr/doctype/job_applicant/job_applicant.py
@@ -29,6 +29,10 @@
 		self.check_email_id_is_unique()
 		validate_email_add(self.email_id, True)
 
+		if not self.applicant_name and self.email_id:
+			guess = self.email_id.split('@')[0]
+			self.applicant_name = ' '.join([p.capitalize() for p in guess.split('.')])
+
 	def check_email_id_is_unique(self):
 		if self.email_id:
 			names = frappe.db.sql_list("""select name from `tabJob Applicant`
diff --git a/erpnext/manufacturing/doctype/production_order/production_order.py b/erpnext/manufacturing/doctype/production_order/production_order.py
index b949dfc..cd24f9b 100644
--- a/erpnext/manufacturing/doctype/production_order/production_order.py
+++ b/erpnext/manufacturing/doctype/production_order/production_order.py
@@ -7,6 +7,7 @@
 import json
 from frappe.utils import flt, get_datetime, getdate, date_diff, cint, nowdate
 from frappe import _
+from frappe.utils import time_diff_in_seconds
 from frappe.model.document import Document
 from frappe.model.mapper import get_mapped_doc
 from erpnext.manufacturing.doctype.bom.bom import validate_bom_no
@@ -262,12 +263,14 @@
 				original_start_time = d.planned_start_time
 
 				# validate operating hours if workstation [not mandatory] is specified
-				self.check_operation_fits_in_working_hours(d)
 				try:
 					timesheet.validate_time_logs()
 				except OverlapError:
 					if frappe.message_log: frappe.message_log.pop()
-					timesheet.move_to_next_non_overlapping_slot(d.idx)
+					timesheet.schedule_for_production_order(d.idx)
+				except WorkstationHolidayError:
+					if frappe.message_log: frappe.message_log.pop()
+					timesheet.schedule_for_production_order(d.idx)
 
 				from_time, to_time = self.get_start_end_time(timesheet, d.name)
 
@@ -294,7 +297,7 @@
 	def get_operations_data(self, data):
 		return {
 			'from_time': data.planned_start_time,
-			'hours': data.time_in_mins / 60,
+			'hours': data.time_in_mins / 60.0,
 			'to_time': data.planned_end_time,
 			'project': self.project,
 			'operation': data.operation,
diff --git a/erpnext/manufacturing/doctype/production_order/test_production_order.py b/erpnext/manufacturing/doctype/production_order/test_production_order.py
index 9013c15..d29544b 100644
--- a/erpnext/manufacturing/doctype/production_order/test_production_order.py
+++ b/erpnext/manufacturing/doctype/production_order/test_production_order.py
@@ -220,7 +220,8 @@
 	pro_order.wip_warehouse = args.wip_warehouse or "_Test Warehouse - _TC"
 	pro_order.fg_warehouse = args.fg_warehouse or "_Test Warehouse 1 - _TC"
 	pro_order.company = args.company or "_Test Company"
-	pro_order.stock_uom = "_Test UOM"
+	pro_order.stock_uom = args.stock_uom or "_Test UOM"
+	pro_order.set_production_order_operations()
 
 	if args.source_warehouse:
 		pro_order.source_warehouse = args.source_warehouse
diff --git a/erpnext/projects/doctype/timesheet/timesheet.py b/erpnext/projects/doctype/timesheet/timesheet.py
index 686f7c2..6881e0b 100644
--- a/erpnext/projects/doctype/timesheet/timesheet.py
+++ b/erpnext/projects/doctype/timesheet/timesheet.py
@@ -6,9 +6,12 @@
 import frappe
 from frappe import _
 
+from datetime import timedelta
 from frappe.utils import flt, time_diff_in_hours, get_datetime, getdate, cint, get_datetime_str
 from frappe.model.document import Document
 from frappe.model.mapper import get_mapped_doc
+from erpnext.manufacturing.doctype.workstation.workstation import (check_if_within_operating_hours,
+	WorkstationHolidayError)
 from erpnext.manufacturing.doctype.manufacturing_settings.manufacturing_settings import get_mins_between_operations
 
 class OverlapError(frappe.ValidationError): pass
@@ -136,8 +139,8 @@
 
 	def validate_time_logs(self):
 		for data in self.get('time_logs'):
-			self.validate_overlap(data)
 			self.check_workstation_timings(data)
+			self.validate_overlap(data)
 
 	def validate_overlap(self, data):
 		if self.production_order:
@@ -179,29 +182,45 @@
 	def check_workstation_timings(self, args):
 		"""Checks if **Time Log** is between operating hours of the **Workstation**."""
 		if args.workstation and args.from_time and args.to_time:
-			from erpnext.manufacturing.doctype.workstation.workstation import check_if_within_operating_hours
 			check_if_within_operating_hours(args.workstation, args.operation, args.from_time, args.to_time)
 
-	def move_to_next_non_overlapping_slot(self, index):
-		from datetime import timedelta
-		if self.time_logs:
-			for data in self.time_logs:
-				if data.idx == index:
-					overlapping = self.get_overlap_for("workstation", data, data.workstation)
-					if not overlapping:
-						frappe.throw(_("Logical error: Must find overlapping"))
-					
-					if overlapping:
-						time_sheet = self.get_last_working_slot(overlapping.name, data.workstation)
-						data.from_time = get_datetime(time_sheet.to_time) + get_mins_between_operations()
-						data.to_time = get_datetime(data.from_time) + timedelta(hours=data.hours)
-					break
+	def schedule_for_production_order(self, index):
+		for data in self.time_logs:
+			if data.idx == index:
+				self.move_to_next_day(data) #check for workstation holiday
+				self.move_to_next_non_overlapping_slot(data) #check for overlap
+				break
+
+	def move_to_next_non_overlapping_slot(self, data):
+		overlapping = self.get_overlap_for("workstation", data, data.workstation)
+		if overlapping:
+			time_sheet = self.get_last_working_slot(overlapping.name, data.workstation)
+			data.from_time = get_datetime(time_sheet.to_time) + get_mins_between_operations()
+			data.to_time = self.get_to_time(data)
+			self.check_workstation_working_day(data)
 
 	def get_last_working_slot(self, time_sheet, workstation):
 		return frappe.db.sql(""" select max(from_time) as from_time, max(to_time) as to_time 
 			from `tabTimesheet Detail` where workstation = %(workstation)s""",
 			{'workstation': workstation}, as_dict=True)[0]
 
+	def move_to_next_day(self, data):
+		"""Move start and end time one day forward"""
+		self.check_workstation_working_day(data)
+
+	def check_workstation_working_day(self, data):
+		while True:
+			try:
+				self.check_workstation_timings(data)
+				break
+			except WorkstationHolidayError:
+				if frappe.message_log: frappe.message_log.pop()
+				data.from_time = get_datetime(data.from_time) + timedelta(hours=24)
+				data.to_time = self.get_to_time(data)
+
+	def get_to_time(self, data):
+		return get_datetime(data.from_time) + timedelta(hours=data.hours)
+
 	def update_cost(self):
 		for data in self.time_logs:
 			if data.activity_type and not data.billing_amount:
diff --git a/erpnext/public/js/utils.js b/erpnext/public/js/utils.js
index d347227..0b6b0a6 100644
--- a/erpnext/public/js/utils.js
+++ b/erpnext/public/js/utils.js
@@ -128,7 +128,7 @@
 	}
 	var _map = function() {
 		// remove first item row if empty
-		if($.isArray(cur_frm.doc.items)) {
+		if($.isArray(cur_frm.doc.items) && cur_frm.doc.items.length > 0) {
 			if(!cur_frm.doc.items[0].item_code) {
 				cur_frm.doc.items = cur_frm.doc.items.splice(1);
 			}
diff --git a/erpnext/stock/doctype/item/item.py b/erpnext/stock/doctype/item/item.py
index 355503e..de5d545 100644
--- a/erpnext/stock/doctype/item/item.py
+++ b/erpnext/stock/doctype/item/item.py
@@ -13,7 +13,8 @@
 from erpnext.setup.doctype.item_group.item_group import invalidate_cache_for, get_parent_item_groups
 from frappe.website.render import clear_cache
 from frappe.website.doctype.website_slideshow.website_slideshow import get_slideshow
-from erpnext.controllers.item_variant import get_variant, copy_attributes_to_variant, ItemVariantExistsError
+from erpnext.controllers.item_variant import (get_variant, copy_attributes_to_variant,
+	make_variant_item_code, validate_item_variant_attributes, ItemVariantExistsError)
 
 class DuplicateReorderRows(frappe.ValidationError): pass
 
@@ -36,12 +37,7 @@
 		if frappe.db.get_default("item_naming_by")=="Naming Series":
 			if self.variant_of:
 				if not self.item_code:
-					item_code_suffix = ""
-					for attribute in self.attributes:
-						attribute_abbr = frappe.db.get_value("Item Attribute Value",
-							{"parent": attribute.attribute, "attribute_value": attribute.attribute_value}, "abbr")
-						item_code_suffix += "-" + str(attribute_abbr or attribute.attribute_value)
-					self.item_code = str(self.variant_of) + item_code_suffix
+					self.item_code = make_variant_item_code(self.variant_of, self)
 			else:
 				from frappe.model.naming import make_autoname
 				self.item_code = make_autoname(self.naming_series+'.#####')
@@ -123,8 +119,8 @@
 	def set_opening_stock(self):
 		'''set opening stock'''
 		if not self.valuation_rate:
-			frappe.throw(_("Valuation Rate is mandatory if Opening Stock entered"))		
-		
+			frappe.throw(_("Valuation Rate is mandatory if Opening Stock entered"))
+
 		from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
 
 		# default warehouse, or Stores
@@ -224,12 +220,12 @@
 					file_doc.make_thumbnail()
 
 				self.thumbnail = file_doc.thumbnail_url
-				
+
 	def validate_fixed_asset(self):
 		if self.is_fixed_asset:
 			if self.is_stock_item:
 				frappe.throw(_("Fixed Asset Item must be a non-stock item."))
-				
+
 			if not self.asset_category:
 				frappe.throw(_("Asset Category is mandatory for Fixed Asset item"))
 
@@ -453,7 +449,7 @@
 
 	def cant_change(self):
 		if not self.get("__islocal"):
-			vals = frappe.db.get_value("Item", self.name, ["has_serial_no", "is_stock_item", 
+			vals = frappe.db.get_value("Item", self.name, ["has_serial_no", "is_stock_item",
 				"valuation_method", "has_batch_no", "is_fixed_asset"], as_dict=True)
 
 			if vals and ((self.is_stock_item != vals.is_stock_item) or
@@ -463,7 +459,7 @@
 					if self.check_if_linked_document_exists():
 						frappe.throw(_("As there are existing transactions for this item, \
 							you can not change the values of 'Has Serial No', 'Has Batch No', 'Is Stock Item' and 'Valuation Method'"))
-							
+
 			if vals and not self.is_fixed_asset and self.is_fixed_asset != vals.is_fixed_asset:
 				asset = frappe.db.get_all("Asset", filters={"item_code": self.name, "docstatus": 1}, limit=1)
 				if asset:
@@ -650,6 +646,8 @@
 				frappe.throw(_("Item variant {0} exists with same attributes")
 					.format(variant), ItemVariantExistsError)
 
+			validate_item_variant_attributes(self, args)
+
 def get_timeline_data(doctype, name):
 	'''returns timeline data based on stock ledger entry'''
 	return dict(frappe.db.sql('''select unix_timestamp(posting_date), count(*)
diff --git a/erpnext/stock/doctype/item/test_item.py b/erpnext/stock/doctype/item/test_item.py
index 47f5162..bd617c6 100644
--- a/erpnext/stock/doctype/item/test_item.py
+++ b/erpnext/stock/doctype/item/test_item.py
@@ -36,6 +36,9 @@
 	return item
 
 class TestItem(unittest.TestCase):
+	def setUp(self):
+		frappe.flags.attribute_values = None
+
 	def get_item(self, idx):
 		item_code = test_records[idx].get("item_code")
 		if not frappe.db.exists("Item", item_code):
@@ -96,6 +99,9 @@
 		attribute = frappe.get_doc('Item Attribute', 'Test Size')
 		attribute.item_attribute_values = []
 
+		# reset flags
+		frappe.flags.attribute_values = None
+
 		self.assertRaises(InvalidItemAttributeValueError, attribute.save)
 		frappe.db.rollback()
 
@@ -112,10 +118,18 @@
 
 	def test_make_item_variant_with_numeric_values(self):
 		# cleanup
+		for d in frappe.db.get_all('Item', filters={'variant_of':
+				'_Test Numeric Template Item'}):
+			frappe.delete_doc_if_exists("Item", d.name)
+
 		frappe.delete_doc_if_exists("Item", "_Test Numeric Template Item")
-		frappe.delete_doc_if_exists("Item", "_Test Numeric Variant-L-1.5")
 		frappe.delete_doc_if_exists("Item Attribute", "Test Item Length")
 
+		frappe.db.sql('''delete from `tabItem Variant Attribute`
+			where attribute="Test Item Length"''')
+
+		frappe.flags.attribute_values = None
+
 		# make item attribute
 		frappe.get_doc({
 			"doctype": "Item Attribute",
@@ -143,7 +157,8 @@
 			"default_warehouse": "_Test Warehouse - _TC"
 		})
 
-		variant = create_variant("_Test Numeric Template Item", {"Test Size": "Large", "Test Item Length": 1.1})
+		variant = create_variant("_Test Numeric Template Item",
+			{"Test Size": "Large", "Test Item Length": 1.1})
 		self.assertEquals(variant.item_code, None)
 		variant.item_code = "_Test Numeric Variant-L-1.1"
 		variant.item_name = "_Test Numeric Variant Large 1.1m"
diff --git a/erpnext/stock/doctype/item_attribute/item_attribute.py b/erpnext/stock/doctype/item_attribute/item_attribute.py
index 7529ef6..3220bc5 100644
--- a/erpnext/stock/doctype/item_attribute/item_attribute.py
+++ b/erpnext/stock/doctype/item_attribute/item_attribute.py
@@ -16,6 +16,7 @@
 		self.flags.ignore_these_exceptions_in_test = [InvalidItemAttributeValueError]
 
 	def validate(self):
+		frappe.flags.attribute_values = None
 		self.validate_numeric()
 		self.validate_duplication()
 
@@ -26,7 +27,7 @@
 		'''Validate that if there are existing items with attributes, they are valid'''
 		for item in frappe.db.sql('''select distinct i.name from `tabItem Variant Attribute` iva, `tabItem` i
 			where iva.attribute = %s and iva.parent = i.name and i.has_variants = 0''', self.name):
-			validate_item_variant_attributes(frappe.get_doc('Item', item[0]))
+			validate_item_variant_attributes(item[0])
 
 	def validate_numeric(self):
 		if self.numeric_values: