blob: d8c50b2622f92ac533903b5591cfb508a6b79f6f [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
Nabin Hait868766d2019-07-15 18:02:58 +053010class OverAllowanceError(frappe.ValidationError): pass
11
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053012def validate_status(status, options):
13 if status not in options:
14 frappe.throw(_("Status must be one of {0}").format(comma_or(options)))
15
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053016status_map = {
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053017 "Lead": [
Nabin Haitf49bbe12016-12-15 11:51:54 +053018 ["Lost Quotation", "has_lost_quotation"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053019 ["Opportunity", "has_opportunity"],
Alec Ruiz-Ramonfcaaa292016-06-09 14:19:51 -040020 ["Quotation", "has_quotation"],
21 ["Converted", "has_customer"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053022 ],
23 "Opportunity": [
Valmik Jangla29563272016-03-29 11:13:07 +053024 ["Lost", "eval:self.status=='Lost'"],
Alec Ruiz-Ramonfcaaa292016-06-09 14:19:51 -040025 ["Lost", "has_lost_quotation"],
Nabin Hait6a5cf672017-05-30 15:34:20 +053026 ["Quotation", "has_active_quotation"],
27 ["Converted", "has_ordered_quotation"],
Valmik Jangla29563272016-03-29 11:13:07 +053028 ["Closed", "eval:self.status=='Closed'"]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053029 ],
30 "Quotation": [
Rushabh Mehta4ac30942015-04-13 16:56:03 +053031 ["Draft", None],
Deepesh Gargea057462019-06-26 11:05:51 +053032 ["Open", "eval:self.docstatus==1"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053033 ["Lost", "eval:self.status=='Lost'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053034 ["Ordered", "has_sales_order"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053035 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053036 ],
37 "Sales Order": [
38 ["Draft", None],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053039 ["To Deliver and Bill", "eval:self.per_delivered < 100 and self.per_billed < 100 and self.docstatus == 1"],
40 ["To Bill", "eval:self.per_delivered == 100 and self.per_billed < 100 and self.docstatus == 1"],
41 ["To Deliver", "eval:self.per_delivered < 100 and self.per_billed == 100 and self.docstatus == 1"],
42 ["Completed", "eval:self.per_delivered == 100 and self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehta86125b22015-10-13 11:48:08 +053043 ["Completed", "eval:self.order_type == 'Maintenance' and self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053044 ["Cancelled", "eval:self.docstatus==2"],
Saurabhc6dbe702015-10-19 14:17:52 +053045 ["Closed", "eval:self.status=='Closed'"],
Mangesh-Khairnar5eb66ae2019-03-01 16:23:27 +053046 ["On Hold", "eval:self.status=='On Hold'"],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053047 ],
Rohit Waghchaure2f1db572016-11-08 12:39:33 +053048 "Purchase Invoice": [
49 ["Draft", None],
50 ["Submitted", "eval:self.docstatus==1"],
Nabin Hait34c551d2019-07-03 10:34:31 +053051 ["Paid", "eval:self.outstanding_amount==0 and self.docstatus==1"],
Rohit Waghchaure2285f902016-11-09 14:16:58 +053052 ["Return", "eval:self.is_return==1 and self.docstatus==1"],
Nabin Hait34c551d2019-07-03 10:34:31 +053053 ["Debit Note Issued", "eval:self.outstanding_amount < 0 and self.docstatus==1"],
Rohit Waghchaure2f1db572016-11-08 12:39:33 +053054 ["Unpaid", "eval:self.outstanding_amount > 0 and getdate(self.due_date) >= getdate(nowdate()) and self.docstatus==1"],
55 ["Overdue", "eval:self.outstanding_amount > 0 and getdate(self.due_date) < getdate(nowdate()) and self.docstatus==1"],
56 ["Cancelled", "eval:self.docstatus==2"],
57 ],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053058 "Purchase Order": [
59 ["Draft", None],
60 ["To Receive and Bill", "eval:self.per_received < 100 and self.per_billed < 100 and self.docstatus == 1"],
61 ["To Bill", "eval:self.per_received == 100 and self.per_billed < 100 and self.docstatus == 1"],
62 ["To Receive", "eval:self.per_received < 100 and self.per_billed == 100 and self.docstatus == 1"],
63 ["Completed", "eval:self.per_received == 100 and self.per_billed == 100 and self.docstatus == 1"],
Saurabh6d64fe32015-10-23 10:40:32 +053064 ["Delivered", "eval:self.status=='Delivered'"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053065 ["Cancelled", "eval:self.docstatus==2"],
Mangesh-Khairnar439546c2019-03-11 16:40:27 +053066 ["On Hold", "eval:self.status=='On Hold'"],
Saurabh98b28752015-10-19 15:16:17 +053067 ["Closed", "eval:self.status=='Closed'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053068 ],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053069 "Delivery Note": [
70 ["Draft", None],
Nabin Hait5b13b992015-12-28 13:03:55 +053071 ["To Bill", "eval:self.per_billed < 100 and self.docstatus == 1"],
72 ["Completed", "eval:self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053073 ["Cancelled", "eval:self.docstatus==2"],
Saurabha8a91cc2015-11-02 12:57:08 +053074 ["Closed", "eval:self.status=='Closed'"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053075 ],
76 "Purchase Receipt": [
77 ["Draft", None],
Nabin Haitbdab0ee2015-12-30 19:08:11 +053078 ["To Bill", "eval:self.per_billed < 100 and self.docstatus == 1"],
79 ["Completed", "eval:self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053080 ["Cancelled", "eval:self.docstatus==2"],
Saurabha8a91cc2015-11-02 12:57:08 +053081 ["Closed", "eval:self.status=='Closed'"],
tundebabzy99b734b2017-06-07 07:32:07 +010082 ],
83 "Material Request": [
84 ["Draft", None],
85 ["Stopped", "eval:self.status == 'Stopped'"],
86 ["Cancelled", "eval:self.docstatus == 2"],
87 ["Pending", "eval:self.status != 'Stopped' and self.per_ordered == 0 and self.docstatus == 1"],
88 ["Partially Ordered", "eval:self.status != 'Stopped' and self.per_ordered < 100 and self.per_ordered > 0 and self.docstatus == 1"],
89 ["Ordered", "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'"],
90 ["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 +053091 ["Issued", "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Material Issue'"],
deepeshgarg007f2fb0e02019-04-29 21:42:48 +053092 ["Received", "eval:self.status != 'Stopped' and self.per_received == 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'"],
Anurag Mishra305da792019-07-22 11:35:16 +053093 ["Partially Received", "eval:self.status != 'Stopped' and self.per_received > 0 and self.per_received < 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'"],
94 ["Manufactured", "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Manufacture'"]
Nabin Hait34c551d2019-07-03 10:34:31 +053095 ],
96 "Bank Transaction": [
97 ["Unreconciled", "eval:self.docstatus == 1 and self.unallocated_amount>0"],
98 ["Reconciled", "eval:self.docstatus == 1 and self.unallocated_amount<=0"]
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053099 ]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530100}
101
Anand Doshi424c0332014-04-21 15:06:56 +0530102class StatusUpdater(Document):
Nabin Hait0feebc12013-06-03 16:45:38 +0530103 """
104 Updates the status of the calling records
105 Delivery Note: Update Delivered Qty, Update Percent and Validate over delivery
106 Sales Invoice: Update Billed Amt, Update Percent and Validate over billing
107 Installation Note: Update Installed Qty, Update Percent Qty and Validate over installation
108 """
109
110 def update_prevdoc_status(self):
111 self.update_qty()
112 self.validate_qty()
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530113
Saurabh70ed6ed2015-12-08 14:02:53 +0530114 def set_status(self, update=False, status=None, update_modified=True):
Rushabh Mehtacb067aa2014-08-19 16:20:04 +0530115 if self.is_new():
Rohit Waghchaure29458832017-01-13 12:51:19 +0530116 if self.get('amended_from'):
117 self.status = 'Draft'
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530118 return
Anand Doshi6b71ef52016-01-06 16:32:06 +0530119
Anand Doshif78d1ae2014-03-28 13:55:00 +0530120 if self.doctype in status_map:
Nabin Haitcabf9c52014-08-21 16:34:38 +0530121 _status = self.status
Rushabh Mehtad48c2392015-11-04 15:20:50 +0530122
123 if status and update:
124 self.db_set("status", status)
125
Anand Doshif78d1ae2014-03-28 13:55:00 +0530126 sl = status_map[self.doctype][:]
Rushabh Mehta6856d742013-10-03 18:12:36 +0530127 sl.reverse()
128 for s in sl:
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530129 if not s[1]:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530130 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530131 break
Rushabh Mehta6856d742013-10-03 18:12:36 +0530132 elif s[1].startswith("eval:"):
Alcheze52ae4e2018-09-06 18:27:06 +0530133 if frappe.safe_eval(s[1][5:], None, { "self": self.as_dict(), "getdate": getdate,
Nabin Hait8a27cf32017-05-16 12:43:00 +0530134 "nowdate": nowdate, "get_value": frappe.db.get_value }):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530135 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530136 break
137 elif getattr(self, s[1])():
Anand Doshif78d1ae2014-03-28 13:55:00 +0530138 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530139 break
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530140
tundebabzy99b734b2017-06-07 07:32:07 +0100141 if self.status != _status and self.status not in ("Cancelled", "Partially Ordered",
142 "Ordered", "Issued", "Transferred"):
Anand Doshi7b34ebe2015-01-07 15:41:32 +0530143 self.add_comment("Label", _(self.status))
Anand Doshi6b71ef52016-01-06 16:32:06 +0530144
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530145 if update:
Rushabh Mehtafc8e5892016-07-20 12:08:47 +0530146 self.db_set('status', self.status, update_modified = update_modified)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530147
Nabin Hait0feebc12013-06-03 16:45:38 +0530148 def validate_qty(self):
Rushabh Mehtaa9ba5ef2014-12-19 16:20:32 +0530149 """Validates qty at row level"""
Nabin Hait868766d2019-07-15 18:02:58 +0530150 self.item_allowance = {}
151 self.global_qty_allowance = None
152 self.global_amount_allowance = None
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530153
Nabin Hait0feebc12013-06-03 16:45:38 +0530154 for args in self.status_updater:
Anand Doshife13bfe2015-08-25 12:49:40 +0530155 if "target_ref_field" not in args:
156 # if target_ref_field is not specified, the programmer does not want to validate qty / amount
157 continue
158
Nabin Hait0feebc12013-06-03 16:45:38 +0530159 # get unique transactions to update
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530160 for d in self.get_all_children():
rohitwaghchaure12aa4262018-03-12 11:20:30 +0530161 if hasattr(d, 'qty') and d.qty < 0 and not self.get('is_return'):
162 frappe.throw(_("For an item {0}, quantity must be positive number").format(d.item_code))
163
rohitwaghchaure70489252018-06-11 12:02:14 +0530164 if hasattr(d, 'qty') and d.qty > 0 and self.get('is_return'):
165 frappe.throw(_("For an item {0}, quantity must be negative number").format(d.item_code))
166
Anand Doshif78d1ae2014-03-28 13:55:00 +0530167 if d.doctype == args['source_dt'] and d.get(args["join_field"]):
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530168 args['name'] = d.get(args['join_field'])
Nabin Hait0feebc12013-06-03 16:45:38 +0530169
170 # get all qty where qty > target_field
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530171 item = frappe.db.sql("""select item_code, `{target_ref_field}`,
172 `{target_field}`, parenttype, parent from `tab{target_dt}`
173 where `{target_ref_field}` < `{target_field}`
174 and name=%s and docstatus=1""".format(**args),
Nabin Hait4d713ac2014-03-03 15:51:13 +0530175 args['name'], as_dict=1)
Nabin Hait0feebc12013-06-03 16:45:38 +0530176 if item:
177 item = item[0]
178 item['idx'] = d.idx
179 item['target_ref_field'] = args['target_ref_field'].replace('_', ' ')
180
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530181 # if not item[args['target_ref_field']]:
182 # 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 Hait868766d2019-07-15 18:02:58 +0530183 if args.get('no_allowance'):
nabinhaitd5fb5d92014-07-09 17:36:38 +0530184 item['reduce_by'] = item[args['target_field']] - item[args['target_ref_field']]
Nabin Hait0feebc12013-06-03 16:45:38 +0530185 if item['reduce_by'] > .01:
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530186 self.limits_crossed_error(args, item)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530187
Nabin Hait47a3f632016-08-26 11:39:23 +0530188 elif item[args['target_ref_field']]:
Nabin Hait868766d2019-07-15 18:02:58 +0530189 self.check_overflow_with_allowance(item, args)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530190
Nabin Hait868766d2019-07-15 18:02:58 +0530191 def check_overflow_with_allowance(self, item, args):
Nabin Hait0feebc12013-06-03 16:45:38 +0530192 """
Nabin Hait868766d2019-07-15 18:02:58 +0530193 Checks if there is overflow condering a relaxation allowance
Nabin Hait0feebc12013-06-03 16:45:38 +0530194 """
Nabin Hait868766d2019-07-15 18:02:58 +0530195 qty_or_amount = "qty" if "qty" in args['target_ref_field'] else "amount"
196
197 # check if overflow is within allowance
198 allowance, self.item_allowance, self.global_qty_allowance, self.global_amount_allowance = \
199 get_allowance_for(item['item_code'], self.item_allowance,
200 self.global_qty_allowance, self.global_amount_allowance, qty_or_amount)
201
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530202 overflow_percent = ((item[args['target_field']] - item[args['target_ref_field']]) /
Nabin Hait0feebc12013-06-03 16:45:38 +0530203 item[args['target_ref_field']]) * 100
nabinhait711e8be2014-07-19 17:00:15 +0530204
Nabin Hait868766d2019-07-15 18:02:58 +0530205 if overflow_percent - allowance > 0.01:
206 item['max_allowed'] = flt(item[args['target_ref_field']] * (100+allowance)/100)
Nabin Hait0feebc12013-06-03 16:45:38 +0530207 item['reduce_by'] = item[args['target_field']] - item['max_allowed']
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530208
Nabin Hait868766d2019-07-15 18:02:58 +0530209 self.limits_crossed_error(args, item, qty_or_amount)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530210
Nabin Hait868766d2019-07-15 18:02:58 +0530211 def limits_crossed_error(self, args, item, qty_or_amount):
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530212 '''Raise exception for limits crossed'''
Nabin Hait868766d2019-07-15 18:02:58 +0530213 if qty_or_amount == "qty":
214 action_msg = _('To allow over receipt / delivery, update "Over Receipt/Delivery Allowance" in Stock Settings or the Item.')
215 else:
216 action_msg = _('To allow over billing, update "Over Billing Allowance" in Accounts Settings or the Item.')
217
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530218 frappe.throw(_('This document is over limit by {0} {1} for item {4}. Are you making another {3} against the same {2}?')
219 .format(
220 frappe.bold(_(item["target_ref_field"].title())),
221 frappe.bold(item["reduce_by"]),
222 frappe.bold(_(args.get('target_dt'))),
223 frappe.bold(_(self.doctype)),
224 frappe.bold(item.get('item_code'))
Nabin Hait868766d2019-07-15 18:02:58 +0530225 ) + '<br><br>' + action_msg, OverAllowanceError, title = _('Limit Crossed'))
Nabin Hait0feebc12013-06-03 16:45:38 +0530226
Anand Doshi6b71ef52016-01-06 16:32:06 +0530227 def update_qty(self, update_modified=True):
Anand Doshife13bfe2015-08-25 12:49:40 +0530228 """Updates qty or amount at row level
229
Anand Doshi6b71ef52016-01-06 16:32:06 +0530230 :param update_modified: If true, updates `modified` and `modified_by` for target parent doc
Nabin Hait0feebc12013-06-03 16:45:38 +0530231 """
232 for args in self.status_updater:
233 # condition to include current record (if submit or no if cancel)
Anand Doshif78d1ae2014-03-28 13:55:00 +0530234 if self.docstatus == 1:
235 args['cond'] = ' or parent="%s"' % self.name.replace('"', '\"')
Nabin Hait0feebc12013-06-03 16:45:38 +0530236 else:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530237 args['cond'] = ' and parent!="%s"' % self.name.replace('"', '\"')
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530238
Anand Doshi6b71ef52016-01-06 16:32:06 +0530239 self._update_children(args, update_modified)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530240
Anand Doshife13bfe2015-08-25 12:49:40 +0530241 if "percent_join_field" in args:
Anand Doshi6b71ef52016-01-06 16:32:06 +0530242 self._update_percent_field_in_targets(args, update_modified)
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530243
Anand Doshi6b71ef52016-01-06 16:32:06 +0530244 def _update_children(self, args, update_modified):
Anand Doshife13bfe2015-08-25 12:49:40 +0530245 """Update quantities or amount in child table"""
246 for d in self.get_all_children():
247 if d.doctype != args['source_dt']:
248 continue
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530249
Anand Doshi6b71ef52016-01-06 16:32:06 +0530250 self._update_modified(args, update_modified)
251
Anand Doshife13bfe2015-08-25 12:49:40 +0530252 # updates qty in the child table
253 args['detail_id'] = d.get(args['join_field'])
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530254
Anand Doshife13bfe2015-08-25 12:49:40 +0530255 args['second_source_condition'] = ""
256 if args.get('second_source_dt') and args.get('second_source_field') \
257 and args.get('second_join_field'):
258 if not args.get("second_source_extra_cond"):
259 args["second_source_extra_cond"] = ""
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530260
Anand Doshife13bfe2015-08-25 12:49:40 +0530261 args['second_source_condition'] = """ + ifnull((select sum(%(second_source_field)s)
262 from `tab%(second_source_dt)s`
263 where `%(second_join_field)s`="%(detail_id)s"
264 and (`tab%(second_source_dt)s`.docstatus=1) %(second_source_extra_cond)s), 0) """ % args
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530265
Anand Doshife13bfe2015-08-25 12:49:40 +0530266 if args['detail_id']:
267 if not args.get("extra_cond"): args["extra_cond"] = ""
Alcheze52ae4e2018-09-06 18:27:06 +0530268
Anand Doshife13bfe2015-08-25 12:49:40 +0530269 frappe.db.sql("""update `tab%(target_dt)s`
Anand Doshi6b71ef52016-01-06 16:32:06 +0530270 set %(target_field)s = (
271 (select ifnull(sum(%(source_field)s), 0)
272 from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s"
273 and (docstatus=1 %(cond)s) %(extra_cond)s)
274 %(second_source_condition)s
275 )
276 %(update_modified)s
Anand Doshife13bfe2015-08-25 12:49:40 +0530277 where name='%(detail_id)s'""" % args)
Anand Doshi6b71ef52016-01-06 16:32:06 +0530278
279 def _update_percent_field_in_targets(self, args, update_modified=True):
Anand Doshife13bfe2015-08-25 12:49:40 +0530280 """Update percent field in parent transaction"""
Anand Doshi6b71ef52016-01-06 16:32:06 +0530281 distinct_transactions = set([d.get(args['percent_join_field'])
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530282 for d in self.get_all_children(args['source_dt'])])
Anand Doshife13bfe2015-08-25 12:49:40 +0530283
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530284 for name in distinct_transactions:
285 if name:
286 args['name'] = name
Anand Doshi6b71ef52016-01-06 16:32:06 +0530287 self._update_percent_field(args, update_modified)
Anand Doshife13bfe2015-08-25 12:49:40 +0530288
Anand Doshi6b71ef52016-01-06 16:32:06 +0530289 def _update_percent_field(self, args, update_modified=True):
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530290 """Update percent field in parent transaction"""
Anand Doshi6b71ef52016-01-06 16:32:06 +0530291
292 self._update_modified(args, update_modified)
Alcheze52ae4e2018-09-06 18:27:06 +0530293
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530294 if args.get('target_parent_field'):
295 frappe.db.sql("""update `tab%(target_parent_dt)s`
296 set %(target_parent_field)s = round(
297 ifnull((select
Rohit Waghchaure5d4d70b2019-07-05 16:59:27 +0530298 ifnull(sum(if(abs(%(target_ref_field)s) > abs(%(target_field)s), abs(%(target_field)s), abs(%(target_ref_field)s))), 0)
RobertSchoutendb33ebb2016-09-12 14:54:46 +0800299 / sum(abs(%(target_ref_field)s)) * 100
rohitwaghchaure85f63a32018-03-27 11:31:44 +0530300 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 +0530301 %(update_modified)s
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530302 where name='%(name)s'""" % args)
Anand Doshife13bfe2015-08-25 12:49:40 +0530303
rohitwaghchaure7be942d2016-11-16 11:14:33 +0530304 # update field
305 if args.get('status_field'):
306 frappe.db.sql("""update `tab%(target_parent_dt)s`
307 set %(status_field)s = if(%(target_parent_field)s<0.001,
rohitwaghchaure85f63a32018-03-27 11:31:44 +0530308 'Not %(keyword)s', if(%(target_parent_field)s>=99.999999,
rohitwaghchaure7be942d2016-11-16 11:14:33 +0530309 'Fully %(keyword)s', 'Partly %(keyword)s'))
310 where name='%(name)s'""" % args)
Anand Doshife13bfe2015-08-25 12:49:40 +0530311
rohitwaghchaure7be942d2016-11-16 11:14:33 +0530312 if update_modified:
313 target = frappe.get_doc(args["target_parent_dt"], args["name"])
314 target.set_status(update=True)
315 target.notify_update()
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530316
Anand Doshi6b71ef52016-01-06 16:32:06 +0530317 def _update_modified(self, args, update_modified):
318 args['update_modified'] = ''
319 if update_modified:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530320 args['update_modified'] = ', modified = now(), modified_by = {0}'\
Anand Doshi6b71ef52016-01-06 16:32:06 +0530321 .format(frappe.db.escape(frappe.session.user))
322
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530323 def update_billing_status_for_zero_amount_refdoc(self, ref_dt):
Himanshu Mishra70029b82019-05-29 14:19:35 +0530324 ref_fieldname = frappe.scrub(ref_dt)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530325
Himanshu Mishra70029b82019-05-29 14:19:35 +0530326 ref_docs = [item.get(ref_fieldname) for item in (self.get('items') or []) if item.get(ref_fieldname)]
327 if not ref_docs:
328 return
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530329
Himanshu Mishra70029b82019-05-29 14:19:35 +0530330 zero_amount_refdocs = frappe.db.sql_list("""
331 SELECT
332 name
333 from
334 `tab{ref_dt}`
335 where
336 docstatus = 1
337 and base_net_total = 0
338 and name in %(ref_docs)s
339 """.format(ref_dt=ref_dt), {
340 'ref_docs': ref_docs
341 })
342
343 if zero_amount_refdocs:
344 self.update_billing_status(zero_amount_refdocs, ref_dt, ref_fieldname)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530345
Rushabh Mehtad48c2392015-11-04 15:20:50 +0530346 def update_billing_status(self, zero_amount_refdoc, ref_dt, ref_fieldname):
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530347 for ref_dn in zero_amount_refdoc:
Anand Doshiebae7262015-11-25 15:51:01 +0530348 ref_doc_qty = flt(frappe.db.sql("""select ifnull(sum(qty), 0) from `tab%s Item`
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530349 where parent=%s""" % (ref_dt, '%s'), (ref_dn))[0][0])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530350
Anand Doshiebae7262015-11-25 15:51:01 +0530351 billed_qty = flt(frappe.db.sql("""select ifnull(sum(qty), 0)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530352 from `tab%s Item` where %s=%s and docstatus=1""" %
Anand Doshif78d1ae2014-03-28 13:55:00 +0530353 (self.doctype, ref_fieldname, '%s'), (ref_dn))[0][0])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530354
Alcheze52ae4e2018-09-06 18:27:06 +0530355 per_billed = (min(ref_doc_qty, billed_qty) / ref_doc_qty) * 100
Rushabh Mehtafc8e5892016-07-20 12:08:47 +0530356
357 ref_doc = frappe.get_doc(ref_dt, ref_dn)
358
359 ref_doc.db_set("per_billed", per_billed)
Rohit Waghchaure770d04e2016-10-05 23:02:15 +0530360 ref_doc.set_status(update=True)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530361
Nabin Hait868766d2019-07-15 18:02:58 +0530362def get_allowance_for(item_code, item_allowance={}, global_qty_allowance=None, global_amount_allowance=None, qty_or_amount="qty"):
Nabin Hait7f0406f2014-01-03 17:43:19 +0530363 """
Nabin Hait868766d2019-07-15 18:02:58 +0530364 Returns the allowance for the item, if not set, returns global allowance
Nabin Hait7f0406f2014-01-03 17:43:19 +0530365 """
Nabin Hait868766d2019-07-15 18:02:58 +0530366 if qty_or_amount == "qty":
367 if item_allowance.get(item_code, frappe._dict()).get("qty"):
368 return item_allowance[item_code].qty, item_allowance, global_qty_allowance, global_amount_allowance
369 else:
370 if item_allowance.get(item_code, frappe._dict()).get("amount"):
371 return item_allowance[item_code].amount, item_allowance, global_qty_allowance, global_amount_allowance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530372
Nabin Hait868766d2019-07-15 18:02:58 +0530373 qty_allowance, over_billing_allowance = \
374 frappe.db.get_value('Item', item_code, ['over_delivery_receipt_allowance', 'over_billing_allowance'])
Nabin Hait7f0406f2014-01-03 17:43:19 +0530375
Nabin Hait868766d2019-07-15 18:02:58 +0530376 if qty_or_amount == "qty" and not qty_allowance:
377 if global_qty_allowance == None:
378 global_qty_allowance = flt(frappe.db.get_single_value('Stock Settings', 'over_delivery_receipt_allowance'))
379 qty_allowance = global_qty_allowance
380 elif qty_or_amount == "amount" and not over_billing_allowance:
381 if global_amount_allowance == None:
382 global_amount_allowance = flt(frappe.db.get_single_value('Accounts Settings', 'over_billing_allowance'))
383 over_billing_allowance = global_amount_allowance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530384
Nabin Hait868766d2019-07-15 18:02:58 +0530385 if qty_or_amount == "qty":
386 allowance = qty_allowance
387 item_allowance.setdefault(item_code, frappe._dict()).setdefault("qty", qty_allowance)
388 else:
389 allowance = over_billing_allowance
390 item_allowance.setdefault(item_code, frappe._dict()).setdefault("amount", over_billing_allowance)
391
392 return allowance, item_allowance, global_qty_allowance, global_amount_allowance