blob: 6330508680988ba99d48438da11c9430a71b9cc8 [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
Rushabh Mehta9f0d6252014-04-14 19:20:45 +05306from frappe.utils import flt
7from frappe import msgprint, _, throw
Anand Doshi424c0332014-04-21 15:06:56 +05308from frappe.model.document import Document
Nabin Hait0feebc12013-06-03 16:45:38 +05309
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053010status_map = {
11 "Contact": [
12 ["Replied", "communication_sent"],
13 ["Open", "communication_received"]
14 ],
15 "Job Applicant": [
16 ["Replied", "communication_sent"],
17 ["Open", "communication_received"]
18 ],
19 "Lead": [
20 ["Replied", "communication_sent"],
21 ["Converted", "has_customer"],
22 ["Opportunity", "has_opportunity"],
23 ["Open", "communication_received"],
24 ],
25 "Opportunity": [
26 ["Draft", None],
Anand Doshif78d1ae2014-03-28 13:55:00 +053027 ["Submitted", "eval:self.docstatus==1"],
28 ["Lost", "eval:self.status=='Lost'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053029 ["Quotation", "has_quotation"],
30 ["Replied", "communication_sent"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053031 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053032 ["Open", "communication_received"],
33 ],
34 "Quotation": [
35 ["Draft", None],
Anand Doshif78d1ae2014-03-28 13:55:00 +053036 ["Submitted", "eval:self.docstatus==1"],
37 ["Lost", "eval:self.status=='Lost'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053038 ["Ordered", "has_sales_order"],
39 ["Replied", "communication_sent"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053040 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053041 ["Open", "communication_received"],
42 ],
43 "Sales Order": [
44 ["Draft", None],
Anand Doshif78d1ae2014-03-28 13:55:00 +053045 ["Submitted", "eval:self.docstatus==1"],
46 ["Stopped", "eval:self.status=='Stopped'"],
47 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053048 ],
49 "Support Ticket": [
50 ["Replied", "communication_sent"],
51 ["Open", "communication_received"]
52 ],
53}
54
Anand Doshi424c0332014-04-21 15:06:56 +053055class StatusUpdater(Document):
Nabin Hait0feebc12013-06-03 16:45:38 +053056 """
57 Updates the status of the calling records
58 Delivery Note: Update Delivered Qty, Update Percent and Validate over delivery
59 Sales Invoice: Update Billed Amt, Update Percent and Validate over billing
60 Installation Note: Update Installed Qty, Update Percent Qty and Validate over installation
61 """
62
63 def update_prevdoc_status(self):
64 self.update_qty()
65 self.validate_qty()
Anand Doshi9fd50bc2014-04-09 19:20:01 +053066
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053067 def set_status(self, update=False):
Anand Doshif78d1ae2014-03-28 13:55:00 +053068 if self.get("__islocal"):
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053069 return
Anand Doshi9fd50bc2014-04-09 19:20:01 +053070
Anand Doshif78d1ae2014-03-28 13:55:00 +053071 if self.doctype in status_map:
72 sl = status_map[self.doctype][:]
Rushabh Mehta6856d742013-10-03 18:12:36 +053073 sl.reverse()
74 for s in sl:
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053075 if not s[1]:
Anand Doshif78d1ae2014-03-28 13:55:00 +053076 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053077 break
Rushabh Mehta6856d742013-10-03 18:12:36 +053078 elif s[1].startswith("eval:"):
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053079 if eval(s[1][5:]):
Anand Doshif78d1ae2014-03-28 13:55:00 +053080 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053081 break
82 elif getattr(self, s[1])():
Anand Doshif78d1ae2014-03-28 13:55:00 +053083 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053084 break
Anand Doshi9fd50bc2014-04-09 19:20:01 +053085
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053086 if update:
Anand Doshif78d1ae2014-03-28 13:55:00 +053087 frappe.db.set_value(self.doctype, self.name, "status", self.status)
Anand Doshi9fd50bc2014-04-09 19:20:01 +053088
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053089 def on_communication(self):
Rushabh Mehtaacc876e2013-10-04 13:33:24 +053090 self.communication_set = True
Nabin Hait85786f32014-05-19 19:31:40 +053091 self.get("communications").sort(key=lambda d: d.creation)
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
Anand Doshi9fd50bc2014-04-09 19:20:01 +053094
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053095 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"
Anand Doshi9fd50bc2014-04-09 19:20:01 +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
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530113
Nabin Hait0feebc12013-06-03 16:45:38 +0530114 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
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530121 item = frappe.db.sql("""select item_code, `{target_ref_field}`,
122 `{target_field}`, parenttype, parent from `tab{target_dt}`
123 where `{target_ref_field}` < `{target_field}`
124 and name=%s and docstatus=1""".format(**args),
Nabin Hait4d713ac2014-03-03 15:51:13 +0530125 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']]:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530132 msgprint(_("Note: System will not check over-delivery and over-booking for Item {0} as quantity or amount is 0").format(item.item_code))
Nabin Hait0feebc12013-06-03 16:45:38 +0530133 elif args.get('no_tolerance'):
134 item['reduce_by'] = item[args['target_field']] - \
135 item[args['target_ref_field']]
136 if item['reduce_by'] > .01:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530137 msgprint(_("Allowance for over-delivery / over-billing crossed for Item {0}").format(item.item_code))
138 throw(_("{0} must be less than or equal to {1}").format(_(item.target_ref_field), item[args["target_ref_field"]]))
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530139
Nabin Hait0feebc12013-06-03 16:45:38 +0530140 else:
141 self.check_overflow_with_tolerance(item, args)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530142
Nabin Hait0feebc12013-06-03 16:45:38 +0530143 def check_overflow_with_tolerance(self, item, args):
144 """
145 Checks if there is overflow condering a relaxation tolerance
146 """
Nabin Hait0feebc12013-06-03 16:45:38 +0530147 # check if overflow is within tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530148 tolerance, self.tolerance, self.global_tolerance = get_tolerance_for(item['item_code'],
Nabin Hait7f0406f2014-01-03 17:43:19 +0530149 self.tolerance, self.global_tolerance)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530150
151 overflow_percent = ((item[args['target_field']] - item[args['target_ref_field']]) /
Nabin Hait0feebc12013-06-03 16:45:38 +0530152 item[args['target_ref_field']]) * 100
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530153
Nabin Hait0feebc12013-06-03 16:45:38 +0530154 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']
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530157
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530158 msgprint(_("Allowance for over-delivery / over-billing crossed for Item {0}").format(item["item_code"]))
159 throw(_("{0} must be less than or equal to {1}").format(_(item["target_ref_field"]), item[args["max_allowed"]]))
Nabin Hait0feebc12013-06-03 16:45:38 +0530160
161 def update_qty(self, change_modified=True):
162 """
163 Updates qty at row level
164 """
165 for args in self.status_updater:
166 # condition to include current record (if submit or no if cancel)
Anand Doshif78d1ae2014-03-28 13:55:00 +0530167 if self.docstatus == 1:
168 args['cond'] = ' or parent="%s"' % self.name.replace('"', '\"')
Nabin Hait0feebc12013-06-03 16:45:38 +0530169 else:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530170 args['cond'] = ' and parent!="%s"' % self.name.replace('"', '\"')
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530171
Nabin Hait0feebc12013-06-03 16:45:38 +0530172 args['modified_cond'] = ''
173 if change_modified:
174 args['modified_cond'] = ', modified = now()'
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530175
Nabin Hait0feebc12013-06-03 16:45:38 +0530176 # update quantities in child table
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530177 for d in self.get_all_children():
Nabin Hait0feebc12013-06-03 16:45:38 +0530178 if d.doctype == args['source_dt']:
179 # updates qty in the child table
Anand Doshif78d1ae2014-03-28 13:55:00 +0530180 args['detail_id'] = d.get(args['join_field'])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530181
Nabin Hait0feebc12013-06-03 16:45:38 +0530182 args['second_source_condition'] = ""
183 if args.get('second_source_dt') and args.get('second_source_field') \
184 and args.get('second_join_field'):
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530185 args['second_source_condition'] = """ + (select sum(%(second_source_field)s)
186 from `tab%(second_source_dt)s`
187 where `%(second_join_field)s`="%(detail_id)s"
Nabin Hait0feebc12013-06-03 16:45:38 +0530188 and (docstatus=1))""" % args
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530189
Nabin Hait0feebc12013-06-03 16:45:38 +0530190 if args['detail_id']:
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530191 frappe.db.sql("""update `tab%(target_dt)s`
192 set %(target_field)s = (select sum(%(source_field)s)
193 from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s"
Nabin Hait0feebc12013-06-03 16:45:38 +0530194 and (docstatus=1 %(cond)s)) %(second_source_condition)s
195 where name='%(detail_id)s'""" % args)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530196
Nabin Hait0feebc12013-06-03 16:45:38 +0530197 # get unique transactions to update
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530198 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 +0530199 if name:
200 args['name'] = name
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530201
Nabin Hait0feebc12013-06-03 16:45:38 +0530202 # update percent complete in the parent table
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530203 frappe.db.sql("""update `tab%(target_parent_dt)s`
204 set %(target_parent_field)s = (select sum(if(%(target_ref_field)s >
205 ifnull(%(target_field)s, 0), %(target_field)s,
206 %(target_ref_field)s))/sum(%(target_ref_field)s)*100
Nabin Hait0feebc12013-06-03 16:45:38 +0530207 from `tab%(target_dt)s` where parent="%(name)s") %(modified_cond)s
208 where name='%(name)s'""" % args)
209
210 # update field
211 if args.get('status_field'):
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530212 frappe.db.sql("""update `tab%(target_parent_dt)s`
213 set %(status_field)s = if(ifnull(%(target_parent_field)s,0)<0.001,
214 'Not %(keyword)s', if(%(target_parent_field)s>=99.99,
Nabin Hait0feebc12013-06-03 16:45:38 +0530215 'Fully %(keyword)s', 'Partly %(keyword)s'))
Nabin Hait7f0406f2014-01-03 17:43:19 +0530216 where name='%(name)s'""" % args)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530217
218
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530219 def update_billing_status_for_zero_amount_refdoc(self, ref_dt):
220 ref_fieldname = ref_dt.lower().replace(" ", "_")
221 zero_amount_refdoc = []
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530222 all_zero_amount_refdoc = frappe.db.sql_list("""select name from `tab%s`
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530223 where docstatus=1 and net_total = 0""" % ref_dt)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530224
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530225 for item in self.get("entries"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530226 if item.get(ref_fieldname) \
227 and item.get(ref_fieldname) in all_zero_amount_refdoc \
228 and item.get(ref_fieldname) not in zero_amount_refdoc:
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530229 zero_amount_refdoc.append(item.get(ref_fieldname))
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530230
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530231 if zero_amount_refdoc:
232 self.update_biling_status(zero_amount_refdoc, ref_dt, ref_fieldname)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530233
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530234 def update_biling_status(self, zero_amount_refdoc, ref_dt, ref_fieldname):
235 for ref_dn in zero_amount_refdoc:
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530236 ref_doc_qty = flt(frappe.db.sql("""select sum(ifnull(qty, 0)) from `tab%s Item`
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530237 where parent=%s""" % (ref_dt, '%s'), (ref_dn))[0][0])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530238
239 billed_qty = flt(frappe.db.sql("""select sum(ifnull(qty, 0))
240 from `tab%s Item` where %s=%s and docstatus=1""" %
Anand Doshif78d1ae2014-03-28 13:55:00 +0530241 (self.doctype, ref_fieldname, '%s'), (ref_dn))[0][0])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530242
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530243 per_billed = ((ref_doc_qty if billed_qty > ref_doc_qty else billed_qty)\
244 / ref_doc_qty)*100
Anand Doshie9baaa62014-02-26 12:35:33 +0530245 frappe.db.set_value(ref_dt, ref_dn, "per_billed", per_billed)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530246
Rushabh Mehta0a0f2492014-03-31 17:27:06 +0530247 if frappe.get_meta(ref_dt).get_field("billing_status"):
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530248 if per_billed < 0.001: billing_status = "Not Billed"
249 elif per_billed >= 99.99: billing_status = "Fully Billed"
250 else: billing_status = "Partly Billed"
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530251
Anand Doshie9baaa62014-02-26 12:35:33 +0530252 frappe.db.set_value(ref_dt, ref_dn, "billing_status", billing_status)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530253
Nabin Hait7f0406f2014-01-03 17:43:19 +0530254def get_tolerance_for(item_code, item_tolerance={}, global_tolerance=None):
255 """
256 Returns the tolerance for the item, if not set, returns global tolerance
257 """
258 if item_tolerance.get(item_code):
259 return item_tolerance[item_code], item_tolerance, global_tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530260
Anand Doshie9baaa62014-02-26 12:35:33 +0530261 tolerance = flt(frappe.db.get_value('Item',item_code,'tolerance') or 0)
Nabin Hait7f0406f2014-01-03 17:43:19 +0530262
263 if not tolerance:
264 if global_tolerance == None:
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530265 global_tolerance = flt(frappe.db.get_value('Global Defaults', None,
Nabin Hait7f0406f2014-01-03 17:43:19 +0530266 'tolerance'))
267 tolerance = global_tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530268
Nabin Hait7f0406f2014-01-03 17:43:19 +0530269 item_tolerance[item_code] = tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530270 return tolerance, item_tolerance, global_tolerance