blob: e16c725411346c0f7dd13e81d7993645c1c39aff [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 = {
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053011 "Lead": [
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053012 ["Converted", "has_customer"],
13 ["Opportunity", "has_opportunity"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053014 ],
15 "Opportunity": [
16 ["Draft", None],
Anand Doshif78d1ae2014-03-28 13:55:00 +053017 ["Submitted", "eval:self.docstatus==1"],
18 ["Lost", "eval:self.status=='Lost'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053019 ["Quotation", "has_quotation"],
Neil Trini Lasrado47a62c62015-02-04 17:33:55 +053020 ["Converted", "has_ordered_quotation"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053021 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053022 ],
23 "Quotation": [
24 ["Draft", None],
Anand Doshif78d1ae2014-03-28 13:55:00 +053025 ["Submitted", "eval:self.docstatus==1"],
26 ["Lost", "eval:self.status=='Lost'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053027 ["Ordered", "has_sales_order"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053028 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053029 ],
30 "Sales Order": [
31 ["Draft", None],
Anand Doshif78d1ae2014-03-28 13:55:00 +053032 ["Submitted", "eval:self.docstatus==1"],
33 ["Stopped", "eval:self.status=='Stopped'"],
34 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053035 ],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053036}
37
Anand Doshi424c0332014-04-21 15:06:56 +053038class StatusUpdater(Document):
Nabin Hait0feebc12013-06-03 16:45:38 +053039 """
40 Updates the status of the calling records
41 Delivery Note: Update Delivered Qty, Update Percent and Validate over delivery
42 Sales Invoice: Update Billed Amt, Update Percent and Validate over billing
43 Installation Note: Update Installed Qty, Update Percent Qty and Validate over installation
44 """
45
46 def update_prevdoc_status(self):
47 self.update_qty()
48 self.validate_qty()
Anand Doshi9fd50bc2014-04-09 19:20:01 +053049
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053050 def set_status(self, update=False):
Rushabh Mehtacb067aa2014-08-19 16:20:04 +053051 if self.is_new():
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053052 return
Anand Doshi9fd50bc2014-04-09 19:20:01 +053053
Anand Doshif78d1ae2014-03-28 13:55:00 +053054 if self.doctype in status_map:
Nabin Haitcabf9c52014-08-21 16:34:38 +053055 _status = self.status
Anand Doshif78d1ae2014-03-28 13:55:00 +053056 sl = status_map[self.doctype][:]
Rushabh Mehta6856d742013-10-03 18:12:36 +053057 sl.reverse()
58 for s in sl:
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053059 if not s[1]:
Anand Doshif78d1ae2014-03-28 13:55:00 +053060 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053061 break
Rushabh Mehta6856d742013-10-03 18:12:36 +053062 elif s[1].startswith("eval:"):
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053063 if eval(s[1][5:]):
Anand Doshif78d1ae2014-03-28 13:55:00 +053064 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053065 break
66 elif getattr(self, s[1])():
Anand Doshif78d1ae2014-03-28 13:55:00 +053067 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053068 break
Anand Doshi9fd50bc2014-04-09 19:20:01 +053069
Rushabh Mehtacb067aa2014-08-19 16:20:04 +053070 if self.status != _status:
Anand Doshi7b34ebe2015-01-07 15:41:32 +053071 self.add_comment("Label", _(self.status))
Rushabh Mehtacb067aa2014-08-19 16:20:04 +053072
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053073 if update:
Anand Doshif78d1ae2014-03-28 13:55:00 +053074 frappe.db.set_value(self.doctype, self.name, "status", self.status)
Anand Doshi9fd50bc2014-04-09 19:20:01 +053075
Nabin Hait0feebc12013-06-03 16:45:38 +053076 def validate_qty(self):
Rushabh Mehtaa9ba5ef2014-12-19 16:20:32 +053077 """Validates qty at row level"""
Nabin Hait0feebc12013-06-03 16:45:38 +053078 self.tolerance = {}
79 self.global_tolerance = None
Anand Doshi9fd50bc2014-04-09 19:20:01 +053080
Nabin Hait0feebc12013-06-03 16:45:38 +053081 for args in self.status_updater:
82 # get unique transactions to update
Rushabh Mehtaf191f852014-04-02 18:09:34 +053083 for d in self.get_all_children():
Anand Doshif78d1ae2014-03-28 13:55:00 +053084 if d.doctype == args['source_dt'] and d.get(args["join_field"]):
Rushabh Mehtaf2227d02014-03-31 23:37:40 +053085 args['name'] = d.get(args['join_field'])
Nabin Hait0feebc12013-06-03 16:45:38 +053086
87 # get all qty where qty > target_field
Anand Doshi9fd50bc2014-04-09 19:20:01 +053088 item = frappe.db.sql("""select item_code, `{target_ref_field}`,
89 `{target_field}`, parenttype, parent from `tab{target_dt}`
90 where `{target_ref_field}` < `{target_field}`
91 and name=%s and docstatus=1""".format(**args),
Nabin Hait4d713ac2014-03-03 15:51:13 +053092 args['name'], as_dict=1)
Nabin Hait0feebc12013-06-03 16:45:38 +053093 if item:
94 item = item[0]
95 item['idx'] = d.idx
96 item['target_ref_field'] = args['target_ref_field'].replace('_', ' ')
97
98 if not item[args['target_ref_field']]:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053099 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 +0530100 elif args.get('no_tolerance'):
nabinhaitd5fb5d92014-07-09 17:36:38 +0530101 item['reduce_by'] = item[args['target_field']] - item[args['target_ref_field']]
Nabin Hait0feebc12013-06-03 16:45:38 +0530102 if item['reduce_by'] > .01:
nabinhaitd5fb5d92014-07-09 17:36:38 +0530103 msgprint(_("Allowance for over-{0} crossed for Item {1}")
104 .format(args["overflow_type"], item.item_code))
105 throw(_("{0} must be reduced by {1} or you should increase overflow tolerance")
106 .format(_(item.target_ref_field.title()), item["reduce_by"]))
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530107
Nabin Hait0feebc12013-06-03 16:45:38 +0530108 else:
109 self.check_overflow_with_tolerance(item, args)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530110
Nabin Hait0feebc12013-06-03 16:45:38 +0530111 def check_overflow_with_tolerance(self, item, args):
112 """
113 Checks if there is overflow condering a relaxation tolerance
114 """
Nabin Hait0feebc12013-06-03 16:45:38 +0530115 # check if overflow is within tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530116 tolerance, self.tolerance, self.global_tolerance = get_tolerance_for(item['item_code'],
Nabin Hait7f0406f2014-01-03 17:43:19 +0530117 self.tolerance, self.global_tolerance)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530118
119 overflow_percent = ((item[args['target_field']] - item[args['target_ref_field']]) /
Nabin Hait0feebc12013-06-03 16:45:38 +0530120 item[args['target_ref_field']]) * 100
nabinhait711e8be2014-07-19 17:00:15 +0530121
Nabin Hait0feebc12013-06-03 16:45:38 +0530122 if overflow_percent - tolerance > 0.01:
123 item['max_allowed'] = flt(item[args['target_ref_field']] * (100+tolerance)/100)
124 item['reduce_by'] = item[args['target_field']] - item['max_allowed']
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530125
nabinhaitd5fb5d92014-07-09 17:36:38 +0530126 msgprint(_("Allowance for over-{0} crossed for Item {1}.")
127 .format(args["overflow_type"], item["item_code"]))
128 throw(_("{0} must be reduced by {1} or you should increase overflow tolerance")
129 .format(_(item["target_ref_field"].title()), item["reduce_by"]))
Nabin Hait0feebc12013-06-03 16:45:38 +0530130
131 def update_qty(self, change_modified=True):
132 """
133 Updates qty at row level
134 """
135 for args in self.status_updater:
136 # condition to include current record (if submit or no if cancel)
Anand Doshif78d1ae2014-03-28 13:55:00 +0530137 if self.docstatus == 1:
138 args['cond'] = ' or parent="%s"' % self.name.replace('"', '\"')
Nabin Hait0feebc12013-06-03 16:45:38 +0530139 else:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530140 args['cond'] = ' and parent!="%s"' % self.name.replace('"', '\"')
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530141
Nabin Hait0feebc12013-06-03 16:45:38 +0530142 args['modified_cond'] = ''
143 if change_modified:
144 args['modified_cond'] = ', modified = now()'
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530145
Nabin Hait0feebc12013-06-03 16:45:38 +0530146 # update quantities in child table
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530147 for d in self.get_all_children():
Nabin Hait0feebc12013-06-03 16:45:38 +0530148 if d.doctype == args['source_dt']:
149 # updates qty in the child table
Anand Doshif78d1ae2014-03-28 13:55:00 +0530150 args['detail_id'] = d.get(args['join_field'])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530151
Nabin Hait0feebc12013-06-03 16:45:38 +0530152 args['second_source_condition'] = ""
153 if args.get('second_source_dt') and args.get('second_source_field') \
154 and args.get('second_join_field'):
Rushabh Mehtaa9ba5ef2014-12-19 16:20:32 +0530155 if not args.get("second_source_extra_cond"):
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530156 args["second_source_extra_cond"] = ""
157
Rushabh Mehtac53efc02014-07-01 17:51:34 +0530158 args['second_source_condition'] = """ + ifnull((select sum(%(second_source_field)s)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530159 from `tab%(second_source_dt)s`
160 where `%(second_join_field)s`="%(detail_id)s"
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530161 and (`tab%(second_source_dt)s`.docstatus=1) %(second_source_extra_cond)s), 0) """ % args
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530162
Nabin Hait0feebc12013-06-03 16:45:38 +0530163 if args['detail_id']:
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530164 if not args.get("extra_cond"): args["extra_cond"] = ""
165
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530166 frappe.db.sql("""update `tab%(target_dt)s`
167 set %(target_field)s = (select sum(%(source_field)s)
168 from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s"
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530169 and (docstatus=1 %(cond)s) %(extra_cond)s) %(second_source_condition)s
Nabin Hait0feebc12013-06-03 16:45:38 +0530170 where name='%(detail_id)s'""" % args)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530171
Nabin Hait0feebc12013-06-03 16:45:38 +0530172 # get unique transactions to update
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530173 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 +0530174 if name:
175 args['name'] = name
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530176
Nabin Hait0feebc12013-06-03 16:45:38 +0530177 # update percent complete in the parent table
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530178 if args.get('target_parent_field'):
179 frappe.db.sql("""update `tab%(target_parent_dt)s`
180 set %(target_parent_field)s = (select sum(if(%(target_ref_field)s >
181 ifnull(%(target_field)s, 0), %(target_field)s,
182 %(target_ref_field)s))/sum(%(target_ref_field)s)*100
183 from `tab%(target_dt)s` where parent="%(name)s") %(modified_cond)s
184 where name='%(name)s'""" % args)
Nabin Hait0feebc12013-06-03 16:45:38 +0530185
186 # update field
187 if args.get('status_field'):
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530188 frappe.db.sql("""update `tab%(target_parent_dt)s`
189 set %(status_field)s = if(ifnull(%(target_parent_field)s,0)<0.001,
190 'Not %(keyword)s', if(%(target_parent_field)s>=99.99,
Nabin Hait0feebc12013-06-03 16:45:38 +0530191 'Fully %(keyword)s', 'Partly %(keyword)s'))
Nabin Hait7f0406f2014-01-03 17:43:19 +0530192 where name='%(name)s'""" % args)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530193
194
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530195 def update_billing_status_for_zero_amount_refdoc(self, ref_dt):
196 ref_fieldname = ref_dt.lower().replace(" ", "_")
197 zero_amount_refdoc = []
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530198 all_zero_amount_refdoc = frappe.db.sql_list("""select name from `tab%s`
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530199 where docstatus=1 and net_total = 0""" % ref_dt)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530200
Nabin Hait4b8185d2014-12-25 18:19:39 +0530201 for item in self.get("items"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530202 if item.get(ref_fieldname) \
203 and item.get(ref_fieldname) in all_zero_amount_refdoc \
204 and item.get(ref_fieldname) not in zero_amount_refdoc:
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530205 zero_amount_refdoc.append(item.get(ref_fieldname))
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530206
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530207 if zero_amount_refdoc:
208 self.update_biling_status(zero_amount_refdoc, ref_dt, ref_fieldname)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530209
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530210 def update_biling_status(self, zero_amount_refdoc, ref_dt, ref_fieldname):
211 for ref_dn in zero_amount_refdoc:
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530212 ref_doc_qty = flt(frappe.db.sql("""select sum(ifnull(qty, 0)) from `tab%s Item`
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530213 where parent=%s""" % (ref_dt, '%s'), (ref_dn))[0][0])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530214
215 billed_qty = flt(frappe.db.sql("""select sum(ifnull(qty, 0))
216 from `tab%s Item` where %s=%s and docstatus=1""" %
Anand Doshif78d1ae2014-03-28 13:55:00 +0530217 (self.doctype, ref_fieldname, '%s'), (ref_dn))[0][0])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530218
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530219 per_billed = ((ref_doc_qty if billed_qty > ref_doc_qty else billed_qty)\
220 / ref_doc_qty)*100
Anand Doshie9baaa62014-02-26 12:35:33 +0530221 frappe.db.set_value(ref_dt, ref_dn, "per_billed", per_billed)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530222
Rushabh Mehta0a0f2492014-03-31 17:27:06 +0530223 if frappe.get_meta(ref_dt).get_field("billing_status"):
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530224 if per_billed < 0.001: billing_status = "Not Billed"
225 elif per_billed >= 99.99: billing_status = "Fully Billed"
226 else: billing_status = "Partly Billed"
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530227
Anand Doshie9baaa62014-02-26 12:35:33 +0530228 frappe.db.set_value(ref_dt, ref_dn, "billing_status", billing_status)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530229
Nabin Hait7f0406f2014-01-03 17:43:19 +0530230def get_tolerance_for(item_code, item_tolerance={}, global_tolerance=None):
231 """
232 Returns the tolerance for the item, if not set, returns global tolerance
233 """
234 if item_tolerance.get(item_code):
235 return item_tolerance[item_code], item_tolerance, global_tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530236
Anand Doshie9baaa62014-02-26 12:35:33 +0530237 tolerance = flt(frappe.db.get_value('Item',item_code,'tolerance') or 0)
Nabin Hait7f0406f2014-01-03 17:43:19 +0530238
239 if not tolerance:
240 if global_tolerance == None:
nabinhaitb1c57382014-07-19 16:53:45 +0530241 global_tolerance = flt(frappe.db.get_value('Stock Settings', None, 'tolerance'))
Nabin Hait7f0406f2014-01-03 17:43:19 +0530242 tolerance = global_tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530243
Nabin Hait7f0406f2014-01-03 17:43:19 +0530244 item_tolerance[item_code] = tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530245 return tolerance, item_tolerance, global_tolerance