blob: a285c4798d4badbcc49c15733650e16d62b95f86 [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
5import webnotes
6from webnotes.utils import flt, cstr
7from webnotes import msgprint
8
9from webnotes.model.controller import DocListController
10
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],
28 ["Submitted", "eval:self.doc.docstatus==1"],
29 ["Lost", "eval:self.doc.status=='Lost'"],
30 ["Quotation", "has_quotation"],
31 ["Replied", "communication_sent"],
32 ["Cancelled", "eval:self.doc.docstatus==2"],
33 ["Open", "communication_received"],
34 ],
35 "Quotation": [
36 ["Draft", None],
37 ["Submitted", "eval:self.doc.docstatus==1"],
38 ["Lost", "eval:self.doc.status=='Lost'"],
39 ["Ordered", "has_sales_order"],
40 ["Replied", "communication_sent"],
41 ["Cancelled", "eval:self.doc.docstatus==2"],
42 ["Open", "communication_received"],
43 ],
44 "Sales Order": [
45 ["Draft", None],
46 ["Submitted", "eval:self.doc.docstatus==1"],
47 ["Stopped", "eval:self.doc.status=='Stopped'"],
48 ["Cancelled", "eval:self.doc.docstatus==2"],
49 ],
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):
69 if self.doc.get("__islocal"):
70 return
71
Rushabh Mehta6856d742013-10-03 18:12:36 +053072 if self.doc.doctype in status_map:
73 sl = status_map[self.doc.doctype][:]
74 sl.reverse()
75 for s in sl:
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053076 if not s[1]:
77 self.doc.status = s[0]
78 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:]):
81 self.doc.status = s[0]
82 break
83 elif getattr(self, s[1])():
84 self.doc.status = s[0]
85 break
86
87 if update:
88 webnotes.conn.set_value(self.doc.doctype, self.doc.name, "status", self.doc.status)
89
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):
97 last_comm = self.doclist.get({"doctype":"Communication"})
98 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):
103 last_comm = self.doclist.get({"doctype":"Communication"})
104 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
116 for d in self.doclist:
117 if d.doctype == args['source_dt'] and d.fields.get(args["join_field"]):
118 args['name'] = d.fields[args['join_field']]
119
120 # get all qty where qty > target_field
121 item = webnotes.conn.sql("""select item_code, `%(target_ref_field)s`,
122 `%(target_field)s`, parenttype, parent from `tab%(target_dt)s`
123 where `%(target_ref_field)s` < `%(target_field)s`
124 and name="%(name)s" and docstatus=1""" % args, as_dict=1)
125 if item:
126 item = item[0]
127 item['idx'] = d.idx
128 item['target_ref_field'] = args['target_ref_field'].replace('_', ' ')
129
130 if not item[args['target_ref_field']]:
131 msgprint("""As %(target_ref_field)s for item: %(item_code)s in \
132 %(parenttype)s: %(parent)s is zero, system will not check \
133 over-delivery or over-billed""" % item)
134 elif args.get('no_tolerance'):
135 item['reduce_by'] = item[args['target_field']] - \
136 item[args['target_ref_field']]
137 if item['reduce_by'] > .01:
138 msgprint("""
139 Row #%(idx)s: Max %(target_ref_field)s allowed for <b>Item \
140 %(item_code)s</b> against <b>%(parenttype)s %(parent)s</b> \
141 is <b>""" % item + cstr(item[args['target_ref_field']]) +
142 """</b>.<br>You must reduce the %(target_ref_field)s by \
143 %(reduce_by)s""" % item, raise_exception=1)
144
145 else:
146 self.check_overflow_with_tolerance(item, args)
147
148 def check_overflow_with_tolerance(self, item, args):
149 """
150 Checks if there is overflow condering a relaxation tolerance
151 """
152
153 # check if overflow is within tolerance
Nabin Hait7f0406f2014-01-03 17:43:19 +0530154 tolerance, self.tolerance, self.global_tolerance = get_tolerance_for(item['item_code'],
155 self.tolerance, self.global_tolerance)
156
Nabin Hait0feebc12013-06-03 16:45:38 +0530157 overflow_percent = ((item[args['target_field']] - item[args['target_ref_field']]) /
158 item[args['target_ref_field']]) * 100
159
160 if overflow_percent - tolerance > 0.01:
161 item['max_allowed'] = flt(item[args['target_ref_field']] * (100+tolerance)/100)
162 item['reduce_by'] = item[args['target_field']] - item['max_allowed']
163
164 msgprint("""
165 Row #%(idx)s: Max %(target_ref_field)s allowed for <b>Item %(item_code)s</b> \
166 against <b>%(parenttype)s %(parent)s</b> is <b>%(max_allowed)s</b>.
167
168 If you want to increase your overflow tolerance, please increase tolerance %% in \
169 Global Defaults or Item master.
170
171 Or, you must reduce the %(target_ref_field)s by %(reduce_by)s
172
173 Also, please check if the order item has already been billed in the Sales Order""" %
174 item, raise_exception=1)
Nabin Hait0feebc12013-06-03 16:45:38 +0530175
176
177 def update_qty(self, change_modified=True):
178 """
179 Updates qty at row level
180 """
181 for args in self.status_updater:
182 # condition to include current record (if submit or no if cancel)
183 if self.doc.docstatus == 1:
184 args['cond'] = ' or parent="%s"' % self.doc.name
185 else:
186 args['cond'] = ' and parent!="%s"' % self.doc.name
187
188 args['modified_cond'] = ''
189 if change_modified:
190 args['modified_cond'] = ', modified = now()'
191
192 # update quantities in child table
193 for d in self.doclist:
194 if d.doctype == args['source_dt']:
195 # updates qty in the child table
196 args['detail_id'] = d.fields.get(args['join_field'])
197
198 args['second_source_condition'] = ""
199 if args.get('second_source_dt') and args.get('second_source_field') \
200 and args.get('second_join_field'):
201 args['second_source_condition'] = """ + (select sum(%(second_source_field)s)
202 from `tab%(second_source_dt)s`
203 where `%(second_join_field)s`="%(detail_id)s"
204 and (docstatus=1))""" % args
205
206 if args['detail_id']:
207 webnotes.conn.sql("""update `tab%(target_dt)s`
208 set %(target_field)s = (select sum(%(source_field)s)
209 from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s"
210 and (docstatus=1 %(cond)s)) %(second_source_condition)s
211 where name='%(detail_id)s'""" % args)
212
213 # get unique transactions to update
214 for name in set([d.fields.get(args['percent_join_field']) for d in self.doclist
215 if d.doctype == args['source_dt']]):
216 if name:
217 args['name'] = name
218
219 # update percent complete in the parent table
220 webnotes.conn.sql("""update `tab%(target_parent_dt)s`
221 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'):
229 webnotes.conn.sql("""update `tab%(target_parent_dt)s`
230 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
235def get_tolerance_for(item_code, item_tolerance={}, global_tolerance=None):
236 """
237 Returns the tolerance for the item, if not set, returns global tolerance
238 """
239 if item_tolerance.get(item_code):
240 return item_tolerance[item_code], item_tolerance, global_tolerance
241
242 tolerance = flt(webnotes.conn.get_value('Item',item_code,'tolerance') or 0)
243
244 if not tolerance:
245 if global_tolerance == None:
246 global_tolerance = flt(webnotes.conn.get_value('Global Defaults', None,
247 'tolerance'))
248 tolerance = global_tolerance
249
250 item_tolerance[item_code] = tolerance
251 return tolerance, item_tolerance, global_tolerance