blob: 7d188678698dddd25ef8d5106ae3b74af8f0e1e6 [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe 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 Mehta9dd8aab2015-05-18 11:18:55 +05306from frappe.utils import flt, comma_or
Rushabh Mehta9f0d6252014-04-14 19:20:45 +05307from 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 Mehta9dd8aab2015-05-18 11:18:55 +053010def validate_status(status, options):
11 if status not in options:
12 frappe.throw(_("Status must be one of {0}").format(comma_or(options)))
13
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053014status_map = {
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053015 "Lead": [
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053016 ["Converted", "has_customer"],
17 ["Opportunity", "has_opportunity"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053018 ],
19 "Opportunity": [
Anand Doshif78d1ae2014-03-28 13:55:00 +053020 ["Lost", "eval:self.status=='Lost'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053021 ["Quotation", "has_quotation"],
Rushabh Mehtafd0f1cb2015-04-13 16:21:58 +053022 ["Converted", "has_ordered_quotation"]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053023 ],
24 "Quotation": [
Rushabh Mehta4ac30942015-04-13 16:56:03 +053025 ["Draft", None],
Anand Doshif78d1ae2014-03-28 13:55:00 +053026 ["Submitted", "eval:self.docstatus==1"],
27 ["Lost", "eval:self.status=='Lost'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053028 ["Ordered", "has_sales_order"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053029 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053030 ],
31 "Sales Order": [
32 ["Draft", None],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053033 ["To Deliver and Bill", "eval:self.per_delivered < 100 and self.per_billed < 100 and self.docstatus == 1"],
34 ["To Bill", "eval:self.per_delivered == 100 and self.per_billed < 100 and self.docstatus == 1"],
35 ["To Deliver", "eval:self.per_delivered < 100 and self.per_billed == 100 and self.docstatus == 1"],
36 ["Completed", "eval:self.per_delivered == 100 and self.per_billed == 100 and self.docstatus == 1"],
37 ["Stopped", "eval:self.status=='Stopped'"],
38 ["Cancelled", "eval:self.docstatus==2"],
39 ],
40 "Purchase Order": [
41 ["Draft", None],
42 ["To Receive and Bill", "eval:self.per_received < 100 and self.per_billed < 100 and self.docstatus == 1"],
43 ["To Bill", "eval:self.per_received == 100 and self.per_billed < 100 and self.docstatus == 1"],
44 ["To Receive", "eval:self.per_received < 100 and self.per_billed == 100 and self.docstatus == 1"],
45 ["Completed", "eval:self.per_received == 100 and self.per_billed == 100 and self.docstatus == 1"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053046 ["Stopped", "eval:self.status=='Stopped'"],
47 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053048 ],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053049 "Delivery Note": [
50 ["Draft", None],
51 ["Submitted", "eval:self.docstatus==1"],
52 ["Cancelled", "eval:self.docstatus==2"],
53 ],
54 "Purchase Receipt": [
55 ["Draft", None],
56 ["Submitted", "eval:self.docstatus==1"],
57 ["Cancelled", "eval:self.docstatus==2"],
58 ]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053059}
60
Anand Doshi424c0332014-04-21 15:06:56 +053061class StatusUpdater(Document):
Nabin Hait0feebc12013-06-03 16:45:38 +053062 """
63 Updates the status of the calling records
64 Delivery Note: Update Delivered Qty, Update Percent and Validate over delivery
65 Sales Invoice: Update Billed Amt, Update Percent and Validate over billing
66 Installation Note: Update Installed Qty, Update Percent Qty and Validate over installation
67 """
68
69 def update_prevdoc_status(self):
70 self.update_qty()
71 self.validate_qty()
Anand Doshi9fd50bc2014-04-09 19:20:01 +053072
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053073 def set_status(self, update=False):
Rushabh Mehtacb067aa2014-08-19 16:20:04 +053074 if self.is_new():
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053075 return
Anand Doshi9fd50bc2014-04-09 19:20:01 +053076
Anand Doshif78d1ae2014-03-28 13:55:00 +053077 if self.doctype in status_map:
Nabin Haitcabf9c52014-08-21 16:34:38 +053078 _status = self.status
Anand Doshif78d1ae2014-03-28 13:55:00 +053079 sl = status_map[self.doctype][:]
Rushabh Mehta6856d742013-10-03 18:12:36 +053080 sl.reverse()
81 for s in sl:
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053082 if not s[1]:
Anand Doshif78d1ae2014-03-28 13:55:00 +053083 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053084 break
Rushabh Mehta6856d742013-10-03 18:12:36 +053085 elif s[1].startswith("eval:"):
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053086 if eval(s[1][5:]):
Anand Doshif78d1ae2014-03-28 13:55:00 +053087 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053088 break
89 elif getattr(self, s[1])():
Anand Doshif78d1ae2014-03-28 13:55:00 +053090 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053091 break
Anand Doshi9fd50bc2014-04-09 19:20:01 +053092
Rushabh Mehtac8b406d2015-06-02 12:17:14 +053093 if self.status != _status and self.status not in ("Submitted", "Cancelled"):
Anand Doshi7b34ebe2015-01-07 15:41:32 +053094 self.add_comment("Label", _(self.status))
Rushabh Mehtacb067aa2014-08-19 16:20:04 +053095
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053096 if update:
Anand Doshif78d1ae2014-03-28 13:55:00 +053097 frappe.db.set_value(self.doctype, self.name, "status", self.status)
Anand Doshi9fd50bc2014-04-09 19:20:01 +053098
Nabin Hait0feebc12013-06-03 16:45:38 +053099 def validate_qty(self):
Rushabh Mehtaa9ba5ef2014-12-19 16:20:32 +0530100 """Validates qty at row level"""
Nabin Hait0feebc12013-06-03 16:45:38 +0530101 self.tolerance = {}
102 self.global_tolerance = None
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530103
Nabin Hait0feebc12013-06-03 16:45:38 +0530104 for args in self.status_updater:
Anand Doshife13bfe2015-08-25 12:49:40 +0530105 if "target_ref_field" not in args:
106 # if target_ref_field is not specified, the programmer does not want to validate qty / amount
107 continue
108
Nabin Hait0feebc12013-06-03 16:45:38 +0530109 # get unique transactions to update
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530110 for d in self.get_all_children():
Anand Doshif78d1ae2014-03-28 13:55:00 +0530111 if d.doctype == args['source_dt'] and d.get(args["join_field"]):
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530112 args['name'] = d.get(args['join_field'])
Nabin Hait0feebc12013-06-03 16:45:38 +0530113
114 # get all qty where qty > target_field
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530115 item = frappe.db.sql("""select item_code, `{target_ref_field}`,
116 `{target_field}`, parenttype, parent from `tab{target_dt}`
117 where `{target_ref_field}` < `{target_field}`
118 and name=%s and docstatus=1""".format(**args),
Nabin Hait4d713ac2014-03-03 15:51:13 +0530119 args['name'], as_dict=1)
Nabin Hait0feebc12013-06-03 16:45:38 +0530120 if item:
121 item = item[0]
122 item['idx'] = d.idx
123 item['target_ref_field'] = args['target_ref_field'].replace('_', ' ')
124
125 if not item[args['target_ref_field']]:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530126 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 +0530127 elif args.get('no_tolerance'):
nabinhaitd5fb5d92014-07-09 17:36:38 +0530128 item['reduce_by'] = item[args['target_field']] - item[args['target_ref_field']]
Nabin Hait0feebc12013-06-03 16:45:38 +0530129 if item['reduce_by'] > .01:
nabinhaitd5fb5d92014-07-09 17:36:38 +0530130 msgprint(_("Allowance for over-{0} crossed for Item {1}")
131 .format(args["overflow_type"], item.item_code))
132 throw(_("{0} must be reduced by {1} or you should increase overflow tolerance")
133 .format(_(item.target_ref_field.title()), item["reduce_by"]))
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530134
Nabin Hait0feebc12013-06-03 16:45:38 +0530135 else:
136 self.check_overflow_with_tolerance(item, args)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530137
Nabin Hait0feebc12013-06-03 16:45:38 +0530138 def check_overflow_with_tolerance(self, item, args):
139 """
140 Checks if there is overflow condering a relaxation tolerance
141 """
Nabin Hait0feebc12013-06-03 16:45:38 +0530142 # check if overflow is within tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530143 tolerance, self.tolerance, self.global_tolerance = get_tolerance_for(item['item_code'],
Nabin Hait7f0406f2014-01-03 17:43:19 +0530144 self.tolerance, self.global_tolerance)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530145
146 overflow_percent = ((item[args['target_field']] - item[args['target_ref_field']]) /
Nabin Hait0feebc12013-06-03 16:45:38 +0530147 item[args['target_ref_field']]) * 100
nabinhait711e8be2014-07-19 17:00:15 +0530148
Nabin Hait0feebc12013-06-03 16:45:38 +0530149 if overflow_percent - tolerance > 0.01:
150 item['max_allowed'] = flt(item[args['target_ref_field']] * (100+tolerance)/100)
151 item['reduce_by'] = item[args['target_field']] - item['max_allowed']
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530152
nabinhaitd5fb5d92014-07-09 17:36:38 +0530153 msgprint(_("Allowance for over-{0} crossed for Item {1}.")
154 .format(args["overflow_type"], item["item_code"]))
155 throw(_("{0} must be reduced by {1} or you should increase overflow tolerance")
156 .format(_(item["target_ref_field"].title()), item["reduce_by"]))
Nabin Hait0feebc12013-06-03 16:45:38 +0530157
158 def update_qty(self, change_modified=True):
Anand Doshife13bfe2015-08-25 12:49:40 +0530159 """Updates qty or amount at row level
160
161 :param change_modified: If true, updates `modified` and `modified_by` for target parent doc
Nabin Hait0feebc12013-06-03 16:45:38 +0530162 """
163 for args in self.status_updater:
164 # condition to include current record (if submit or no if cancel)
Anand Doshif78d1ae2014-03-28 13:55:00 +0530165 if self.docstatus == 1:
166 args['cond'] = ' or parent="%s"' % self.name.replace('"', '\"')
Nabin Hait0feebc12013-06-03 16:45:38 +0530167 else:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530168 args['cond'] = ' and parent!="%s"' % self.name.replace('"', '\"')
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530169
Anand Doshife13bfe2015-08-25 12:49:40 +0530170 args['set_modified'] = ''
Nabin Hait0feebc12013-06-03 16:45:38 +0530171 if change_modified:
Anand Doshife13bfe2015-08-25 12:49:40 +0530172 args['set_modified'] = ', modified = now(), modified_by = "{0}"'\
173 .format(frappe.db.escape(frappe.session.user))
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530174
Anand Doshife13bfe2015-08-25 12:49:40 +0530175 self._update_children(args)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530176
Anand Doshife13bfe2015-08-25 12:49:40 +0530177 if "percent_join_field" in args:
178 self._update_percent_field(args)
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530179
Anand Doshife13bfe2015-08-25 12:49:40 +0530180 def _update_children(self, args):
181 """Update quantities or amount in child table"""
182 for d in self.get_all_children():
183 if d.doctype != args['source_dt']:
184 continue
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530185
Anand Doshife13bfe2015-08-25 12:49:40 +0530186 # updates qty in the child table
187 args['detail_id'] = d.get(args['join_field'])
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530188
Anand Doshife13bfe2015-08-25 12:49:40 +0530189 args['second_source_condition'] = ""
190 if args.get('second_source_dt') and args.get('second_source_field') \
191 and args.get('second_join_field'):
192 if not args.get("second_source_extra_cond"):
193 args["second_source_extra_cond"] = ""
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530194
Anand Doshife13bfe2015-08-25 12:49:40 +0530195 args['second_source_condition'] = """ + ifnull((select sum(%(second_source_field)s)
196 from `tab%(second_source_dt)s`
197 where `%(second_join_field)s`="%(detail_id)s"
198 and (`tab%(second_source_dt)s`.docstatus=1) %(second_source_extra_cond)s), 0) """ % args
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530199
Anand Doshife13bfe2015-08-25 12:49:40 +0530200 if args['detail_id']:
201 if not args.get("extra_cond"): args["extra_cond"] = ""
Nabin Hait0feebc12013-06-03 16:45:38 +0530202
Anand Doshife13bfe2015-08-25 12:49:40 +0530203 frappe.db.sql("""update `tab%(target_dt)s`
204 set %(target_field)s = (select sum(%(source_field)s)
205 from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s"
206 and (docstatus=1 %(cond)s) %(extra_cond)s) %(second_source_condition)s
207 where name='%(detail_id)s'""" % args)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530208
Anand Doshife13bfe2015-08-25 12:49:40 +0530209 def _update_percent_field(self, args):
210 """Update percent field in parent transaction"""
211 unique_transactions = set([d.get(args['percent_join_field']) for d in self.get_all_children(args['source_dt'])])
212
213 for name in unique_transactions:
214 if not name:
215 continue
216
217 args['name'] = name
218
219 # update percent complete in the parent table
220 if args.get('target_parent_field'):
221 frappe.db.sql("""update `tab%(target_parent_dt)s`
Anand Doshid970b002015-09-25 17:57:20 +0530222 set %(target_parent_field)s = round((select sum(if(%(target_ref_field)s >
Anand Doshife13bfe2015-08-25 12:49:40 +0530223 ifnull(%(target_field)s, 0), %(target_field)s,
224 %(target_ref_field)s))/sum(%(target_ref_field)s)*100
Anand Doshid970b002015-09-25 17:57:20 +0530225 from `tab%(target_dt)s` where parent="%(name)s"), 2) %(set_modified)s
Anand Doshife13bfe2015-08-25 12:49:40 +0530226 where name='%(name)s'""" % args)
227
228 # update field
229 if args.get('status_field'):
230 frappe.db.sql("""update `tab%(target_parent_dt)s`
231 set %(status_field)s = if(ifnull(%(target_parent_field)s,0)<0.001,
232 'Not %(keyword)s', if(%(target_parent_field)s>=99.99,
233 'Fully %(keyword)s', 'Partly %(keyword)s'))
234 where name='%(name)s'""" % args)
235
236 if args.get("set_modified"):
Rushabh Mehtad10ba852015-10-02 12:42:48 +0530237 target = frappe.get_doc(args["target_parent_dt"], name)
238 target.set_status(update=True)
239 target.notify_update()
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530240
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530241 def update_billing_status_for_zero_amount_refdoc(self, ref_dt):
242 ref_fieldname = ref_dt.lower().replace(" ", "_")
243 zero_amount_refdoc = []
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530244 all_zero_amount_refdoc = frappe.db.sql_list("""select name from `tab%s`
Nabin Hait5690be12015-02-12 16:09:11 +0530245 where docstatus=1 and base_net_total = 0""" % ref_dt)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530246
Nabin Hait4b8185d2014-12-25 18:19:39 +0530247 for item in self.get("items"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530248 if item.get(ref_fieldname) \
249 and item.get(ref_fieldname) in all_zero_amount_refdoc \
250 and item.get(ref_fieldname) not in zero_amount_refdoc:
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530251 zero_amount_refdoc.append(item.get(ref_fieldname))
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530252
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530253 if zero_amount_refdoc:
254 self.update_biling_status(zero_amount_refdoc, ref_dt, ref_fieldname)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530255
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530256 def update_biling_status(self, zero_amount_refdoc, ref_dt, ref_fieldname):
257 for ref_dn in zero_amount_refdoc:
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530258 ref_doc_qty = flt(frappe.db.sql("""select sum(ifnull(qty, 0)) from `tab%s Item`
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530259 where parent=%s""" % (ref_dt, '%s'), (ref_dn))[0][0])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530260
261 billed_qty = flt(frappe.db.sql("""select sum(ifnull(qty, 0))
262 from `tab%s Item` where %s=%s and docstatus=1""" %
Anand Doshif78d1ae2014-03-28 13:55:00 +0530263 (self.doctype, ref_fieldname, '%s'), (ref_dn))[0][0])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530264
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530265 per_billed = ((ref_doc_qty if billed_qty > ref_doc_qty else billed_qty)\
266 / ref_doc_qty)*100
Anand Doshie9baaa62014-02-26 12:35:33 +0530267 frappe.db.set_value(ref_dt, ref_dn, "per_billed", per_billed)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530268
Rushabh Mehta0a0f2492014-03-31 17:27:06 +0530269 if frappe.get_meta(ref_dt).get_field("billing_status"):
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530270 if per_billed < 0.001: billing_status = "Not Billed"
271 elif per_billed >= 99.99: billing_status = "Fully Billed"
272 else: billing_status = "Partly Billed"
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530273
Anand Doshie9baaa62014-02-26 12:35:33 +0530274 frappe.db.set_value(ref_dt, ref_dn, "billing_status", billing_status)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530275
Nabin Hait7f0406f2014-01-03 17:43:19 +0530276def get_tolerance_for(item_code, item_tolerance={}, global_tolerance=None):
277 """
278 Returns the tolerance for the item, if not set, returns global tolerance
279 """
280 if item_tolerance.get(item_code):
281 return item_tolerance[item_code], item_tolerance, global_tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530282
Anand Doshie9baaa62014-02-26 12:35:33 +0530283 tolerance = flt(frappe.db.get_value('Item',item_code,'tolerance') or 0)
Nabin Hait7f0406f2014-01-03 17:43:19 +0530284
285 if not tolerance:
286 if global_tolerance == None:
nabinhaitb1c57382014-07-19 16:53:45 +0530287 global_tolerance = flt(frappe.db.get_value('Stock Settings', None, 'tolerance'))
Nabin Hait7f0406f2014-01-03 17:43:19 +0530288 tolerance = global_tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530289
Nabin Hait7f0406f2014-01-03 17:43:19 +0530290 item_tolerance[item_code] = tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530291 return tolerance, item_tolerance, global_tolerance