blob: cb783b4db348da8d5ed16222728169105c1f2d6a [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
Rohit Waghchaure2f1db572016-11-08 12:39:33 +05306from frappe.utils import flt, comma_or, nowdate, getdate
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05307from frappe import _
Anand Doshi424c0332014-04-21 15:06:56 +05308from frappe.model.document import Document
Rushabh Mehtafc8e5892016-07-20 12:08:47 +05309from erpnext.accounts.party_status import notify_status
Nabin Hait0feebc12013-06-03 16:45:38 +053010
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053011def validate_status(status, options):
12 if status not in options:
13 frappe.throw(_("Status must be one of {0}").format(comma_or(options)))
14
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053015status_map = {
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053016 "Lead": [
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053017 ["Converted", "has_customer"],
18 ["Opportunity", "has_opportunity"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053019 ],
20 "Opportunity": [
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053021 ["Quotation", "has_quotation"],
Valmik Jangla29563272016-03-29 11:13:07 +053022 ["Converted", "has_ordered_quotation"],
23 ["Lost", "eval:self.status=='Lost'"],
24 ["Closed", "eval:self.status=='Closed'"]
25
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053026 ],
27 "Quotation": [
Rushabh Mehta4ac30942015-04-13 16:56:03 +053028 ["Draft", None],
Anand Doshif78d1ae2014-03-28 13:55:00 +053029 ["Submitted", "eval:self.docstatus==1"],
30 ["Lost", "eval:self.status=='Lost'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053031 ["Ordered", "has_sales_order"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053032 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053033 ],
34 "Sales Order": [
35 ["Draft", None],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053036 ["To Deliver and Bill", "eval:self.per_delivered < 100 and self.per_billed < 100 and self.docstatus == 1"],
37 ["To Bill", "eval:self.per_delivered == 100 and self.per_billed < 100 and self.docstatus == 1"],
38 ["To Deliver", "eval:self.per_delivered < 100 and self.per_billed == 100 and self.docstatus == 1"],
39 ["Completed", "eval:self.per_delivered == 100 and self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehta86125b22015-10-13 11:48:08 +053040 ["Completed", "eval:self.order_type == 'Maintenance' and self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053041 ["Cancelled", "eval:self.docstatus==2"],
Saurabhc6dbe702015-10-19 14:17:52 +053042 ["Closed", "eval:self.status=='Closed'"],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053043 ],
Rohit Waghchaure2f1db572016-11-08 12:39:33 +053044 "Sales Invoice": [
45 ["Draft", None],
46 ["Submitted", "eval:self.docstatus==1"],
47 ["Paid", "eval:self.outstanding_amount==0 and self.docstatus==1"],
48 ["Unpaid", "eval:self.outstanding_amount > 0 and getdate(self.due_date) >= getdate(nowdate()) and self.docstatus==1"],
49 ["Overdue", "eval:self.outstanding_amount > 0 and getdate(self.due_date) < getdate(nowdate()) and self.docstatus==1"],
50 ["Cancelled", "eval:self.docstatus==2"],
51 ],
52 "Purchase Invoice": [
53 ["Draft", None],
54 ["Submitted", "eval:self.docstatus==1"],
55 ["Paid", "eval:self.outstanding_amount==0 and self.docstatus==1"],
56 ["Unpaid", "eval:self.outstanding_amount > 0 and getdate(self.due_date) >= getdate(nowdate()) and self.docstatus==1"],
57 ["Overdue", "eval:self.outstanding_amount > 0 and getdate(self.due_date) < getdate(nowdate()) and self.docstatus==1"],
58 ["Cancelled", "eval:self.docstatus==2"],
59 ],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053060 "Purchase Order": [
61 ["Draft", None],
62 ["To Receive and Bill", "eval:self.per_received < 100 and self.per_billed < 100 and self.docstatus == 1"],
63 ["To Bill", "eval:self.per_received == 100 and self.per_billed < 100 and self.docstatus == 1"],
64 ["To Receive", "eval:self.per_received < 100 and self.per_billed == 100 and self.docstatus == 1"],
65 ["Completed", "eval:self.per_received == 100 and self.per_billed == 100 and self.docstatus == 1"],
Saurabh6d64fe32015-10-23 10:40:32 +053066 ["Delivered", "eval:self.status=='Delivered'"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053067 ["Cancelled", "eval:self.docstatus==2"],
Saurabh98b28752015-10-19 15:16:17 +053068 ["Closed", "eval:self.status=='Closed'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053069 ],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053070 "Delivery Note": [
71 ["Draft", None],
Nabin Hait5b13b992015-12-28 13:03:55 +053072 ["To Bill", "eval:self.per_billed < 100 and self.docstatus == 1"],
73 ["Completed", "eval:self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053074 ["Cancelled", "eval:self.docstatus==2"],
Saurabha8a91cc2015-11-02 12:57:08 +053075 ["Closed", "eval:self.status=='Closed'"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053076 ],
77 "Purchase Receipt": [
78 ["Draft", None],
Nabin Haitbdab0ee2015-12-30 19:08:11 +053079 ["To Bill", "eval:self.per_billed < 100 and self.docstatus == 1"],
80 ["Completed", "eval:self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053081 ["Cancelled", "eval:self.docstatus==2"],
Saurabha8a91cc2015-11-02 12:57:08 +053082 ["Closed", "eval:self.status=='Closed'"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053083 ]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053084}
85
Anand Doshi424c0332014-04-21 15:06:56 +053086class StatusUpdater(Document):
Nabin Hait0feebc12013-06-03 16:45:38 +053087 """
88 Updates the status of the calling records
89 Delivery Note: Update Delivered Qty, Update Percent and Validate over delivery
90 Sales Invoice: Update Billed Amt, Update Percent and Validate over billing
91 Installation Note: Update Installed Qty, Update Percent Qty and Validate over installation
92 """
93
94 def update_prevdoc_status(self):
95 self.update_qty()
96 self.validate_qty()
Anand Doshi9fd50bc2014-04-09 19:20:01 +053097
Saurabh70ed6ed2015-12-08 14:02:53 +053098 def set_status(self, update=False, status=None, update_modified=True):
Rushabh Mehtacb067aa2014-08-19 16:20:04 +053099 if self.is_new():
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530100 return
Anand Doshi6b71ef52016-01-06 16:32:06 +0530101
Anand Doshif78d1ae2014-03-28 13:55:00 +0530102 if self.doctype in status_map:
Nabin Haitcabf9c52014-08-21 16:34:38 +0530103 _status = self.status
Rushabh Mehtad48c2392015-11-04 15:20:50 +0530104
105 if status and update:
106 self.db_set("status", status)
107
Anand Doshif78d1ae2014-03-28 13:55:00 +0530108 sl = status_map[self.doctype][:]
Rushabh Mehta6856d742013-10-03 18:12:36 +0530109 sl.reverse()
110 for s in sl:
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530111 if not s[1]:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530112 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530113 break
Rushabh Mehta6856d742013-10-03 18:12:36 +0530114 elif s[1].startswith("eval:"):
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530115 if eval(s[1][5:]):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530116 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530117 break
118 elif getattr(self, s[1])():
Anand Doshif78d1ae2014-03-28 13:55:00 +0530119 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530120 break
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530121
Rushabh Mehtac8b406d2015-06-02 12:17:14 +0530122 if self.status != _status and self.status not in ("Submitted", "Cancelled"):
Anand Doshi7b34ebe2015-01-07 15:41:32 +0530123 self.add_comment("Label", _(self.status))
Anand Doshi6b71ef52016-01-06 16:32:06 +0530124
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530125 if update:
Rushabh Mehtafc8e5892016-07-20 12:08:47 +0530126 self.db_set('status', self.status, update_modified = update_modified)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530127
Nabin Hait0feebc12013-06-03 16:45:38 +0530128 def validate_qty(self):
Rushabh Mehtaa9ba5ef2014-12-19 16:20:32 +0530129 """Validates qty at row level"""
Nabin Hait0feebc12013-06-03 16:45:38 +0530130 self.tolerance = {}
131 self.global_tolerance = None
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530132
Nabin Hait0feebc12013-06-03 16:45:38 +0530133 for args in self.status_updater:
Anand Doshife13bfe2015-08-25 12:49:40 +0530134 if "target_ref_field" not in args:
135 # if target_ref_field is not specified, the programmer does not want to validate qty / amount
136 continue
137
Nabin Hait0feebc12013-06-03 16:45:38 +0530138 # get unique transactions to update
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530139 for d in self.get_all_children():
Anand Doshif78d1ae2014-03-28 13:55:00 +0530140 if d.doctype == args['source_dt'] and d.get(args["join_field"]):
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530141 args['name'] = d.get(args['join_field'])
Nabin Hait0feebc12013-06-03 16:45:38 +0530142
143 # get all qty where qty > target_field
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530144 item = frappe.db.sql("""select item_code, `{target_ref_field}`,
145 `{target_field}`, parenttype, parent from `tab{target_dt}`
146 where `{target_ref_field}` < `{target_field}`
147 and name=%s and docstatus=1""".format(**args),
Nabin Hait4d713ac2014-03-03 15:51:13 +0530148 args['name'], as_dict=1)
Nabin Hait0feebc12013-06-03 16:45:38 +0530149 if item:
150 item = item[0]
151 item['idx'] = d.idx
152 item['target_ref_field'] = args['target_ref_field'].replace('_', ' ')
153
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530154 # if not item[args['target_ref_field']]:
155 # msgprint(_("Note: System will not check over-delivery and over-booking for Item {0} as quantity or amount is 0").format(item.item_code))
156 if args.get('no_tolerance'):
nabinhaitd5fb5d92014-07-09 17:36:38 +0530157 item['reduce_by'] = item[args['target_field']] - item[args['target_ref_field']]
Nabin Hait0feebc12013-06-03 16:45:38 +0530158 if item['reduce_by'] > .01:
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530159 self.limits_crossed_error(args, item)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530160
Nabin Hait47a3f632016-08-26 11:39:23 +0530161 elif item[args['target_ref_field']]:
Nabin Hait0feebc12013-06-03 16:45:38 +0530162 self.check_overflow_with_tolerance(item, args)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530163
Nabin Hait0feebc12013-06-03 16:45:38 +0530164 def check_overflow_with_tolerance(self, item, args):
165 """
166 Checks if there is overflow condering a relaxation tolerance
167 """
Nabin Hait0feebc12013-06-03 16:45:38 +0530168 # check if overflow is within tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530169 tolerance, self.tolerance, self.global_tolerance = get_tolerance_for(item['item_code'],
Nabin Hait7f0406f2014-01-03 17:43:19 +0530170 self.tolerance, self.global_tolerance)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530171 overflow_percent = ((item[args['target_field']] - item[args['target_ref_field']]) /
Nabin Hait0feebc12013-06-03 16:45:38 +0530172 item[args['target_ref_field']]) * 100
nabinhait711e8be2014-07-19 17:00:15 +0530173
Nabin Hait0feebc12013-06-03 16:45:38 +0530174 if overflow_percent - tolerance > 0.01:
175 item['max_allowed'] = flt(item[args['target_ref_field']] * (100+tolerance)/100)
176 item['reduce_by'] = item[args['target_field']] - item['max_allowed']
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530177
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530178 self.limits_crossed_error(args, item)
179
180 def limits_crossed_error(self, args, item):
181 '''Raise exception for limits crossed'''
182 frappe.throw(_('This document is over limit by {0} {1} for item {4}. Are you making another {3} against the same {2}?')
183 .format(
184 frappe.bold(_(item["target_ref_field"].title())),
185 frappe.bold(item["reduce_by"]),
186 frappe.bold(_(args.get('target_dt'))),
187 frappe.bold(_(self.doctype)),
188 frappe.bold(item.get('item_code'))
189 ) + '<br><br>' +
190 _('To allow over-billing or over-ordering, update "Allowance" in Stock Settings or the Item.'),
191 title = _('Limit Crossed'))
Nabin Hait0feebc12013-06-03 16:45:38 +0530192
Anand Doshi6b71ef52016-01-06 16:32:06 +0530193 def update_qty(self, update_modified=True):
Anand Doshife13bfe2015-08-25 12:49:40 +0530194 """Updates qty or amount at row level
195
Anand Doshi6b71ef52016-01-06 16:32:06 +0530196 :param update_modified: If true, updates `modified` and `modified_by` for target parent doc
Nabin Hait0feebc12013-06-03 16:45:38 +0530197 """
198 for args in self.status_updater:
199 # condition to include current record (if submit or no if cancel)
Anand Doshif78d1ae2014-03-28 13:55:00 +0530200 if self.docstatus == 1:
201 args['cond'] = ' or parent="%s"' % self.name.replace('"', '\"')
Nabin Hait0feebc12013-06-03 16:45:38 +0530202 else:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530203 args['cond'] = ' and parent!="%s"' % self.name.replace('"', '\"')
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530204
Anand Doshi6b71ef52016-01-06 16:32:06 +0530205 self._update_children(args, update_modified)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530206
Anand Doshife13bfe2015-08-25 12:49:40 +0530207 if "percent_join_field" in args:
Anand Doshi6b71ef52016-01-06 16:32:06 +0530208 self._update_percent_field_in_targets(args, update_modified)
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530209
Anand Doshi6b71ef52016-01-06 16:32:06 +0530210 def _update_children(self, args, update_modified):
Anand Doshife13bfe2015-08-25 12:49:40 +0530211 """Update quantities or amount in child table"""
212 for d in self.get_all_children():
213 if d.doctype != args['source_dt']:
214 continue
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530215
Anand Doshi6b71ef52016-01-06 16:32:06 +0530216 self._update_modified(args, update_modified)
217
Anand Doshife13bfe2015-08-25 12:49:40 +0530218 # updates qty in the child table
219 args['detail_id'] = d.get(args['join_field'])
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530220
Anand Doshife13bfe2015-08-25 12:49:40 +0530221 args['second_source_condition'] = ""
222 if args.get('second_source_dt') and args.get('second_source_field') \
223 and args.get('second_join_field'):
224 if not args.get("second_source_extra_cond"):
225 args["second_source_extra_cond"] = ""
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530226
Anand Doshife13bfe2015-08-25 12:49:40 +0530227 args['second_source_condition'] = """ + ifnull((select sum(%(second_source_field)s)
228 from `tab%(second_source_dt)s`
229 where `%(second_join_field)s`="%(detail_id)s"
230 and (`tab%(second_source_dt)s`.docstatus=1) %(second_source_extra_cond)s), 0) """ % args
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530231
Anand Doshife13bfe2015-08-25 12:49:40 +0530232 if args['detail_id']:
233 if not args.get("extra_cond"): args["extra_cond"] = ""
Nabin Hait0feebc12013-06-03 16:45:38 +0530234
Anand Doshife13bfe2015-08-25 12:49:40 +0530235 frappe.db.sql("""update `tab%(target_dt)s`
Anand Doshi6b71ef52016-01-06 16:32:06 +0530236 set %(target_field)s = (
237 (select ifnull(sum(%(source_field)s), 0)
238 from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s"
239 and (docstatus=1 %(cond)s) %(extra_cond)s)
240 %(second_source_condition)s
241 )
242 %(update_modified)s
Anand Doshife13bfe2015-08-25 12:49:40 +0530243 where name='%(detail_id)s'""" % args)
Anand Doshi6b71ef52016-01-06 16:32:06 +0530244
245 def _update_percent_field_in_targets(self, args, update_modified=True):
Anand Doshife13bfe2015-08-25 12:49:40 +0530246 """Update percent field in parent transaction"""
Anand Doshi6b71ef52016-01-06 16:32:06 +0530247 distinct_transactions = set([d.get(args['percent_join_field'])
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530248 for d in self.get_all_children(args['source_dt'])])
Anand Doshife13bfe2015-08-25 12:49:40 +0530249
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530250 for name in distinct_transactions:
251 if name:
252 args['name'] = name
Anand Doshi6b71ef52016-01-06 16:32:06 +0530253 self._update_percent_field(args, update_modified)
Anand Doshife13bfe2015-08-25 12:49:40 +0530254
Anand Doshi6b71ef52016-01-06 16:32:06 +0530255 def _update_percent_field(self, args, update_modified=True):
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530256 """Update percent field in parent transaction"""
Anand Doshi6b71ef52016-01-06 16:32:06 +0530257
258 self._update_modified(args, update_modified)
259
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530260 if args.get('target_parent_field'):
261 frappe.db.sql("""update `tab%(target_parent_dt)s`
262 set %(target_parent_field)s = round(
263 ifnull((select
RobertSchoutendb33ebb2016-09-12 14:54:46 +0800264 ifnull(sum(if(%(target_ref_field)s > %(target_field)s, abs(%(target_field)s), abs(%(target_ref_field)s))), 0)
265 / sum(abs(%(target_ref_field)s)) * 100
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530266 from `tab%(target_dt)s` where parent="%(name)s"), 0), 2)
Anand Doshi6b71ef52016-01-06 16:32:06 +0530267 %(update_modified)s
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530268 where name='%(name)s'""" % args)
Anand Doshife13bfe2015-08-25 12:49:40 +0530269
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530270 # update field
271 if args.get('status_field'):
272 frappe.db.sql("""update `tab%(target_parent_dt)s`
273 set %(status_field)s = if(%(target_parent_field)s<0.001,
274 'Not %(keyword)s', if(%(target_parent_field)s>=99.99,
275 'Fully %(keyword)s', 'Partly %(keyword)s'))
276 where name='%(name)s'""" % args)
Anand Doshife13bfe2015-08-25 12:49:40 +0530277
Anand Doshi6b71ef52016-01-06 16:32:06 +0530278 if update_modified:
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530279 target = frappe.get_doc(args["target_parent_dt"], args["name"])
280 target.set_status(update=True)
281 target.notify_update()
Rushabh Mehtafc8e5892016-07-20 12:08:47 +0530282 notify_status(target)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530283
Anand Doshi6b71ef52016-01-06 16:32:06 +0530284 def _update_modified(self, args, update_modified):
285 args['update_modified'] = ''
286 if update_modified:
287 args['update_modified'] = ', modified = now(), modified_by = "{0}"'\
288 .format(frappe.db.escape(frappe.session.user))
289
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530290 def update_billing_status_for_zero_amount_refdoc(self, ref_dt):
291 ref_fieldname = ref_dt.lower().replace(" ", "_")
292 zero_amount_refdoc = []
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530293 all_zero_amount_refdoc = frappe.db.sql_list("""select name from `tab%s`
Nabin Hait5690be12015-02-12 16:09:11 +0530294 where docstatus=1 and base_net_total = 0""" % ref_dt)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530295
Nabin Hait4b8185d2014-12-25 18:19:39 +0530296 for item in self.get("items"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530297 if item.get(ref_fieldname) \
298 and item.get(ref_fieldname) in all_zero_amount_refdoc \
299 and item.get(ref_fieldname) not in zero_amount_refdoc:
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530300 zero_amount_refdoc.append(item.get(ref_fieldname))
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530301
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530302 if zero_amount_refdoc:
Rushabh Mehtad48c2392015-11-04 15:20:50 +0530303 self.update_billing_status(zero_amount_refdoc, ref_dt, ref_fieldname)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530304
Rushabh Mehtad48c2392015-11-04 15:20:50 +0530305 def update_billing_status(self, zero_amount_refdoc, ref_dt, ref_fieldname):
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530306 for ref_dn in zero_amount_refdoc:
Anand Doshiebae7262015-11-25 15:51:01 +0530307 ref_doc_qty = flt(frappe.db.sql("""select ifnull(sum(qty), 0) from `tab%s Item`
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530308 where parent=%s""" % (ref_dt, '%s'), (ref_dn))[0][0])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530309
Anand Doshiebae7262015-11-25 15:51:01 +0530310 billed_qty = flt(frappe.db.sql("""select ifnull(sum(qty), 0)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530311 from `tab%s Item` where %s=%s and docstatus=1""" %
Anand Doshif78d1ae2014-03-28 13:55:00 +0530312 (self.doctype, ref_fieldname, '%s'), (ref_dn))[0][0])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530313
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530314 per_billed = ((ref_doc_qty if billed_qty > ref_doc_qty else billed_qty)\
315 / ref_doc_qty)*100
Rushabh Mehtafc8e5892016-07-20 12:08:47 +0530316
317 ref_doc = frappe.get_doc(ref_dt, ref_dn)
318
319 ref_doc.db_set("per_billed", per_billed)
Rohit Waghchaure770d04e2016-10-05 23:02:15 +0530320 ref_doc.set_status(update=True)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530321
Nabin Hait7f0406f2014-01-03 17:43:19 +0530322def get_tolerance_for(item_code, item_tolerance={}, global_tolerance=None):
323 """
324 Returns the tolerance for the item, if not set, returns global tolerance
325 """
326 if item_tolerance.get(item_code):
327 return item_tolerance[item_code], item_tolerance, global_tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530328
Anand Doshie9baaa62014-02-26 12:35:33 +0530329 tolerance = flt(frappe.db.get_value('Item',item_code,'tolerance') or 0)
Nabin Hait7f0406f2014-01-03 17:43:19 +0530330
331 if not tolerance:
332 if global_tolerance == None:
nabinhaitb1c57382014-07-19 16:53:45 +0530333 global_tolerance = flt(frappe.db.get_value('Stock Settings', None, 'tolerance'))
Nabin Hait7f0406f2014-01-03 17:43:19 +0530334 tolerance = global_tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530335
Nabin Hait7f0406f2014-01-03 17:43:19 +0530336 item_tolerance[item_code] = tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530337 return tolerance, item_tolerance, global_tolerance