blob: 7228100c9568002f1b16c025c02e1f2f7eb3afe4 [file] [log] [blame]
Rushabh Mehtaad45e312013-11-20 12:59:58 +05301# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05302# License: GNU General Public License v3. See license.txt
Nabin Hait0feebc12013-06-03 16:45:38 +05303
4from __future__ import unicode_literals
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
6from frappe.utils import flt, cstr
7from frappe import msgprint
Nabin Hait0feebc12013-06-03 16:45:38 +05308
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05309from frappe.model.controller import DocListController
Nabin Hait0feebc12013-06-03 16:45:38 +053010
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053011status_map = {
12 "Contact": [
13 ["Replied", "communication_sent"],
14 ["Open", "communication_received"]
15 ],
16 "Job Applicant": [
17 ["Replied", "communication_sent"],
18 ["Open", "communication_received"]
19 ],
20 "Lead": [
21 ["Replied", "communication_sent"],
22 ["Converted", "has_customer"],
23 ["Opportunity", "has_opportunity"],
24 ["Open", "communication_received"],
25 ],
26 "Opportunity": [
27 ["Draft", None],
Anand Doshif78d1ae2014-03-28 13:55:00 +053028 ["Submitted", "eval:self.docstatus==1"],
29 ["Lost", "eval:self.status=='Lost'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053030 ["Quotation", "has_quotation"],
31 ["Replied", "communication_sent"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053032 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053033 ["Open", "communication_received"],
34 ],
35 "Quotation": [
36 ["Draft", None],
Anand Doshif78d1ae2014-03-28 13:55:00 +053037 ["Submitted", "eval:self.docstatus==1"],
38 ["Lost", "eval:self.status=='Lost'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053039 ["Ordered", "has_sales_order"],
40 ["Replied", "communication_sent"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053041 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053042 ["Open", "communication_received"],
43 ],
44 "Sales Order": [
45 ["Draft", None],
Anand Doshif78d1ae2014-03-28 13:55:00 +053046 ["Submitted", "eval:self.docstatus==1"],
47 ["Stopped", "eval:self.status=='Stopped'"],
48 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053049 ],
50 "Support Ticket": [
51 ["Replied", "communication_sent"],
52 ["Open", "communication_received"]
53 ],
54}
55
Nabin Hait0feebc12013-06-03 16:45:38 +053056class StatusUpdater(DocListController):
57 """
58 Updates the status of the calling records
59 Delivery Note: Update Delivered Qty, Update Percent and Validate over delivery
60 Sales Invoice: Update Billed Amt, Update Percent and Validate over billing
61 Installation Note: Update Installed Qty, Update Percent Qty and Validate over installation
62 """
63
64 def update_prevdoc_status(self):
65 self.update_qty()
66 self.validate_qty()
67
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053068 def set_status(self, update=False):
Anand Doshif78d1ae2014-03-28 13:55:00 +053069 if self.get("__islocal"):
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053070 return
71
Anand Doshif78d1ae2014-03-28 13:55:00 +053072 if self.doctype in status_map:
73 sl = status_map[self.doctype][:]
Rushabh Mehta6856d742013-10-03 18:12:36 +053074 sl.reverse()
75 for s in sl:
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053076 if not s[1]:
Anand Doshif78d1ae2014-03-28 13:55:00 +053077 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053078 break
Rushabh Mehta6856d742013-10-03 18:12:36 +053079 elif s[1].startswith("eval:"):
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053080 if eval(s[1][5:]):
Anand Doshif78d1ae2014-03-28 13:55:00 +053081 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053082 break
83 elif getattr(self, s[1])():
Anand Doshif78d1ae2014-03-28 13:55:00 +053084 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053085 break
86
87 if update:
Anand Doshif78d1ae2014-03-28 13:55:00 +053088 frappe.db.set_value(self.doctype, self.name, "status", self.status)
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053089
90 def on_communication(self):
Rushabh Mehtaacc876e2013-10-04 13:33:24 +053091 self.communication_set = True
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053092 self.set_status(update=True)
Rushabh Mehtaacc876e2013-10-04 13:33:24 +053093 del self.communication_set
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053094
95 def communication_received(self):
Rushabh Mehtaacc876e2013-10-04 13:33:24 +053096 if getattr(self, "communication_set", False):
Rushabh Mehtaf191f852014-04-02 18:09:34 +053097 last_comm = self.get("communications")
Rushabh Mehtaacc876e2013-10-04 13:33:24 +053098 if last_comm:
99 return last_comm[-1].sent_or_received == "Received"
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530100
101 def communication_sent(self):
Rushabh Mehtaacc876e2013-10-04 13:33:24 +0530102 if getattr(self, "communication_set", False):
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530103 last_comm = self.get("communications")
Rushabh Mehtaacc876e2013-10-04 13:33:24 +0530104 if last_comm:
105 return last_comm[-1].sent_or_received == "Sent"
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530106
Nabin Hait0feebc12013-06-03 16:45:38 +0530107 def validate_qty(self):
108 """
109 Validates qty at row level
110 """
111 self.tolerance = {}
112 self.global_tolerance = None
113
114 for args in self.status_updater:
115 # get unique transactions to update
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530116 for d in self.get_all_children():
Anand Doshif78d1ae2014-03-28 13:55:00 +0530117 if d.doctype == args['source_dt'] and d.get(args["join_field"]):
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530118 args['name'] = d.get(args['join_field'])
Nabin Hait0feebc12013-06-03 16:45:38 +0530119
120 # get all qty where qty > target_field
Nabin Hait4d713ac2014-03-03 15:51:13 +0530121 item = frappe.db.sql("""select item_code, `{target_ref_field}`,
Nabin Hait2c517e02014-03-25 18:28:49 +0530122 `{target_field}`, parenttype, parent from `tab{target_dt}`
Nabin Hait4d713ac2014-03-03 15:51:13 +0530123 where `{target_ref_field}` < `{target_field}`
124 and name=%s and docstatus=1""".format(**args),
125 args['name'], as_dict=1)
Nabin Hait0feebc12013-06-03 16:45:38 +0530126 if item:
127 item = item[0]
128 item['idx'] = d.idx
129 item['target_ref_field'] = args['target_ref_field'].replace('_', ' ')
130
131 if not item[args['target_ref_field']]:
132 msgprint("""As %(target_ref_field)s for item: %(item_code)s in \
133 %(parenttype)s: %(parent)s is zero, system will not check \
134 over-delivery or over-billed""" % item)
135 elif args.get('no_tolerance'):
136 item['reduce_by'] = item[args['target_field']] - \
137 item[args['target_ref_field']]
138 if item['reduce_by'] > .01:
139 msgprint("""
140 Row #%(idx)s: Max %(target_ref_field)s allowed for <b>Item \
141 %(item_code)s</b> against <b>%(parenttype)s %(parent)s</b> \
142 is <b>""" % item + cstr(item[args['target_ref_field']]) +
143 """</b>.<br>You must reduce the %(target_ref_field)s by \
144 %(reduce_by)s""" % item, raise_exception=1)
145
146 else:
147 self.check_overflow_with_tolerance(item, args)
148
149 def check_overflow_with_tolerance(self, item, args):
150 """
151 Checks if there is overflow condering a relaxation tolerance
152 """
153
154 # check if overflow is within tolerance
Nabin Hait7f0406f2014-01-03 17:43:19 +0530155 tolerance, self.tolerance, self.global_tolerance = get_tolerance_for(item['item_code'],
156 self.tolerance, self.global_tolerance)
157
Nabin Hait0feebc12013-06-03 16:45:38 +0530158 overflow_percent = ((item[args['target_field']] - item[args['target_ref_field']]) /
159 item[args['target_ref_field']]) * 100
160
161 if overflow_percent - tolerance > 0.01:
162 item['max_allowed'] = flt(item[args['target_ref_field']] * (100+tolerance)/100)
163 item['reduce_by'] = item[args['target_field']] - item['max_allowed']
164
165 msgprint("""
166 Row #%(idx)s: Max %(target_ref_field)s allowed for <b>Item %(item_code)s</b> \
167 against <b>%(parenttype)s %(parent)s</b> is <b>%(max_allowed)s</b>.
168
169 If you want to increase your overflow tolerance, please increase tolerance %% in \
170 Global Defaults or Item master.
171
172 Or, you must reduce the %(target_ref_field)s by %(reduce_by)s
173
174 Also, please check if the order item has already been billed in the Sales Order""" %
175 item, raise_exception=1)
Nabin Hait0feebc12013-06-03 16:45:38 +0530176
177
178 def update_qty(self, change_modified=True):
179 """
180 Updates qty at row level
181 """
182 for args in self.status_updater:
183 # condition to include current record (if submit or no if cancel)
Anand Doshif78d1ae2014-03-28 13:55:00 +0530184 if self.docstatus == 1:
185 args['cond'] = ' or parent="%s"' % self.name.replace('"', '\"')
Nabin Hait0feebc12013-06-03 16:45:38 +0530186 else:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530187 args['cond'] = ' and parent!="%s"' % self.name.replace('"', '\"')
Nabin Hait0feebc12013-06-03 16:45:38 +0530188
189 args['modified_cond'] = ''
190 if change_modified:
191 args['modified_cond'] = ', modified = now()'
192
193 # update quantities in child table
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530194 for d in self.get_all_children():
Nabin Hait0feebc12013-06-03 16:45:38 +0530195 if d.doctype == args['source_dt']:
196 # updates qty in the child table
Anand Doshif78d1ae2014-03-28 13:55:00 +0530197 args['detail_id'] = d.get(args['join_field'])
Nabin Hait0feebc12013-06-03 16:45:38 +0530198
199 args['second_source_condition'] = ""
200 if args.get('second_source_dt') and args.get('second_source_field') \
201 and args.get('second_join_field'):
202 args['second_source_condition'] = """ + (select sum(%(second_source_field)s)
203 from `tab%(second_source_dt)s`
204 where `%(second_join_field)s`="%(detail_id)s"
205 and (docstatus=1))""" % args
206
207 if args['detail_id']:
Anand Doshie9baaa62014-02-26 12:35:33 +0530208 frappe.db.sql("""update `tab%(target_dt)s`
Nabin Hait0feebc12013-06-03 16:45:38 +0530209 set %(target_field)s = (select sum(%(source_field)s)
210 from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s"
211 and (docstatus=1 %(cond)s)) %(second_source_condition)s
212 where name='%(detail_id)s'""" % args)
213
214 # get unique transactions to update
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530215 for name in set([d.get(args['percent_join_field']) for d in self.get_all_children(args['source_dt'])]):
Nabin Hait0feebc12013-06-03 16:45:38 +0530216 if name:
217 args['name'] = name
218
219 # update percent complete in the parent table
Anand Doshie9baaa62014-02-26 12:35:33 +0530220 frappe.db.sql("""update `tab%(target_parent_dt)s`
Nabin Hait0feebc12013-06-03 16:45:38 +0530221 set %(target_parent_field)s = (select sum(if(%(target_ref_field)s >
222 ifnull(%(target_field)s, 0), %(target_field)s,
223 %(target_ref_field)s))/sum(%(target_ref_field)s)*100
224 from `tab%(target_dt)s` where parent="%(name)s") %(modified_cond)s
225 where name='%(name)s'""" % args)
226
227 # update field
228 if args.get('status_field'):
Anand Doshie9baaa62014-02-26 12:35:33 +0530229 frappe.db.sql("""update `tab%(target_parent_dt)s`
Nabin Hait0feebc12013-06-03 16:45:38 +0530230 set %(status_field)s = if(ifnull(%(target_parent_field)s,0)<0.001,
231 'Not %(keyword)s', if(%(target_parent_field)s>=99.99,
232 'Fully %(keyword)s', 'Partly %(keyword)s'))
Nabin Hait7f0406f2014-01-03 17:43:19 +0530233 where name='%(name)s'""" % args)
234
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530235
236 def update_billing_status_for_zero_amount_refdoc(self, ref_dt):
237 ref_fieldname = ref_dt.lower().replace(" ", "_")
238 zero_amount_refdoc = []
Anand Doshie9baaa62014-02-26 12:35:33 +0530239 all_zero_amount_refdoc = frappe.db.sql_list("""select name from `tab%s`
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530240 where docstatus=1 and net_total = 0""" % ref_dt)
241
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530242 for item in self.get("entries"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530243 if item.get(ref_fieldname) \
244 and item.get(ref_fieldname) in all_zero_amount_refdoc \
245 and item.get(ref_fieldname) not in zero_amount_refdoc:
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530246 zero_amount_refdoc.append(item.get(ref_fieldname))
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530247
248 if zero_amount_refdoc:
249 self.update_biling_status(zero_amount_refdoc, ref_dt, ref_fieldname)
250
251 def update_biling_status(self, zero_amount_refdoc, ref_dt, ref_fieldname):
252 for ref_dn in zero_amount_refdoc:
Anand Doshie9baaa62014-02-26 12:35:33 +0530253 ref_doc_qty = flt(frappe.db.sql("""select sum(ifnull(qty, 0)) from `tab%s Item`
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530254 where parent=%s""" % (ref_dt, '%s'), (ref_dn))[0][0])
255
Anand Doshie9baaa62014-02-26 12:35:33 +0530256 billed_qty = flt(frappe.db.sql("""select sum(ifnull(qty, 0))
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530257 from `tab%s Item` where %s=%s and docstatus=1""" %
Anand Doshif78d1ae2014-03-28 13:55:00 +0530258 (self.doctype, ref_fieldname, '%s'), (ref_dn))[0][0])
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530259
260 per_billed = ((ref_doc_qty if billed_qty > ref_doc_qty else billed_qty)\
261 / ref_doc_qty)*100
Anand Doshie9baaa62014-02-26 12:35:33 +0530262 frappe.db.set_value(ref_dt, ref_dn, "per_billed", per_billed)
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530263
Rushabh Mehta0a0f2492014-03-31 17:27:06 +0530264 if frappe.get_meta(ref_dt).get_field("billing_status"):
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530265 if per_billed < 0.001: billing_status = "Not Billed"
266 elif per_billed >= 99.99: billing_status = "Fully Billed"
267 else: billing_status = "Partly Billed"
268
Anand Doshie9baaa62014-02-26 12:35:33 +0530269 frappe.db.set_value(ref_dt, ref_dn, "billing_status", billing_status)
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530270
Nabin Hait7f0406f2014-01-03 17:43:19 +0530271def get_tolerance_for(item_code, item_tolerance={}, global_tolerance=None):
272 """
273 Returns the tolerance for the item, if not set, returns global tolerance
274 """
275 if item_tolerance.get(item_code):
276 return item_tolerance[item_code], item_tolerance, global_tolerance
277
Anand Doshie9baaa62014-02-26 12:35:33 +0530278 tolerance = flt(frappe.db.get_value('Item',item_code,'tolerance') or 0)
Nabin Hait7f0406f2014-01-03 17:43:19 +0530279
280 if not tolerance:
281 if global_tolerance == None:
Anand Doshie9baaa62014-02-26 12:35:33 +0530282 global_tolerance = flt(frappe.db.get_value('Global Defaults', None,
Nabin Hait7f0406f2014-01-03 17:43:19 +0530283 'tolerance'))
284 tolerance = global_tolerance
285
286 item_tolerance[item_code] = tolerance
287 return tolerance, item_tolerance, global_tolerance