blob: ddfd8b398c6b68272d743c19ed88020b1c37277e [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
Makarand Bauskar4782e8b2017-04-07 06:46:16 -05006from 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
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": [
Nabin Haitf49bbe12016-12-15 11:51:54 +053016 ["Lost Quotation", "has_lost_quotation"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053017 ["Opportunity", "has_opportunity"],
Alec Ruiz-Ramonfcaaa292016-06-09 14:19:51 -040018 ["Quotation", "has_quotation"],
19 ["Converted", "has_customer"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053020 ],
21 "Opportunity": [
Valmik Jangla29563272016-03-29 11:13:07 +053022 ["Lost", "eval:self.status=='Lost'"],
Alec Ruiz-Ramonfcaaa292016-06-09 14:19:51 -040023 ["Lost", "has_lost_quotation"],
Nabin Hait6a5cf672017-05-30 15:34:20 +053024 ["Quotation", "has_active_quotation"],
25 ["Converted", "has_ordered_quotation"],
Valmik Jangla29563272016-03-29 11:13:07 +053026 ["Closed", "eval:self.status=='Closed'"]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053027 ],
28 "Quotation": [
Rushabh Mehta4ac30942015-04-13 16:56:03 +053029 ["Draft", None],
Anand Doshif78d1ae2014-03-28 13:55:00 +053030 ["Submitted", "eval:self.docstatus==1"],
31 ["Lost", "eval:self.status=='Lost'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053032 ["Ordered", "has_sales_order"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053033 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053034 ],
35 "Sales Order": [
36 ["Draft", None],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053037 ["To Deliver and Bill", "eval:self.per_delivered < 100 and self.per_billed < 100 and self.docstatus == 1"],
38 ["To Bill", "eval:self.per_delivered == 100 and self.per_billed < 100 and self.docstatus == 1"],
39 ["To Deliver", "eval:self.per_delivered < 100 and self.per_billed == 100 and self.docstatus == 1"],
40 ["Completed", "eval:self.per_delivered == 100 and self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehta86125b22015-10-13 11:48:08 +053041 ["Completed", "eval:self.order_type == 'Maintenance' and self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053042 ["Cancelled", "eval:self.docstatus==2"],
Saurabhc6dbe702015-10-19 14:17:52 +053043 ["Closed", "eval:self.status=='Closed'"],
Mangesh-Khairnar5eb66ae2019-03-01 16:23:27 +053044 ["On Hold", "eval:self.status=='On Hold'"],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053045 ],
Rohit Waghchaure2f1db572016-11-08 12:39:33 +053046 "Sales Invoice": [
47 ["Draft", None],
48 ["Submitted", "eval:self.docstatus==1"],
Rohit Waghchaure2285f902016-11-09 14:16:58 +053049 ["Return", "eval:self.is_return==1 and self.docstatus==1"],
Nabin Hait8a27cf32017-05-16 12:43:00 +053050 ["Paid", "eval:self.outstanding_amount<=0 and self.docstatus==1 and self.is_return==0"],
51 ["Credit Note Issued", "eval:self.outstanding_amount < 0 and self.docstatus==1 and self.is_return==0 and get_value('Sales Invoice', {'is_return': 1, 'return_against': self.name, 'docstatus': 1})"],
Rohit Waghchaure2f1db572016-11-08 12:39:33 +053052 ["Unpaid", "eval:self.outstanding_amount > 0 and getdate(self.due_date) >= getdate(nowdate()) and self.docstatus==1"],
53 ["Overdue", "eval:self.outstanding_amount > 0 and getdate(self.due_date) < getdate(nowdate()) and self.docstatus==1"],
54 ["Cancelled", "eval:self.docstatus==2"],
55 ],
56 "Purchase Invoice": [
57 ["Draft", None],
58 ["Submitted", "eval:self.docstatus==1"],
Rohit Waghchaure2285f902016-11-09 14:16:58 +053059 ["Return", "eval:self.is_return==1 and self.docstatus==1"],
Nabin Hait8a27cf32017-05-16 12:43:00 +053060 ["Paid", "eval:self.outstanding_amount<=0 and self.docstatus==1 and self.is_return==0"],
61 ["Debit Note Issued", "eval:self.outstanding_amount < 0 and self.docstatus==1 and self.is_return==0 and get_value('Purchase Invoice', {'is_return': 1, 'return_against': self.name, 'docstatus': 1})"],
Rohit Waghchaure2f1db572016-11-08 12:39:33 +053062 ["Unpaid", "eval:self.outstanding_amount > 0 and getdate(self.due_date) >= getdate(nowdate()) and self.docstatus==1"],
63 ["Overdue", "eval:self.outstanding_amount > 0 and getdate(self.due_date) < getdate(nowdate()) and self.docstatus==1"],
64 ["Cancelled", "eval:self.docstatus==2"],
65 ],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053066 "Purchase Order": [
67 ["Draft", None],
68 ["To Receive and Bill", "eval:self.per_received < 100 and self.per_billed < 100 and self.docstatus == 1"],
69 ["To Bill", "eval:self.per_received == 100 and self.per_billed < 100 and self.docstatus == 1"],
70 ["To Receive", "eval:self.per_received < 100 and self.per_billed == 100 and self.docstatus == 1"],
71 ["Completed", "eval:self.per_received == 100 and self.per_billed == 100 and self.docstatus == 1"],
Saurabh6d64fe32015-10-23 10:40:32 +053072 ["Delivered", "eval:self.status=='Delivered'"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053073 ["Cancelled", "eval:self.docstatus==2"],
Mangesh-Khairnar439546c2019-03-11 16:40:27 +053074 ["On Hold", "eval:self.status=='On Hold'"],
Saurabh98b28752015-10-19 15:16:17 +053075 ["Closed", "eval:self.status=='Closed'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053076 ],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053077 "Delivery Note": [
78 ["Draft", None],
Nabin Hait5b13b992015-12-28 13:03:55 +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 ],
84 "Purchase Receipt": [
85 ["Draft", None],
Nabin Haitbdab0ee2015-12-30 19:08:11 +053086 ["To Bill", "eval:self.per_billed < 100 and self.docstatus == 1"],
87 ["Completed", "eval:self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053088 ["Cancelled", "eval:self.docstatus==2"],
Saurabha8a91cc2015-11-02 12:57:08 +053089 ["Closed", "eval:self.status=='Closed'"],
tundebabzy99b734b2017-06-07 07:32:07 +010090 ],
91 "Material Request": [
92 ["Draft", None],
93 ["Stopped", "eval:self.status == 'Stopped'"],
94 ["Cancelled", "eval:self.docstatus == 2"],
95 ["Pending", "eval:self.status != 'Stopped' and self.per_ordered == 0 and self.docstatus == 1"],
96 ["Partially Ordered", "eval:self.status != 'Stopped' and self.per_ordered < 100 and self.per_ordered > 0 and self.docstatus == 1"],
97 ["Ordered", "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'"],
98 ["Transferred", "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Material Transfer'"],
deepeshgarg00706c20402019-04-22 12:25:14 +053099 ["Issued", "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Material Issue'"],
100 ["Received", "eval:self.status != 'Stopped' and self.per_received == 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'"]
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +0530101 ]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530102}
103
Anand Doshi424c0332014-04-21 15:06:56 +0530104class StatusUpdater(Document):
Nabin Hait0feebc12013-06-03 16:45:38 +0530105 """
106 Updates the status of the calling records
107 Delivery Note: Update Delivered Qty, Update Percent and Validate over delivery
108 Sales Invoice: Update Billed Amt, Update Percent and Validate over billing
109 Installation Note: Update Installed Qty, Update Percent Qty and Validate over installation
110 """
111
112 def update_prevdoc_status(self):
113 self.update_qty()
114 self.validate_qty()
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530115
Saurabh70ed6ed2015-12-08 14:02:53 +0530116 def set_status(self, update=False, status=None, update_modified=True):
Rushabh Mehtacb067aa2014-08-19 16:20:04 +0530117 if self.is_new():
Rohit Waghchaure29458832017-01-13 12:51:19 +0530118 if self.get('amended_from'):
119 self.status = 'Draft'
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530120 return
Anand Doshi6b71ef52016-01-06 16:32:06 +0530121
Anand Doshif78d1ae2014-03-28 13:55:00 +0530122 if self.doctype in status_map:
Nabin Haitcabf9c52014-08-21 16:34:38 +0530123 _status = self.status
Rushabh Mehtad48c2392015-11-04 15:20:50 +0530124
125 if status and update:
126 self.db_set("status", status)
127
Anand Doshif78d1ae2014-03-28 13:55:00 +0530128 sl = status_map[self.doctype][:]
Rushabh Mehta6856d742013-10-03 18:12:36 +0530129 sl.reverse()
130 for s in sl:
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530131 if not s[1]:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530132 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530133 break
Rushabh Mehta6856d742013-10-03 18:12:36 +0530134 elif s[1].startswith("eval:"):
Alcheze52ae4e2018-09-06 18:27:06 +0530135 if frappe.safe_eval(s[1][5:], None, { "self": self.as_dict(), "getdate": getdate,
Nabin Hait8a27cf32017-05-16 12:43:00 +0530136 "nowdate": nowdate, "get_value": frappe.db.get_value }):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530137 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530138 break
139 elif getattr(self, s[1])():
Anand Doshif78d1ae2014-03-28 13:55:00 +0530140 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530141 break
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530142
tundebabzy99b734b2017-06-07 07:32:07 +0100143 if self.status != _status and self.status not in ("Cancelled", "Partially Ordered",
144 "Ordered", "Issued", "Transferred"):
Anand Doshi7b34ebe2015-01-07 15:41:32 +0530145 self.add_comment("Label", _(self.status))
Anand Doshi6b71ef52016-01-06 16:32:06 +0530146
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530147 if update:
Rushabh Mehtafc8e5892016-07-20 12:08:47 +0530148 self.db_set('status', self.status, update_modified = update_modified)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530149
Nabin Hait0feebc12013-06-03 16:45:38 +0530150 def validate_qty(self):
Rushabh Mehtaa9ba5ef2014-12-19 16:20:32 +0530151 """Validates qty at row level"""
Nabin Hait0feebc12013-06-03 16:45:38 +0530152 self.tolerance = {}
153 self.global_tolerance = None
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530154
Nabin Hait0feebc12013-06-03 16:45:38 +0530155 for args in self.status_updater:
Anand Doshife13bfe2015-08-25 12:49:40 +0530156 if "target_ref_field" not in args:
157 # if target_ref_field is not specified, the programmer does not want to validate qty / amount
158 continue
159
Nabin Hait0feebc12013-06-03 16:45:38 +0530160 # get unique transactions to update
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530161 for d in self.get_all_children():
rohitwaghchaure12aa4262018-03-12 11:20:30 +0530162 if hasattr(d, 'qty') and d.qty < 0 and not self.get('is_return'):
163 frappe.throw(_("For an item {0}, quantity must be positive number").format(d.item_code))
164
rohitwaghchaure70489252018-06-11 12:02:14 +0530165 if hasattr(d, 'qty') and d.qty > 0 and self.get('is_return'):
166 frappe.throw(_("For an item {0}, quantity must be negative number").format(d.item_code))
167
Anand Doshif78d1ae2014-03-28 13:55:00 +0530168 if d.doctype == args['source_dt'] and d.get(args["join_field"]):
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530169 args['name'] = d.get(args['join_field'])
Nabin Hait0feebc12013-06-03 16:45:38 +0530170
171 # get all qty where qty > target_field
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530172 item = frappe.db.sql("""select item_code, `{target_ref_field}`,
173 `{target_field}`, parenttype, parent from `tab{target_dt}`
174 where `{target_ref_field}` < `{target_field}`
175 and name=%s and docstatus=1""".format(**args),
Nabin Hait4d713ac2014-03-03 15:51:13 +0530176 args['name'], as_dict=1)
Nabin Hait0feebc12013-06-03 16:45:38 +0530177 if item:
178 item = item[0]
179 item['idx'] = d.idx
180 item['target_ref_field'] = args['target_ref_field'].replace('_', ' ')
181
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530182 # if not item[args['target_ref_field']]:
183 # msgprint(_("Note: System will not check over-delivery and over-booking for Item {0} as quantity or amount is 0").format(item.item_code))
184 if args.get('no_tolerance'):
nabinhaitd5fb5d92014-07-09 17:36:38 +0530185 item['reduce_by'] = item[args['target_field']] - item[args['target_ref_field']]
Nabin Hait0feebc12013-06-03 16:45:38 +0530186 if item['reduce_by'] > .01:
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530187 self.limits_crossed_error(args, item)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530188
Nabin Hait47a3f632016-08-26 11:39:23 +0530189 elif item[args['target_ref_field']]:
Nabin Hait0feebc12013-06-03 16:45:38 +0530190 self.check_overflow_with_tolerance(item, args)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530191
Nabin Hait0feebc12013-06-03 16:45:38 +0530192 def check_overflow_with_tolerance(self, item, args):
193 """
194 Checks if there is overflow condering a relaxation tolerance
195 """
Nabin Hait0feebc12013-06-03 16:45:38 +0530196 # check if overflow is within tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530197 tolerance, self.tolerance, self.global_tolerance = get_tolerance_for(item['item_code'],
Nabin Hait7f0406f2014-01-03 17:43:19 +0530198 self.tolerance, self.global_tolerance)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530199 overflow_percent = ((item[args['target_field']] - item[args['target_ref_field']]) /
Nabin Hait0feebc12013-06-03 16:45:38 +0530200 item[args['target_ref_field']]) * 100
nabinhait711e8be2014-07-19 17:00:15 +0530201
Nabin Hait0feebc12013-06-03 16:45:38 +0530202 if overflow_percent - tolerance > 0.01:
203 item['max_allowed'] = flt(item[args['target_ref_field']] * (100+tolerance)/100)
204 item['reduce_by'] = item[args['target_field']] - item['max_allowed']
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530205
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530206 self.limits_crossed_error(args, item)
207
208 def limits_crossed_error(self, args, item):
209 '''Raise exception for limits crossed'''
210 frappe.throw(_('This document is over limit by {0} {1} for item {4}. Are you making another {3} against the same {2}?')
211 .format(
212 frappe.bold(_(item["target_ref_field"].title())),
213 frappe.bold(item["reduce_by"]),
214 frappe.bold(_(args.get('target_dt'))),
215 frappe.bold(_(self.doctype)),
216 frappe.bold(item.get('item_code'))
217 ) + '<br><br>' +
218 _('To allow over-billing or over-ordering, update "Allowance" in Stock Settings or the Item.'),
219 title = _('Limit Crossed'))
Nabin Hait0feebc12013-06-03 16:45:38 +0530220
Anand Doshi6b71ef52016-01-06 16:32:06 +0530221 def update_qty(self, update_modified=True):
Anand Doshife13bfe2015-08-25 12:49:40 +0530222 """Updates qty or amount at row level
223
Anand Doshi6b71ef52016-01-06 16:32:06 +0530224 :param update_modified: If true, updates `modified` and `modified_by` for target parent doc
Nabin Hait0feebc12013-06-03 16:45:38 +0530225 """
226 for args in self.status_updater:
227 # condition to include current record (if submit or no if cancel)
Anand Doshif78d1ae2014-03-28 13:55:00 +0530228 if self.docstatus == 1:
229 args['cond'] = ' or parent="%s"' % self.name.replace('"', '\"')
Nabin Hait0feebc12013-06-03 16:45:38 +0530230 else:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530231 args['cond'] = ' and parent!="%s"' % self.name.replace('"', '\"')
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530232
Anand Doshi6b71ef52016-01-06 16:32:06 +0530233 self._update_children(args, update_modified)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530234
Anand Doshife13bfe2015-08-25 12:49:40 +0530235 if "percent_join_field" in args:
Anand Doshi6b71ef52016-01-06 16:32:06 +0530236 self._update_percent_field_in_targets(args, update_modified)
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530237
Anand Doshi6b71ef52016-01-06 16:32:06 +0530238 def _update_children(self, args, update_modified):
Anand Doshife13bfe2015-08-25 12:49:40 +0530239 """Update quantities or amount in child table"""
240 for d in self.get_all_children():
241 if d.doctype != args['source_dt']:
242 continue
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530243
Anand Doshi6b71ef52016-01-06 16:32:06 +0530244 self._update_modified(args, update_modified)
245
Anand Doshife13bfe2015-08-25 12:49:40 +0530246 # updates qty in the child table
247 args['detail_id'] = d.get(args['join_field'])
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530248
Anand Doshife13bfe2015-08-25 12:49:40 +0530249 args['second_source_condition'] = ""
250 if args.get('second_source_dt') and args.get('second_source_field') \
251 and args.get('second_join_field'):
252 if not args.get("second_source_extra_cond"):
253 args["second_source_extra_cond"] = ""
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530254
Anand Doshife13bfe2015-08-25 12:49:40 +0530255 args['second_source_condition'] = """ + ifnull((select sum(%(second_source_field)s)
256 from `tab%(second_source_dt)s`
257 where `%(second_join_field)s`="%(detail_id)s"
258 and (`tab%(second_source_dt)s`.docstatus=1) %(second_source_extra_cond)s), 0) """ % args
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530259
Anand Doshife13bfe2015-08-25 12:49:40 +0530260 if args['detail_id']:
261 if not args.get("extra_cond"): args["extra_cond"] = ""
Alcheze52ae4e2018-09-06 18:27:06 +0530262
Anand Doshife13bfe2015-08-25 12:49:40 +0530263 frappe.db.sql("""update `tab%(target_dt)s`
Anand Doshi6b71ef52016-01-06 16:32:06 +0530264 set %(target_field)s = (
265 (select ifnull(sum(%(source_field)s), 0)
266 from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s"
267 and (docstatus=1 %(cond)s) %(extra_cond)s)
268 %(second_source_condition)s
269 )
270 %(update_modified)s
Anand Doshife13bfe2015-08-25 12:49:40 +0530271 where name='%(detail_id)s'""" % args)
Anand Doshi6b71ef52016-01-06 16:32:06 +0530272
273 def _update_percent_field_in_targets(self, args, update_modified=True):
Anand Doshife13bfe2015-08-25 12:49:40 +0530274 """Update percent field in parent transaction"""
Anand Doshi6b71ef52016-01-06 16:32:06 +0530275 distinct_transactions = set([d.get(args['percent_join_field'])
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530276 for d in self.get_all_children(args['source_dt'])])
Anand Doshife13bfe2015-08-25 12:49:40 +0530277
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530278 for name in distinct_transactions:
279 if name:
280 args['name'] = name
Anand Doshi6b71ef52016-01-06 16:32:06 +0530281 self._update_percent_field(args, update_modified)
Anand Doshife13bfe2015-08-25 12:49:40 +0530282
Anand Doshi6b71ef52016-01-06 16:32:06 +0530283 def _update_percent_field(self, args, update_modified=True):
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530284 """Update percent field in parent transaction"""
Anand Doshi6b71ef52016-01-06 16:32:06 +0530285
286 self._update_modified(args, update_modified)
Alcheze52ae4e2018-09-06 18:27:06 +0530287
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530288 if args.get('target_parent_field'):
289 frappe.db.sql("""update `tab%(target_parent_dt)s`
290 set %(target_parent_field)s = round(
291 ifnull((select
RobertSchoutendb33ebb2016-09-12 14:54:46 +0800292 ifnull(sum(if(%(target_ref_field)s > %(target_field)s, abs(%(target_field)s), abs(%(target_ref_field)s))), 0)
293 / sum(abs(%(target_ref_field)s)) * 100
rohitwaghchaure85f63a32018-03-27 11:31:44 +0530294 from `tab%(target_dt)s` where parent="%(name)s" having sum(abs(%(target_ref_field)s)) > 0), 0), 6)
Anand Doshi6b71ef52016-01-06 16:32:06 +0530295 %(update_modified)s
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530296 where name='%(name)s'""" % args)
Anand Doshife13bfe2015-08-25 12:49:40 +0530297
rohitwaghchaure7be942d2016-11-16 11:14:33 +0530298 # update field
299 if args.get('status_field'):
300 frappe.db.sql("""update `tab%(target_parent_dt)s`
301 set %(status_field)s = if(%(target_parent_field)s<0.001,
rohitwaghchaure85f63a32018-03-27 11:31:44 +0530302 'Not %(keyword)s', if(%(target_parent_field)s>=99.999999,
rohitwaghchaure7be942d2016-11-16 11:14:33 +0530303 'Fully %(keyword)s', 'Partly %(keyword)s'))
304 where name='%(name)s'""" % args)
Anand Doshife13bfe2015-08-25 12:49:40 +0530305
rohitwaghchaure7be942d2016-11-16 11:14:33 +0530306 if update_modified:
307 target = frappe.get_doc(args["target_parent_dt"], args["name"])
308 target.set_status(update=True)
309 target.notify_update()
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530310
Anand Doshi6b71ef52016-01-06 16:32:06 +0530311 def _update_modified(self, args, update_modified):
312 args['update_modified'] = ''
313 if update_modified:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530314 args['update_modified'] = ', modified = now(), modified_by = {0}'\
Anand Doshi6b71ef52016-01-06 16:32:06 +0530315 .format(frappe.db.escape(frappe.session.user))
316
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530317 def update_billing_status_for_zero_amount_refdoc(self, ref_dt):
318 ref_fieldname = ref_dt.lower().replace(" ", "_")
319 zero_amount_refdoc = []
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530320 all_zero_amount_refdoc = frappe.db.sql_list("""select name from `tab%s`
Nabin Hait5690be12015-02-12 16:09:11 +0530321 where docstatus=1 and base_net_total = 0""" % ref_dt)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530322
Nabin Hait4b8185d2014-12-25 18:19:39 +0530323 for item in self.get("items"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530324 if item.get(ref_fieldname) \
325 and item.get(ref_fieldname) in all_zero_amount_refdoc \
326 and item.get(ref_fieldname) not in zero_amount_refdoc:
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530327 zero_amount_refdoc.append(item.get(ref_fieldname))
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530328
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530329 if zero_amount_refdoc:
Rushabh Mehtad48c2392015-11-04 15:20:50 +0530330 self.update_billing_status(zero_amount_refdoc, ref_dt, ref_fieldname)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530331
Rushabh Mehtad48c2392015-11-04 15:20:50 +0530332 def update_billing_status(self, zero_amount_refdoc, ref_dt, ref_fieldname):
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530333 for ref_dn in zero_amount_refdoc:
Anand Doshiebae7262015-11-25 15:51:01 +0530334 ref_doc_qty = flt(frappe.db.sql("""select ifnull(sum(qty), 0) from `tab%s Item`
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530335 where parent=%s""" % (ref_dt, '%s'), (ref_dn))[0][0])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530336
Anand Doshiebae7262015-11-25 15:51:01 +0530337 billed_qty = flt(frappe.db.sql("""select ifnull(sum(qty), 0)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530338 from `tab%s Item` where %s=%s and docstatus=1""" %
Anand Doshif78d1ae2014-03-28 13:55:00 +0530339 (self.doctype, ref_fieldname, '%s'), (ref_dn))[0][0])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530340
Alcheze52ae4e2018-09-06 18:27:06 +0530341 per_billed = (min(ref_doc_qty, billed_qty) / ref_doc_qty) * 100
Rushabh Mehtafc8e5892016-07-20 12:08:47 +0530342
343 ref_doc = frappe.get_doc(ref_dt, ref_dn)
344
345 ref_doc.db_set("per_billed", per_billed)
Rohit Waghchaure770d04e2016-10-05 23:02:15 +0530346 ref_doc.set_status(update=True)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530347
Nabin Hait7f0406f2014-01-03 17:43:19 +0530348def get_tolerance_for(item_code, item_tolerance={}, global_tolerance=None):
349 """
350 Returns the tolerance for the item, if not set, returns global tolerance
351 """
352 if item_tolerance.get(item_code):
353 return item_tolerance[item_code], item_tolerance, global_tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530354
Anand Doshie9baaa62014-02-26 12:35:33 +0530355 tolerance = flt(frappe.db.get_value('Item',item_code,'tolerance') or 0)
Nabin Hait7f0406f2014-01-03 17:43:19 +0530356
357 if not tolerance:
358 if global_tolerance == None:
nabinhaitb1c57382014-07-19 16:53:45 +0530359 global_tolerance = flt(frappe.db.get_value('Stock Settings', None, 'tolerance'))
Nabin Hait7f0406f2014-01-03 17:43:19 +0530360 tolerance = global_tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530361
Nabin Hait7f0406f2014-01-03 17:43:19 +0530362 item_tolerance[item_code] = tolerance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530363 return tolerance, item_tolerance, global_tolerance