blob: e457fa957eff4779ae2c2697f5535e9cada5ec9f [file] [log] [blame]
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05301# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
2# 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):
91 self.set_status(update=True)
92
93 def communication_received(self):
Rushabh Mehta6856d742013-10-03 18:12:36 +053094 last_comm = self.doclist.get({"doctype":"Communication"})
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053095 if last_comm:
Rushabh Mehta6856d742013-10-03 18:12:36 +053096 return last_comm[-1].sent_or_received == "Received"
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053097
98 def communication_sent(self):
Rushabh Mehta6856d742013-10-03 18:12:36 +053099 last_comm = self.doclist.get({"doctype":"Communication"})
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530100 if last_comm:
Rushabh Mehta6856d742013-10-03 18:12:36 +0530101 return last_comm[-1].sent_or_received == "Sent"
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530102
Nabin Hait0feebc12013-06-03 16:45:38 +0530103 def validate_qty(self):
104 """
105 Validates qty at row level
106 """
107 self.tolerance = {}
108 self.global_tolerance = None
109
110 for args in self.status_updater:
111 # get unique transactions to update
112 for d in self.doclist:
113 if d.doctype == args['source_dt'] and d.fields.get(args["join_field"]):
114 args['name'] = d.fields[args['join_field']]
115
116 # get all qty where qty > target_field
117 item = webnotes.conn.sql("""select item_code, `%(target_ref_field)s`,
118 `%(target_field)s`, parenttype, parent from `tab%(target_dt)s`
119 where `%(target_ref_field)s` < `%(target_field)s`
120 and name="%(name)s" and docstatus=1""" % args, as_dict=1)
121 if item:
122 item = item[0]
123 item['idx'] = d.idx
124 item['target_ref_field'] = args['target_ref_field'].replace('_', ' ')
125
126 if not item[args['target_ref_field']]:
127 msgprint("""As %(target_ref_field)s for item: %(item_code)s in \
128 %(parenttype)s: %(parent)s is zero, system will not check \
129 over-delivery or over-billed""" % item)
130 elif args.get('no_tolerance'):
131 item['reduce_by'] = item[args['target_field']] - \
132 item[args['target_ref_field']]
133 if item['reduce_by'] > .01:
134 msgprint("""
135 Row #%(idx)s: Max %(target_ref_field)s allowed for <b>Item \
136 %(item_code)s</b> against <b>%(parenttype)s %(parent)s</b> \
137 is <b>""" % item + cstr(item[args['target_ref_field']]) +
138 """</b>.<br>You must reduce the %(target_ref_field)s by \
139 %(reduce_by)s""" % item, raise_exception=1)
140
141 else:
142 self.check_overflow_with_tolerance(item, args)
143
144 def check_overflow_with_tolerance(self, item, args):
145 """
146 Checks if there is overflow condering a relaxation tolerance
147 """
148
149 # check if overflow is within tolerance
150 tolerance = self.get_tolerance_for(item['item_code'])
151 overflow_percent = ((item[args['target_field']] - item[args['target_ref_field']]) /
152 item[args['target_ref_field']]) * 100
153
154 if overflow_percent - tolerance > 0.01:
155 item['max_allowed'] = flt(item[args['target_ref_field']] * (100+tolerance)/100)
156 item['reduce_by'] = item[args['target_field']] - item['max_allowed']
157
158 msgprint("""
159 Row #%(idx)s: Max %(target_ref_field)s allowed for <b>Item %(item_code)s</b> \
160 against <b>%(parenttype)s %(parent)s</b> is <b>%(max_allowed)s</b>.
161
162 If you want to increase your overflow tolerance, please increase tolerance %% in \
163 Global Defaults or Item master.
164
165 Or, you must reduce the %(target_ref_field)s by %(reduce_by)s
166
167 Also, please check if the order item has already been billed in the Sales Order""" %
168 item, raise_exception=1)
169
170 def get_tolerance_for(self, item_code):
171 """
172 Returns the tolerance for the item, if not set, returns global tolerance
173 """
174 if self.tolerance.get(item_code): return self.tolerance[item_code]
175
176 tolerance = flt(webnotes.conn.get_value('Item',item_code,'tolerance') or 0)
177
178 if not tolerance:
179 if self.global_tolerance == None:
180 self.global_tolerance = flt(webnotes.conn.get_value('Global Defaults', None,
181 'tolerance'))
182 tolerance = self.global_tolerance
183
184 self.tolerance[item_code] = tolerance
185 return tolerance
186
187
188 def update_qty(self, change_modified=True):
189 """
190 Updates qty at row level
191 """
192 for args in self.status_updater:
193 # condition to include current record (if submit or no if cancel)
194 if self.doc.docstatus == 1:
195 args['cond'] = ' or parent="%s"' % self.doc.name
196 else:
197 args['cond'] = ' and parent!="%s"' % self.doc.name
198
199 args['modified_cond'] = ''
200 if change_modified:
201 args['modified_cond'] = ', modified = now()'
202
203 # update quantities in child table
204 for d in self.doclist:
205 if d.doctype == args['source_dt']:
206 # updates qty in the child table
207 args['detail_id'] = d.fields.get(args['join_field'])
208
209 args['second_source_condition'] = ""
210 if args.get('second_source_dt') and args.get('second_source_field') \
211 and args.get('second_join_field'):
212 args['second_source_condition'] = """ + (select sum(%(second_source_field)s)
213 from `tab%(second_source_dt)s`
214 where `%(second_join_field)s`="%(detail_id)s"
215 and (docstatus=1))""" % args
216
217 if args['detail_id']:
218 webnotes.conn.sql("""update `tab%(target_dt)s`
219 set %(target_field)s = (select sum(%(source_field)s)
220 from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s"
221 and (docstatus=1 %(cond)s)) %(second_source_condition)s
222 where name='%(detail_id)s'""" % args)
223
224 # get unique transactions to update
225 for name in set([d.fields.get(args['percent_join_field']) for d in self.doclist
226 if d.doctype == args['source_dt']]):
227 if name:
228 args['name'] = name
229
230 # update percent complete in the parent table
231 webnotes.conn.sql("""update `tab%(target_parent_dt)s`
232 set %(target_parent_field)s = (select sum(if(%(target_ref_field)s >
233 ifnull(%(target_field)s, 0), %(target_field)s,
234 %(target_ref_field)s))/sum(%(target_ref_field)s)*100
235 from `tab%(target_dt)s` where parent="%(name)s") %(modified_cond)s
236 where name='%(name)s'""" % args)
237
238 # update field
239 if args.get('status_field'):
240 webnotes.conn.sql("""update `tab%(target_parent_dt)s`
241 set %(status_field)s = if(ifnull(%(target_parent_field)s,0)<0.001,
242 'Not %(keyword)s', if(%(target_parent_field)s>=99.99,
243 'Fully %(keyword)s', 'Partly %(keyword)s'))
244 where name='%(name)s'""" % args)