Maintenance schedule: get no of visits and period validation. Fixes #1591
diff --git a/erpnext/support/doctype/maintenance_schedule/maintenance_schedule.js b/erpnext/support/doctype/maintenance_schedule/maintenance_schedule.js
index 9852eec..476530b 100644
--- a/erpnext/support/doctype/maintenance_schedule/maintenance_schedule.js
+++ b/erpnext/support/doctype/maintenance_schedule/maintenance_schedule.js
@@ -3,12 +3,12 @@
 
 frappe.provide("erpnext.support");
 
-frappe.ui.form.on_change("Maintenance Schedule", "customer", function(frm) { 
+frappe.ui.form.on_change("Maintenance Schedule", "customer", function(frm) {
 	erpnext.utils.get_party_details(frm) });
-frappe.ui.form.on_change("Maintenance Schedule", "customer_address", 
+frappe.ui.form.on_change("Maintenance Schedule", "customer_address",
 	erpnext.utils.get_address_display);
-frappe.ui.form.on_change("Maintenance Schedule", "contact_person", 
-	erpnext.utils.get_contact_details);	
+frappe.ui.form.on_change("Maintenance Schedule", "contact_person",
+	erpnext.utils.get_contact_details);
 
 // TODO commonify this code
 erpnext.support.MaintenanceSchedule = frappe.ui.form.Controller.extend({
@@ -16,7 +16,7 @@
 		var me = this;
 
 		if (this.frm.doc.docstatus === 0) {
-			this.frm.add_custom_button(__('From Sales Order'), 
+			this.frm.add_custom_button(__('From Sales Order'),
 				function() {
 					frappe.model.map_current_doc({
 						method: "erpnext.selling.doctype.sales_order.sales_order.make_maintenance_schedule",
@@ -38,16 +38,52 @@
 			});
 		}
 	},
+
+	start_date: function(doc, cdt, cdn) {
+		this.set_no_of_visits(doc, cdt, cdn);
+	},
+
+	end_date: function(doc, cdt, cdn) {
+		this.set_no_of_visits(doc, cdt, cdn);
+	},
+
+	periodicity: function(doc, cdt, cdn) {
+		this.set_no_of_visits(doc, cdt, cdn);
+	},
+
+	set_no_of_visits: function(doc, cdt, cdn) {
+		var item = frappe.get_doc(cdt, cdn);
+
+		if (item.start_date && item.end_date && item.periodicity) {
+			if(item.start_date > item.end_date) {
+				msgprint(__("Row {0}:Start Date must be before End Date", [item.idx]));
+				return;
+			}
+
+			var date_diff = frappe.datetime.get_diff(item.end_date, item.start_date) + 1;
+
+			var days_in_period = {
+				"Weekly": 7,
+				"Monthly": 30,
+				"Quarterly": 91,
+				"Half Yearly": 182,
+				"Yearly": 365
+			}
+
+			var no_of_visits = cint(date_diff / days_in_period[item.periodicity]);
+			frappe.model.set_value(item.doctype, item.name, "no_of_visits", no_of_visits);
+		}
+	},
 });
 
 $.extend(cur_frm.cscript, new erpnext.support.MaintenanceSchedule({frm: cur_frm}));
 
 cur_frm.cscript.onload = function(doc, dt, dn) {
   if(!doc.status) set_multiple(dt,dn,{status:'Draft'});
-  
+
   if(doc.__islocal){
     set_multiple(dt,dn,{transaction_date:get_today()});
-  }   
+  }
 }
 
 cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
@@ -62,7 +98,7 @@
 	}
 }
 
-//
+
 cur_frm.fields_dict['item_maintenance_detail'].grid.get_field('item_code').get_query = function(doc, cdt, cdn) {
 	return {
 		filters:{ 'is_service_item': "Yes" }
@@ -73,25 +109,11 @@
 	var fname = cur_frm.cscript.fname;
 	var d = locals[cdt][cdn];
 	if (d.item_code) {
-		return get_server_fields('get_item_details', d.item_code, 'item_maintenance_detail', 
+		return get_server_fields('get_item_details', d.item_code, 'item_maintenance_detail',
 			doc, cdt, cdn, 1);
 	}
 }
 
-cur_frm.cscript.periodicity = function(doc, cdt, cdn){
-	var d = locals[cdt][cdn];
-	if(d.start_date && d.end_date) {
-		arg = {}
-		arg.start_date = d.start_date;
-		arg.end_date = d.end_date;
-		arg.periodicity = d.periodicity;
-		return get_server_fields('get_no_of_visits', docstring(arg), 
-			'item_maintenance_detail', doc, cdt, cdn, 1);
-	} else {
-		msgprint(__("Please enter Start Date and End Date"));
-	}
-}
-
 cur_frm.cscript.generate_schedule = function(doc, cdt, cdn) {
 	if (!doc.__islocal) {
 		return $c('runserverobj', args={'method':'generate_schedule', 'docs':doc},
diff --git a/erpnext/support/doctype/maintenance_schedule/maintenance_schedule.py b/erpnext/support/doctype/maintenance_schedule/maintenance_schedule.py
index 74d0e2e..a0eba19 100644
--- a/erpnext/support/doctype/maintenance_schedule/maintenance_schedule.py
+++ b/erpnext/support/doctype/maintenance_schedule/maintenance_schedule.py
@@ -133,40 +133,22 @@
 
 		return schedule_date
 
-	def validate_period(self, arg):
-		args = eval(arg)
-		if getdate(args['start_date']) >= getdate(args['end_date']):
-			throw(_("Start date should be less than end date."))
+	def validate_dates_with_periodicity(self):
+		for d in self.get("item_maintenance_detail"):
+			if d.start_date and d.end_date and d.periodicity:
+				date_diff = (getdate(d.end_date) - getdate(d.start_date)).days + 1
+				days_in_period = {
+					"Weekly": 7,
+					"Monthly": 30,
+					"Quarterly": 90,
+					"Half Yearly": 180,
+					"Yearly": 365
+				}
 
-		period = (getdate(args['end_date']) - getdate(args['start_date'])).days + 1
-
-		if (args['periodicity'] == 'Yearly' or args['periodicity'] == 'Half Yearly' or
-			args['periodicity'] == 'Quarterly') and period < 90:
-			throw(_("Period is too short"))
-		elif args['periodicity'] == 'Monthly' and period < 30:
-			throw(_("Period is too short"))
-		elif args['periodicity'] == 'Weekly' and period < 7:
-			throw(_("Period is too short"))
-
-	def get_no_of_visits(self, arg):
-		args = eval(arg)
-		self.validate_period(arg)
-		period = (getdate(args['end_date']) - getdate(args['start_date'])).days + 1
-		count = 0
-
-		if args['periodicity'] == 'Weekly':
-			count = period/7
-		elif args['periodicity'] == 'Monthly':
-			count = period/30
-		elif args['periodicity'] == 'Quarterly':
-			count = period/91
-		elif args['periodicity'] == 'Half Yearly':
-			count = period/182
-		elif args['periodicity'] == 'Yearly':
-			count = period/365
-
-		ret = {'no_of_visits' : count}
-		return ret
+				if date_diff < days_in_period[d.periodicity]:
+					throw(_("Row {0}: To set {1} periodicity, difference between from and to date \
+						must be greater than or equal to {2}")
+						.format(d.idx, d.periodicity, days_in_period[d.periodicity]))
 
 	def validate_maintenance_detail(self):
 		if not self.get('item_maintenance_detail'):
@@ -196,6 +178,7 @@
 
 	def validate(self):
 		self.validate_maintenance_detail()
+		self.validate_dates_with_periodicity()
 		self.validate_sales_order()
 
 	def on_update(self):